From fdd5cf2fa6ae20a378bb10a03fa11b9c30a7c39c Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Sun, 14 May 2023 20:39:24 +0000 Subject: [PATCH] Bump version to 5.1.1-rc and LKG. --- lib/lib.es5.d.ts | 18 +- lib/tsc.js | 1806 +++-- lib/tsserver.js | 12844 ++++++++++++++++++---------------- lib/tsserverlibrary.d.ts | 132 +- lib/tsserverlibrary.js | 13213 +++++++++++++++++++---------------- lib/typescript.d.ts | 80 +- lib/typescript.js | 12747 +++++++++++++++++---------------- lib/typingsInstaller.js | 350 +- package.json | 2 +- src/compiler/corePublic.ts | 2 +- 10 files changed, 22111 insertions(+), 19083 deletions(-) diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index be7dfbd5995..870d8a04c01 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -4329,12 +4329,21 @@ interface Float64Array { sort(compareFn?: (a: number, b: number) => number): this; /** + * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin?: number, end?: number): Float64Array; + /** + * Converts a number to a string by using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an array. + */ toString(): string; /** Returns the primitive value of the specified object. */ @@ -4383,11 +4392,12 @@ declare var Float64Array: Float64ArrayConstructor; declare namespace Intl { interface CollatorOptions { - usage?: string | undefined; - localeMatcher?: string | undefined; + usage?: "sort" | "search" | undefined; + localeMatcher?: "lookup" | "best fit" | undefined; numeric?: boolean | undefined; - caseFirst?: string | undefined; - sensitivity?: string | undefined; + caseFirst?: "upper" | "lower" | "false" | undefined; + sensitivity?: "base" | "accent" | "case" | "variant" | undefined; + collation?: "big5han" | "compat" | "dict" | "direct" | "ducet" | "emoji" | "eor" | "gb2312" | "phonebk" | "phonetic" | "pinyin" | "reformed" | "searchjl" | "stroke" | "trad" | "unihan" | "zhuyin" | undefined; ignorePunctuation?: boolean | undefined; } diff --git a/lib/tsc.js b/lib/tsc.js index 0123889823f..fcc131f2a9c 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -18,7 +18,7 @@ and limitations under the License. // src/compiler/corePublic.ts var versionMajorMinor = "5.1"; -var version = "5.1.0-beta"; +var version = "5.1.1-rc"; // src/compiler/core.ts var emptyArray = []; @@ -3396,10 +3396,8 @@ var SyntaxKind = /* @__PURE__ */ ((SyntaxKind4) => { SyntaxKind4[SyntaxKind4["NotEmittedStatement"] = 358] = "NotEmittedStatement"; SyntaxKind4[SyntaxKind4["PartiallyEmittedExpression"] = 359] = "PartiallyEmittedExpression"; SyntaxKind4[SyntaxKind4["CommaListExpression"] = 360] = "CommaListExpression"; - SyntaxKind4[SyntaxKind4["MergeDeclarationMarker"] = 361] = "MergeDeclarationMarker"; - SyntaxKind4[SyntaxKind4["EndOfDeclarationMarker"] = 362] = "EndOfDeclarationMarker"; - SyntaxKind4[SyntaxKind4["SyntheticReferenceExpression"] = 363] = "SyntheticReferenceExpression"; - SyntaxKind4[SyntaxKind4["Count"] = 364] = "Count"; + SyntaxKind4[SyntaxKind4["SyntheticReferenceExpression"] = 361] = "SyntheticReferenceExpression"; + SyntaxKind4[SyntaxKind4["Count"] = 362] = "Count"; SyntaxKind4[SyntaxKind4["FirstAssignment"] = 64 /* EqualsToken */] = "FirstAssignment"; SyntaxKind4[SyntaxKind4["LastAssignment"] = 79 /* CaretEqualsToken */] = "LastAssignment"; SyntaxKind4[SyntaxKind4["FirstCompoundAssignment"] = 65 /* PlusEqualsToken */] = "FirstCompoundAssignment"; @@ -3891,9 +3889,8 @@ var EmitFlags = /* @__PURE__ */ ((EmitFlags3) => { EmitFlags3[EmitFlags3["ReuseTempVariableScope"] = 1048576] = "ReuseTempVariableScope"; EmitFlags3[EmitFlags3["CustomPrologue"] = 2097152] = "CustomPrologue"; EmitFlags3[EmitFlags3["NoHoisting"] = 4194304] = "NoHoisting"; - EmitFlags3[EmitFlags3["HasEndOfDeclarationMarker"] = 8388608] = "HasEndOfDeclarationMarker"; - EmitFlags3[EmitFlags3["Iterator"] = 16777216] = "Iterator"; - EmitFlags3[EmitFlags3["NoAsciiEscaping"] = 33554432] = "NoAsciiEscaping"; + EmitFlags3[EmitFlags3["Iterator"] = 8388608] = "Iterator"; + EmitFlags3[EmitFlags3["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; return EmitFlags3; })(EmitFlags || {}); var commentPragmas = { @@ -6974,6 +6971,7 @@ var Diagnostics = { List_of_folders_to_include_type_definitions_from: diag(6161, 3 /* Message */, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), Disable_size_limitations_on_JavaScript_projects: diag(6162, 3 /* Message */, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), The_character_set_of_the_input_files: diag(6163, 3 /* Message */, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1: diag(6164, 3 /* Message */, "Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1_6164", "Skipping module '{0}' that looks like an absolute URI, target file types: {1}."), Do_not_truncate_error_messages: diag(6165, 3 /* Message */, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), Output_directory_for_generated_declaration_files: diag(6166, 3 /* Message */, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, 3 /* Message */, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), @@ -7453,6 +7451,7 @@ var Diagnostics = { You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder: diag(8036, 1 /* Error */, "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036", "You cannot rename elements that are defined in another 'node_modules' folder."), Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files: diag(8037, 1 /* Error */, "Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files_8037", "Type satisfaction expressions can only be used in TypeScript files."), Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export: diag(8038, 1 /* Error */, "Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export_8038", "Decorators may not appear after 'export' or 'export default' if they also appear before 'export'."), + A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag: diag(8039, 1 /* Error */, "A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag_8039", "A JSDoc '@template' tag may not follow a '@typedef', '@callback', or '@overload' tag"), Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, 1 /* Error */, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."), Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, 1 /* Error */, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."), JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17e3, 1 /* Error */, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), @@ -7704,6 +7703,7 @@ var Diagnostics = { Use_Number_isNaN_in_all_conditions: diag(95175, 3 /* Message */, "Use_Number_isNaN_in_all_conditions_95175", "Use `Number.isNaN` in all conditions."), Convert_typedef_to_TypeScript_type: diag(95176, 3 /* Message */, "Convert_typedef_to_TypeScript_type_95176", "Convert typedef to TypeScript type."), Convert_all_typedef_to_TypeScript_types: diag(95177, 3 /* Message */, "Convert_all_typedef_to_TypeScript_types_95177", "Convert all typedef to TypeScript types."), + Move_to_file: diag(95178, 3 /* Message */, "Move_to_file_95178", "Move to file"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, 1 /* Error */, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, 1 /* Error */, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, 1 /* Error */, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -10917,7 +10917,6 @@ function isLeftHandSideExpressionKind(kind) { case 283 /* JsxElement */: case 284 /* JsxSelfClosingElement */: case 287 /* JsxFragment */: - case 294 /* JsxNamespacedName */: case 214 /* TaggedTemplateExpression */: case 208 /* ArrayLiteralExpression */: case 216 /* ParenthesizedExpression */: @@ -11159,7 +11158,7 @@ function isDeclarationStatementKind(kind) { return kind === 261 /* FunctionDeclaration */ || kind === 281 /* MissingDeclaration */ || kind === 262 /* ClassDeclaration */ || kind === 263 /* InterfaceDeclaration */ || kind === 264 /* TypeAliasDeclaration */ || kind === 265 /* EnumDeclaration */ || kind === 266 /* ModuleDeclaration */ || kind === 271 /* ImportDeclaration */ || kind === 270 /* ImportEqualsDeclaration */ || kind === 277 /* ExportDeclaration */ || kind === 276 /* ExportAssignment */ || kind === 269 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 251 /* BreakStatement */ || kind === 250 /* ContinueStatement */ || kind === 258 /* DebuggerStatement */ || kind === 245 /* DoStatement */ || kind === 243 /* ExpressionStatement */ || kind === 241 /* EmptyStatement */ || kind === 248 /* ForInStatement */ || kind === 249 /* ForOfStatement */ || kind === 247 /* ForStatement */ || kind === 244 /* IfStatement */ || kind === 255 /* LabeledStatement */ || kind === 252 /* ReturnStatement */ || kind === 254 /* SwitchStatement */ || kind === 256 /* ThrowStatement */ || kind === 257 /* TryStatement */ || kind === 242 /* VariableStatement */ || kind === 246 /* WhileStatement */ || kind === 253 /* WithStatement */ || kind === 358 /* NotEmittedStatement */ || kind === 362 /* EndOfDeclarationMarker */ || kind === 361 /* MergeDeclarationMarker */; + return kind === 251 /* BreakStatement */ || kind === 250 /* ContinueStatement */ || kind === 258 /* DebuggerStatement */ || kind === 245 /* DoStatement */ || kind === 243 /* ExpressionStatement */ || kind === 241 /* EmptyStatement */ || kind === 248 /* ForInStatement */ || kind === 249 /* ForOfStatement */ || kind === 247 /* ForStatement */ || kind === 244 /* IfStatement */ || kind === 255 /* LabeledStatement */ || kind === 252 /* ReturnStatement */ || kind === 254 /* SwitchStatement */ || kind === 256 /* ThrowStatement */ || kind === 257 /* TryStatement */ || kind === 242 /* VariableStatement */ || kind === 246 /* WhileStatement */ || kind === 253 /* WithStatement */ || kind === 358 /* NotEmittedStatement */; } function isDeclaration(node) { if (node.kind === 167 /* TypeParameter */) { @@ -11431,7 +11430,39 @@ function projectReferenceIsEqualTo(oldRef, newRef) { return oldRef.path === newRef.path && !oldRef.prepend === !newRef.prepend && !oldRef.circular === !newRef.circular; } function moduleResolutionIsEqualTo(oldResolution, newResolution) { - 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); + 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; +} +function createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageName) { + var _a, _b; + const node10Result = (_b = (_a = sourceFile.resolvedModules) == null ? void 0 : _a.get(moduleReference, mode)) == null ? void 0 : _b.node10Result; + const result = node10Result ? chainDiagnosticMessages( + /*details*/ + void 0, + 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 + ) : host.typesPackageExists(packageName) ? chainDiagnosticMessages( + /*details*/ + void 0, + 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*/ + void 0, + 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*/ + void 0, + 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 ? void 0 : packageName }); + return result; } function packageIdIsEqual(a, b) { return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; @@ -12059,7 +12090,7 @@ function getLiteralText(node, sourceFile, flags) { } switch (node.kind) { case 11 /* StringLiteral */: { - const escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString : flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + const escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString : flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; if (node.singleQuote) { return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; } else { @@ -12070,7 +12101,7 @@ function getLiteralText(node, sourceFile, flags) { case 16 /* TemplateHead */: case 17 /* TemplateMiddle */: case 18 /* TemplateTail */: { - const escapeText = flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + const escapeText = flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; const rawText = node.rawText ?? escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */)); switch (node.kind) { case 15 /* NoSubstitutionTemplateLiteral */: @@ -12163,7 +12194,7 @@ function isCommonJSContainingModuleKind(kind) { return kind === 1 /* CommonJS */ || kind === 100 /* Node16 */ || kind === 199 /* NodeNext */; } function isEffectiveExternalModule(node, compilerOptions) { - return isExternalModule(node) || getIsolatedModules(compilerOptions) || isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator; + return isExternalModule(node) || isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator; } function isEffectiveStrictModeSourceFile(node, compilerOptions) { switch (node.scriptKind) { @@ -12283,6 +12314,8 @@ function tryGetTextOfPropertyName(name) { if (isStringOrNumericLiteralLike(name.expression)) return escapeLeadingUnderscores(name.expression.text); return void 0; + case 294 /* JsxNamespacedName */: + return getEscapedTextOfJsxNamespacedName(name); default: return Debug.assertNever(name); } @@ -13736,6 +13769,7 @@ function canHaveJSDoc(node) { case 171 /* PropertyDeclaration */: case 170 /* PropertySignature */: case 252 /* ReturnStatement */: + case 239 /* SemicolonClassElement */: case 177 /* SetAccessor */: case 303 /* ShorthandPropertyAssignment */: case 304 /* SpreadAssignment */: @@ -14163,6 +14197,8 @@ function getPropertyNameForPropertyNameNode(name) { return nameExpression.operand.text; } return void 0; + case 294 /* JsxNamespacedName */: + return getEscapedTextOfJsxNamespacedName(name); default: return Debug.assertNever(name); } @@ -14179,10 +14215,10 @@ function isPropertyNameLiteral(node) { } } function getTextOfIdentifierOrLiteral(node) { - return isMemberName(node) ? idText(node) : node.text; + return isMemberName(node) ? idText(node) : isJsxNamespacedName(node) ? getTextOfJsxNamespacedName(node) : node.text; } function getEscapedTextOfIdentifierOrLiteral(node) { - return isMemberName(node) ? node.escapedText : escapeLeadingUnderscores(node.text); + return isMemberName(node) ? node.escapedText : isJsxNamespacedName(node) ? getEscapedTextOfJsxNamespacedName(node) : escapeLeadingUnderscores(node.text); } function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) { return `__#${getSymbolId(containingClassSymbol)}@${description}`; @@ -15413,6 +15449,8 @@ function tryGetPropertyAccessOrIdentifierToString(expr) { } } else if (isIdentifier(expr)) { return unescapeLeadingUnderscores(expr.escapedText); + } else if (isJsxNamespacedName(expr)) { + return getTextOfJsxNamespacedName(expr); } return void 0; } @@ -16601,7 +16639,7 @@ function getScriptKindFromFileName(fileName) { var supportedTSExtensions = [[".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */], [".cts" /* Cts */, ".d.cts" /* Dcts */], [".mts" /* Mts */, ".d.mts" /* Dmts */]]; var supportedTSExtensionsFlat = flatten(supportedTSExtensions); var supportedTSExtensionsWithJson = [...supportedTSExtensions, [".json" /* Json */]]; -var supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */, ".cts" /* Cts */, ".mts" /* Mts */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".cts" /* Cts */, ".mts" /* Mts */]; +var supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */, ".cts" /* Cts */, ".mts" /* Mts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; var supportedJSExtensions = [[".js" /* Js */, ".jsx" /* Jsx */], [".mjs" /* Mjs */], [".cjs" /* Cjs */]]; var supportedJSExtensionsFlat = flatten(supportedJSExtensions); var allSupportedExtensions = [[".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".js" /* Js */, ".jsx" /* Jsx */], [".cts" /* Cts */, ".d.cts" /* Dcts */, ".cjs" /* Cjs */], [".mts" /* Mts */, ".d.mts" /* Dmts */, ".mjs" /* Mjs */]]; @@ -18383,8 +18421,6 @@ function createNodeFactory(flags, baseFactory2) { updatePartiallyEmittedExpression, createCommaListExpression, updateCommaListExpression, - createEndOfDeclarationMarker, - createMergeDeclarationMarker, createSyntheticReferenceExpression, updateSyntheticReferenceExpression, cloneNode, @@ -21452,20 +21488,8 @@ function createNodeFactory(flags, baseFactory2) { function updateCommaListExpression(node, elements) { return node.elements !== elements ? update(createCommaListExpression(elements), node) : node; } - function createEndOfDeclarationMarker(original) { - const node = createBaseNode(362 /* EndOfDeclarationMarker */); - node.emitNode = {}; - node.original = original; - return node; - } - function createMergeDeclarationMarker(original) { - const node = createBaseNode(361 /* MergeDeclarationMarker */); - node.emitNode = {}; - node.original = original; - return node; - } function createSyntheticReferenceExpression(expression, thisArg) { - const node = createBaseNode(363 /* SyntheticReferenceExpression */); + const node = createBaseNode(361 /* SyntheticReferenceExpression */); node.expression = expression; node.thisArg = thisArg; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.thisArg); @@ -21857,8 +21881,8 @@ function createNodeFactory(flags, baseFactory2) { function inlineExpressions(expressions) { return expressions.length > 10 ? createCommaListExpression(expressions) : reduceLeft(expressions, factory2.createComma); } - function getName(node, allowComments, allowSourceMaps, emitFlags = 0) { - const nodeName = getNameOfDeclaration(node); + function getName(node, allowComments, allowSourceMaps, emitFlags = 0, ignoreAssignedName) { + const nodeName = ignoreAssignedName ? node && getNonAssignedNameOfDeclaration(node) : getNameOfDeclaration(node); if (nodeName && isIdentifier(nodeName) && !isGeneratedIdentifier(nodeName)) { const name = setParent(setTextRange(cloneNode(nodeName), nodeName), nodeName.parent); emitFlags |= getEmitFlags(nodeName); @@ -21875,8 +21899,8 @@ function createNodeFactory(flags, baseFactory2) { function getInternalName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */ | 65536 /* InternalName */); } - function getLocalName(node, allowComments, allowSourceMaps) { - return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */); + function getLocalName(node, allowComments, allowSourceMaps, ignoreAssignedName) { + return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */, ignoreAssignedName); } function getExportName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps, 16384 /* ExportName */); @@ -24169,7 +24193,7 @@ function isNotEmittedStatement(node) { return node.kind === 358 /* NotEmittedStatement */; } function isSyntheticReference(node) { - return node.kind === 363 /* SyntheticReferenceExpression */; + return node.kind === 361 /* SyntheticReferenceExpression */; } function isExternalModuleReference(node) { return node.kind === 282 /* ExternalModuleReference */; @@ -27183,8 +27207,13 @@ var Parser; return tokenIsIdentifierOrKeyword(token()) || token() === 19 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; + case 25 /* JSDocComment */: + return true; + case 26 /* Count */: + return Debug.fail("ParsingContext.Count used as a context"); + default: + Debug.assertNever(parsingContext2, "Non-exhaustive case in 'isListElement'."); } - return Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { Debug.assert(token() === 19 /* OpenBraceToken */); @@ -27278,7 +27307,8 @@ var Parser; return false; } function isInSomeParsingContext() { - for (let kind = 0; kind < 25 /* Count */; kind++) { + Debug.assert(parsingContext, "Missing parsing context"); + for (let kind = 0; kind < 26 /* Count */; kind++) { if (parsingContext & 1 << kind) { if (isListElement( kind, @@ -27537,7 +27567,9 @@ var Parser; return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); case 24 /* AssertEntries */: return parseErrorAtCurrentToken(Diagnostics.Identifier_or_string_literal_expected); - case 25 /* Count */: + case 25 /* JSDocComment */: + return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); + case 26 /* Count */: return Debug.fail("ParsingContext.Count used as a context"); default: Debug.assertNever(context); @@ -29588,7 +29620,11 @@ var Parser; } function parseJsxElementName() { const pos = getNodePos(); - let expression = parseJsxTagName(); + const initialExpression = parseJsxTagName(); + if (isJsxNamespacedName(initialExpression)) { + return initialExpression; + } + let expression = initialExpression; while (parseOptional(25 /* DotToken */)) { expression = finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot( /*allowIdentifierNames*/ @@ -31118,11 +31154,11 @@ var Parser; } function parseClassElement() { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); if (token() === 27 /* SemicolonToken */) { nextToken(); - return finishNode(factory2.createSemicolonClassElement(), pos); + return withJSDoc(finishNode(factory2.createSemicolonClassElement(), pos), hasJSDoc); } - const hasJSDoc = hasPrecedingJSDocComment(); const modifiers = parseModifiers( /*allowDecorators*/ true, @@ -31669,7 +31705,8 @@ var Parser; ParsingContext2[ParsingContext2["HeritageClauses"] = 22] = "HeritageClauses"; ParsingContext2[ParsingContext2["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; ParsingContext2[ParsingContext2["AssertEntries"] = 24] = "AssertEntries"; - ParsingContext2[ParsingContext2["Count"] = 25] = "Count"; + ParsingContext2[ParsingContext2["JSDocComment"] = 25] = "JSDocComment"; + ParsingContext2[ParsingContext2["Count"] = 26] = "Count"; })(ParsingContext || (ParsingContext = {})); let Tristate; ((Tristate2) => { @@ -31791,6 +31828,8 @@ var Parser; PropertyLikeParse2[PropertyLikeParse2["CallbackParameter"] = 4] = "CallbackParameter"; })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start = 0, length2) { + const saveParsingContext = parsingContext; + parsingContext |= 1 << 25 /* JSDocComment */; const content = sourceText; const end = length2 === void 0 ? content.length : start + length2; length2 = end - start; @@ -31807,7 +31846,10 @@ var Parser; let commentsPos; let comments = []; const parts = []; - return scanner.scanRange(start + 3, length2 - 5, () => { + const result = scanner.scanRange(start + 3, length2 - 5, doJSDocScan); + parsingContext = saveParsingContext; + return result; + function doJSDocScan() { let state = 1 /* SawAsterisk */; let margin; let indent2 = start - (content.lastIndexOf("\n", start) + 1) + 4; @@ -31903,7 +31945,7 @@ var Parser; Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); const tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); return finishNode(factory2.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : trimmedComments.length ? trimmedComments : void 0, tagsArray), start, end); - }); + } function removeLeadingNewlines(comments2) { while (comments2.length && (comments2[0] === "\n" || comments2[0] === "\r")) { comments2.shift(); @@ -32262,8 +32304,8 @@ var Parser; typeExpression = nestedTypeLiteral; isNameFirst = true; } - const result = target === 1 /* Property */ ? factory2.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) : factory2.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment); - return finishNode(result, start2); + const result2 = target === 1 /* Property */ ? factory2.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) : factory2.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment); + return finishNode(result2, start2); } function parseNestedTypeLiteral(typeExpression, name, target, indent2) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { @@ -32273,6 +32315,8 @@ var Parser; while (child = tryParse(() => parseChildParameterOrPropertyTag(target, indent2, name))) { if (child.kind === 347 /* JSDocParameterTag */ || child.kind === 354 /* JSDocPropertyTag */) { children = append(children, child); + } else if (child.kind === 351 /* JSDocTemplateTag */) { + parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag); } } if (children) { @@ -32360,7 +32404,9 @@ var Parser; const usedBrace = parseOptional(19 /* OpenBraceToken */); const pos = getNodePos(); const expression = parsePropertyAccessEntityNameExpression(); + scanner.setInJSDocType(true); const typeArguments = tryParseTypeArguments(); + scanner.setInJSDocType(false); const node = factory2.createExpressionWithTypeArguments(expression, typeArguments); const res = finishNode(node, pos); if (usedBrace) { @@ -32409,6 +32455,9 @@ var Parser; let jsDocPropertyTags; let hasChildren = false; while (child = tryParse(() => parseChildPropertyTag(indent2))) { + if (child.kind === 351 /* JSDocTemplateTag */) { + break; + } hasChildren = true; if (child.kind === 350 /* JSDocTypeTag */) { if (childTypeTag) { @@ -32468,6 +32517,10 @@ var Parser; let child; let parameters; while (child = tryParse(() => parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent2))) { + if (child.kind === 351 /* JSDocTemplateTag */) { + parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag); + break; + } parameters = append(parameters, child); } return createNodeArray(parameters || [], pos); @@ -32562,7 +32615,7 @@ var Parser; const start2 = scanner.getTokenFullStart(); nextTokenJSDoc(); const tagName = parseJSDocIdentifierName(); - skipWhitespace(); + const indentText = skipWhitespaceOrAsterisk(); let t; switch (tagName.escapedText) { case "type": @@ -32576,6 +32629,8 @@ var Parser; case "param": t = 2 /* Parameter */ | 4 /* CallbackParameter */; break; + case "template": + return parseTemplateTag(start2, tagName, indent2, indentText); default: return false; } @@ -32663,9 +32718,9 @@ var Parser; const end2 = scanner.getTokenEnd(); const originalKeywordKind = token(); const text = internIdentifier(scanner.getTokenValue()); - const result = finishNode(factoryCreateIdentifier(text, originalKeywordKind), start2, end2); + const result2 = finishNode(factoryCreateIdentifier(text, originalKeywordKind), start2, end2); nextTokenJSDoc(); - return result; + return result2; } } })(JSDocParser = Parser2.JSDocParser || (Parser2.JSDocParser = {})); @@ -37140,13 +37195,12 @@ function createModuleOrTypeReferenceResolutionCache(currentDirectory, getCanonic nonRelativeNameResolutionCache.update(options2); } } -function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) { +function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache) { const result = createModuleOrTypeReferenceResolutionCache( currentDirectory, getCanonicalFileName, options, - /*packageJsonInfoCache*/ - void 0, + packageJsonInfoCache, getOriginalOrResolvedModuleFileName ); result.getOrCreateCacheForModuleName = (nonRelativeName, mode, redirectedReference) => result.getOrCreateCacheForNonRelativeName(nonRelativeName, mode, redirectedReference); @@ -37161,6 +37215,12 @@ function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanoni getOriginalOrResolvedTypeReferenceFileName ); } +function getOptionsForLibraryResolution(options) { + return { moduleResolution: 2 /* Node10 */, traceResolution: options.traceResolution }; +} +function resolveLibrary(libraryName, resolveFrom, compilerOptions, host, cache) { + return resolveModuleName(libraryName, resolveFrom, getOptionsForLibraryResolution(compilerOptions), host, cache); +} function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, resolutionMode) { var _a, _b, _c; const traceEnabled = isTraceEnabled(compilerOptions, host); @@ -37506,8 +37566,6 @@ function nodeModuleNameResolverWorker(features, moduleName, containingDirectory, const diagnosticState = { ...state, features: state.features & ~8 /* Exports */, - failedLookupLocations: [], - affectingLocations: [], reportDiagnostic: noop }; const diagnosticResult = tryResolve(extensions & (1 /* TypeScript */ | 4 /* Declaration */), diagnosticState); @@ -37547,6 +37605,12 @@ function nodeModuleNameResolverWorker(features, moduleName, containingDirectory, resolved2 = loadModuleFromSelfNameReference(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); } if (!resolved2) { + if (moduleName.indexOf(":") > -1) { + if (traceEnabled) { + trace(host, Diagnostics.Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); + } + return void 0; + } if (traceEnabled) { trace(host, Diagnostics.Loading_module_0_from_node_modules_folder_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); } @@ -37633,22 +37697,22 @@ var nodeModulesPathPart = "/node_modules/"; function pathContainsNodeModules(path) { return stringContains(path, nodeModulesPathPart); } -function parseNodeModuleFromPath(resolved) { +function parseNodeModuleFromPath(resolved, isFolder) { const path = normalizePath(resolved); const idx = path.lastIndexOf(nodeModulesPathPart); if (idx === -1) { return void 0; } const indexAfterNodeModules = idx + nodeModulesPathPart.length; - let indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + let indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules, isFolder); if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { - indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName, isFolder); } return path.slice(0, indexAfterPackageName); } -function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { +function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex, isFolder) { const nextSeparatorIndex = path.indexOf(directorySeparator, prevSeparatorIndex + 1); - return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + return nextSeparatorIndex === -1 ? isFolder ? path.length : prevSeparatorIndex : nextSeparatorIndex; } function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); @@ -38479,7 +38543,7 @@ function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, node return withPackageId(packageInfo, fromDirectory); } const loader = (extensions2, candidate2, onlyRecordFailures, state2) => { - let pathAndExtension = loadModuleFromFile(extensions2, candidate2, onlyRecordFailures, state2) || loadNodeModuleFromDirectoryWorker( + let pathAndExtension = (rest || !(state2.features & 32 /* EsmMode */)) && loadModuleFromFile(extensions2, candidate2, onlyRecordFailures, state2) || loadNodeModuleFromDirectoryWorker( extensions2, candidate2, onlyRecordFailures, @@ -39024,7 +39088,7 @@ function createBinder() { return getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText); } if (isJsxNamespacedName(name)) { - return getEscapedTextOfJsxAttributeName(name); + return getEscapedTextOfJsxNamespacedName(name); } return isPropertyNameLiteral(name) ? getEscapedTextOfIdentifierOrLiteral(name) : void 0; } @@ -41791,15 +41855,16 @@ function getPreferences({ importModuleSpecifierPreference, importModuleSpecifier if (getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */) { return preferredEnding === 2 /* JsExtension */ ? [2 /* JsExtension */, 1 /* Index */] : [1 /* Index */, 2 /* JsExtension */]; } + const allowImportingTsExtension = shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName); switch (preferredEnding) { case 2 /* JsExtension */: - return [2 /* JsExtension */, 0 /* Minimal */, 1 /* Index */]; + return allowImportingTsExtension ? [2 /* JsExtension */, 3 /* TsExtension */, 0 /* Minimal */, 1 /* Index */] : [2 /* JsExtension */, 0 /* Minimal */, 1 /* Index */]; case 3 /* TsExtension */: return [3 /* TsExtension */, 0 /* Minimal */, 2 /* JsExtension */, 1 /* Index */]; case 1 /* Index */: - return [1 /* Index */, 0 /* Minimal */, 2 /* JsExtension */]; + return allowImportingTsExtension ? [1 /* Index */, 0 /* Minimal */, 3 /* TsExtension */, 2 /* JsExtension */] : [1 /* Index */, 0 /* Minimal */, 2 /* JsExtension */]; case 0 /* Minimal */: - return [0 /* Minimal */, 1 /* Index */, 2 /* JsExtension */]; + return allowImportingTsExtension ? [0 /* Minimal */, 1 /* Index */, 3 /* TsExtension */, 2 /* JsExtension */] : [0 /* Minimal */, 1 /* Index */, 2 /* JsExtension */]; default: Debug.assertNever(preferredEnding); } @@ -41962,7 +42027,7 @@ function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, im return pathsOnly ? void 0 : relativePath; } const baseDirectory = getNormalizedAbsolutePath(getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); - const relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); + const relativeToBaseUrl = getRelativePathIfInSameVolume(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) { return pathsOnly ? void 0 : relativePath; } @@ -42170,7 +42235,7 @@ function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, hos for (const { ending, value } of candidates) { if (value.length >= prefix.length + suffix.length && startsWith(value, prefix) && endsWith(value, suffix) && validateEnding({ ending, value })) { const matchedStar = value.substring(prefix.length, value.length - suffix.length); - return key.replace("*", matchedStar); + return pathIsRelative(matchedStar) ? void 0 : key.replace("*", matchedStar); } } } else if (some(candidates, (c) => c.ending !== 0 /* Minimal */ && pattern === c.value) || some(candidates, (c) => c.ending === 0 /* Minimal */ && pattern === c.value && validateEnding(c))) { @@ -42359,7 +42424,10 @@ function tryGetModuleNameAsNodeModule({ path, isRedirect }, { getCanonicalFileNa const mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main || "index.js"; if (isString(mainFileRelative) && !(maybeBlockedByTypesVersions && matchPatternOrExact(tryParsePatterns(versionPaths.paths), mainFileRelative))) { const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (removeFileExtension(mainExportFile) === removeFileExtension(getCanonicalFileName(moduleFileToTry))) { + const canonicalModuleFileToTry = getCanonicalFileName(moduleFileToTry); + if (removeFileExtension(mainExportFile) === removeFileExtension(canonicalModuleFileToTry)) { + return { packageRootPath, moduleFileToTry }; + } else if (packageJsonContent.type !== "module" && !fileExtensionIsOneOf(canonicalModuleFileToTry, extensionsNotSupportingExtensionlessResolution) && startsWith(canonicalModuleFileToTry, mainExportFile) && getDirectoryPath(canonicalModuleFileToTry) === removeTrailingDirectorySeparator(mainExportFile) && removeFileExtension(getBaseFileName(canonicalModuleFileToTry)) === "index") { return { packageRootPath, moduleFileToTry }; } } @@ -42385,7 +42453,7 @@ function tryGetAnyFileFromPath(host, path) { } function getPathsRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { return mapDefined(rootDirs, (rootDir) => { - const relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + const relativePath = getRelativePathIfInSameVolume(path, rootDir, getCanonicalFileName); return relativePath !== void 0 && isPathRelativeToParent(relativePath) ? void 0 : relativePath; }); } @@ -42397,7 +42465,11 @@ function processEnding(fileName, allowedEndings, options, host) { if (fileName === noExtension) { return fileName; } - if (fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".d.cts" /* Dcts */, ".cts" /* Cts */])) { + const jsPriority = allowedEndings.indexOf(2 /* JsExtension */); + const tsPriority = allowedEndings.indexOf(3 /* TsExtension */); + if (fileExtensionIsOneOf(fileName, [".mts" /* Mts */, ".cts" /* Cts */]) && tsPriority !== -1 && tsPriority < jsPriority) { + return fileName; + } else if (fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".d.cts" /* Dcts */, ".cts" /* Cts */])) { return noExtension + getJSExtensionForFile(fileName, options); } else if (!fileExtensionIsOneOf(fileName, [".d.ts" /* Dts */]) && fileExtensionIsOneOf(fileName, [".ts" /* Ts */]) && stringContains(fileName, ".d.")) { return tryGetRealFileNameForNonJsDeclarationFileName(fileName); @@ -42416,7 +42488,6 @@ function processEnding(fileName, allowedEndings, options, host) { case 3 /* TsExtension */: if (isDeclarationFileName(fileName)) { const extensionlessPriority = allowedEndings.findIndex((e) => e === 0 /* Minimal */ || e === 1 /* Index */); - const jsPriority = allowedEndings.indexOf(2 /* JsExtension */); return extensionlessPriority !== -1 && extensionlessPriority < jsPriority ? noExtension : noExtension + getJSExtensionForFile(fileName, options); } return fileName; @@ -42459,7 +42530,7 @@ function tryGetJSExtensionForFile(fileName, options) { return void 0; } } -function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { +function getRelativePathIfInSameVolume(path, directoryPath, getCanonicalFileName) { const relativePath = getRelativePathToDirectoryOrUrl( directoryPath, path, @@ -42622,18 +42693,6 @@ function isInstantiatedModule(node, preserveConstEnums) { return moduleState === 1 /* Instantiated */ || preserveConstEnums && moduleState === 2 /* ConstEnumOnly */; } function createTypeChecker(host) { - var getPackagesMap = memoize(() => { - var map2 = /* @__PURE__ */ new Map(); - host.getSourceFiles().forEach((sf) => { - if (!sf.resolvedModules) - return; - sf.resolvedModules.forEach(({ resolvedModule }) => { - if (resolvedModule == null ? void 0 : resolvedModule.packageId) - map2.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!map2.get(resolvedModule.packageId.name)); - }); - }); - return map2; - }); var deferredDiagnosticsCallbacks = []; var addLazyDiagnostic = (arg) => { deferredDiagnosticsCallbacks.push(arg); @@ -43364,7 +43423,7 @@ function createTypeChecker(host) { getGlobalIterableType: getGlobalAsyncIterableType, getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType, getGlobalGeneratorType: getGlobalAsyncGeneratorType, - resolveIterationType: getAwaitedType, + resolveIterationType: (type, errorNode) => getAwaitedType(type, errorNode, Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member), mustHaveANextMethodDiagnostic: Diagnostics.An_async_iterator_must_have_a_next_method, mustBeAMethodDiagnostic: Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method, mustHaveAValueDiagnostic: Diagnostics.The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property @@ -43646,13 +43705,14 @@ function createTypeChecker(host) { return diagnostic; } function isDeprecatedSymbol(symbol) { - if (length(symbol.declarations) > 1) { - const parentSymbol = getParentOfSymbol(symbol); - if (parentSymbol && parentSymbol.flags & 64 /* Interface */) { - return some(symbol.declarations, (d) => !!(getCombinedNodeFlags(d) & 268435456 /* Deprecated */)); - } + const parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol && length(symbol.declarations) > 1) { + return parentSymbol.flags & 64 /* Interface */ ? some(symbol.declarations, isDeprecatedDeclaration) : every(symbol.declarations, isDeprecatedDeclaration); } - return !!(getDeclarationNodeFlagsFromSymbol(symbol) & 268435456 /* Deprecated */); + return !!symbol.valueDeclaration && isDeprecatedDeclaration(symbol.valueDeclaration) || length(symbol.declarations) && every(symbol.declarations, isDeprecatedDeclaration); + } + function isDeprecatedDeclaration(declaration) { + return !!(getCombinedNodeFlags(declaration) & 268435456 /* Deprecated */); } function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { const diagnostic = createDiagnosticForNode(location, Diagnostics._0_is_deprecated, deprecatedEntity); @@ -44006,7 +44066,7 @@ function createTypeChecker(host) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { + if (getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */ && useDefineForClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration( declaration, usage, @@ -44169,6 +44229,10 @@ function createTypeChecker(host) { if (name === "const" && isConstAssertion(location)) { return void 0; } + if (isModuleDeclaration(location) && lastLocation && location.name === lastLocation) { + lastLocation = location; + location = location.parent; + } if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) { if (result = lookup(location.locals, name, meaning)) { let useResult = true; @@ -44359,6 +44423,11 @@ function createTypeChecker(host) { } } break; + case 280 /* ExportSpecifier */: + if (lastLocation && lastLocation === location.propertyName && location.parent.parent.moduleSpecifier) { + location = location.parent.parent.parent; + } + break; } if (isSelfReferenceLocation(location)) { lastSelfReferenceLocation = location; @@ -44406,7 +44475,7 @@ function createTypeChecker(host) { if (!result) { if (nameNotFoundMessage) { addLazyDiagnostic(() => { - if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 + if (!errorLocation || errorLocation.parent.kind !== 330 /* 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)) { let suggestion; let suggestedLib; @@ -45959,35 +46028,9 @@ function createTypeChecker(host) { } } function errorOnImplicitAnyModule(isError, errorNode, sourceFile, mode, { packageId, resolvedFileName }, moduleReference) { - var _a, _b; let errorInfo; if (!isExternalModuleNameRelative(moduleReference) && packageId) { - const node10Result = (_b = (_a = sourceFile.resolvedModules) == null ? void 0 : _a.get(moduleReference, mode)) == null ? void 0 : _b.node10Result; - errorInfo = node10Result ? chainDiagnosticMessages( - /*details*/ - void 0, - 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(packageId.name)}` : packageId.name - ) : typesPackageExists(packageId.name) ? chainDiagnosticMessages( - /*details*/ - void 0, - 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, - packageId.name, - mangleScopedPackageName(packageId.name) - ) : packageBundlesTypes(packageId.name) ? chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1, - packageId.name, - moduleReference - ) : chainDiagnosticMessages( - /*details*/ - void 0, - 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(packageId.name) - ); + errorInfo = createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageId.name); } errorOrSuggestion(isError, errorNode, chainDiagnosticMessages( errorInfo, @@ -45996,12 +46039,6 @@ function createTypeChecker(host) { resolvedFileName )); } - function typesPackageExists(packageName) { - return getPackagesMap().has(getTypesPackageName(packageName)); - } - function packageBundlesTypes(packageName) { - return !!getPackagesMap().get(packageName); - } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { if (moduleSymbol == null ? void 0 : moduleSymbol.exports) { const exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias); @@ -47164,7 +47201,7 @@ function createTypeChecker(host) { } if (type.flags & 128 /* StringLiteral */) { context.approximateLength += type.value.length + 2; - return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 33554432 /* NoAsciiEscaping */)); + return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */)); } if (type.flags & 256 /* NumberLiteral */) { const value = type.value; @@ -48052,7 +48089,7 @@ function createTypeChecker(host) { const typePredicate = getTypePredicateOfSignature(signature); if (typePredicate) { const assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? factory.createToken(131 /* AssertsKeyword */) : void 0; - const parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? setEmitFlags(factory.createIdentifier(typePredicate.parameterName), 33554432 /* NoAsciiEscaping */) : factory.createThisTypeNode(); + const parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? setEmitFlags(factory.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : factory.createThisTypeNode(); const typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = factory.createTypePredicateNode(assertsModifier, parameterName, typeNode); } else { @@ -48179,7 +48216,7 @@ function createTypeChecker(host) { const modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && canHaveModifiers(parameterDeclaration) ? map(getModifiers(parameterDeclaration), factory.cloneNode) : void 0; const isRest = parameterDeclaration && isRestParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 32768 /* RestParameter */; const dotDotDotToken = isRest ? factory.createToken(26 /* DotDotDotToken */) : void 0; - const name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 80 /* Identifier */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), 33554432 /* NoAsciiEscaping */) : parameterDeclaration.name.kind === 165 /* QualifiedName */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), 33554432 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol); + const name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 80 /* Identifier */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : parameterDeclaration.name.kind === 165 /* QualifiedName */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol); const isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */; const questionToken = isOptional ? factory.createToken(58 /* QuestionToken */) : void 0; const parameterNode = factory.createParameterDeclaration( @@ -48220,7 +48257,7 @@ function createTypeChecker(host) { if (!nodeIsSynthesized(visited)) { visited = factory.cloneNode(visited); } - return setEmitFlags(visited, 1 /* SingleLine */ | 33554432 /* NoAsciiEscaping */); + return setEmitFlags(visited, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); } } } @@ -48545,7 +48582,7 @@ function createTypeChecker(host) { return factory.createIndexedAccessTypeNode(factory.createTypeReferenceNode(LHS, typeParameterNodes), factory.createLiteralTypeNode(factory.createStringLiteral(symbolName2))); } } - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; @@ -48631,7 +48668,7 @@ function createTypeChecker(host) { if (index === 0) { context.flags ^= 16777216 /* InInitialEntityName */; } - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; @@ -48656,7 +48693,7 @@ function createTypeChecker(host) { return factory.createStringLiteral(getSpecifierForModuleSymbol(symbol2, context)); } if (index === 0 || canUsePropertyAccess(symbolName2, languageVersion)) { - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; @@ -48673,7 +48710,7 @@ function createTypeChecker(host) { expression = factory.createNumericLiteral(+symbolName2); } if (!expression) { - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; @@ -48826,7 +48863,7 @@ function createTypeChecker(host) { const type = getDeclaredTypeOfSymbol(sym); const name = sym.flags & 262144 /* TypeParameter */ && !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration) ? typeParameterToName(type, context) : factory.cloneNode(node); name.symbol = sym; - return { introducesError, node: setEmitFlags(setOriginalNode(name, node), 33554432 /* NoAsciiEscaping */) }; + return { introducesError, node: setEmitFlags(setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */) }; } } return { introducesError, node }; @@ -49269,7 +49306,7 @@ function createTypeChecker(host) { if (symbol.flags & 524288 /* TypeAlias */) { serializeTypeAlias(symbol, symbolName2, modifierFlags); } - if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && symbol.escapedName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) && !(symbol.flags & 32 /* Class */) && !(symbol.flags & 8192 /* Method */) && !isConstMergedWithNSPrintableAsSignatureMerge) { + if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */ | 98304 /* Accessor */) && symbol.escapedName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) && !(symbol.flags & 32 /* Class */) && !(symbol.flags & 8192 /* Method */) && !isConstMergedWithNSPrintableAsSignatureMerge) { if (propertyAsAlias) { const createdExport = serializeMaybeAliasAssignment(symbol); if (createdExport) { @@ -49687,7 +49724,7 @@ function createTypeChecker(host) { context.enclosingDeclaration = originalDecl || oldEnclosing; const localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); const typeParamDecls = map(localParams, (p) => typeParameterToDeclaration(p, context)); - const classType = getDeclaredTypeOfClassOrInterface(symbol); + const classType = getTypeWithThisArgument(getDeclaredTypeOfClassOrInterface(symbol)); const baseTypes = getBaseTypes(classType); const originalImplements = originalDecl && getEffectiveImplementsTypeNodes(originalDecl); const implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements) || mapDefined(getImplementsTypes(classType), serializeImplementedType); @@ -50886,7 +50923,7 @@ function createTypeChecker(host) { const elementType = checkIteratedTypeOrElementType(65 /* Destructuring */ | (declaration.dotDotDotToken ? 0 : 128 /* PossiblyOutOfBounds */), parentType, undefinedType, pattern); const index = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - const baseConstraint = getBaseConstraintOrType(parentType); + const baseConstraint = mapType(parentType, (t) => t.flags & 58982400 /* InstantiableNonPrimitive */ ? getBaseConstraintOrType(t) : t); type = everyType(baseConstraint, isTupleType) ? mapType(baseConstraint, (t) => sliceTupleType(t, index)) : createArrayType(elementType); } else if (isArrayLikeType(parentType)) { const indexType = getNumberLiteralType(index); @@ -52614,6 +52651,9 @@ function createTypeChecker(host) { } return needApparentType ? getApparentType(type) : type; } + function getThisArgument(type) { + return getObjectFlags(type) & 4 /* Reference */ && length(getTypeArguments(type)) > getTypeReferenceArity(type) ? last(getTypeArguments(type)) : type; + } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { let mapper; let members; @@ -52744,7 +52784,7 @@ function createTypeChecker(host) { } return [sig.parameters]; function expandSignatureParametersWithTupleMembers(restType, restIndex) { - const elementTypes = getTypeArguments(restType); + const elementTypes = getElementTypes(restType); const associatedNames = getUniqAssociatedNamesFromTupleType(restType); const restParams = map(elementTypes, (t, i) => { const name = associatedNames && associatedNames[i] ? associatedNames[i] : getParameterNameAtPosition(sig, restIndex + i, restType); @@ -53560,7 +53600,7 @@ function createTypeChecker(host) { } function isConstTypeVariable(type) { var _a; - return !!(type && (type.flags & 262144 /* TypeParameter */ && some((_a = type.symbol) == null ? void 0 : _a.declarations, (d) => hasSyntacticModifier(d, 2048 /* Const */)) || type.flags & 1048576 /* Union */ && some(type.types, isConstTypeVariable) || type.flags & 8388608 /* IndexedAccess */ && isConstTypeVariable(type.objectType) || type.flags & 16777216 /* Conditional */ && isConstTypeVariable(getConstraintOfConditionalType(type)) || type.flags & 33554432 /* Substitution */ && isConstTypeVariable(type.baseType) || isGenericTupleType(type) && findIndex(getTypeArguments(type), (t, i) => !!(type.target.elementFlags[i] & 8 /* Variadic */) && isConstTypeVariable(t)) >= 0)); + return !!(type && (type.flags & 262144 /* TypeParameter */ && some((_a = type.symbol) == null ? void 0 : _a.declarations, (d) => hasSyntacticModifier(d, 2048 /* Const */)) || type.flags & 1048576 /* Union */ && some(type.types, isConstTypeVariable) || type.flags & 8388608 /* IndexedAccess */ && isConstTypeVariable(type.objectType) || type.flags & 16777216 /* Conditional */ && isConstTypeVariable(getConstraintOfConditionalType(type)) || type.flags & 33554432 /* Substitution */ && isConstTypeVariable(type.baseType) || isGenericTupleType(type) && findIndex(getElementTypes(type), (t, i) => !!(type.target.elementFlags[i] & 8 /* Variadic */) && isConstTypeVariable(t)) >= 0)); } function getConstraintOfIndexedAccess(type) { return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : void 0; @@ -53662,7 +53702,7 @@ function createTypeChecker(host) { return void 0; } function getBaseConstraintOfType(type) { - if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) { + if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) || isGenericTupleType(type)) { const constraint = getResolvedBaseConstraint(type); return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : void 0; } @@ -53679,7 +53719,7 @@ function createTypeChecker(host) { return type.resolvedBaseConstraint; } const stack = []; - return type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type); + return type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), getThisArgument(type)); function getImmediateBaseConstraint(t) { if (!t.immediateBaseConstraint) { if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { @@ -53769,6 +53809,13 @@ function createTypeChecker(host) { if (t.flags & 33554432 /* Substitution */) { return getBaseConstraint(getSubstitutionIntersection(t)); } + if (isGenericTupleType(t)) { + const newElements = map(getElementTypes(t), (v, i) => { + const constraint = t.target.elementFlags[i] & 8 /* Variadic */ && getBaseConstraint(v) || v; + return constraint && everyType(constraint, (c) => isArrayOrTupleType(c) && !isGenericTupleType(c)) ? constraint : v; + }); + return createTupleType(newElements, t.target.elementFlags, t.target.readonly, t.target.labeledElementDeclarations); + } return t; } } @@ -54309,7 +54356,8 @@ function createTypeChecker(host) { thisParameter = createSymbolWithType(createSymbol(1 /* FunctionScopedVariable */, "this" /* This */), getTypeFromTypeNode(thisTag.typeExpression)); } } - const classType = declaration.kind === 175 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : void 0; + const hostDeclaration = isJSDocSignature(declaration) ? getEffectiveJSDocHost(declaration) : declaration; + const classType = hostDeclaration && isConstructorDeclaration(hostDeclaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(hostDeclaration.parent.symbol)) : void 0; const typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); if (hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { flags |= 1 /* HasRestParameter */; @@ -54535,16 +54583,16 @@ function createTypeChecker(host) { if (declaration.kind === 175 /* Constructor */) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); } + const typeNode = getEffectiveReturnTypeNode(declaration); if (isJSDocSignature(declaration)) { const root = getJSDocRoot(declaration); - if (root && isConstructorDeclaration(root.parent)) { + if (root && isConstructorDeclaration(root.parent) && !typeNode) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(root.parent.parent.symbol)); } } if (isJSDocConstructSignature(declaration)) { return getTypeFromTypeNode(declaration.parameters[0].type); } - const typeNode = getEffectiveReturnTypeNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); } @@ -55822,7 +55870,7 @@ function createTypeChecker(host) { if (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type)) { addElement(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) == null ? void 0 : _a[i]); } else if (isTupleType(type)) { - const elements = getTypeArguments(type); + const elements = getElementTypes(type); if (elements.length + expandedTypes.length >= 1e4) { 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; @@ -55900,6 +55948,11 @@ function createTypeChecker(host) { function getEndElementCount(type, flags) { return type.elementFlags.length - findLastIndex(type.elementFlags, (f) => !(f & flags)) - 1; } + function getElementTypes(type) { + const typeArguments = getTypeArguments(type); + const arity = getTypeReferenceArity(type); + return typeArguments.length === arity ? typeArguments : typeArguments.slice(0, arity); + } function getTypeFromOptionalTypeNode(node) { return addOptionality( getTypeFromTypeNode(node.type), @@ -56496,7 +56549,20 @@ function createTypeChecker(host) { if (isPrivateIdentifier(name)) { return neverType; } - return isIdentifier(name) ? getStringLiteralType(unescapeLeadingUnderscores(name.escapedText)) : getRegularTypeOfLiteralType(isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + if (isNumericLiteral(name)) { + return getRegularTypeOfLiteralType(checkExpression(name)); + } + if (isComputedPropertyName(name)) { + return getRegularTypeOfLiteralType(checkComputedPropertyName(name)); + } + const propertyName = getPropertyNameForPropertyNameNode(name); + if (propertyName !== void 0) { + return getStringLiteralType(unescapeLeadingUnderscores(propertyName)); + } + if (isExpression(name)) { + return getRegularTypeOfLiteralType(checkExpression(name)); + } + return neverType; } function getLiteralTypeFromProperty(prop, include, includeNonPublic) { if (includeNonPublic || !(getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { @@ -57150,7 +57216,7 @@ function createTypeChecker(host) { return isTupleTypeNode(node) && length(node.elements) > 0 && !some(node.elements, (e) => isOptionalTypeNode(e) || isRestTypeNode(e) || isNamedTupleMember(e) && !!(e.questionToken || e.dotDotDotToken)); } function isDeferredType(type, checkTuples) { - return isGenericType(type) || checkTuples && isTupleType(type) && some(getTypeArguments(type), isGenericType); + return isGenericType(type) || checkTuples && isTupleType(type) && some(getElementTypes(type), isGenericType); } function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { let result; @@ -58085,7 +58151,7 @@ function createTypeChecker(host) { } function instantiateMappedGenericTupleType(tupleType, mappedType, typeVariable, mapper) { const elementFlags = tupleType.target.elementFlags; - const elementTypes = map(getTypeArguments(tupleType), (t, i) => { + const elementTypes = map(getElementTypes(tupleType), (t, i) => { const singleton = elementFlags[i] & 8 /* Variadic */ ? t : elementFlags[i] & 4 /* Rest */ ? createArrayType(t) : createTupleType([t], [elementFlags[i]]); return instantiateMappedType(mappedType, prependTypeMapping(typeVariable, singleton, mapper)); }); @@ -58104,7 +58170,7 @@ function createTypeChecker(host) { } function instantiateMappedTupleType(tupleType, mappedType, mapper) { const elementFlags = tupleType.target.elementFlags; - const elementTypes = map(getTypeArguments(tupleType), (_, i) => instantiateMappedTypeTemplate(mappedType, getStringLiteralType("" + i), !!(elementFlags[i] & 2 /* Optional */), mapper)); + const elementTypes = map(getElementTypes(tupleType), (_, i) => instantiateMappedTypeTemplate(mappedType, getStringLiteralType("" + i), !!(elementFlags[i] & 2 /* Optional */), mapper)); const modifiers = getMappedTypeModifiers(mappedType); const newTupleModifiers = modifiers & 4 /* IncludeOptional */ ? map(elementFlags, (f) => f & 1 /* Required */ ? 2 /* Optional */ : f) : modifiers & 8 /* ExcludeOptional */ ? map(elementFlags, (f) => f & 2 /* Optional */ ? 1 /* Required */ : f) : elementFlags; const newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers); @@ -59290,7 +59356,7 @@ function createTypeChecker(host) { return type; } function getNormalizedTupleType(type, writing) { - const elements = getTypeArguments(type); + const elements = getElementTypes(type); const normalizedElements = sameMap(elements, (t) => t.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(t, writing) : t); return elements !== normalizedElements ? createNormalizedTupleType(type.target, normalizedElements) : type; } @@ -59579,6 +59645,8 @@ function createTypeChecker(host) { return isRelatedTo(source2, target2, 3 /* Both */, reportErrors2); } function isRelatedTo(originalSource, originalTarget, recursionFlags = 3 /* Both */, reportErrors2 = false, headMessage2, intersectionState = 0 /* None */) { + if (originalSource === originalTarget) + return -1 /* True */; if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 402784252 /* Primitive */) { if (relation === comparableRelation && !(originalTarget.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(originalTarget, originalSource, relation) || isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors2 ? reportError : void 0)) { return -1 /* True */; @@ -60797,6 +60865,11 @@ function createTypeChecker(host) { } else { return 0 /* False */; } + } else if (isGenericTupleType(source2) && isTupleType(target2) && !isGenericTupleType(target2)) { + const constraint = getBaseConstraintOrType(source2); + if (constraint !== source2) { + return isRelatedTo(constraint, target2, 1 /* Source */, reportErrors2); + } } else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target2) && getObjectFlags(target2) & 8192 /* FreshLiteral */ && !isEmptyObjectType(source2)) { return 0 /* False */; } @@ -62712,7 +62785,7 @@ function createTypeChecker(host) { return type; } function isPartiallyInferableType(type) { - return !(getObjectFlags(type) & 262144 /* NonInferrableType */) || isObjectLiteralType(type) && some(getPropertiesOfType(type), (prop) => isPartiallyInferableType(getTypeOfSymbol(prop))) || isTupleType(type) && some(getTypeArguments(type), isPartiallyInferableType); + return !(getObjectFlags(type) & 262144 /* NonInferrableType */) || isObjectLiteralType(type) && some(getPropertiesOfType(type), (prop) => isPartiallyInferableType(getTypeOfSymbol(prop))) || isTupleType(type) && some(getElementTypes(type), isPartiallyInferableType); } function createReverseMappedType(source, target, constraint) { if (!(getIndexInfoOfType(source, stringType) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) { @@ -62722,7 +62795,7 @@ function createTypeChecker(host) { return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source)); } if (isTupleType(source)) { - const elementTypes = map(getTypeArguments(source), (t) => inferReverseMappedType(t, target, constraint)); + const elementTypes = map(getElementTypes(source), (t) => inferReverseMappedType(t, target, constraint)); const elementFlags = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? sameMap(source.target.elementFlags, (f) => f & 2 /* Optional */ ? 1 /* Required */ : f) : source.target.elementFlags; return createTupleType(elementTypes, elementFlags, source.target.readonly, source.target.labeledElementDeclarations); } @@ -63558,14 +63631,14 @@ function createTypeChecker(host) { const inference = context.inferences[index]; if (!inference.inferredType) { let inferredType; - const signature = context.signature; - if (signature) { - const inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : void 0; - if (inference.contraCandidates) { - const useCovariantType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* 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))); - inferredType = useCovariantType ? inferredCovariantType : getContravariantInference(inference); - } else if (inferredCovariantType) { - inferredType = inferredCovariantType; + let fallbackType; + if (context.signature) { + const inferredCovariantType = inference.candidates ? getCovariantInference(inference, context.signature) : void 0; + const inferredContravariantType = inference.contraCandidates ? getContravariantInference(inference) : void 0; + if (inferredCovariantType || inferredContravariantType) { + const preferCovariantType = inferredCovariantType && (!inferredContravariantType || !(inferredCovariantType.flags & 131072 /* 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)))); + inferredType = preferCovariantType ? inferredCovariantType : inferredContravariantType; + fallbackType = preferCovariantType ? inferredContravariantType : inferredCovariantType; } else if (context.flags & 1 /* NoDefault */) { inferredType = silentNeverType; } else { @@ -63582,7 +63655,7 @@ function createTypeChecker(host) { if (constraint) { const instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper); if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - inference.inferredType = inferredType = instantiatedConstraint; + inference.inferredType = fallbackType && context.compareTypes(fallbackType, getTypeWithThisArgument(instantiatedConstraint, fallbackType)) ? fallbackType : instantiatedConstraint; } } } @@ -65802,7 +65875,7 @@ function createTypeChecker(host) { markAliasReferenced(symbol, node); } const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - const targetSymbol = checkDeprecatedAliasedSymbol(localOrExportSymbol, node); + const targetSymbol = resolveAliasWithDeprecationCheck(localOrExportSymbol, node); if (isDeprecatedSymbol(targetSymbol) && isUncalledFunctionReference(node, targetSymbol) && targetSymbol.declarations) { addDeprecatedSuggestion(node, targetSymbol.declarations, node.escapedText); } @@ -66895,7 +66968,7 @@ function createTypeChecker(host) { return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : void 0; } function getContextualTypeForChildJsxExpression(node, child, contextFlags) { - const attributesType = getApparentTypeOfContextualType(node.openingElement.tagName, contextFlags); + const attributesType = getApparentTypeOfContextualType(node.openingElement.attributes, contextFlags); const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { return void 0; @@ -66971,6 +67044,7 @@ function createTypeChecker(host) { ); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { + const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); return discriminateTypeByDiscriminableItems( contextualType, concatenate( @@ -66981,7 +67055,14 @@ function createTypeChecker(host) { map( filter(getPropertiesOfType(contextualType), (s) => { var _a; - return !!(s.flags & 16777216 /* Optional */) && !!((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); + if (!(s.flags & 16777216 /* Optional */) || !((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members)) { + return false; + } + const element = node.parent.parent; + if (s.escapedName === jsxChildrenPropertyName && isJsxElement(element) && getSemanticJsxChildren(element.children).length) { + return false; + } + return !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), (s) => [() => undefinedType, s.escapedName] ) @@ -67223,18 +67304,10 @@ function createTypeChecker(host) { function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { const managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { - const declaredManagedType = getDeclaredTypeOfSymbol(managedSym); const ctorType = getStaticTypeOfReferencedJsxConstructor(context); - if (managedSym.flags & 524288 /* TypeAlias */) { - const params = getSymbolLinks(managedSym).typeParameters; - if (length(params) >= 2) { - const args = fillMissingTypeArguments([ctorType, attributesType], params, 2, isInJSFile(context)); - return getTypeAliasInstantiation(managedSym, args); - } - } - if (length(declaredManagedType.typeParameters) >= 2) { - const args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, isInJSFile(context)); - return createTypeReference(declaredManagedType, args); + const result = instantiateAliasOrInterfaceWithDefaults(managedSym, isInJSFile(context), ctorType, attributesType); + if (result) { + return result; } } return attributesType; @@ -67592,7 +67665,7 @@ function createTypeChecker(host) { } return links.immediateTarget; } - function checkObjectLiteral(node, checkMode) { + function checkObjectLiteral(node, checkMode = 0 /* Normal */) { var _a; const inDestructuringPattern = isAssignmentTarget(node); checkGrammarObjectLiteralExpression(node, inDestructuringPattern); @@ -67675,7 +67748,7 @@ function createTypeChecker(host) { prop.links.target = member; member = prop; allPropertiesTable == null ? void 0 : allPropertiesTable.set(prop.escapedName, prop); - if (contextualType && checkMode && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && (memberDecl.kind === 302 /* PropertyAssignment */ || memberDecl.kind === 173 /* MethodDeclaration */) && isContextSensitive(memberDecl)) { + if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && (memberDecl.kind === 302 /* PropertyAssignment */ || memberDecl.kind === 173 /* MethodDeclaration */) && isContextSensitive(memberDecl)) { const inferenceContext = getInferenceContext(node); Debug.assert(inferenceContext); const inferenceNode = memberDecl.kind === 302 /* PropertyAssignment */ ? memberDecl.initializer : memberDecl; @@ -67693,7 +67766,7 @@ function createTypeChecker(host) { hasComputedNumberProperty = false; hasComputedSymbolProperty = false; } - const type = getReducedType(checkExpression(memberDecl.expression)); + const type = getReducedType(checkExpression(memberDecl.expression, checkMode & 2 /* Inferential */)); if (isValidSpreadType(type)) { const mergedType = tryMergeUnionOfObjectTypeAndEmptyObject(type, inConstContext); if (allPropertiesTable) { @@ -67834,7 +67907,7 @@ function createTypeChecker(host) { function checkJsxAttribute(node, checkMode) { return node.initializer ? checkExpressionForMutableLocation(node.initializer, checkMode) : trueType; } - function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode = 0 /* Normal */) { const attributes = openingLikeElement.attributes; const contextualType = getContextualType(attributes, 0 /* None */); const allAttributesTable = strictNullChecks ? createSymbolTable() : void 0; @@ -67869,7 +67942,7 @@ function createTypeChecker(host) { addDeprecatedSuggestion(attributeDecl.name, prop.declarations, attributeDecl.name.escapedText); } } - if (contextualType && checkMode && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && isContextSensitive(attributeDecl)) { + if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && isContextSensitive(attributeDecl)) { const inferenceContext = getInferenceContext(attributes); Debug.assert(inferenceContext); const inferenceNode = attributeDecl.initializer.expression; @@ -67888,7 +67961,7 @@ function createTypeChecker(host) { ); attributesTable = createSymbolTable(); } - const exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode)); + const exprType = getReducedType(checkExpression(attributeDecl.expression, checkMode & 2 /* Inferential */)); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } @@ -68121,6 +68194,9 @@ function createTypeChecker(host) { function getJsxLibraryManagedAttributes(jsxNamespace) { return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */); } + function getJsxElementTypeSymbol(jsxNamespace) { + return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementType, 788968 /* Type */); + } function getJsxElementPropertiesName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); } @@ -68227,11 +68303,32 @@ function createTypeChecker(host) { } } function getJsxElementTypeTypeAt(location) { - const type = getJsxType(JsxNames.ElementType, location); - if (isErrorType(type)) + const ns = getJsxNamespaceAt(location); + if (!ns) + return void 0; + const sym = getJsxElementTypeSymbol(ns); + if (!sym) + return void 0; + const type = instantiateAliasOrInterfaceWithDefaults(sym, isInJSFile(location)); + if (!type || isErrorType(type)) return void 0; return type; } + function instantiateAliasOrInterfaceWithDefaults(managedSym, inJs, ...typeArguments) { + const declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + if (managedSym.flags & 524288 /* TypeAlias */) { + const params = getSymbolLinks(managedSym).typeParameters; + if (length(params) >= typeArguments.length) { + const args = fillMissingTypeArguments(typeArguments, params, typeArguments.length, inJs); + return length(args) === 0 ? declaredManagedType : getTypeAliasInstantiation(managedSym, args); + } + } + if (length(declaredManagedType.typeParameters) >= typeArguments.length) { + const args = fillMissingTypeArguments(typeArguments, declaredManagedType.typeParameters, typeArguments.length, inJs); + return createTypeReference(declaredManagedType, args); + } + return void 0; + } function getJsxIntrinsicTagNamesAt(location) { const intrinsics = getJsxType(JsxNames.IntrinsicElements, location); return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; @@ -68782,8 +68879,9 @@ function createTypeChecker(host) { addDeprecatedSuggestion(right, [indexInfo.declaration], right.escapedText); } } else { - if (isDeprecatedSymbol(prop) && isUncalledFunctionReference(node, prop) && prop.declarations) { - addDeprecatedSuggestion(right, prop.declarations, right.escapedText); + const targetPropSymbol = resolveAliasWithDeprecationCheck(prop, right); + if (isDeprecatedSymbol(targetPropSymbol) && isUncalledFunctionReference(node, targetPropSymbol) && targetPropSymbol.declarations) { + addDeprecatedSuggestion(right, targetPropSymbol.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, isSelfTypeAccess(left, parentSymbol)); @@ -69478,7 +69576,7 @@ function createTypeChecker(host) { } function getMutableArrayOrTupleType(type) { return type.flags & 1048576 /* Union */ ? mapType(type, getMutableArrayOrTupleType) : type.flags & 1 /* Any */ || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type : isTupleType(type) ? createTupleType( - getTypeArguments(type), + getElementTypes(type), type.target.elementFlags, /*readonly*/ false, @@ -69594,7 +69692,7 @@ function createTypeChecker(host) { if (getJsxNamespaceContainerForImplicitImport(node)) { return true; } - const tagType = isJsxOpeningElement(node) || isJsxSelfClosingElement(node) && !isJsxIntrinsicTagName(node.tagName) ? checkExpression(node.tagName) : void 0; + const tagType = (isJsxOpeningElement(node) || isJsxSelfClosingElement(node)) && !(isJsxIntrinsicTagName(node.tagName) || isJsxNamespacedName(node.tagName)) ? checkExpression(node.tagName) : void 0; if (!tagType) { return true; } @@ -69792,7 +69890,7 @@ function createTypeChecker(host) { const arg = args[i]; const spreadType = arg.kind === 229 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); if (spreadType && isTupleType(spreadType)) { - forEach(getTypeArguments(spreadType), (t, i2) => { + forEach(getElementTypes(spreadType), (t, i2) => { var _a; const flags = spreadType.target.elementFlags[i2]; const syntheticArg = createSyntheticExpression( @@ -71319,6 +71417,8 @@ function createTypeChecker(host) { } return getRegularTypeOfLiteralType(exprType); } + const links = getNodeLinks(node); + links.assertionExpressionType = exprType; checkSourceElement(type); checkNodeDeferred(node); return getTypeFromTypeNode(type); @@ -71340,9 +71440,11 @@ function createTypeChecker(host) { return { type, expression }; } function checkAssertionDeferred(node) { - const { type, expression } = getAssertionTypeAndExpression(node); + const { type } = getAssertionTypeAndExpression(node); const errNode = isParenthesizedExpression(node) ? type : node; - const exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression))); + const links = getNodeLinks(node); + Debug.assertIsDefined(links.assertionExpressionType); + const exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(links.assertionExpressionType)); const targetType = getTypeFromTypeNode(type); if (!isErrorType(targetType)) { addLazyDiagnostic(() => { @@ -72306,6 +72408,10 @@ function createTypeChecker(host) { forEachReturnStatement(func.body, (returnStatement) => { const expr = returnStatement.expression; if (expr) { + if (expr.kind === 212 /* CallExpression */ && expr.expression.kind === 80 /* Identifier */ && checkExpressionCached(expr.expression).symbol === func.symbol) { + hasReturnOfTypeNever = true; + return; + } let type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */); if (functionFlags & 2 /* Async */) { type = unwrapAwaitedType(checkAwaitedType( @@ -73786,7 +73892,7 @@ function createTypeChecker(host) { } function padTupleType(type, pattern) { const patternElements = pattern.elements; - const elementTypes = getTypeArguments(type).slice(); + const elementTypes = getElementTypes(type).slice(); const elementFlags = type.target.elementFlags.slice(); for (let i = getTypeReferenceArity(type); i < patternElements.length; i++) { const e = patternElements[i]; @@ -79059,19 +79165,17 @@ function createTypeChecker(host) { } } if (isImportSpecifier(node)) { - const targetSymbol = checkDeprecatedAliasedSymbol(symbol, node); - if (isDeprecatedAliasedSymbol(targetSymbol) && targetSymbol.declarations) { + const targetSymbol = resolveAliasWithDeprecationCheck(symbol, node); + if (isDeprecatedSymbol(targetSymbol) && targetSymbol.declarations) { addDeprecatedSuggestion(node, targetSymbol.declarations, targetSymbol.escapedName); } } } } - function isDeprecatedAliasedSymbol(symbol) { - return !!symbol.declarations && every(symbol.declarations, (d) => !!(getCombinedNodeFlags(d) & 268435456 /* Deprecated */)); - } - function checkDeprecatedAliasedSymbol(symbol, location) { - if (!(symbol.flags & 2097152 /* Alias */)) + function resolveAliasWithDeprecationCheck(symbol, location) { + if (!(symbol.flags & 2097152 /* Alias */) || isDeprecatedSymbol(symbol) || !getDeclarationOfAliasSymbol(symbol)) { return symbol; + } const targetSymbol = resolveAlias(symbol); if (targetSymbol === unknownSymbol) return targetSymbol; @@ -79081,7 +79185,7 @@ function createTypeChecker(host) { if (target === targetSymbol) break; if (target.declarations && length(target.declarations)) { - if (isDeprecatedAliasedSymbol(target)) { + if (isDeprecatedSymbol(target)) { addDeprecatedSuggestion(location, target.declarations, target.escapedName); break; } else { @@ -80174,7 +80278,7 @@ function createTypeChecker(host) { name, meaning, /*ignoreErrors*/ - false, + true, /*dontResolveAlias*/ true, getHostSignatureFromJSDoc(name) @@ -80185,7 +80289,7 @@ function createTypeChecker(host) { return resolveJSDocMemberName( name, /*ignoreErrors*/ - false, + true, getSymbolOfDeclaration(container) ); } @@ -81038,6 +81142,41 @@ function createTypeChecker(host) { } return void 0; } + function getReferencedValueDeclarations(referenceIn) { + if (!isGeneratedIdentifier(referenceIn)) { + const reference = getParseTreeNode(referenceIn, isIdentifier); + if (reference) { + const symbol = getReferencedValueSymbol(reference); + if (symbol) { + return filter(getExportSymbolOfValueSymbolIfExported(symbol).declarations, (declaration) => { + switch (declaration.kind) { + case 259 /* VariableDeclaration */: + case 168 /* Parameter */: + case 207 /* BindingElement */: + case 171 /* PropertyDeclaration */: + case 302 /* PropertyAssignment */: + case 303 /* ShorthandPropertyAssignment */: + case 305 /* EnumMember */: + case 209 /* ObjectLiteralExpression */: + case 261 /* FunctionDeclaration */: + case 217 /* FunctionExpression */: + case 218 /* ArrowFunction */: + case 262 /* ClassDeclaration */: + case 230 /* ClassExpression */: + case 265 /* EnumDeclaration */: + case 173 /* MethodDeclaration */: + case 176 /* GetAccessor */: + case 177 /* SetAccessor */: + case 266 /* ModuleDeclaration */: + return true; + } + return false; + }); + } + } + } + return void 0; + } function isLiteralConstDeclaration(node) { if (isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node)) { return isFreshLiteralType(getTypeOfSymbol(getSymbolOfDeclaration(node))); @@ -81136,6 +81275,7 @@ function createTypeChecker(host) { }, collectLinkedAliases, getReferencedValueDeclaration, + getReferencedValueDeclarations, getTypeReferenceSerializationKind, isOptionalParameter, moduleExportsSomeValue, @@ -85008,7 +85148,7 @@ function collectExternalModuleInfo(context, sourceFile, resolver, compilerOption case 242 /* VariableStatement */: if (hasSyntacticModifier(node, 1 /* Export */)) { for (const decl of node.declarationList.declarations) { - exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings); } } break; @@ -85070,11 +85210,11 @@ function collectExternalModuleInfo(context, sourceFile, resolver, compilerOption } } } -function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { +function collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings) { if (isBindingPattern(decl.name)) { for (const element of decl.name.elements) { if (!isOmittedExpression(element)) { - exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames, exportedBindings); } } } else if (!isGeneratedIdentifier(decl.name)) { @@ -85082,6 +85222,9 @@ function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { if (!uniqueExports.get(text)) { uniqueExports.set(text, true); exportedNames = append(exportedNames, decl.name); + if (isLocalName(decl.name)) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), decl.name); + } } } return exportedNames; @@ -86196,7 +86339,7 @@ function transformTypeScript(context) { if (promoteToIIFE) { context.startLexicalEnvironment(); } - const moveModifiers = promoteToIIFE || facts & 8 /* IsExportOfNamespace */ || facts & 2 /* HasClassOrConstructorParameterDecorators */ && legacyDecorators || facts & 1 /* HasStaticInitializedProperties */; + const moveModifiers = promoteToIIFE || facts & 8 /* IsExportOfNamespace */; let modifiers = moveModifiers ? visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike) : visitNodes2(node.modifiers, visitor, isModifierLike); if (facts & 2 /* HasClassOrConstructorParameterDecorators */) { modifiers = injectClassTypeMetadata(modifiers, node); @@ -86262,13 +86405,13 @@ function transformTypeScript(context) { } if (moveModifiers) { if (facts & 8 /* IsExportOfNamespace */) { - return demarcateMultiStatementExport( + return [ statement, createExportMemberAssignmentStatement(node) - ); + ]; } if (facts & 32 /* IsDefaultExternalExport */) { - return demarcateMultiStatementExport( + return [ statement, factory2.createExportDefault(factory2.getLocalName( node, @@ -86277,10 +86420,10 @@ function transformTypeScript(context) { /*allowSourceMaps*/ true )) - ); + ]; } if (facts & 16 /* IsNamedExternalExport */ && !promoteToIIFE) { - return demarcateMultiStatementExport( + return [ statement, factory2.createExternalModuleExport(factory2.getLocalName( node, @@ -86289,19 +86432,11 @@ function transformTypeScript(context) { /*allowSourceMaps*/ true )) - ); + ]; } } return statement; } - function demarcateMultiStatementExport(declarationStatement, exportStatement) { - addEmitFlags(declarationStatement, 8388608 /* HasEndOfDeclarationMarker */); - return [ - declarationStatement, - exportStatement, - factory2.createEndOfDeclarationMarker(declarationStatement) - ]; - } function visitClassExpression(node) { let modifiers = visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike); if (classOrConstructorParameterIsDecorated(legacyDecorators, node)) { @@ -86919,14 +87054,14 @@ function transformTypeScript(context) { } const parameterName = getNamespaceParameterName(node); const containerName = getNamespaceContainerName(node); - const exportName = hasSyntacticModifier(node, 1 /* Export */) ? factory2.getExternalModuleOrNamespaceExportName( + const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName( currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true - ) : factory2.getLocalName( + ) : factory2.getDeclarationName( node, /*allowComments*/ false, @@ -86940,7 +87075,7 @@ function transformTypeScript(context) { factory2.createObjectLiteralExpression() ) ); - if (hasNamespaceQualifiedExportName(node)) { + if (isExportOfNamespace(node)) { const localName = factory2.getLocalName( node, /*allowComments*/ @@ -86985,7 +87120,6 @@ function transformTypeScript(context) { setTextRange(enumStatement, node); addEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); - statements.push(factory2.createEndOfDeclarationMarker(node)); return statements; } function transformEnumBody(node, localName) { @@ -87058,9 +87192,6 @@ function transformTypeScript(context) { } return isInstantiatedModule(node, shouldPreserveConstEnums(compilerOptions)); } - function hasNamespaceQualifiedExportName(node) { - return isExportOfNamespace(node) || isExternalModuleExport(node) && moduleKind !== 5 /* ES2015 */ && moduleKind !== 6 /* ES2020 */ && moduleKind !== 7 /* ES2022 */ && moduleKind !== 99 /* ESNext */ && moduleKind !== 4 /* System */; - } function recordEmittedDeclarationInScope(node) { if (!currentScopeFirstDeclarationsOfName) { currentScopeFirstDeclarationsOfName = /* @__PURE__ */ new Map(); @@ -87082,20 +87213,21 @@ function transformTypeScript(context) { return node.name.escapedText; } function addVarForEnumOrModuleDeclaration(statements, node) { + const varDecl = factory2.createVariableDeclaration(factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + )); + const varFlags = currentLexicalScope.kind === 311 /* SourceFile */ ? 0 /* None */ : 1 /* Let */; const statement = factory2.createVariableStatement( visitNodes2(node.modifiers, modifierVisitor, isModifier), - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - factory2.getLocalName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ) - ) - ], currentLexicalScope.kind === 311 /* SourceFile */ ? 0 /* None */ : 1 /* Let */) + factory2.createVariableDeclarationList([varDecl], varFlags) ); + setOriginalNode(varDecl, node); + setSyntheticLeadingComments(varDecl, void 0); + setSyntheticTrailingComments(varDecl, void 0); setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -87105,15 +87237,11 @@ function transformTypeScript(context) { setSourceMapRange(statement, node); } setCommentRange(statement, node); - addEmitFlags(statement, 2048 /* NoTrailingComments */ | 8388608 /* HasEndOfDeclarationMarker */); + addEmitFlags(statement, 2048 /* NoTrailingComments */); statements.push(statement); return true; - } else { - const mergeMarker = factory2.createMergeDeclarationMarker(statement); - setEmitFlags(mergeMarker, 3072 /* NoComments */ | 8388608 /* HasEndOfDeclarationMarker */); - statements.push(mergeMarker); - return false; } + return false; } function visitModuleDeclaration(node) { if (!shouldEmitModuleDeclaration(node)) { @@ -87131,14 +87259,14 @@ function transformTypeScript(context) { } const parameterName = getNamespaceParameterName(node); const containerName = getNamespaceContainerName(node); - const exportName = hasSyntacticModifier(node, 1 /* Export */) ? factory2.getExternalModuleOrNamespaceExportName( + const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName( currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true - ) : factory2.getLocalName( + ) : factory2.getDeclarationName( node, /*allowComments*/ false, @@ -87152,7 +87280,7 @@ function transformTypeScript(context) { factory2.createObjectLiteralExpression() ) ); - if (hasNamespaceQualifiedExportName(node)) { + if (isExportOfNamespace(node)) { const localName = factory2.getLocalName( node, /*allowComments*/ @@ -87197,7 +87325,6 @@ function transformTypeScript(context) { setTextRange(moduleStatement, node); addEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); - statements.push(factory2.createEndOfDeclarationMarker(node)); return statements; } function transformModuleBody(node, namespaceLocalName) { @@ -88783,23 +88910,12 @@ function transformClassFields(context) { getClassLexicalEnvironment().classThis = node.emitNode.classThis; } } - const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); + const isExport = hasSyntacticModifier(node, 1 /* Export */); + const isDefault = hasSyntacticModifier(node, 1024 /* Default */); + let modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); const heritageClauses = visitNodes2(node.heritageClauses, heritageClauseVisitor, isHeritageClause); const { members, prologue } = transformClassMembers(node); - const classDecl = factory2.updateClassDeclaration( - node, - modifiers, - node.name, - /*typeParameters*/ - void 0, - heritageClauses, - members - ); const statements = []; - if (prologue) { - statements.push(factory2.createExpressionStatement(prologue)); - } - statements.push(classDecl); if (pendingClassReferenceAssignment) { getPendingExpressions().unshift(pendingClassReferenceAssignment); } @@ -88812,6 +88928,35 @@ function transformClassFields(context) { addPropertyOrClassStaticBlockStatements(statements, staticProperties, factory2.getInternalName(node)); } } + if (statements.length > 0 && isExport && isDefault) { + modifiers = visitNodes2(modifiers, (node2) => isExportOrDefaultModifier(node2) ? void 0 : node2, isModifier); + statements.push(factory2.createExportAssignment( + /*modifiers*/ + void 0, + /*isExportEquals*/ + false, + factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ) + )); + } + const classDecl = factory2.updateClassDeclaration( + node, + modifiers, + node.name, + /*typeParameters*/ + void 0, + heritageClauses, + members + ); + statements.unshift(classDecl); + if (prologue) { + statements.unshift(factory2.createExpressionStatement(prologue)); + } return statements; } function visitClassExpression(node, referencedName) { @@ -90249,10 +90394,6 @@ function transformLegacyDecorators(context) { true, node ) ? transformClassDeclarationWithClassDecorators(node, node.name) : transformClassDeclarationWithoutClassDecorators(node, node.name); - if (statements.length > 1) { - statements.push(factory2.createEndOfDeclarationMarker(node)); - setEmitFlags(statements[0], getEmitFlags(statements[0]) | 8388608 /* HasEndOfDeclarationMarker */); - } return singleOrMany(statements); } function decoratorContainsPrivateIdentifierInExpression(decorator) { @@ -90325,9 +90466,12 @@ function transformLegacyDecorators(context) { return addRange([updated], decorationStatements); } function transformClassDeclarationWithClassDecorators(node, name) { + const isExport = hasSyntacticModifier(node, 1 /* Export */); + const isDefault = hasSyntacticModifier(node, 1024 /* Default */); + const modifiers = visitNodes2(node.modifiers, (node2) => isExportOrDefaultModifier(node2) || isDecorator(node2) ? void 0 : node2, isModifierLike); const location = moveRangePastModifiers(node); const classAlias = getClassAliasIfNeeded(node); - const declName = languageVersion <= 2 /* ES2015 */ ? factory2.getInternalName( + const declName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName( node, /*allowComments*/ false, @@ -90344,9 +90488,21 @@ function transformLegacyDecorators(context) { let members = visitNodes2(node.members, visitor, isClassElement); let decorationStatements = []; ({ members, decorationStatements } = transformDecoratorsOfClassElements(node, members)); + const assignClassAliasInStaticBlock = languageVersion >= 9 /* ES2022 */ && !!classAlias && some(members, (member) => isPropertyDeclaration(member) && hasSyntacticModifier(member, 32 /* Static */) || isClassStaticBlockDeclaration(member)); + if (assignClassAliasInStaticBlock) { + members = setTextRange(factory2.createNodeArray([ + factory2.createClassStaticBlockDeclaration( + factory2.createBlock([ + factory2.createExpressionStatement( + factory2.createAssignment(classAlias, factory2.createThis()) + ) + ]) + ), + ...members + ]), members); + } const classExpression = factory2.createClassExpression( - /*modifiers*/ - void 0, + modifiers, name && isGeneratedIdentifier(name) ? void 0 : name, /*typeParameters*/ void 0, @@ -90355,18 +90511,23 @@ function transformLegacyDecorators(context) { ); setOriginalNode(classExpression, node); setTextRange(classExpression, location); - const statement = factory2.createVariableStatement( - /*modifiers*/ + const varDecl = factory2.createVariableDeclaration( + declName, + /*exclamationToken*/ void 0, + /*type*/ + void 0, + classAlias && !assignClassAliasInStaticBlock ? factory2.createAssignment(classAlias, classExpression) : classExpression + ); + setOriginalNode(varDecl, node); + let varModifiers; + if (isExport && !isDefault) { + varModifiers = factory2.createModifiersFromModifierFlags(1 /* Export */); + } + const statement = factory2.createVariableStatement( + varModifiers, factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - declName, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - classAlias ? factory2.createAssignment(classAlias, classExpression) : classExpression - ) + varDecl ], 1 /* Let */) ); setOriginalNode(statement, node); @@ -90375,6 +90536,15 @@ function transformLegacyDecorators(context) { const statements = [statement]; addRange(statements, decorationStatements); addConstructorDecorationStatement(statements, node); + if (isExport && isDefault) { + statements.push(factory2.createExportAssignment( + /*modifiers*/ + void 0, + /*isExportEquals*/ + false, + declName + )); + } return statements; } function visitClassExpression(node) { @@ -90551,13 +90721,13 @@ function transformLegacyDecorators(context) { return void 0; } const classAlias = classAliases && classAliases[getOriginalNodeId(node)]; - const localName = languageVersion <= 2 /* ES2015 */ ? factory2.getInternalName( + const localName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName( node, /*allowComments*/ false, /*allowSourceMaps*/ true - ) : factory2.getLocalName( + ) : factory2.getDeclarationName( node, /*allowComments*/ false, @@ -91046,7 +91216,15 @@ function transformESDecorators(context) { function transformClassLike(node, className) { var _a; startLexicalEnvironment(); - const classReference = node.name ?? factory2.getGeneratedNameForNode(node); + const classReference = factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + false, + /*ignoreAssignedName*/ + true + ); const classInfo2 = createClassInfo(node); const classDefinitionStatements = []; let leadingBlockStatements; @@ -91362,6 +91540,7 @@ function transformESDecorators(context) { void 0, iife ); + setOriginalNode(varDecl, node); const varDecls = factory2.createVariableDeclarationList([varDecl], 1 /* Let */); const statement = factory2.createVariableStatement(modifiers, varDecls); setOriginalNode(statement, node); @@ -93686,10 +93865,7 @@ function transformES2018(context) { const exitNonUserCodeExpression = factory2.createAssignment(nonUserCode, factory2.createFalse()); const exitNonUserCodeStatement = factory2.createExpressionStatement(exitNonUserCodeExpression); setSourceMapRange(exitNonUserCodeStatement, node.expression); - const enterNonUserCodeExpression = factory2.createAssignment(nonUserCode, factory2.createTrue()); - const enterNonUserCodeStatement = factory2.createExpressionStatement(enterNonUserCodeExpression); - setSourceMapRange(exitNonUserCodeStatement, node.expression); - const statements = []; + const statements = [iteratorValueStatement, exitNonUserCodeStatement]; const binding = createForOfBindingStatement(factory2, node.initializer, value); statements.push(visitNode(binding, visitor, isStatement)); let bodyLocation; @@ -93702,29 +93878,14 @@ function transformES2018(context) { } else { statements.push(statement); } - const body = setEmitFlags( - setTextRange( - factory2.createBlock( - setTextRange(factory2.createNodeArray(statements), statementsLocation), - /*multiLine*/ - true - ), - bodyLocation + return setTextRange( + factory2.createBlock( + setTextRange(factory2.createNodeArray(statements), statementsLocation), + /*multiLine*/ + true ), - 96 /* NoSourceMap */ | 768 /* NoTokenSourceMaps */ + bodyLocation ); - return factory2.createBlock([ - iteratorValueStatement, - exitNonUserCodeStatement, - factory2.createTryStatement( - body, - /*catchClause*/ - void 0, - factory2.createBlock([ - enterNonUserCodeStatement - ]) - ) - ]); } function createDownlevelAwait(expression) { return enclosingFunctionFlags & 1 /* Generator */ ? factory2.createYieldExpression( @@ -93803,7 +93964,7 @@ function transformES2018(context) { factory2.createLogicalNot(done) ]), /*incrementor*/ - void 0, + factory2.createAssignment(nonUserCode, factory2.createTrue()), /*statement*/ convertForOfStatementHead(node, getValue, nonUserCode) ), @@ -96054,11 +96215,6 @@ function transformES2015(context) { setOriginalNode(exportStatement, statement); statements.push(exportStatement); } - const emitFlags = getEmitFlags(node); - if ((emitFlags & 8388608 /* HasEndOfDeclarationMarker */) === 0) { - statements.push(factory2.createEndOfDeclarationMarker(node)); - setEmitFlags(statement, emitFlags | 8388608 /* HasEndOfDeclarationMarker */); - } return singleOrMany(statements); } function visitClassExpression(node) { @@ -98021,7 +98177,7 @@ function transformES2015(context) { ); const callResult = containsYield ? factory2.createYieldExpression( factory2.createToken(42 /* AsteriskToken */), - setEmitFlags(call, 16777216 /* Iterator */) + setEmitFlags(call, 8388608 /* Iterator */) ) : call; return factory2.createExpressionStatement(callResult); } @@ -98036,7 +98192,7 @@ function transformES2015(context) { ); const callResult = containsYield ? factory2.createYieldExpression( factory2.createToken(42 /* AsteriskToken */), - setEmitFlags(call, 16777216 /* Iterator */) + setEmitFlags(call, 8388608 /* Iterator */) ) : call; if (isSimpleLoop) { statements.push(factory2.createExpressionStatement(callResult)); @@ -99360,7 +99516,7 @@ function transformGenerators(context) { const resumeLabel = defineLabel(); const expression = visitNode(node.expression, visitor, isExpression); if (node.asteriskToken) { - const iterator = (getEmitFlags(node.expression) & 16777216 /* Iterator */) === 0 ? setTextRange(emitHelpers().createValuesHelper(expression), node) : expression; + const iterator = (getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0 ? setTextRange(emitHelpers().createValuesHelper(expression), node) : expression; emitYieldStar( iterator, /*location*/ @@ -100908,7 +101064,6 @@ function transformModule(context) { context.enableSubstitution(303 /* ShorthandPropertyAssignment */); context.enableEmitNotification(311 /* SourceFile */); const moduleInfoMap = []; - const deferredExports = []; let currentSourceFile; let currentModuleInfo; const noSubstitution = []; @@ -101327,16 +101482,56 @@ function transformModule(context) { return visitExportDeclaration(node); case 276 /* ExportAssignment */: return visitExportAssignment(node); + case 261 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 262 /* ClassDeclaration */: + return visitClassDeclaration(node); + default: + return topLevelNestedVisitor(node); + } + } + function topLevelNestedVisitor(node) { + switch (node.kind) { case 242 /* VariableStatement */: return visitVariableStatement(node); case 261 /* FunctionDeclaration */: return visitFunctionDeclaration(node); case 262 /* ClassDeclaration */: return visitClassDeclaration(node); - case 361 /* MergeDeclarationMarker */: - return visitMergeDeclarationMarker(node); - case 362 /* EndOfDeclarationMarker */: - return visitEndOfDeclarationMarker(node); + case 247 /* ForStatement */: + return visitForStatement( + node, + /*isTopLevel*/ + true + ); + case 248 /* ForInStatement */: + return visitForInStatement(node); + case 249 /* ForOfStatement */: + return visitForOfStatement(node); + case 245 /* DoStatement */: + return visitDoStatement(node); + case 246 /* WhileStatement */: + return visitWhileStatement(node); + case 255 /* LabeledStatement */: + return visitLabeledStatement(node); + case 253 /* WithStatement */: + return visitWithStatement(node); + case 244 /* IfStatement */: + return visitIfStatement(node); + case 254 /* SwitchStatement */: + return visitSwitchStatement(node); + case 268 /* CaseBlock */: + return visitCaseBlock(node); + case 295 /* CaseClause */: + return visitCaseClause(node); + case 296 /* DefaultClause */: + return visitDefaultClause(node); + case 257 /* TryStatement */: + return visitTryStatement(node); + case 298 /* CatchClause */: + return visitCatchClause(node); + case 240 /* Block */: + return visitBlock(node); default: return visitor(node); } @@ -101347,7 +101542,11 @@ function transformModule(context) { } switch (node.kind) { case 247 /* ForStatement */: - return visitForStatement(node); + return visitForStatement( + node, + /*isTopLevel*/ + false + ); case 243 /* ExpressionStatement */: return visitExpressionStatement(node); case 216 /* ParenthesizedExpression */: @@ -101432,15 +101631,177 @@ function transformModule(context) { } return visitEachChild(node, visitor, context); } - function visitForStatement(node) { + function visitForStatement(node, isTopLevel) { + if (isTopLevel && node.initializer && isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 3 /* BlockScoped */)) { + const exportStatements = appendExportsOfVariableDeclarationList( + /*statements*/ + void 0, + node.initializer, + /*isForInOrOfInitializer*/ + false + ); + if (exportStatements) { + const statements = []; + const varDeclList = visitNode(node.initializer, discardedValueVisitor, isVariableDeclarationList); + const varStatement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + varDeclList + ); + statements.push(varStatement); + addRange(statements, exportStatements); + const condition = visitNode(node.condition, visitor, isExpression); + const incrementor = visitNode(node.incrementor, discardedValueVisitor, isExpression); + const body = visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context); + statements.push(factory2.updateForStatement( + node, + /*initializer*/ + void 0, + condition, + incrementor, + body + )); + return statements; + } + } return factory2.updateForStatement( node, visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, discardedValueVisitor, isExpression), - visitIterationBody(node.statement, visitor, context) + visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context) ); } + function visitForInStatement(node) { + if (isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 3 /* BlockScoped */)) { + const exportStatements = appendExportsOfVariableDeclarationList( + /*statements*/ + void 0, + node.initializer, + /*isForInOrOfInitializer*/ + true + ); + if (some(exportStatements)) { + const initializer = visitNode(node.initializer, discardedValueVisitor, isForInitializer); + const expression = visitNode(node.expression, visitor, isExpression); + const body = visitIterationBody(node.statement, topLevelNestedVisitor, context); + const mergedBody = isBlock(body) ? factory2.updateBlock(body, [...exportStatements, ...body.statements]) : factory2.createBlock( + [...exportStatements, body], + /*multiLine*/ + true + ); + return factory2.updateForInStatement(node, initializer, expression, mergedBody); + } + } + return factory2.updateForInStatement( + node, + visitNode(node.initializer, discardedValueVisitor, isForInitializer), + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + } + function visitForOfStatement(node) { + if (isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 3 /* BlockScoped */)) { + const exportStatements = appendExportsOfVariableDeclarationList( + /*statements*/ + void 0, + node.initializer, + /*isForInOrOfInitializer*/ + true + ); + const initializer = visitNode(node.initializer, discardedValueVisitor, isForInitializer); + const expression = visitNode(node.expression, visitor, isExpression); + let body = visitIterationBody(node.statement, topLevelNestedVisitor, context); + if (some(exportStatements)) { + body = isBlock(body) ? factory2.updateBlock(body, [...exportStatements, ...body.statements]) : factory2.createBlock( + [...exportStatements, body], + /*multiLine*/ + true + ); + } + return factory2.updateForOfStatement(node, node.awaitModifier, initializer, expression, body); + } + return factory2.updateForOfStatement( + node, + node.awaitModifier, + visitNode(node.initializer, discardedValueVisitor, isForInitializer), + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + } + function visitDoStatement(node) { + return factory2.updateDoStatement( + node, + visitIterationBody(node.statement, topLevelNestedVisitor, context), + visitNode(node.expression, visitor, isExpression) + ); + } + function visitWhileStatement(node) { + return factory2.updateWhileStatement( + node, + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + } + function visitLabeledStatement(node) { + return factory2.updateLabeledStatement( + node, + node.label, + Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) + ); + } + function visitWithStatement(node) { + return factory2.updateWithStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) + ); + } + function visitIfStatement(node) { + return factory2.updateIfStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)), + visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) + ); + } + function visitSwitchStatement(node) { + return factory2.updateSwitchStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock)) + ); + } + function visitCaseBlock(node) { + return factory2.updateCaseBlock( + node, + visitNodes2(node.clauses, topLevelNestedVisitor, isCaseOrDefaultClause) + ); + } + function visitCaseClause(node) { + return factory2.updateCaseClause( + node, + visitNode(node.expression, visitor, isExpression), + visitNodes2(node.statements, topLevelNestedVisitor, isStatement) + ); + } + function visitDefaultClause(node) { + return visitEachChild(node, topLevelNestedVisitor, context); + } + function visitTryStatement(node) { + return visitEachChild(node, topLevelNestedVisitor, context); + } + function visitCatchClause(node) { + return factory2.updateCatchClause( + node, + node.variableDeclaration, + Debug.checkDefined(visitNode(node.block, topLevelNestedVisitor, isBlock)) + ); + } + function visitBlock(node) { + node = visitEachChild(node, topLevelNestedVisitor, context); + return node; + } function visitExpressionStatement(node) { return factory2.updateExpressionStatement( node, @@ -101813,12 +102174,7 @@ function transformModule(context) { ) ); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfImportDeclaration(statements, node); - } + statements = appendExportsOfImportDeclaration(statements, node); return singleOrMany(statements); } function createRequireCall(importNode) { @@ -101899,12 +102255,7 @@ function transformModule(context) { ); } } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfImportEqualsDeclaration(statements, node); - } + statements = appendExportsOfImportEqualsDeclaration(statements, node); return singleOrMany(statements); } function visitExportDeclaration(node) { @@ -102013,31 +102364,14 @@ function transformModule(context) { if (node.isExportEquals) { return void 0; } - let statements; - const original = node.original; - if (original && hasAssociatedEndOfDeclarationMarker(original)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportStatement( - deferredExports[id], - factory2.createIdentifier("default"), - visitNode(node.expression, visitor, isExpression), - /*location*/ - node, - /*allowComments*/ - true - ); - } else { - statements = appendExportStatement( - statements, - factory2.createIdentifier("default"), - visitNode(node.expression, visitor, isExpression), - /*location*/ - node, - /*allowComments*/ - true - ); - } - return singleOrMany(statements); + return createExportStatement( + factory2.createIdentifier("default"), + visitNode(node.expression, visitor, isExpression), + /*location*/ + node, + /*allowComments*/ + true + ); } function visitFunctionDeclaration(node) { let statements; @@ -102073,12 +102407,7 @@ function transformModule(context) { } else { statements = append(statements, visitEachChild(node, visitor, context)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfHoistedDeclaration(statements, node); - } + statements = appendExportsOfHoistedDeclaration(statements, node); return singleOrMany(statements); } function visitClassDeclaration(node) { @@ -102110,12 +102439,7 @@ function transformModule(context) { } else { statements = append(statements, visitEachChild(node, visitor, context)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfHoistedDeclaration(statements, node); - } + statements = appendExportsOfHoistedDeclaration(statements, node); return singleOrMany(statements); } function visitVariableStatement(node) { @@ -102187,12 +102511,7 @@ function transformModule(context) { } else { statements = append(statements, visitEachChild(node, visitor, context)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); - } else { - statements = appendExportsOfVariableStatement(statements, node); - } + statements = appendExportsOfVariableStatement(statements, node); return singleOrMany(statements); } function createAllExportExpressions(name, value, location) { @@ -102237,25 +102556,6 @@ function transformModule(context) { ); } } - function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 242 /* VariableStatement */) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); - } - return node; - } - function hasAssociatedEndOfDeclarationMarker(node) { - return (getEmitFlags(node) & 8388608 /* HasEndOfDeclarationMarker */) !== 0; - } - function visitEndOfDeclarationMarker(node) { - const id = getOriginalNodeId(node); - const statements = deferredExports[id]; - if (statements) { - delete deferredExports[id]; - return append(statements, node); - } - return node; - } function appendExportsOfImportDeclaration(statements, decl) { if (currentModuleInfo.exportEquals) { return statements; @@ -102294,25 +102594,33 @@ function transformModule(context) { return appendExportsOfDeclaration(statements, decl); } function appendExportsOfVariableStatement(statements, node) { + return appendExportsOfVariableDeclarationList( + statements, + node.declarationList, + /*isForInOrOfInitializer*/ + false + ); + } + function appendExportsOfVariableDeclarationList(statements, node, isForInOrOfInitializer) { if (currentModuleInfo.exportEquals) { return statements; } - for (const decl of node.declarationList.declarations) { - statements = appendExportsOfBindingElement(statements, decl); + for (const decl of node.declarations) { + statements = appendExportsOfBindingElement(statements, decl, isForInOrOfInitializer); } return statements; } - function appendExportsOfBindingElement(statements, decl) { + function appendExportsOfBindingElement(statements, decl, isForInOrOfInitializer) { if (currentModuleInfo.exportEquals) { return statements; } if (isBindingPattern(decl.name)) { for (const element of decl.name.elements) { if (!isOmittedExpression(element)) { - statements = appendExportsOfBindingElement(statements, element); + statements = appendExportsOfBindingElement(statements, element, isForInOrOfInitializer); } } - } else if (!isGeneratedIdentifier(decl.name)) { + } else if (!isGeneratedIdentifier(decl.name) && (!isVariableDeclaration(decl) || decl.initializer || isForInOrOfInitializer)) { statements = appendExportsOfDeclaration(statements, decl); } return statements; @@ -102583,7 +102891,7 @@ function transformModule(context) { return node; } function substituteBinaryExpression(node) { - if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left) && !isDeclarationNameOfEnumOrNamespace(node.left)) { + if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left)) { const exportedNames = getExports(node.left); if (exportedNames) { let expression = node; @@ -102603,9 +102911,24 @@ function transformModule(context) { } function getExports(name) { if (!isGeneratedIdentifier(name)) { - const valueDeclaration = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); - if (valueDeclaration) { - return currentModuleInfo && currentModuleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]; + const importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + return currentModuleInfo == null ? void 0 : currentModuleInfo.exportedBindings[getOriginalNodeId(importDeclaration)]; + } + const bindingsSet = /* @__PURE__ */ new Set(); + const declarations = resolver.getReferencedValueDeclarations(name); + if (declarations) { + for (const declaration of declarations) { + const bindings = currentModuleInfo == null ? void 0 : currentModuleInfo.exportedBindings[getOriginalNodeId(declaration)]; + if (bindings) { + for (const binding of bindings) { + bindingsSet.add(binding); + } + } + } + if (bindingsSet.size) { + return arrayFrom(bindingsSet); + } } } } @@ -102638,7 +102961,6 @@ function transformSystemModule(context) { context.enableSubstitution(235 /* MetaProperty */); context.enableEmitNotification(311 /* SourceFile */); const moduleInfoMap = []; - const deferredExports = []; const exportFunctionsMap = []; const noSubstitutionMap = []; const contextObjectMap = []; @@ -103111,13 +103433,7 @@ function transformSystemModule(context) { if (node.importClause) { hoistVariableDeclaration(getLocalNameForExternalImport(factory2, node, currentSourceFile)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfImportDeclaration(statements, node); - } - return singleOrMany(statements); + return singleOrMany(appendExportsOfImportDeclaration(statements, node)); } function visitExportDeclaration(node) { Debug.assertIsDefined(node); @@ -103127,37 +103443,19 @@ function transformSystemModule(context) { Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); let statements; hoistVariableDeclaration(getLocalNameForExternalImport(factory2, node, currentSourceFile)); - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfImportEqualsDeclaration(statements, node); - } - return singleOrMany(statements); + return singleOrMany(appendExportsOfImportEqualsDeclaration(statements, node)); } function visitExportAssignment(node) { if (node.isExportEquals) { return void 0; } const expression = visitNode(node.expression, visitor, isExpression); - const original = node.original; - if (original && hasAssociatedEndOfDeclarationMarker(original)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportStatement( - deferredExports[id], - factory2.createIdentifier("default"), - expression, - /*allowComments*/ - true - ); - } else { - return createExportStatement( - factory2.createIdentifier("default"), - expression, - /*allowComments*/ - true - ); - } + return createExportStatement( + factory2.createIdentifier("default"), + expression, + /*allowComments*/ + true + ); } function visitFunctionDeclaration(node) { if (hasSyntacticModifier(node, 1 /* Export */)) { @@ -103185,12 +103483,7 @@ function transformSystemModule(context) { } else { hoistedStatements = append(hoistedStatements, visitEachChild(node, visitor, context)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else { - hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); - } + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); return void 0; } function visitClassDeclaration(node) { @@ -103219,12 +103512,7 @@ function transformSystemModule(context) { node ) ); - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfHoistedDeclaration(statements, node); - } + statements = appendExportsOfHoistedDeclaration(statements, node); return singleOrMany(statements); } function visitVariableStatement(node) { @@ -103233,10 +103521,9 @@ function transformSystemModule(context) { } let expressions; const isExportedDeclaration = hasSyntacticModifier(node, 1 /* Export */); - const isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); for (const variable of node.declarationList.declarations) { if (variable.initializer) { - expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration)); + expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration)); } else { hoistBindingElement(variable); } @@ -103245,17 +103532,12 @@ function transformSystemModule(context) { if (expressions) { statements = append(statements, setTextRange(factory2.createExpressionStatement(factory2.inlineExpressions(expressions)), node)); } - if (isMarkedDeclaration) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); - } else { - statements = appendExportsOfVariableStatement( - statements, - node, - /*exportSelf*/ - false - ); - } + statements = appendExportsOfVariableStatement( + statements, + node, + /*exportSelf*/ + false + ); return singleOrMany(statements); } function hoistBindingElement(node) { @@ -103306,31 +103588,6 @@ function transformSystemModule(context) { hoistVariableDeclaration(factory2.cloneNode(name)); return isExportedDeclaration ? createExportExpression(name, preventSubstitution(setTextRange(factory2.createAssignment(name, value), location))) : preventSubstitution(setTextRange(factory2.createAssignment(name, value), location)); } - function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 242 /* VariableStatement */) { - const id = getOriginalNodeId(node); - const isExportedDeclaration = hasSyntacticModifier(node.original, 1 /* Export */); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); - } - return node; - } - function hasAssociatedEndOfDeclarationMarker(node) { - return (getEmitFlags(node) & 8388608 /* HasEndOfDeclarationMarker */) !== 0; - } - function visitEndOfDeclarationMarker(node) { - const id = getOriginalNodeId(node); - const statements = deferredExports[id]; - if (statements) { - delete deferredExports[id]; - return append(statements, node); - } else { - const original = getOriginalNode(node); - if (isModuleOrEnumDeclaration(original)) { - return append(appendExportsOfDeclaration(statements, original), node); - } - } - return node; - } function appendExportsOfImportDeclaration(statements, decl) { if (moduleInfo.exportEquals) { return statements; @@ -103472,6 +103729,8 @@ function transformSystemModule(context) { return visitLabeledStatement(node); case 253 /* WithStatement */: return visitWithStatement(node); + case 244 /* IfStatement */: + return visitIfStatement(node); case 254 /* SwitchStatement */: return visitSwitchStatement(node); case 268 /* CaseBlock */: @@ -103486,10 +103745,6 @@ function transformSystemModule(context) { return visitCatchClause(node); case 240 /* Block */: return visitBlock(node); - case 361 /* MergeDeclarationMarker */: - return visitMergeDeclarationMarker(node); - case 362 /* EndOfDeclarationMarker */: - return visitEndOfDeclarationMarker(node); default: return visitor(node); } @@ -103581,6 +103836,14 @@ function transformSystemModule(context) { Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) ); } + function visitIfStatement(node) { + return factory2.updateIfStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)), + visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) + ); + } function visitSwitchStatement(node) { return factory2.updateSwitchStatement( node, @@ -103895,7 +104158,7 @@ function transformSystemModule(context) { return node; } function substituteBinaryExpression(node) { - if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left) && !isDeclarationNameOfEnumOrNamespace(node.left)) { + if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left)) { const exportedNames = getExports(node.left); if (exportedNames) { let expression = node; @@ -103915,22 +104178,38 @@ function transformSystemModule(context) { } function getExports(name) { let exportedNames; - if (!isGeneratedIdentifier(name)) { - const valueDeclaration = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); - if (valueDeclaration) { - const exportContainer = resolver.getReferencedExportContainer( - name, - /*prefixLocals*/ - false - ); - if (exportContainer && exportContainer.kind === 311 /* SourceFile */) { - exportedNames = append(exportedNames, factory2.getDeclarationName(valueDeclaration)); - } - exportedNames = addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]); + const valueDeclaration = getReferencedDeclaration(name); + if (valueDeclaration) { + const exportContainer = resolver.getReferencedExportContainer( + name, + /*prefixLocals*/ + false + ); + if (exportContainer && exportContainer.kind === 311 /* SourceFile */) { + exportedNames = append(exportedNames, factory2.getDeclarationName(valueDeclaration)); } + exportedNames = addRange(exportedNames, moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]); } return exportedNames; } + function getReferencedDeclaration(name) { + if (!isGeneratedIdentifier(name)) { + const importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) + return importDeclaration; + const valueDeclaration = resolver.getReferencedValueDeclaration(name); + if (valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)])) + return valueDeclaration; + const declarations = resolver.getReferencedValueDeclarations(name); + if (declarations) { + for (const declaration of declarations) { + if (declaration !== valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(declaration)])) + return declaration; + } + } + return valueDeclaration; + } + } function preventSubstitution(node) { if (noSubstitution === void 0) noSubstitution = []; @@ -106343,7 +106622,7 @@ function noEmitNotification(hint, node, callback) { } function transformNodes(resolver, host, factory2, options, nodes, transformers, allowDtsFiles) { var _a, _b; - const enabledSyntaxKindFeatures = new Array(364 /* Count */); + const enabledSyntaxKindFeatures = new Array(362 /* Count */); let lexicalEnvironmentVariableDeclarations; let lexicalEnvironmentFunctionDeclarations; let lexicalEnvironmentStatements; @@ -107276,6 +107555,7 @@ var notImplementedResolver = { // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant getConstantValue: notImplemented, getReferencedValueDeclaration: notImplemented, + getReferencedValueDeclarations: notImplemented, getTypeReferenceSerializationKind: notImplemented, isOptionalParameter: notImplemented, moduleExportsSomeValue: notImplemented, @@ -108134,6 +108414,8 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitJsxSpreadAttribute(node); case 293 /* JsxExpression */: return emitJsxExpression(node); + case 294 /* JsxNamespacedName */: + return emitJsxNamespacedName(node); case 295 /* CaseClause */: return emitCaseClause(node); case 296 /* DefaultClause */: @@ -108229,8 +108511,6 @@ function createPrinter(printerOptions = {}, handlers = {}) { case 353 /* JSDocSeeTag */: return emitJSDocSeeTag(node); case 358 /* NotEmittedStatement */: - case 362 /* EndOfDeclarationMarker */: - case 361 /* MergeDeclarationMarker */: return; } if (isExpression(node)) { @@ -108331,8 +108611,6 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitJsxSelfClosingElement(node); case 287 /* JsxFragment */: return emitJsxFragment(node); - case 294 /* JsxNamespacedName */: - return emitJsxNamespacedName(node); case 357 /* SyntaxList */: return Debug.fail("SyntaxList should not be printed"); case 358 /* NotEmittedStatement */: @@ -108341,10 +108619,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitPartiallyEmittedExpression(node); case 360 /* CommaListExpression */: return emitCommaList(node); - case 361 /* MergeDeclarationMarker */: - case 362 /* EndOfDeclarationMarker */: - return; - case 363 /* SyntheticReferenceExpression */: + case 361 /* SyntheticReferenceExpression */: return Debug.fail("SyntheticReferenceExpression should not be printed"); } } @@ -110666,7 +110941,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } } function emitEmbeddedStatement(parent, node) { - if (isBlock(node) || getEmitFlags(parent) & 1 /* SingleLine */) { + if (isBlock(node) || getEmitFlags(parent) & 1 /* SingleLine */ || preserveSourceNewlines && !getLeadingLineTerminatorCount(parent, node, 0 /* None */)) { writeSpace(); emit(node); } else { @@ -111167,6 +111442,10 @@ function createPrinter(printerOptions = {}, handlers = {}) { if (!canUseSourceFile || getSourceFileOfNode(node) !== getOriginalNode(sourceFile)) { return idText(node); } + } else if (isJsxNamespacedName(node)) { + if (!canUseSourceFile || getSourceFileOfNode(node) !== getOriginalNode(sourceFile)) { + return getTextOfJsxNamespacedName(node); + } } else { Debug.assertNode(node, isLiteralExpression); if (!canUseSourceFile) { @@ -111178,9 +111457,9 @@ function createPrinter(printerOptions = {}, handlers = {}) { function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) { if (node.kind === 11 /* StringLiteral */ && node.textSourceNode) { const textSourceNode = node.textSourceNode; - if (isIdentifier(textSourceNode) || isPrivateIdentifier(textSourceNode) || isNumericLiteral(textSourceNode)) { + if (isIdentifier(textSourceNode) || isPrivateIdentifier(textSourceNode) || isNumericLiteral(textSourceNode) || isJsxNamespacedName(textSourceNode)) { const text = isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode2(textSourceNode); - return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` : neverAsciiEscape || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? `"${escapeString(text)}"` : `"${escapeNonAsciiString(text)}"`; + return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` : neverAsciiEscape || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? `"${escapeString(text)}"` : `"${escapeNonAsciiString(text)}"`; } else { return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape); } @@ -113127,6 +113406,25 @@ function forEachProjectReference(projectReferences, resolvedProjectReferences, c } } var inferredTypesContainingFile = "__inferred type names__.ts"; +function getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName) { + const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : currentDirectory; + return combinePaths(containingDirectory, `__lib_node_modules_lookup_${libFileName}__.ts`); +} +function getLibraryNameFromLibFileName(libFileName) { + const components = libFileName.split("."); + let path = components[1]; + let i = 2; + while (components[i] && components[i] !== "d") { + path += (i === 2 ? "/" : "-") + components[i]; + i++; + } + return "@typescript/lib-" + path; +} +function getLibFileNameFromLibReference(libReference) { + const libName = toFileNameLowerCase(libReference.fileName); + const libFileName = libMap.get(libName); + return { libName, libFileName }; +} function isReferencedFile(reason) { switch (reason == null ? void 0 : reason.kind) { case 3 /* Import */: @@ -113170,7 +113468,7 @@ function getReferencedFileLocation(getSourceFileByPath, ref) { } return { file, pos, end, packageId }; } -function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) { +function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) { if (!program || (hasChangedAutomaticTypeDirectiveNames == null ? void 0 : hasChangedAutomaticTypeDirectiveNames())) return false; if (!arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) @@ -113185,6 +113483,8 @@ function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, const currentOptions = program.getCompilerOptions(); if (!compareDataObjects(currentOptions, newOptions)) return false; + if (program.resolvedLibReferences && forEachEntry(program.resolvedLibReferences, (_value, libFileName) => hasInvalidatedLibResolutions(libFileName))) + return false; if (currentOptions.configFile && newOptions.configFile) return currentOptions.configFile.text === newOptions.configFile.text; return true; @@ -113367,6 +113667,9 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config let fileProcessingDiagnostics; let automaticTypeDirectiveNames; let automaticTypeDirectiveResolutions; + let resolvedLibReferences; + let resolvedLibProcessing; + let packageMap; const maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; let currentNodeModulesDepth = 0; const modulesWithElidedImports = /* @__PURE__ */ new Map(); @@ -113454,6 +113757,14 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config createTypeReferenceResolutionLoader ); } + const hasInvalidatedLibResolutions = host.hasInvalidatedLibResolutions || returnFalse; + let actualResolveLibrary; + if (host.resolveLibrary) { + actualResolveLibrary = host.resolveLibrary.bind(host); + } else { + const libraryResolutionCache = createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + actualResolveLibrary = (libraryName, resolveFrom, options2) => resolveLibrary(libraryName, resolveFrom, options2, host, libraryResolutionCache); + } const packageIdToSourceFile = /* @__PURE__ */ new Map(); let sourceFileToPackageName = /* @__PURE__ */ new Map(); let redirectTargetsMap = createMultiMap(); @@ -113530,7 +113841,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config automaticTypeDirectiveResolutions = createModeAwareCache(); if (automaticTypeDirectiveNames.length) { (_k = tracing) == null ? void 0 : _k.push(tracing.Phase.Program, "processTypeReferences", { count: automaticTypeDirectiveNames.length }); - const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : currentDirectory; const containingFilename = combinePaths(containingDirectory, inferredTypesContainingFile); const resolutions = resolveTypeReferenceDirectiveNamesReusingOldState(automaticTypeDirectiveNames, containingFilename); for (let i = 0; i < automaticTypeDirectiveNames.length; i++) { @@ -113620,6 +113931,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config ); } oldProgram = void 0; + resolvedLibProcessing = void 0; const program = { getRootFileNames: () => rootNames, getSourceFile, @@ -113661,6 +113973,10 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config sourceFileToPackageName, redirectTargetsMap, usesUriStyleNodeCoreModules, + resolvedLibReferences, + getCurrentPackagesMap: () => packageMap, + typesPackageExists, + packageBundlesTypes, isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics2, getProjectReferences, @@ -113701,6 +114017,26 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config measure("Program", "beforeProgram", "afterProgram"); (_p = tracing) == null ? void 0 : _p.pop(); return program; + function getPackagesMap() { + if (packageMap) + return packageMap; + packageMap = /* @__PURE__ */ new Map(); + files.forEach((sf) => { + if (!sf.resolvedModules) + return; + sf.resolvedModules.forEach(({ resolvedModule }) => { + if (resolvedModule == null ? void 0 : resolvedModule.packageId) + packageMap.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!packageMap.get(resolvedModule.packageId.name)); + }); + }); + return packageMap; + } + function typesPackageExists(packageName) { + return getPackagesMap().has(getTypesPackageName(packageName)); + } + function packageBundlesTypes(packageName) { + return !!getPackagesMap().get(packageName); + } function addResolutionDiagnostics(resolution) { var _a2; if (!((_a2 = resolution.resolutionDiagnostics) == null ? void 0 : _a2.length)) @@ -114149,6 +114485,9 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config if (changesAffectingProgramStructure(oldOptions, options)) { return 1 /* SafeModules */; } + if (oldProgram.resolvedLibReferences && forEachEntry(oldProgram.resolvedLibReferences, (resolution, libFileName) => pathForLibFileWorker(libFileName).actual !== resolution.actual)) { + return 1 /* SafeModules */; + } if (host.hasChangedAutomaticTypeDirectiveNames) { if (host.hasChangedAutomaticTypeDirectiveNames()) return 1 /* SafeModules */; @@ -114185,6 +114524,8 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; usesUriStyleNodeCoreModules = oldProgram.usesUriStyleNodeCoreModules; + resolvedLibReferences = oldProgram.resolvedLibReferences; + packageMap = oldProgram.getCurrentPackagesMap(); return 2 /* Completely */; } function getEmitHost(writeFileCallback) { @@ -114294,7 +114635,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config if (!options.lib) { return equalityComparer(file.fileName, getDefaultLibraryFileName()); } else { - return some(options.lib, (libFileName) => equalityComparer(file.fileName, pathForLibFile(libFileName))); + return some(options.lib, (libFileName) => equalityComparer(file.fileName, resolvedLibReferences.get(libFileName).actual)); } } function getTypeChecker() { @@ -114885,11 +115226,10 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } } function getLibFileFromReference(ref) { - const libName = toFileNameLowerCase(ref.fileName); - const libFileName = libMap.get(libName); - if (libFileName) { - return getSourceFile(pathForLibFile(libFileName)); - } + var _a2; + const { libFileName } = getLibFileNameFromLibReference(ref); + const actualFileName = libFileName && ((_a2 = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName)) == null ? void 0 : _a2.actual); + return actualFileName !== void 0 ? getSourceFile(actualFileName) : void 0; } function getSourceFileFromReference(referencingFile, ref) { return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), getSourceFile); @@ -115314,24 +115654,55 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } } function pathForLibFile(libFileName) { - const components = libFileName.split("."); - let path = components[1]; - let i = 2; - while (components[i] && components[i] !== "d") { - path += (i === 2 ? "/" : "-") + components[i]; - i++; + const existing = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName); + if (existing) + return existing.actual; + const result = pathForLibFileWorker(libFileName); + (resolvedLibReferences ?? (resolvedLibReferences = /* @__PURE__ */ new Map())).set(libFileName, result); + return result.actual; + } + function pathForLibFileWorker(libFileName) { + var _a2, _b2, _c2, _d2, _e2; + const existing = resolvedLibProcessing == null ? void 0 : resolvedLibProcessing.get(libFileName); + if (existing) + return existing; + if (structureIsReused !== 0 /* Not */ && oldProgram && !hasInvalidatedLibResolutions(libFileName)) { + const oldResolution = (_a2 = oldProgram.resolvedLibReferences) == null ? void 0 : _a2.get(libFileName); + if (oldResolution) { + if (oldResolution.resolution && isTraceEnabled(options, host)) { + const libraryName2 = getLibraryNameFromLibFileName(libFileName); + const resolveFrom2 = getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName); + trace( + host, + oldResolution.resolution.resolvedModule ? 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, + libraryName2, + getNormalizedAbsolutePath(resolveFrom2, currentDirectory), + (_b2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _b2.resolvedFileName, + ((_c2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _c2.packageId) && packageIdToString(oldResolution.resolution.resolvedModule.packageId) + ); + } + (resolvedLibProcessing ?? (resolvedLibProcessing = /* @__PURE__ */ new Map())).set(libFileName, oldResolution); + return oldResolution; + } } - const resolveFrom = combinePaths(currentDirectory, `__lib_node_modules_lookup_${libFileName}__.ts`); - const localOverrideModuleResult = resolveModuleName("@typescript/lib-" + path, resolveFrom, { moduleResolution: 2 /* Node10 */ }, host, moduleResolutionCache); - if (localOverrideModuleResult == null ? void 0 : localOverrideModuleResult.resolvedModule) { - return localOverrideModuleResult.resolvedModule.resolvedFileName; - } - return combinePaths(defaultLibraryPath, libFileName); + const libraryName = getLibraryNameFromLibFileName(libFileName); + const resolveFrom = getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName); + (_d2 = tracing) == null ? void 0 : _d2.push(tracing.Phase.Program, "resolveLibrary", { resolveFrom }); + mark("beforeResolveLibrary"); + const resolution = actualResolveLibrary(libraryName, resolveFrom, options, libFileName); + mark("afterResolveLibrary"); + measure("ResolveLibrary", "beforeResolveLibrary", "afterResolveLibrary"); + (_e2 = tracing) == null ? void 0 : _e2.pop(); + const result = { + resolution, + actual: resolution.resolvedModule ? resolution.resolvedModule.resolvedFileName : combinePaths(defaultLibraryPath, libFileName) + }; + (resolvedLibProcessing ?? (resolvedLibProcessing = /* @__PURE__ */ new Map())).set(libFileName, result); + return result; } function processLibReferenceDirectives(file) { forEach(file.libReferenceDirectives, (libReference, index) => { - const libName = toFileNameLowerCase(libReference.fileName); - const libFileName = libMap.get(libName); + const { libName, libFileName } = getLibFileNameFromLibReference(libReference); if (libFileName) { processRootFile( pathForLibFile(libFileName), @@ -115457,7 +115828,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config void 0 ); } else { - const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), host.getCurrentDirectory()); + const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), currentDirectory); sourceFile = host.getSourceFile(refPath, 100 /* JSON */); addFileToFilesByName( sourceFile, @@ -117010,7 +117381,10 @@ function createBuilderProgramState(newProgram, oldState) { return; const diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { - state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics); + state.semanticDiagnosticsPerFile.set( + sourceFilePath, + oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : repopulateDiagnostics(diagnostics, newProgram) + ); if (!state.semanticDiagnosticsFromOldState) { state.semanticDiagnosticsFromOldState = /* @__PURE__ */ new Set(); } @@ -117081,6 +117455,33 @@ function getEmitSignatureFromOldSignature(options, oldOptions, oldEmitSignature) isString(oldEmitSignature) ? [oldEmitSignature] : oldEmitSignature[0] ); } +function repopulateDiagnostics(diagnostics, newProgram) { + if (!diagnostics.length) + return diagnostics; + return sameMap(diagnostics, (diag2) => { + if (isString(diag2.messageText)) + return diag2; + const repopulatedChain = convertOrRepopulateDiagnosticMessageChain(diag2.messageText, diag2.file, newProgram, (chain) => { + var _a; + return (_a = chain.repopulateInfo) == null ? void 0 : _a.call(chain); + }); + return repopulatedChain === diag2.messageText ? diag2 : { ...diag2, messageText: repopulatedChain }; + }); +} +function convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo) { + const info = repopulateInfo(chain); + if (info) { + return { + ...createModuleNotFoundChain(sourceFile, newProgram, info.moduleReference, info.mode, info.packageName || info.moduleReference), + next: convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo) + }; + } + const next = convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo); + return next === chain.next ? chain : { ...chain, next }; +} +function convertOrRepopulateDiagnosticMessageChainArray(array, sourceFile, newProgram, repopulateInfo) { + return sameMap(array, (chain) => convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo)); +} function convertToDiagnostics(diagnostics, newProgram) { if (!diagnostics.length) return emptyArray; @@ -117102,9 +117503,11 @@ function convertToDiagnostics(diagnostics, newProgram) { } function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath3) { const { file } = diagnostic; + const sourceFile = file ? newProgram.getSourceFileByPath(toPath3(file)) : void 0; return { ...diagnostic, - file: file ? newProgram.getSourceFileByPath(toPath3(file)) : void 0 + file: sourceFile, + messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertOrRepopulateDiagnosticMessageChain(diagnostic.messageText, sourceFile, newProgram, (chain) => chain.info) }; } function releaseCache(state) { @@ -117646,9 +118049,35 @@ function convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBui const { file } = diagnostic; return { ...diagnostic, - file: file ? relativeToBuildInfo(file.resolvedPath) : void 0 + file: file ? relativeToBuildInfo(file.resolvedPath) : void 0, + messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertToReusableDiagnosticMessageChain(diagnostic.messageText) }; } +function convertToReusableDiagnosticMessageChain(chain) { + if (chain.repopulateInfo) { + return { + info: chain.repopulateInfo(), + next: convertToReusableDiagnosticMessageChainArray(chain.next) + }; + } + const next = convertToReusableDiagnosticMessageChainArray(chain.next); + return next === chain.next ? chain : { ...chain, next }; +} +function convertToReusableDiagnosticMessageChainArray(array) { + if (!array) + return array; + return forEach(array, (chain, index) => { + const reusable = convertToReusableDiagnosticMessageChain(chain); + if (chain === reusable) + return void 0; + const result = index > 0 ? array.slice(0, index - 1) : []; + result.push(reusable); + for (let i = index + 1; i < array.length; i++) { + result.push(convertToReusableDiagnosticMessageChain(array[i])); + } + return result; + }) || array; +} function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { let host; let newProgram; @@ -118298,6 +118727,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW let failedLookupChecks; let startsWithPathChecks; let isInDirectoryChecks; + let allModuleAndTypeResolutionsAreInvalidated = false; const getCurrentDirectory = memoize(() => resolutionHost.getCurrentDirectory()); const cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); const resolvedModuleNames = /* @__PURE__ */ new Map(); @@ -118313,6 +118743,13 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW resolutionHost.getCompilationSettings(), moduleResolutionCache.getPackageJsonInfoCache() ); + const resolvedLibraries = /* @__PURE__ */ new Map(); + const libraryResolutionCache = createModuleResolutionCache( + getCurrentDirectory(), + resolutionHost.getCanonicalFileName, + getOptionsForLibraryResolution(resolutionHost.getCompilationSettings()), + moduleResolutionCache.getPackageJsonInfoCache() + ); const directoryWatchesOfFailedLookups = /* @__PURE__ */ new Map(); const fileWatchesOfAffectingLocations = /* @__PURE__ */ new Map(); const rootDir = getRootDirectoryOfResolutionCache(rootDirForResolution, getCurrentDirectory); @@ -118329,6 +118766,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW finishCachingPerDirectoryResolution, resolveModuleNameLiterals, resolveTypeReferenceDirectiveReferences, + resolveLibrary: resolveLibrary2, resolveSingleModuleNameWithoutWatching, removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile, @@ -118340,7 +118778,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch, closeTypeRootsWatch, - clear: clear2 + clear: clear2, + onChangesAffectModuleResolution }; function getResolvedModule2(resolution) { return resolution.resolvedModule; @@ -118363,13 +118802,23 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW isInDirectoryChecks = void 0; affectingPathChecks = void 0; affectingPathChecksForFile = void 0; + allModuleAndTypeResolutionsAreInvalidated = false; moduleResolutionCache.clear(); typeReferenceDirectiveResolutionCache.clear(); moduleResolutionCache.update(resolutionHost.getCompilationSettings()); typeReferenceDirectiveResolutionCache.update(resolutionHost.getCompilationSettings()); + libraryResolutionCache.clear(); impliedFormatPackageJsons.clear(); + resolvedLibraries.clear(); hasChangedAutomaticTypeDirectiveNames = false; } + function onChangesAffectModuleResolution() { + allModuleAndTypeResolutionsAreInvalidated = true; + moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); + typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + moduleResolutionCache.update(resolutionHost.getCompilationSettings()); + typeReferenceDirectiveResolutionCache.update(resolutionHost.getCompilationSettings()); + } function startRecordingFilesWithChangedResolutions() { filesWithChangedSetOfUnresolvedImports = []; } @@ -118385,23 +118834,45 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW const value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); return !!value && !!value.length; } - function createHasInvalidatedResolutions(customHasInvalidatedResolutions) { + function createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidatedLibResolutions) { invalidateResolutionsOfFailedLookupLocations(); const collected = filesWithInvalidatedResolutions; filesWithInvalidatedResolutions = void 0; - return (path) => customHasInvalidatedResolutions(path) || !!(collected == null ? void 0 : collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); + return { + hasInvalidatedResolutions: (path) => customHasInvalidatedResolutions(path) || allModuleAndTypeResolutionsAreInvalidated || !!(collected == null ? void 0 : collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path), + hasInvalidatedLibResolutions: (libFileName) => { + var _a; + return customHasInvalidatedLibResolutions(libFileName) || !!((_a = resolvedLibraries == null ? void 0 : resolvedLibraries.get(libFileName)) == null ? void 0 : _a.isInvalidated); + } + }; } function startCachingPerDirectoryResolution() { moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + libraryResolutionCache.clearAllExceptPackageJsonInfoCache(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } + function cleanupLibResolutionWatching(newProgram) { + resolvedLibraries.forEach((resolution, libFileName) => { + var _a; + if (!((_a = newProgram == null ? void 0 : newProgram.resolvedLibReferences) == null ? void 0 : _a.has(libFileName))) { + stopWatchFailedLookupLocationOfResolution( + resolution, + resolutionHost.toPath(getInferredLibraryNameResolveFrom(newProgram.getCompilerOptions(), getCurrentDirectory(), libFileName)), + getResolvedModule2 + ); + resolvedLibraries.delete(libFileName); + } + }); + } function finishCachingPerDirectoryResolution(newProgram, oldProgram) { filesWithInvalidatedNonRelativeUnresolvedImports = void 0; + allModuleAndTypeResolutionsAreInvalidated = false; nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); if (newProgram !== oldProgram) { + cleanupLibResolutionWatching(newProgram); newProgram == null ? void 0 : newProgram.getSourceFiles().forEach((newFile) => { var _a; const expected = isExternalOrCommonJsModule(newFile) ? ((_a = newFile.packageJsonLocations) == null ? void 0 : _a.length) ?? 0 : 0; @@ -118493,6 +118964,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW reusedNames, loader, getResolutionWithResolvedFileName, + deferWatchingNonRelativeResolution, shouldRetryResolution, logChanges }) { @@ -118509,15 +118981,15 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW const name = loader.nameAndMode.getName(entry); const mode = loader.nameAndMode.getMode(entry, containingSourceFile); let resolution = resolutionsInFile.get(name, mode); - if (!seenNamesInFile.has(name, mode) && unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate - hasInvalidatedNonRelativeUnresolvedImport && !isExternalModuleNameRelative(name) && shouldRetryResolution(resolution)) { + 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))) { const existingResolution = resolution; resolution = loader.resolve(name, mode); if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) { resolutionHost.onDiscoveredSymlink(); } resolutionsInFile.set(name, mode, resolution); - watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution); if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName); } @@ -118593,7 +119065,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW typeReferenceDirectiveResolutionCache ), getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective, - shouldRetryResolution: (resolution) => resolution.resolvedTypeReferenceDirective === void 0 + shouldRetryResolution: (resolution) => resolution.resolvedTypeReferenceDirective === void 0, + deferWatchingNonRelativeResolution: false }); } function resolveModuleNameLiterals(moduleLiterals, containingFile, redirectedReference, options, containingSourceFile, reusedNames) { @@ -118612,9 +119085,46 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW ), getResolutionWithResolvedFileName: getResolvedModule2, shouldRetryResolution: (resolution) => !resolution.resolvedModule || !resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension), - logChanges: logChangesWhenResolvingModule + logChanges: logChangesWhenResolvingModule, + deferWatchingNonRelativeResolution: true + // Defer non relative resolution watch because we could be using ambient modules }); } + function resolveLibrary2(libraryName, resolveFrom, options, libFileName) { + var _a; + const host = ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost; + let resolution = resolvedLibraries == null ? void 0 : resolvedLibraries.get(libFileName); + if (!resolution || resolution.isInvalidated) { + const existingResolution = resolution; + resolution = resolveLibrary(libraryName, resolveFrom, options, host, libraryResolutionCache); + const path = resolutionHost.toPath(resolveFrom); + watchFailedLookupLocationsOfExternalModuleResolutions( + libraryName, + resolution, + path, + getResolvedModule2, + /*deferWatchingNonRelativeResolution*/ + false + ); + resolvedLibraries.set(libFileName, resolution); + if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolvedModule2); + } + } else { + if (isTraceEnabled(options, host)) { + const resolved = getResolvedModule2(resolution); + trace( + host, + (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.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, + resolveFrom, + resolved == null ? void 0 : resolved.resolvedFileName, + (resolved == null ? void 0 : resolved.packageId) && packageIdToString(resolved.packageId) + ); + } + } + return resolution; + } function resolveSingleModuleNameWithoutWatching(moduleName, containingFile) { const path = resolutionHost.toPath(containingFile); const resolutionsInFile = resolvedModuleNames.get(path); @@ -118630,7 +119140,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW function isNodeModulesAtTypesDirectory(dirPath) { return endsWith(dirPath, "/node_modules/@types"); } - function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) { + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution) { var _a; if (resolution.refCount) { resolution.refCount++; @@ -118638,7 +119148,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW } else { resolution.refCount = 1; Debug.assert(!((_a = resolution.files) == null ? void 0 : _a.size)); - if (isExternalModuleNameRelative(name)) { + if (!deferWatchingNonRelativeResolution || isExternalModuleNameRelative(name)) { watchFailedLookupLocationOfResolution(resolution); } else { nonRelativeExternalModuleResolutions.add(name, resolution); @@ -118654,45 +119164,51 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW } (resolution.files ?? (resolution.files = /* @__PURE__ */ new Set())).add(filePath); } + function watchFailedLookupLocation(failedLookupLocation, setAtRoot) { + const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + const toWatch = getDirectoryToWatchFailedLookupLocation( + failedLookupLocation, + failedLookupLocationPath, + rootDir, + rootPath, + rootPathComponents, + getCurrentDirectory + ); + if (toWatch) { + const { dir, dirPath, nonRecursive } = toWatch; + if (dirPath === rootPath) { + Debug.assert(nonRecursive); + setAtRoot = true; + } else { + setDirectoryWatcher(dir, dirPath, nonRecursive); + } + } + return setAtRoot; + } function watchFailedLookupLocationOfResolution(resolution) { Debug.assert(!!resolution.refCount); - const { failedLookupLocations, affectingLocations } = resolution; - if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length)) + const { failedLookupLocations, affectingLocations, node10Result } = resolution; + if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length) && !node10Result) return; - if (failedLookupLocations == null ? void 0 : failedLookupLocations.length) + if ((failedLookupLocations == null ? void 0 : failedLookupLocations.length) || node10Result) resolutionsWithFailedLookups.add(resolution); let setAtRoot = false; if (failedLookupLocations) { for (const failedLookupLocation of failedLookupLocations) { - const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - const toWatch = getDirectoryToWatchFailedLookupLocation( - failedLookupLocation, - failedLookupLocationPath, - rootDir, - rootPath, - rootPathComponents, - getCurrentDirectory - ); - if (toWatch) { - const { dir, dirPath, nonRecursive } = toWatch; - if (dirPath === rootPath) { - Debug.assert(nonRecursive); - setAtRoot = true; - } else { - setDirectoryWatcher(dir, dirPath, nonRecursive); - } - } - } - if (setAtRoot) { - setDirectoryWatcher( - rootDir, - rootPath, - /*nonRecursive*/ - true - ); + setAtRoot = watchFailedLookupLocation(failedLookupLocation, setAtRoot); } } - watchAffectingLocationsOfResolution(resolution, !(failedLookupLocations == null ? void 0 : failedLookupLocations.length)); + if (node10Result) + setAtRoot = watchFailedLookupLocation(node10Result, setAtRoot); + if (setAtRoot) { + setDirectoryWatcher( + rootDir, + rootPath, + /*nonRecursive*/ + true + ); + } + watchAffectingLocationsOfResolution(resolution, !(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !node10Result); } function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) { Debug.assert(!!resolution.refCount); @@ -118786,6 +119302,26 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive }); } } + function stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot) { + const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + const toWatch = getDirectoryToWatchFailedLookupLocation( + failedLookupLocation, + failedLookupLocationPath, + rootDir, + rootPath, + rootPathComponents, + getCurrentDirectory + ); + if (toWatch) { + const { dirPath } = toWatch; + if (dirPath === rootPath) { + removeAtRoot = true; + } else { + removeDirectoryWatcher(dirPath); + } + } + return removeAtRoot; + } function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) { Debug.checkDefined(resolution.files).delete(filePath); resolution.refCount--; @@ -118799,31 +119335,18 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW if ((resolutions == null ? void 0 : resolutions.delete(resolution)) && !resolutions.size) resolvedFileToResolution.delete(key); } - const { failedLookupLocations, affectingLocations } = resolution; + const { failedLookupLocations, affectingLocations, node10Result } = resolution; if (resolutionsWithFailedLookups.delete(resolution)) { let removeAtRoot = false; - for (const failedLookupLocation of failedLookupLocations) { - const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - const toWatch = getDirectoryToWatchFailedLookupLocation( - failedLookupLocation, - failedLookupLocationPath, - rootDir, - rootPath, - rootPathComponents, - getCurrentDirectory - ); - if (toWatch) { - const { dirPath } = toWatch; - if (dirPath === rootPath) { - removeAtRoot = true; - } else { - removeDirectoryWatcher(dirPath); - } + if (failedLookupLocations) { + for (const failedLookupLocation of failedLookupLocations) { + removeAtRoot = stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot); } } - if (removeAtRoot) { + if (node10Result) + removeAtRoot = stopWatchFailedLookupLocation(node10Result, removeAtRoot); + if (removeAtRoot) removeDirectoryWatcher(rootPath); - } } else if (affectingLocations == null ? void 0 : affectingLocations.length) { resolutionsWithOnlyAffectingLocations.delete(resolution); } @@ -118918,15 +119441,37 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW return false; } (failedLookupChecks || (failedLookupChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); - const packagePath = parseNodeModuleFromPath(fileOrDirectoryPath); + const packagePath = parseNodeModuleFromPath( + fileOrDirectoryPath, + /*isFolder*/ + true + ); if (packagePath) (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } + function invalidatePackageJsonMap() { + const packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) { + packageJsonMap.forEach((_value, path) => isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : void 0); + } + } function invalidateResolutionsOfFailedLookupLocations() { var _a; + if (allModuleAndTypeResolutionsAreInvalidated) { + affectingPathChecksForFile = void 0; + invalidatePackageJsonMap(); + if (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks || affectingPathChecks) { + invalidateResolutions(resolvedLibraries, canInvalidateFailedLookupResolution); + } + failedLookupChecks = void 0; + startsWithPathChecks = void 0; + isInDirectoryChecks = void 0; + affectingPathChecks = void 0; + return true; + } let invalidated = false; if (affectingPathChecksForFile) { (_a = resolutionHost.getCurrentProgram()) == null ? void 0 : _a.getSourceFiles().forEach((f) => { @@ -118941,10 +119486,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW return invalidated; } invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution) || invalidated; - const packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); - if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) { - packageJsonMap.forEach((_value, path) => isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : void 0); - } + invalidatePackageJsonMap(); failedLookupChecks = void 0; startsWithPathChecks = void 0; isInDirectoryChecks = void 0; @@ -118958,7 +119500,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW return true; if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) return false; - return (_a = resolution.failedLookupLocations) == null ? void 0 : _a.some((location) => isInvalidatedFailedLookup(resolutionHost.toPath(location))); + return ((_a = resolution.failedLookupLocations) == null ? void 0 : _a.some((location) => isInvalidatedFailedLookup(resolutionHost.toPath(location)))) || !!resolution.node10Result && isInvalidatedFailedLookup(resolutionHost.toPath(resolution.node10Result)); } function isInvalidatedFailedLookup(locationPath) { return (failedLookupChecks == null ? void 0 : failedLookupChecks.has(locationPath)) || firstDefinedIterator((startsWithPathChecks == null ? void 0 : startsWithPathChecks.keys()) || [], (fileOrDirectoryPath) => startsWith(locationPath, fileOrDirectoryPath) ? true : void 0) || firstDefinedIterator((isInDirectoryChecks == null ? void 0 : isInDirectoryChecks.keys()) || [], (dirPath) => locationPath.length > dirPath.length && startsWith(locationPath, dirPath) && (isDiskPathRoot(dirPath) || locationPath[dirPath.length] === directorySeparator) ? true : void 0); @@ -119487,7 +120029,9 @@ var WatchType = { 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" + NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation", + TypingInstallerLocationFile: "File location for typing installer", + TypingInstallerLocationDirectory: "Directory location for typing installer" }; function createWatchFactory(host, options) { const watchLogLevel = host.trace ? options.extendedDiagnostics ? 2 /* Verbose */ : options.diagnostics ? 1 /* TriggerOnly */ : 0 /* None */ : 0 /* None */; @@ -119800,9 +120344,11 @@ function createWatchProgram(host) { if (!compilerHost.resolveTypeReferenceDirectiveReferences && !compilerHost.resolveTypeReferenceDirectives) { compilerHost.resolveTypeReferenceDirectiveReferences = resolutionCache.resolveTypeReferenceDirectiveReferences.bind(resolutionCache); } + compilerHost.resolveLibrary = !host.resolveLibrary ? resolutionCache.resolveLibrary.bind(resolutionCache) : host.resolveLibrary.bind(host); compilerHost.getModuleResolutionCache = host.resolveModuleNameLiterals || host.resolveModuleNames ? maybeBind(host, host.getModuleResolutionCache) : () => resolutionCache.getModuleResolutionCache(); const userProvidedResolution = !!host.resolveModuleNameLiterals || !!host.resolveTypeReferenceDirectiveReferences || !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; const customHasInvalidatedResolutions = userProvidedResolution ? maybeBind(host, host.hasInvalidatedResolutions) || returnTrue : returnFalse; + const customHasInvalidLibResolutions = host.resolveLibrary ? maybeBind(host, host.hasInvalidatedLibResolutions) || returnTrue : returnFalse; builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); watchConfigFileWildCardDirectories(); @@ -119863,10 +120409,11 @@ function createWatchProgram(host) { if (hasChangedCompilerOptions) { newLine = updateNewLine(); if (program && changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { - resolutionCache.clear(); + debugger; + resolutionCache.onChangesAffectModuleResolution(); } } - const hasInvalidatedResolutions = resolutionCache.createHasInvalidatedResolutions(customHasInvalidatedResolutions); + const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = resolutionCache.createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidLibResolutions); const { originalReadFile, originalFileExists, @@ -119875,7 +120422,7 @@ function createWatchProgram(host) { originalWriteFile, readFileWithCache } = changeCompilerHostLikeToUseCache(compilerHost, toPath3); - if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, (path) => getSourceVersion(path, readFileWithCache), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, (path) => getSourceVersion(path, readFileWithCache), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { if (reportFileChangeDetectedOnCreateProgram) { reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation); @@ -119896,7 +120443,7 @@ function createWatchProgram(host) { if (reportFileChangeDetectedOnCreateProgram) { reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation); } - createNewProgram(hasInvalidatedResolutions); + createNewProgram(hasInvalidatedResolutions, hasInvalidatedLibResolutions); } reportFileChangeDetectedOnCreateProgram = false; if (host.afterProgramCreate && program !== builderProgram) { @@ -119909,7 +120456,7 @@ function createWatchProgram(host) { compilerHost.writeFile = originalWriteFile; return builderProgram; } - function createNewProgram(hasInvalidatedResolutions) { + function createNewProgram(hasInvalidatedResolutions, hasInvalidatedLibResolutions) { writeLog("CreatingProgramWith::"); writeLog(` roots: ${JSON.stringify(rootFileNames)}`); writeLog(` options: ${JSON.stringify(compilerOptions)}`); @@ -119920,6 +120467,7 @@ function createWatchProgram(host) { hasChangedConfigFileParsingErrors = false; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolutions = hasInvalidatedResolutions; + compilerHost.hasInvalidatedLibResolutions = hasInvalidatedLibResolutions; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; const oldProgram = getCurrentProgram(); builderProgram = createProgram2(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); @@ -120472,6 +121020,7 @@ function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, optio compilerHost.getParsedCommandLine = (fileName) => parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); compilerHost.resolveModuleNameLiterals = maybeBind(host, host.resolveModuleNameLiterals); compilerHost.resolveTypeReferenceDirectiveReferences = maybeBind(host, host.resolveTypeReferenceDirectiveReferences); + compilerHost.resolveLibrary = maybeBind(host, host.resolveLibrary); compilerHost.resolveModuleNames = maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = maybeBind(host, host.resolveTypeReferenceDirectives); compilerHost.getModuleResolutionCache = maybeBind(host, host.getModuleResolutionCache); @@ -120509,6 +121058,23 @@ function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, optio createTypeReferenceResolutionLoader ); } + let libraryResolutionCache; + if (!compilerHost.resolveLibrary) { + libraryResolutionCache = createModuleResolutionCache( + compilerHost.getCurrentDirectory(), + compilerHost.getCanonicalFileName, + /*options*/ + void 0, + moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache() + ); + compilerHost.resolveLibrary = (libraryName, resolveFrom, options2) => resolveLibrary( + libraryName, + resolveFrom, + options2, + host, + libraryResolutionCache + ); + } compilerHost.getBuildInfo = (fileName, configFilePath) => getBuildInfo3( state, fileName, @@ -120540,6 +121106,7 @@ function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, optio compilerHost, moduleResolutionCache, typeReferenceDirectiveResolutionCache, + libraryResolutionCache, // Mutable state buildOrder: void 0, readFileWithCache: (f) => host.readFile(f), @@ -120757,7 +121324,7 @@ function enableCache(state) { function disableCache(state) { if (!state.cache) return; - const { cache, host, compilerHost, extendedConfigCache, moduleResolutionCache, typeReferenceDirectiveResolutionCache } = state; + const { cache, host, compilerHost, extendedConfigCache, moduleResolutionCache, typeReferenceDirectiveResolutionCache, libraryResolutionCache } = state; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -120768,6 +121335,7 @@ function disableCache(state) { extendedConfigCache.clear(); moduleResolutionCache == null ? void 0 : moduleResolutionCache.clear(); typeReferenceDirectiveResolutionCache == null ? void 0 : typeReferenceDirectiveResolutionCache.clear(); + libraryResolutionCache == null ? void 0 : libraryResolutionCache.clear(); state.cache = void 0; } function clearProjectStatus(state, resolved) { diff --git a/lib/tsserver.js b/lib/tsserver.js index 1bcfee52452..c7ad068df92 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -418,6 +418,7 @@ __export(server_exports, { createMemberAccessForPropertyName: () => createMemberAccessForPropertyName, createModeAwareCache: () => createModeAwareCache, createModeAwareCacheKey: () => createModeAwareCacheKey, + createModuleNotFoundChain: () => createModuleNotFoundChain, createModuleResolutionCache: () => createModuleResolutionCache, createModuleResolutionLoader: () => createModuleResolutionLoader, createModuleSpecifierResolutionHost: () => createModuleSpecifierResolutionHost, @@ -552,6 +553,7 @@ __export(server_exports, { fileExtensionIs: () => fileExtensionIs, fileExtensionIsOneOf: () => fileExtensionIsOneOf, fileIncludeReasonToDiagnostics: () => fileIncludeReasonToDiagnostics, + fileShouldUseJavaScriptRequire: () => fileShouldUseJavaScriptRequire, filter: () => filter, filterMutate: () => filterMutate, filterSemanticDiagnostics: () => filterSemanticDiagnostics, @@ -787,6 +789,7 @@ __export(server_exports, { getImportNeedsImportStarHelper: () => getImportNeedsImportStarHelper, getIndentSize: () => getIndentSize, getIndentString: () => getIndentString, + getInferredLibraryNameResolveFrom: () => getInferredLibraryNameResolveFrom, getInitializedVariables: () => getInitializedVariables, getInitializerOfBinaryExpression: () => getInitializerOfBinaryExpression, getInitializerOfBindingOrAssignmentElement: () => getInitializerOfBindingOrAssignmentElement, @@ -907,6 +910,7 @@ __export(server_exports, { getOperatorAssociativity: () => getOperatorAssociativity, getOperatorPrecedence: () => getOperatorPrecedence, getOptionFromName: () => getOptionFromName, + getOptionsForLibraryResolution: () => getOptionsForLibraryResolution, getOptionsNameMap: () => getOptionsNameMap, getOrCreateEmitNode: () => getOrCreateEmitNode, getOrCreateExternalHelpersModuleNameIfNeeded: () => getOrCreateExternalHelpersModuleNameIfNeeded, @@ -1297,7 +1301,6 @@ __export(server_exports, { isEmptyObjectLiteral: () => isEmptyObjectLiteral, isEmptyStatement: () => isEmptyStatement, isEmptyStringLiteral: () => isEmptyStringLiteral, - isEndOfDeclarationMarker: () => isEndOfDeclarationMarker, isEntityName: () => isEntityName, isEntityNameExpression: () => isEntityNameExpression, isEnumConst: () => isEnumConst, @@ -1528,7 +1531,6 @@ __export(server_exports, { isLogicalOrCoalescingBinaryOperator: () => isLogicalOrCoalescingBinaryOperator, isMappedTypeNode: () => isMappedTypeNode, isMemberName: () => isMemberName, - isMergeDeclarationMarker: () => isMergeDeclarationMarker, isMetaProperty: () => isMetaProperty, isMethodDeclaration: () => isMethodDeclaration, isMethodOrAccessor: () => isMethodOrAccessor, @@ -2018,6 +2020,7 @@ __export(server_exports, { resolutionExtensionIsTSOrJson: () => resolutionExtensionIsTSOrJson, resolveConfigFileProjectName: () => resolveConfigFileProjectName, resolveJSModule: () => resolveJSModule, + resolveLibrary: () => resolveLibrary, resolveModuleName: () => resolveModuleName, resolveModuleNameFromCache: () => resolveModuleNameFromCache, resolvePackageNameToPackageJson: () => resolvePackageNameToPackageJson, @@ -2301,7 +2304,7 @@ module.exports = __toCommonJS(server_exports); // src/compiler/corePublic.ts var versionMajorMinor = "5.1"; -var version = "5.1.0-beta"; +var version = "5.1.1-rc"; var Comparison = /* @__PURE__ */ ((Comparison3) => { Comparison3[Comparison3["LessThan"] = -1] = "LessThan"; Comparison3[Comparison3["EqualTo"] = 0] = "EqualTo"; @@ -6094,10 +6097,8 @@ var SyntaxKind = /* @__PURE__ */ ((SyntaxKind5) => { SyntaxKind5[SyntaxKind5["NotEmittedStatement"] = 358] = "NotEmittedStatement"; SyntaxKind5[SyntaxKind5["PartiallyEmittedExpression"] = 359] = "PartiallyEmittedExpression"; SyntaxKind5[SyntaxKind5["CommaListExpression"] = 360] = "CommaListExpression"; - SyntaxKind5[SyntaxKind5["MergeDeclarationMarker"] = 361] = "MergeDeclarationMarker"; - SyntaxKind5[SyntaxKind5["EndOfDeclarationMarker"] = 362] = "EndOfDeclarationMarker"; - SyntaxKind5[SyntaxKind5["SyntheticReferenceExpression"] = 363] = "SyntheticReferenceExpression"; - SyntaxKind5[SyntaxKind5["Count"] = 364] = "Count"; + SyntaxKind5[SyntaxKind5["SyntheticReferenceExpression"] = 361] = "SyntheticReferenceExpression"; + SyntaxKind5[SyntaxKind5["Count"] = 362] = "Count"; SyntaxKind5[SyntaxKind5["FirstAssignment"] = 64 /* EqualsToken */] = "FirstAssignment"; SyntaxKind5[SyntaxKind5["LastAssignment"] = 79 /* CaretEqualsToken */] = "LastAssignment"; SyntaxKind5[SyntaxKind5["FirstCompoundAssignment"] = 65 /* PlusEqualsToken */] = "FirstCompoundAssignment"; @@ -6951,10 +6952,10 @@ var LanguageVariant = /* @__PURE__ */ ((LanguageVariant4) => { LanguageVariant4[LanguageVariant4["JSX"] = 1] = "JSX"; return LanguageVariant4; })(LanguageVariant || {}); -var WatchDirectoryFlags = /* @__PURE__ */ ((WatchDirectoryFlags4) => { - WatchDirectoryFlags4[WatchDirectoryFlags4["None"] = 0] = "None"; - WatchDirectoryFlags4[WatchDirectoryFlags4["Recursive"] = 1] = "Recursive"; - return WatchDirectoryFlags4; +var WatchDirectoryFlags = /* @__PURE__ */ ((WatchDirectoryFlags3) => { + WatchDirectoryFlags3[WatchDirectoryFlags3["None"] = 0] = "None"; + WatchDirectoryFlags3[WatchDirectoryFlags3["Recursive"] = 1] = "Recursive"; + return WatchDirectoryFlags3; })(WatchDirectoryFlags || {}); var CharacterCodes = /* @__PURE__ */ ((CharacterCodes2) => { CharacterCodes2[CharacterCodes2["nullCharacter"] = 0] = "nullCharacter"; @@ -7202,9 +7203,8 @@ var EmitFlags = /* @__PURE__ */ ((EmitFlags3) => { EmitFlags3[EmitFlags3["ReuseTempVariableScope"] = 1048576] = "ReuseTempVariableScope"; EmitFlags3[EmitFlags3["CustomPrologue"] = 2097152] = "CustomPrologue"; EmitFlags3[EmitFlags3["NoHoisting"] = 4194304] = "NoHoisting"; - EmitFlags3[EmitFlags3["HasEndOfDeclarationMarker"] = 8388608] = "HasEndOfDeclarationMarker"; - EmitFlags3[EmitFlags3["Iterator"] = 16777216] = "Iterator"; - EmitFlags3[EmitFlags3["NoAsciiEscaping"] = 33554432] = "NoAsciiEscaping"; + EmitFlags3[EmitFlags3["Iterator"] = 8388608] = "Iterator"; + EmitFlags3[EmitFlags3["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; return EmitFlags3; })(EmitFlags || {}); var InternalEmitFlags = /* @__PURE__ */ ((InternalEmitFlags3) => { @@ -10479,6 +10479,7 @@ var Diagnostics = { List_of_folders_to_include_type_definitions_from: diag(6161, 3 /* Message */, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), Disable_size_limitations_on_JavaScript_projects: diag(6162, 3 /* Message */, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), The_character_set_of_the_input_files: diag(6163, 3 /* Message */, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1: diag(6164, 3 /* Message */, "Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1_6164", "Skipping module '{0}' that looks like an absolute URI, target file types: {1}."), Do_not_truncate_error_messages: diag(6165, 3 /* Message */, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), Output_directory_for_generated_declaration_files: diag(6166, 3 /* Message */, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, 3 /* Message */, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), @@ -10958,6 +10959,7 @@ var Diagnostics = { You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder: diag(8036, 1 /* Error */, "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036", "You cannot rename elements that are defined in another 'node_modules' folder."), Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files: diag(8037, 1 /* Error */, "Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files_8037", "Type satisfaction expressions can only be used in TypeScript files."), Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export: diag(8038, 1 /* Error */, "Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export_8038", "Decorators may not appear after 'export' or 'export default' if they also appear before 'export'."), + A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag: diag(8039, 1 /* Error */, "A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag_8039", "A JSDoc '@template' tag may not follow a '@typedef', '@callback', or '@overload' tag"), Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, 1 /* Error */, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."), Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, 1 /* Error */, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."), JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17e3, 1 /* Error */, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), @@ -11209,6 +11211,7 @@ var Diagnostics = { Use_Number_isNaN_in_all_conditions: diag(95175, 3 /* Message */, "Use_Number_isNaN_in_all_conditions_95175", "Use `Number.isNaN` in all conditions."), Convert_typedef_to_TypeScript_type: diag(95176, 3 /* Message */, "Convert_typedef_to_TypeScript_type_95176", "Convert typedef to TypeScript type."), Convert_all_typedef_to_TypeScript_types: diag(95177, 3 /* Message */, "Convert_all_typedef_to_TypeScript_types_95177", "Convert all typedef to TypeScript types."), + Move_to_file: diag(95178, 3 /* Message */, "Move_to_file_95178", "Move to file"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, 1 /* Error */, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, 1 /* Error */, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, 1 /* Error */, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -14572,7 +14575,6 @@ function isLeftHandSideExpressionKind(kind) { case 283 /* JsxElement */: case 284 /* JsxSelfClosingElement */: case 287 /* JsxFragment */: - case 294 /* JsxNamespacedName */: case 214 /* TaggedTemplateExpression */: case 208 /* ArrayLiteralExpression */: case 216 /* ParenthesizedExpression */: @@ -14838,7 +14840,7 @@ function isDeclarationStatementKind(kind) { return kind === 261 /* FunctionDeclaration */ || kind === 281 /* MissingDeclaration */ || kind === 262 /* ClassDeclaration */ || kind === 263 /* InterfaceDeclaration */ || kind === 264 /* TypeAliasDeclaration */ || kind === 265 /* EnumDeclaration */ || kind === 266 /* ModuleDeclaration */ || kind === 271 /* ImportDeclaration */ || kind === 270 /* ImportEqualsDeclaration */ || kind === 277 /* ExportDeclaration */ || kind === 276 /* ExportAssignment */ || kind === 269 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 251 /* BreakStatement */ || kind === 250 /* ContinueStatement */ || kind === 258 /* DebuggerStatement */ || kind === 245 /* DoStatement */ || kind === 243 /* ExpressionStatement */ || kind === 241 /* EmptyStatement */ || kind === 248 /* ForInStatement */ || kind === 249 /* ForOfStatement */ || kind === 247 /* ForStatement */ || kind === 244 /* IfStatement */ || kind === 255 /* LabeledStatement */ || kind === 252 /* ReturnStatement */ || kind === 254 /* SwitchStatement */ || kind === 256 /* ThrowStatement */ || kind === 257 /* TryStatement */ || kind === 242 /* VariableStatement */ || kind === 246 /* WhileStatement */ || kind === 253 /* WithStatement */ || kind === 358 /* NotEmittedStatement */ || kind === 362 /* EndOfDeclarationMarker */ || kind === 361 /* MergeDeclarationMarker */; + return kind === 251 /* BreakStatement */ || kind === 250 /* ContinueStatement */ || kind === 258 /* DebuggerStatement */ || kind === 245 /* DoStatement */ || kind === 243 /* ExpressionStatement */ || kind === 241 /* EmptyStatement */ || kind === 248 /* ForInStatement */ || kind === 249 /* ForOfStatement */ || kind === 247 /* ForStatement */ || kind === 244 /* IfStatement */ || kind === 255 /* LabeledStatement */ || kind === 252 /* ReturnStatement */ || kind === 254 /* SwitchStatement */ || kind === 256 /* ThrowStatement */ || kind === 257 /* TryStatement */ || kind === 242 /* VariableStatement */ || kind === 246 /* WhileStatement */ || kind === 253 /* WithStatement */ || kind === 358 /* NotEmittedStatement */; } function isDeclaration(node) { if (node.kind === 167 /* TypeParameter */) { @@ -15132,7 +15134,39 @@ function projectReferenceIsEqualTo(oldRef, newRef) { return oldRef.path === newRef.path && !oldRef.prepend === !newRef.prepend && !oldRef.circular === !newRef.circular; } function moduleResolutionIsEqualTo(oldResolution, newResolution) { - 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); + 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; +} +function createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageName) { + var _a, _b; + const node10Result = (_b = (_a = sourceFile.resolvedModules) == null ? void 0 : _a.get(moduleReference, mode)) == null ? void 0 : _b.node10Result; + const result = node10Result ? chainDiagnosticMessages( + /*details*/ + void 0, + 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 + ) : host.typesPackageExists(packageName) ? chainDiagnosticMessages( + /*details*/ + void 0, + 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*/ + void 0, + 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*/ + void 0, + 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 ? void 0 : packageName }); + return result; } function packageIdIsEqual(a, b) { return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; @@ -15817,7 +15851,7 @@ function getLiteralText(node, sourceFile, flags) { } switch (node.kind) { case 11 /* StringLiteral */: { - const escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString : flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + const escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString : flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; if (node.singleQuote) { return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; } else { @@ -15828,7 +15862,7 @@ function getLiteralText(node, sourceFile, flags) { case 16 /* TemplateHead */: case 17 /* TemplateMiddle */: case 18 /* TemplateTail */: { - const escapeText = flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + const escapeText = flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; const rawText = node.rawText ?? escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */)); switch (node.kind) { case 15 /* NoSubstitutionTemplateLiteral */: @@ -15924,7 +15958,7 @@ function isCommonJSContainingModuleKind(kind) { return kind === 1 /* CommonJS */ || kind === 100 /* Node16 */ || kind === 199 /* NodeNext */; } function isEffectiveExternalModule(node, compilerOptions) { - return isExternalModule(node) || getIsolatedModules(compilerOptions) || isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator; + return isExternalModule(node) || isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator; } function isEffectiveStrictModeSourceFile(node, compilerOptions) { switch (node.scriptKind) { @@ -16087,6 +16121,8 @@ function tryGetTextOfPropertyName(name) { if (isStringOrNumericLiteralLike(name.expression)) return escapeLeadingUnderscores(name.expression.text); return void 0; + case 294 /* JsxNamespacedName */: + return getEscapedTextOfJsxNamespacedName(name); default: return Debug.assertNever(name); } @@ -17584,6 +17620,7 @@ function canHaveJSDoc(node) { case 171 /* PropertyDeclaration */: case 170 /* PropertySignature */: case 252 /* ReturnStatement */: + case 239 /* SemicolonClassElement */: case 177 /* SetAccessor */: case 303 /* ShorthandPropertyAssignment */: case 304 /* SpreadAssignment */: @@ -18071,6 +18108,8 @@ function getPropertyNameForPropertyNameNode(name) { return nameExpression.operand.text; } return void 0; + case 294 /* JsxNamespacedName */: + return getEscapedTextOfJsxNamespacedName(name); default: return Debug.assertNever(name); } @@ -18087,16 +18126,16 @@ function isPropertyNameLiteral(node) { } } function getTextOfIdentifierOrLiteral(node) { - return isMemberName(node) ? idText(node) : node.text; + return isMemberName(node) ? idText(node) : isJsxNamespacedName(node) ? getTextOfJsxNamespacedName(node) : node.text; } function getEscapedTextOfIdentifierOrLiteral(node) { - return isMemberName(node) ? node.escapedText : escapeLeadingUnderscores(node.text); + return isMemberName(node) ? node.escapedText : isJsxNamespacedName(node) ? getEscapedTextOfJsxNamespacedName(node) : escapeLeadingUnderscores(node.text); } function getPropertyNameForUniqueESSymbol(symbol) { return `__@${getSymbolId(symbol)}@${symbol.escapedName}`; } -function getSymbolNameForPrivateIdentifier(containingClassSymbol, description2) { - return `__#${getSymbolId(containingClassSymbol)}@${description2}`; +function getSymbolNameForPrivateIdentifier(containingClassSymbol, description3) { + return `__#${getSymbolId(containingClassSymbol)}@${description3}`; } function isKnownSymbol(symbol) { return startsWith(symbol.escapedName, "__@"); @@ -19385,6 +19424,8 @@ function tryGetPropertyAccessOrIdentifierToString(expr) { } } else if (isIdentifier(expr)) { return unescapeLeadingUnderscores(expr.escapedText); + } else if (isJsxNamespacedName(expr)) { + return getTextOfJsxNamespacedName(expr); } return void 0; } @@ -20751,7 +20792,7 @@ function getScriptKindFromFileName(fileName) { var supportedTSExtensions = [[".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */], [".cts" /* Cts */, ".d.cts" /* Dcts */], [".mts" /* Mts */, ".d.mts" /* Dmts */]]; var supportedTSExtensionsFlat = flatten(supportedTSExtensions); var supportedTSExtensionsWithJson = [...supportedTSExtensions, [".json" /* Json */]]; -var supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */, ".cts" /* Cts */, ".mts" /* Mts */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".cts" /* Cts */, ".mts" /* Mts */]; +var supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */, ".cts" /* Cts */, ".mts" /* Mts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; var supportedJSExtensions = [[".js" /* Js */, ".jsx" /* Jsx */], [".mjs" /* Mjs */], [".cjs" /* Cjs */]]; var supportedJSExtensionsFlat = flatten(supportedJSExtensions); var allSupportedExtensions = [[".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".js" /* Js */, ".jsx" /* Jsx */], [".cts" /* Cts */, ".d.cts" /* Dcts */, ".cjs" /* Cjs */], [".mts" /* Mts */, ".d.mts" /* Dmts */, ".mjs" /* Mjs */]]; @@ -22575,8 +22616,6 @@ function createNodeFactory(flags, baseFactory2) { updatePartiallyEmittedExpression, createCommaListExpression, updateCommaListExpression, - createEndOfDeclarationMarker, - createMergeDeclarationMarker, createSyntheticReferenceExpression, updateSyntheticReferenceExpression, cloneNode, @@ -25644,20 +25683,8 @@ function createNodeFactory(flags, baseFactory2) { function updateCommaListExpression(node, elements) { return node.elements !== elements ? update(createCommaListExpression(elements), node) : node; } - function createEndOfDeclarationMarker(original) { - const node = createBaseNode(362 /* EndOfDeclarationMarker */); - node.emitNode = {}; - node.original = original; - return node; - } - function createMergeDeclarationMarker(original) { - const node = createBaseNode(361 /* MergeDeclarationMarker */); - node.emitNode = {}; - node.original = original; - return node; - } function createSyntheticReferenceExpression(expression, thisArg) { - const node = createBaseNode(363 /* SyntheticReferenceExpression */); + const node = createBaseNode(361 /* SyntheticReferenceExpression */); node.expression = expression; node.thisArg = thisArg; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.thisArg); @@ -26049,8 +26076,8 @@ function createNodeFactory(flags, baseFactory2) { function inlineExpressions(expressions) { return expressions.length > 10 ? createCommaListExpression(expressions) : reduceLeft(expressions, factory2.createComma); } - function getName(node, allowComments, allowSourceMaps, emitFlags = 0) { - const nodeName = getNameOfDeclaration(node); + function getName(node, allowComments, allowSourceMaps, emitFlags = 0, ignoreAssignedName) { + const nodeName = ignoreAssignedName ? node && getNonAssignedNameOfDeclaration(node) : getNameOfDeclaration(node); if (nodeName && isIdentifier(nodeName) && !isGeneratedIdentifier(nodeName)) { const name = setParent(setTextRange(cloneNode(nodeName), nodeName), nodeName.parent); emitFlags |= getEmitFlags(nodeName); @@ -26067,8 +26094,8 @@ function createNodeFactory(flags, baseFactory2) { function getInternalName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */ | 65536 /* InternalName */); } - function getLocalName(node, allowComments, allowSourceMaps) { - return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */); + function getLocalName(node, allowComments, allowSourceMaps, ignoreAssignedName) { + return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */, ignoreAssignedName); } function getExportName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps, 16384 /* ExportName */); @@ -28480,13 +28507,7 @@ function isNotEmittedStatement(node) { return node.kind === 358 /* NotEmittedStatement */; } function isSyntheticReference(node) { - return node.kind === 363 /* SyntheticReferenceExpression */; -} -function isMergeDeclarationMarker(node) { - return node.kind === 361 /* MergeDeclarationMarker */; -} -function isEndOfDeclarationMarker(node) { - return node.kind === 362 /* EndOfDeclarationMarker */; + return node.kind === 361 /* SyntheticReferenceExpression */; } function isExternalModuleReference(node) { return node.kind === 282 /* ExternalModuleReference */; @@ -31571,8 +31592,13 @@ var Parser; return tokenIsIdentifierOrKeyword(token()) || token() === 19 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; + case 25 /* JSDocComment */: + return true; + case 26 /* Count */: + return Debug.fail("ParsingContext.Count used as a context"); + default: + Debug.assertNever(parsingContext2, "Non-exhaustive case in 'isListElement'."); } - return Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { Debug.assert(token() === 19 /* OpenBraceToken */); @@ -31666,7 +31692,8 @@ var Parser; return false; } function isInSomeParsingContext() { - for (let kind = 0; kind < 25 /* Count */; kind++) { + Debug.assert(parsingContext, "Missing parsing context"); + for (let kind = 0; kind < 26 /* Count */; kind++) { if (parsingContext & 1 << kind) { if (isListElement2( kind, @@ -31925,7 +31952,9 @@ var Parser; return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); case 24 /* AssertEntries */: return parseErrorAtCurrentToken(Diagnostics.Identifier_or_string_literal_expected); - case 25 /* Count */: + case 25 /* JSDocComment */: + return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); + case 26 /* Count */: return Debug.fail("ParsingContext.Count used as a context"); default: Debug.assertNever(context); @@ -33976,7 +34005,11 @@ var Parser; } function parseJsxElementName() { const pos = getNodePos(); - let expression = parseJsxTagName(); + const initialExpression = parseJsxTagName(); + if (isJsxNamespacedName(initialExpression)) { + return initialExpression; + } + let expression = initialExpression; while (parseOptional(25 /* DotToken */)) { expression = finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot( /*allowIdentifierNames*/ @@ -35506,11 +35539,11 @@ var Parser; } function parseClassElement() { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); if (token() === 27 /* SemicolonToken */) { nextToken(); - return finishNode(factory2.createSemicolonClassElement(), pos); + return withJSDoc(finishNode(factory2.createSemicolonClassElement(), pos), hasJSDoc); } - const hasJSDoc = hasPrecedingJSDocComment(); const modifiers = parseModifiers( /*allowDecorators*/ true, @@ -36057,7 +36090,8 @@ var Parser; ParsingContext2[ParsingContext2["HeritageClauses"] = 22] = "HeritageClauses"; ParsingContext2[ParsingContext2["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; ParsingContext2[ParsingContext2["AssertEntries"] = 24] = "AssertEntries"; - ParsingContext2[ParsingContext2["Count"] = 25] = "Count"; + ParsingContext2[ParsingContext2["JSDocComment"] = 25] = "JSDocComment"; + ParsingContext2[ParsingContext2["Count"] = 26] = "Count"; })(ParsingContext || (ParsingContext = {})); let Tristate; ((Tristate2) => { @@ -36179,6 +36213,8 @@ var Parser; PropertyLikeParse2[PropertyLikeParse2["CallbackParameter"] = 4] = "CallbackParameter"; })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start2 = 0, length2) { + const saveParsingContext = parsingContext; + parsingContext |= 1 << 25 /* JSDocComment */; const content = sourceText; const end = length2 === void 0 ? content.length : start2 + length2; length2 = end - start2; @@ -36195,7 +36231,10 @@ var Parser; let commentsPos; let comments = []; const parts = []; - return scanner2.scanRange(start2 + 3, length2 - 5, () => { + const result = scanner2.scanRange(start2 + 3, length2 - 5, doJSDocScan); + parsingContext = saveParsingContext; + return result; + function doJSDocScan() { let state = 1 /* SawAsterisk */; let margin; let indent3 = start2 - (content.lastIndexOf("\n", start2) + 1) + 4; @@ -36291,7 +36330,7 @@ var Parser; Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); const tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); return finishNode(factory2.createJSDocComment(parts.length ? createNodeArray(parts, start2, commentsPos) : trimmedComments.length ? trimmedComments : void 0, tagsArray), start2, end); - }); + } function removeLeadingNewlines(comments2) { while (comments2.length && (comments2[0] === "\n" || comments2[0] === "\r")) { comments2.shift(); @@ -36650,8 +36689,8 @@ var Parser; typeExpression = nestedTypeLiteral; isNameFirst = true; } - const result = target === 1 /* Property */ ? factory2.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) : factory2.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment); - return finishNode(result, start3); + const result2 = target === 1 /* Property */ ? factory2.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) : factory2.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment); + return finishNode(result2, start3); } function parseNestedTypeLiteral(typeExpression, name, target, indent3) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { @@ -36661,6 +36700,8 @@ var Parser; while (child = tryParse(() => parseChildParameterOrPropertyTag(target, indent3, name))) { if (child.kind === 347 /* JSDocParameterTag */ || child.kind === 354 /* JSDocPropertyTag */) { children = append(children, child); + } else if (child.kind === 351 /* JSDocTemplateTag */) { + parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag); } } if (children) { @@ -36748,7 +36789,9 @@ var Parser; const usedBrace = parseOptional(19 /* OpenBraceToken */); const pos = getNodePos(); const expression = parsePropertyAccessEntityNameExpression(); + scanner2.setInJSDocType(true); const typeArguments = tryParseTypeArguments(); + scanner2.setInJSDocType(false); const node = factory2.createExpressionWithTypeArguments(expression, typeArguments); const res = finishNode(node, pos); if (usedBrace) { @@ -36797,6 +36840,9 @@ var Parser; let jsDocPropertyTags; let hasChildren = false; while (child = tryParse(() => parseChildPropertyTag(indent3))) { + if (child.kind === 351 /* JSDocTemplateTag */) { + break; + } hasChildren = true; if (child.kind === 350 /* JSDocTypeTag */) { if (childTypeTag) { @@ -36856,6 +36902,10 @@ var Parser; let child; let parameters; while (child = tryParse(() => parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent3))) { + if (child.kind === 351 /* JSDocTemplateTag */) { + parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag); + break; + } parameters = append(parameters, child); } return createNodeArray(parameters || [], pos); @@ -36950,7 +37000,7 @@ var Parser; const start3 = scanner2.getTokenFullStart(); nextTokenJSDoc(); const tagName = parseJSDocIdentifierName(); - skipWhitespace(); + const indentText = skipWhitespaceOrAsterisk(); let t; switch (tagName.escapedText) { case "type": @@ -36964,6 +37014,8 @@ var Parser; case "param": t = 2 /* Parameter */ | 4 /* CallbackParameter */; break; + case "template": + return parseTemplateTag(start3, tagName, indent3, indentText); default: return false; } @@ -37051,9 +37103,9 @@ var Parser; const end2 = scanner2.getTokenEnd(); const originalKeywordKind = token(); const text = internIdentifier(scanner2.getTokenValue()); - const result = finishNode(factoryCreateIdentifier(text, originalKeywordKind), start3, end2); + const result2 = finishNode(factoryCreateIdentifier(text, originalKeywordKind), start3, end2); nextTokenJSDoc(); - return result; + return result2; } } })(JSDocParser = Parser2.JSDocParser || (Parser2.JSDocParser = {})); @@ -39918,8 +39970,8 @@ function generateTSConfig(options, fileNames, newLine) { result.push(`${tab}${tab}/* ${getLocaleSpecificMessage(Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file)} */`); result.push(""); for (const entry of entries) { - const { value, description: description2 = "" } = entry; - result.push(value && `${tab}${tab}${value}${description2 && makePadding(marginLength - value.length + 2) + description2}`); + const { value, description: description3 = "" } = entry; + result.push(value && `${tab}${tab}${value}${description3 && makePadding(marginLength - value.length + 2) + description3}`); } if (fileNames.length) { result.push(`${tab}},`); @@ -41616,13 +41668,12 @@ function createModuleOrTypeReferenceResolutionCache(currentDirectory, getCanonic nonRelativeNameResolutionCache.update(options2); } } -function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) { +function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache) { const result = createModuleOrTypeReferenceResolutionCache( currentDirectory, getCanonicalFileName, options, - /*packageJsonInfoCache*/ - void 0, + packageJsonInfoCache, getOriginalOrResolvedModuleFileName ); result.getOrCreateCacheForModuleName = (nonRelativeName, mode, redirectedReference) => result.getOrCreateCacheForNonRelativeName(nonRelativeName, mode, redirectedReference); @@ -41637,6 +41688,12 @@ function createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanoni getOriginalOrResolvedTypeReferenceFileName ); } +function getOptionsForLibraryResolution(options) { + return { moduleResolution: 2 /* Node10 */, traceResolution: options.traceResolution }; +} +function resolveLibrary(libraryName, resolveFrom, compilerOptions, host, cache) { + return resolveModuleName(libraryName, resolveFrom, getOptionsForLibraryResolution(compilerOptions), host, cache); +} function resolveModuleNameFromCache(moduleName, containingFile, cache, mode) { const containingDirectory = getDirectoryPath(containingFile); return cache.getFromDirectoryCache( @@ -42005,8 +42062,6 @@ function nodeModuleNameResolverWorker(features, moduleName, containingDirectory, const diagnosticState = { ...state, features: state.features & ~8 /* Exports */, - failedLookupLocations: [], - affectingLocations: [], reportDiagnostic: noop }; const diagnosticResult = tryResolve(extensions & (1 /* TypeScript */ | 4 /* Declaration */), diagnosticState); @@ -42046,6 +42101,12 @@ function nodeModuleNameResolverWorker(features, moduleName, containingDirectory, resolved2 = loadModuleFromSelfNameReference(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); } if (!resolved2) { + if (moduleName.indexOf(":") > -1) { + if (traceEnabled) { + trace(host, Diagnostics.Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); + } + return void 0; + } if (traceEnabled) { trace(host, Diagnostics.Loading_module_0_from_node_modules_folder_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); } @@ -42132,22 +42193,22 @@ var nodeModulesPathPart = "/node_modules/"; function pathContainsNodeModules(path) { return stringContains(path, nodeModulesPathPart); } -function parseNodeModuleFromPath(resolved) { +function parseNodeModuleFromPath(resolved, isFolder) { const path = normalizePath(resolved); const idx = path.lastIndexOf(nodeModulesPathPart); if (idx === -1) { return void 0; } const indexAfterNodeModules = idx + nodeModulesPathPart.length; - let indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + let indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules, isFolder); if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { - indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName, isFolder); } return path.slice(0, indexAfterPackageName); } -function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { +function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex, isFolder) { const nextSeparatorIndex = path.indexOf(directorySeparator, prevSeparatorIndex + 1); - return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + return nextSeparatorIndex === -1 ? isFolder ? path.length : prevSeparatorIndex : nextSeparatorIndex; } function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); @@ -43079,7 +43140,7 @@ function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, node return withPackageId(packageInfo, fromDirectory); } const loader = (extensions2, candidate2, onlyRecordFailures, state2) => { - let pathAndExtension = loadModuleFromFile(extensions2, candidate2, onlyRecordFailures, state2) || loadNodeModuleFromDirectoryWorker( + let pathAndExtension = (rest || !(state2.features & 32 /* EsmMode */)) && loadModuleFromFile(extensions2, candidate2, onlyRecordFailures, state2) || loadNodeModuleFromDirectoryWorker( extensions2, candidate2, onlyRecordFailures, @@ -43516,7 +43577,7 @@ function createBinder() { var inStrictMode; var inAssignmentPattern = false; var symbolCount = 0; - var Symbol46; + var Symbol47; var classifiableNames; var unreachableFlow = { flags: 1 /* Unreachable */ }; var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; @@ -43533,7 +43594,7 @@ function createBinder() { inStrictMode = bindInStrictMode(file, opts); classifiableNames = /* @__PURE__ */ new Set(); symbolCount = 0; - Symbol46 = objectAllocator.getSymbolConstructor(); + Symbol47 = objectAllocator.getSymbolConstructor(); Debug.attachFlowNodeDebugInfo(unreachableFlow); Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { @@ -43581,7 +43642,7 @@ function createBinder() { } function createSymbol(flags, name) { symbolCount++; - return new Symbol46(flags, name); + return new Symbol47(flags, name); } function addDeclarationToSymbol(symbol, node, symbolFlags) { symbol.flags |= symbolFlags; @@ -43630,7 +43691,7 @@ function createBinder() { return getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText); } if (isJsxNamespacedName(name)) { - return getEscapedTextOfJsxAttributeName(name); + return getEscapedTextOfJsxNamespacedName(name); } return isPropertyNameLiteral(name) ? getEscapedTextOfIdentifierOrLiteral(name) : void 0; } @@ -46412,15 +46473,16 @@ function getPreferences({ importModuleSpecifierPreference, importModuleSpecifier if (getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */) { return preferredEnding === 2 /* JsExtension */ ? [2 /* JsExtension */, 1 /* Index */] : [1 /* Index */, 2 /* JsExtension */]; } + const allowImportingTsExtension = shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName); switch (preferredEnding) { case 2 /* JsExtension */: - return [2 /* JsExtension */, 0 /* Minimal */, 1 /* Index */]; + return allowImportingTsExtension ? [2 /* JsExtension */, 3 /* TsExtension */, 0 /* Minimal */, 1 /* Index */] : [2 /* JsExtension */, 0 /* Minimal */, 1 /* Index */]; case 3 /* TsExtension */: return [3 /* TsExtension */, 0 /* Minimal */, 2 /* JsExtension */, 1 /* Index */]; case 1 /* Index */: - return [1 /* Index */, 0 /* Minimal */, 2 /* JsExtension */]; + return allowImportingTsExtension ? [1 /* Index */, 0 /* Minimal */, 3 /* TsExtension */, 2 /* JsExtension */] : [1 /* Index */, 0 /* Minimal */, 2 /* JsExtension */]; case 0 /* Minimal */: - return [0 /* Minimal */, 1 /* Index */, 2 /* JsExtension */]; + return allowImportingTsExtension ? [0 /* Minimal */, 1 /* Index */, 3 /* TsExtension */, 2 /* JsExtension */] : [0 /* Minimal */, 1 /* Index */, 2 /* JsExtension */]; default: Debug.assertNever(preferredEnding); } @@ -46616,7 +46678,7 @@ function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, im return pathsOnly ? void 0 : relativePath; } const baseDirectory = getNormalizedAbsolutePath(getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); - const relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); + const relativeToBaseUrl = getRelativePathIfInSameVolume(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) { return pathsOnly ? void 0 : relativePath; } @@ -46824,7 +46886,7 @@ function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, hos for (const { ending, value } of candidates) { if (value.length >= prefix.length + suffix.length && startsWith(value, prefix) && endsWith(value, suffix) && validateEnding({ ending, value })) { const matchedStar = value.substring(prefix.length, value.length - suffix.length); - return key.replace("*", matchedStar); + return pathIsRelative(matchedStar) ? void 0 : key.replace("*", matchedStar); } } } else if (some(candidates, (c) => c.ending !== 0 /* Minimal */ && pattern === c.value) || some(candidates, (c) => c.ending === 0 /* Minimal */ && pattern === c.value && validateEnding(c))) { @@ -47013,7 +47075,10 @@ function tryGetModuleNameAsNodeModule({ path, isRedirect }, { getCanonicalFileNa const mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main || "index.js"; if (isString(mainFileRelative) && !(maybeBlockedByTypesVersions && matchPatternOrExact(tryParsePatterns(versionPaths.paths), mainFileRelative))) { const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (removeFileExtension(mainExportFile) === removeFileExtension(getCanonicalFileName(moduleFileToTry))) { + const canonicalModuleFileToTry = getCanonicalFileName(moduleFileToTry); + if (removeFileExtension(mainExportFile) === removeFileExtension(canonicalModuleFileToTry)) { + return { packageRootPath, moduleFileToTry }; + } else if (packageJsonContent.type !== "module" && !fileExtensionIsOneOf(canonicalModuleFileToTry, extensionsNotSupportingExtensionlessResolution) && startsWith(canonicalModuleFileToTry, mainExportFile) && getDirectoryPath(canonicalModuleFileToTry) === removeTrailingDirectorySeparator(mainExportFile) && removeFileExtension(getBaseFileName(canonicalModuleFileToTry)) === "index") { return { packageRootPath, moduleFileToTry }; } } @@ -47039,7 +47104,7 @@ function tryGetAnyFileFromPath(host, path) { } function getPathsRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { return mapDefined(rootDirs, (rootDir) => { - const relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + const relativePath = getRelativePathIfInSameVolume(path, rootDir, getCanonicalFileName); return relativePath !== void 0 && isPathRelativeToParent(relativePath) ? void 0 : relativePath; }); } @@ -47051,7 +47116,11 @@ function processEnding(fileName, allowedEndings, options, host) { if (fileName === noExtension) { return fileName; } - if (fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".d.cts" /* Dcts */, ".cts" /* Cts */])) { + const jsPriority = allowedEndings.indexOf(2 /* JsExtension */); + const tsPriority = allowedEndings.indexOf(3 /* TsExtension */); + if (fileExtensionIsOneOf(fileName, [".mts" /* Mts */, ".cts" /* Cts */]) && tsPriority !== -1 && tsPriority < jsPriority) { + return fileName; + } else if (fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".d.cts" /* Dcts */, ".cts" /* Cts */])) { return noExtension + getJSExtensionForFile(fileName, options); } else if (!fileExtensionIsOneOf(fileName, [".d.ts" /* Dts */]) && fileExtensionIsOneOf(fileName, [".ts" /* Ts */]) && stringContains(fileName, ".d.")) { return tryGetRealFileNameForNonJsDeclarationFileName(fileName); @@ -47070,7 +47139,6 @@ function processEnding(fileName, allowedEndings, options, host) { case 3 /* TsExtension */: if (isDeclarationFileName(fileName)) { const extensionlessPriority = allowedEndings.findIndex((e) => e === 0 /* Minimal */ || e === 1 /* Index */); - const jsPriority = allowedEndings.indexOf(2 /* JsExtension */); return extensionlessPriority !== -1 && extensionlessPriority < jsPriority ? noExtension : noExtension + getJSExtensionForFile(fileName, options); } return fileName; @@ -47113,7 +47181,7 @@ function tryGetJSExtensionForFile(fileName, options) { return void 0; } } -function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { +function getRelativePathIfInSameVolume(path, directoryPath, getCanonicalFileName) { const relativePath = getRelativePathToDirectoryOrUrl( directoryPath, path, @@ -47276,18 +47344,6 @@ function isInstantiatedModule(node, preserveConstEnums) { return moduleState === 1 /* Instantiated */ || preserveConstEnums && moduleState === 2 /* ConstEnumOnly */; } function createTypeChecker(host) { - var getPackagesMap = memoize(() => { - var map2 = /* @__PURE__ */ new Map(); - host.getSourceFiles().forEach((sf) => { - if (!sf.resolvedModules) - return; - sf.resolvedModules.forEach(({ resolvedModule }) => { - if (resolvedModule == null ? void 0 : resolvedModule.packageId) - map2.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!map2.get(resolvedModule.packageId.name)); - }); - }); - return map2; - }); var deferredDiagnosticsCallbacks = []; var addLazyDiagnostic = (arg) => { deferredDiagnosticsCallbacks.push(arg); @@ -47296,7 +47352,7 @@ function createTypeChecker(host) { var requestedExternalEmitHelperNames = /* @__PURE__ */ new Set(); var requestedExternalEmitHelpers; var externalHelpersModule; - var Symbol46 = objectAllocator.getSymbolConstructor(); + var Symbol47 = objectAllocator.getSymbolConstructor(); var Type27 = objectAllocator.getTypeConstructor(); var Signature15 = objectAllocator.getSignatureConstructor(); var typeCount = 0; @@ -48018,7 +48074,7 @@ function createTypeChecker(host) { getGlobalIterableType: getGlobalAsyncIterableType, getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType, getGlobalGeneratorType: getGlobalAsyncGeneratorType, - resolveIterationType: getAwaitedType, + resolveIterationType: (type, errorNode) => getAwaitedType(type, errorNode, Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member), mustHaveANextMethodDiagnostic: Diagnostics.An_async_iterator_must_have_a_next_method, mustBeAMethodDiagnostic: Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method, mustHaveAValueDiagnostic: Diagnostics.The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property @@ -48300,13 +48356,14 @@ function createTypeChecker(host) { return diagnostic; } function isDeprecatedSymbol(symbol) { - if (length(symbol.declarations) > 1) { - const parentSymbol = getParentOfSymbol(symbol); - if (parentSymbol && parentSymbol.flags & 64 /* Interface */) { - return some(symbol.declarations, (d) => !!(getCombinedNodeFlags(d) & 268435456 /* Deprecated */)); - } + const parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol && length(symbol.declarations) > 1) { + return parentSymbol.flags & 64 /* Interface */ ? some(symbol.declarations, isDeprecatedDeclaration2) : every(symbol.declarations, isDeprecatedDeclaration2); } - return !!(getDeclarationNodeFlagsFromSymbol(symbol) & 268435456 /* Deprecated */); + return !!symbol.valueDeclaration && isDeprecatedDeclaration2(symbol.valueDeclaration) || length(symbol.declarations) && every(symbol.declarations, isDeprecatedDeclaration2); + } + function isDeprecatedDeclaration2(declaration) { + return !!(getCombinedNodeFlags(declaration) & 268435456 /* Deprecated */); } function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { const diagnostic = createDiagnosticForNode(location, Diagnostics._0_is_deprecated, deprecatedEntity); @@ -48318,7 +48375,7 @@ function createTypeChecker(host) { } function createSymbol(flags, name, checkFlags) { symbolCount++; - const symbol = new Symbol46(flags | 33554432 /* Transient */, name); + const symbol = new Symbol47(flags | 33554432 /* Transient */, name); symbol.links = new SymbolLinks(); symbol.links.checkFlags = checkFlags || 0 /* None */; return symbol; @@ -48660,7 +48717,7 @@ function createTypeChecker(host) { return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { + if (getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */ && useDefineForClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration( declaration, usage, @@ -48823,6 +48880,10 @@ function createTypeChecker(host) { if (name === "const" && isConstAssertion(location)) { return void 0; } + if (isModuleDeclaration(location) && lastLocation && location.name === lastLocation) { + lastLocation = location; + location = location.parent; + } if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) { if (result = lookup(location.locals, name, meaning)) { let useResult = true; @@ -49013,6 +49074,11 @@ function createTypeChecker(host) { } } break; + case 280 /* ExportSpecifier */: + if (lastLocation && lastLocation === location.propertyName && location.parent.parent.moduleSpecifier) { + location = location.parent.parent.parent; + } + break; } if (isSelfReferenceLocation(location)) { lastSelfReferenceLocation = location; @@ -49060,7 +49126,7 @@ function createTypeChecker(host) { if (!result) { if (nameNotFoundMessage) { addLazyDiagnostic(() => { - if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 + if (!errorLocation || errorLocation.parent.kind !== 330 /* 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)) { let suggestion; let suggestedLib; @@ -50613,35 +50679,9 @@ function createTypeChecker(host) { } } function errorOnImplicitAnyModule(isError, errorNode, sourceFile, mode, { packageId, resolvedFileName }, moduleReference) { - var _a, _b; let errorInfo; if (!isExternalModuleNameRelative(moduleReference) && packageId) { - const node10Result = (_b = (_a = sourceFile.resolvedModules) == null ? void 0 : _a.get(moduleReference, mode)) == null ? void 0 : _b.node10Result; - errorInfo = node10Result ? chainDiagnosticMessages( - /*details*/ - void 0, - 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(packageId.name)}` : packageId.name - ) : typesPackageExists(packageId.name) ? chainDiagnosticMessages( - /*details*/ - void 0, - 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, - packageId.name, - mangleScopedPackageName(packageId.name) - ) : packageBundlesTypes(packageId.name) ? chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1, - packageId.name, - moduleReference - ) : chainDiagnosticMessages( - /*details*/ - void 0, - 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(packageId.name) - ); + errorInfo = createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageId.name); } errorOrSuggestion(isError, errorNode, chainDiagnosticMessages( errorInfo, @@ -50650,12 +50690,6 @@ function createTypeChecker(host) { resolvedFileName )); } - function typesPackageExists(packageName) { - return getPackagesMap().has(getTypesPackageName(packageName)); - } - function packageBundlesTypes(packageName) { - return !!getPackagesMap().get(packageName); - } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { if (moduleSymbol == null ? void 0 : moduleSymbol.exports) { const exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias); @@ -51818,7 +51852,7 @@ function createTypeChecker(host) { } if (type.flags & 128 /* StringLiteral */) { context.approximateLength += type.value.length + 2; - return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 33554432 /* NoAsciiEscaping */)); + return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */)); } if (type.flags & 256 /* NumberLiteral */) { const value = type.value; @@ -52706,7 +52740,7 @@ function createTypeChecker(host) { const typePredicate = getTypePredicateOfSignature(signature); if (typePredicate) { const assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? factory.createToken(131 /* AssertsKeyword */) : void 0; - const parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? setEmitFlags(factory.createIdentifier(typePredicate.parameterName), 33554432 /* NoAsciiEscaping */) : factory.createThisTypeNode(); + const parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? setEmitFlags(factory.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : factory.createThisTypeNode(); const typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = factory.createTypePredicateNode(assertsModifier, parameterName, typeNode); } else { @@ -52833,7 +52867,7 @@ function createTypeChecker(host) { const modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && canHaveModifiers(parameterDeclaration) ? map(getModifiers(parameterDeclaration), factory.cloneNode) : void 0; const isRest = parameterDeclaration && isRestParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 32768 /* RestParameter */; const dotDotDotToken = isRest ? factory.createToken(26 /* DotDotDotToken */) : void 0; - const name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 80 /* Identifier */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), 33554432 /* NoAsciiEscaping */) : parameterDeclaration.name.kind === 165 /* QualifiedName */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), 33554432 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol); + const name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 80 /* Identifier */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : parameterDeclaration.name.kind === 165 /* QualifiedName */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol); const isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */; const questionToken = isOptional ? factory.createToken(58 /* QuestionToken */) : void 0; const parameterNode = factory.createParameterDeclaration( @@ -52874,7 +52908,7 @@ function createTypeChecker(host) { if (!nodeIsSynthesized(visited)) { visited = factory.cloneNode(visited); } - return setEmitFlags(visited, 1 /* SingleLine */ | 33554432 /* NoAsciiEscaping */); + return setEmitFlags(visited, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); } } } @@ -53199,7 +53233,7 @@ function createTypeChecker(host) { return factory.createIndexedAccessTypeNode(factory.createTypeReferenceNode(LHS, typeParameterNodes), factory.createLiteralTypeNode(factory.createStringLiteral(symbolName2))); } } - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; @@ -53285,7 +53319,7 @@ function createTypeChecker(host) { if (index === 0) { context.flags ^= 16777216 /* InInitialEntityName */; } - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; @@ -53310,7 +53344,7 @@ function createTypeChecker(host) { return factory.createStringLiteral(getSpecifierForModuleSymbol(symbol2, context)); } if (index === 0 || canUsePropertyAccess(symbolName2, languageVersion)) { - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; @@ -53327,7 +53361,7 @@ function createTypeChecker(host) { expression = factory.createNumericLiteral(+symbolName2); } if (!expression) { - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; @@ -53480,7 +53514,7 @@ function createTypeChecker(host) { const type = getDeclaredTypeOfSymbol(sym); const name = sym.flags & 262144 /* TypeParameter */ && !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration) ? typeParameterToName(type, context) : factory.cloneNode(node); name.symbol = sym; - return { introducesError, node: setEmitFlags(setOriginalNode(name, node), 33554432 /* NoAsciiEscaping */) }; + return { introducesError, node: setEmitFlags(setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */) }; } } return { introducesError, node }; @@ -53923,7 +53957,7 @@ function createTypeChecker(host) { if (symbol.flags & 524288 /* TypeAlias */) { serializeTypeAlias(symbol, symbolName2, modifierFlags); } - if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && symbol.escapedName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) && !(symbol.flags & 32 /* Class */) && !(symbol.flags & 8192 /* Method */) && !isConstMergedWithNSPrintableAsSignatureMerge) { + if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */ | 98304 /* Accessor */) && symbol.escapedName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) && !(symbol.flags & 32 /* Class */) && !(symbol.flags & 8192 /* Method */) && !isConstMergedWithNSPrintableAsSignatureMerge) { if (propertyAsAlias) { const createdExport = serializeMaybeAliasAssignment(symbol); if (createdExport) { @@ -54341,7 +54375,7 @@ function createTypeChecker(host) { context.enclosingDeclaration = originalDecl || oldEnclosing; const localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); const typeParamDecls = map(localParams, (p) => typeParameterToDeclaration(p, context)); - const classType = getDeclaredTypeOfClassOrInterface(symbol); + const classType = getTypeWithThisArgument(getDeclaredTypeOfClassOrInterface(symbol)); const baseTypes = getBaseTypes(classType); const originalImplements = originalDecl && getEffectiveImplementsTypeNodes(originalDecl); const implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements) || mapDefined(getImplementsTypes(classType), serializeImplementedType); @@ -55540,7 +55574,7 @@ function createTypeChecker(host) { const elementType = checkIteratedTypeOrElementType(65 /* Destructuring */ | (declaration.dotDotDotToken ? 0 : 128 /* PossiblyOutOfBounds */), parentType, undefinedType, pattern); const index = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - const baseConstraint = getBaseConstraintOrType(parentType); + const baseConstraint = mapType(parentType, (t) => t.flags & 58982400 /* InstantiableNonPrimitive */ ? getBaseConstraintOrType(t) : t); type = everyType(baseConstraint, isTupleType) ? mapType(baseConstraint, (t) => sliceTupleType(t, index)) : createArrayType(elementType); } else if (isArrayLikeType(parentType)) { const indexType = getNumberLiteralType(index); @@ -57268,6 +57302,9 @@ function createTypeChecker(host) { } return needApparentType ? getApparentType(type) : type; } + function getThisArgument(type) { + return getObjectFlags(type) & 4 /* Reference */ && length(getTypeArguments(type)) > getTypeReferenceArity(type) ? last(getTypeArguments(type)) : type; + } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { let mapper; let members; @@ -57398,7 +57435,7 @@ function createTypeChecker(host) { } return [sig.parameters]; function expandSignatureParametersWithTupleMembers(restType, restIndex) { - const elementTypes = getTypeArguments(restType); + const elementTypes = getElementTypes(restType); const associatedNames = getUniqAssociatedNamesFromTupleType(restType); const restParams = map(elementTypes, (t, i) => { const name = associatedNames && associatedNames[i] ? associatedNames[i] : getParameterNameAtPosition(sig, restIndex + i, restType); @@ -58214,7 +58251,7 @@ function createTypeChecker(host) { } function isConstTypeVariable(type) { var _a; - return !!(type && (type.flags & 262144 /* TypeParameter */ && some((_a = type.symbol) == null ? void 0 : _a.declarations, (d) => hasSyntacticModifier(d, 2048 /* Const */)) || type.flags & 1048576 /* Union */ && some(type.types, isConstTypeVariable) || type.flags & 8388608 /* IndexedAccess */ && isConstTypeVariable(type.objectType) || type.flags & 16777216 /* Conditional */ && isConstTypeVariable(getConstraintOfConditionalType(type)) || type.flags & 33554432 /* Substitution */ && isConstTypeVariable(type.baseType) || isGenericTupleType(type) && findIndex(getTypeArguments(type), (t, i) => !!(type.target.elementFlags[i] & 8 /* Variadic */) && isConstTypeVariable(t)) >= 0)); + return !!(type && (type.flags & 262144 /* TypeParameter */ && some((_a = type.symbol) == null ? void 0 : _a.declarations, (d) => hasSyntacticModifier(d, 2048 /* Const */)) || type.flags & 1048576 /* Union */ && some(type.types, isConstTypeVariable) || type.flags & 8388608 /* IndexedAccess */ && isConstTypeVariable(type.objectType) || type.flags & 16777216 /* Conditional */ && isConstTypeVariable(getConstraintOfConditionalType(type)) || type.flags & 33554432 /* Substitution */ && isConstTypeVariable(type.baseType) || isGenericTupleType(type) && findIndex(getElementTypes(type), (t, i) => !!(type.target.elementFlags[i] & 8 /* Variadic */) && isConstTypeVariable(t)) >= 0)); } function getConstraintOfIndexedAccess(type) { return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : void 0; @@ -58316,7 +58353,7 @@ function createTypeChecker(host) { return void 0; } function getBaseConstraintOfType(type) { - if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) { + if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) || isGenericTupleType(type)) { const constraint = getResolvedBaseConstraint(type); return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : void 0; } @@ -58333,7 +58370,7 @@ function createTypeChecker(host) { return type.resolvedBaseConstraint; } const stack = []; - return type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type); + return type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), getThisArgument(type)); function getImmediateBaseConstraint(t) { if (!t.immediateBaseConstraint) { if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { @@ -58423,6 +58460,13 @@ function createTypeChecker(host) { if (t.flags & 33554432 /* Substitution */) { return getBaseConstraint(getSubstitutionIntersection(t)); } + if (isGenericTupleType(t)) { + const newElements = map(getElementTypes(t), (v, i) => { + const constraint = t.target.elementFlags[i] & 8 /* Variadic */ && getBaseConstraint(v) || v; + return constraint && everyType(constraint, (c) => isArrayOrTupleType(c) && !isGenericTupleType(c)) ? constraint : v; + }); + return createTupleType(newElements, t.target.elementFlags, t.target.readonly, t.target.labeledElementDeclarations); + } return t; } } @@ -58963,7 +59007,8 @@ function createTypeChecker(host) { thisParameter = createSymbolWithType(createSymbol(1 /* FunctionScopedVariable */, "this" /* This */), getTypeFromTypeNode(thisTag.typeExpression)); } } - const classType = declaration.kind === 175 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : void 0; + const hostDeclaration = isJSDocSignature(declaration) ? getEffectiveJSDocHost(declaration) : declaration; + const classType = hostDeclaration && isConstructorDeclaration(hostDeclaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(hostDeclaration.parent.symbol)) : void 0; const typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); if (hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { flags |= 1 /* HasRestParameter */; @@ -59189,16 +59234,16 @@ function createTypeChecker(host) { if (declaration.kind === 175 /* Constructor */) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); } + const typeNode = getEffectiveReturnTypeNode(declaration); if (isJSDocSignature(declaration)) { const root = getJSDocRoot(declaration); - if (root && isConstructorDeclaration(root.parent)) { + if (root && isConstructorDeclaration(root.parent) && !typeNode) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(root.parent.parent.symbol)); } } if (isJSDocConstructSignature(declaration)) { return getTypeFromTypeNode(declaration.parameters[0].type); } - const typeNode = getEffectiveReturnTypeNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); } @@ -60476,7 +60521,7 @@ function createTypeChecker(host) { if (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type)) { addElement(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) == null ? void 0 : _a[i]); } else if (isTupleType(type)) { - const elements = getTypeArguments(type); + const elements = getElementTypes(type); if (elements.length + expandedTypes.length >= 1e4) { 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; @@ -60554,6 +60599,11 @@ function createTypeChecker(host) { function getEndElementCount(type, flags) { return type.elementFlags.length - findLastIndex(type.elementFlags, (f) => !(f & flags)) - 1; } + function getElementTypes(type) { + const typeArguments = getTypeArguments(type); + const arity = getTypeReferenceArity(type); + return typeArguments.length === arity ? typeArguments : typeArguments.slice(0, arity); + } function getTypeFromOptionalTypeNode(node) { return addOptionality( getTypeFromTypeNode(node.type), @@ -61150,7 +61200,20 @@ function createTypeChecker(host) { if (isPrivateIdentifier(name)) { return neverType; } - return isIdentifier(name) ? getStringLiteralType(unescapeLeadingUnderscores(name.escapedText)) : getRegularTypeOfLiteralType(isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + if (isNumericLiteral(name)) { + return getRegularTypeOfLiteralType(checkExpression(name)); + } + if (isComputedPropertyName(name)) { + return getRegularTypeOfLiteralType(checkComputedPropertyName(name)); + } + const propertyName = getPropertyNameForPropertyNameNode(name); + if (propertyName !== void 0) { + return getStringLiteralType(unescapeLeadingUnderscores(propertyName)); + } + if (isExpression(name)) { + return getRegularTypeOfLiteralType(checkExpression(name)); + } + return neverType; } function getLiteralTypeFromProperty(prop, include, includeNonPublic) { if (includeNonPublic || !(getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { @@ -61804,7 +61867,7 @@ function createTypeChecker(host) { return isTupleTypeNode(node) && length(node.elements) > 0 && !some(node.elements, (e) => isOptionalTypeNode(e) || isRestTypeNode(e) || isNamedTupleMember(e) && !!(e.questionToken || e.dotDotDotToken)); } function isDeferredType(type, checkTuples) { - return isGenericType(type) || checkTuples && isTupleType(type) && some(getTypeArguments(type), isGenericType); + return isGenericType(type) || checkTuples && isTupleType(type) && some(getElementTypes(type), isGenericType); } function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { let result; @@ -62739,7 +62802,7 @@ function createTypeChecker(host) { } function instantiateMappedGenericTupleType(tupleType, mappedType, typeVariable, mapper) { const elementFlags = tupleType.target.elementFlags; - const elementTypes = map(getTypeArguments(tupleType), (t, i) => { + const elementTypes = map(getElementTypes(tupleType), (t, i) => { const singleton = elementFlags[i] & 8 /* Variadic */ ? t : elementFlags[i] & 4 /* Rest */ ? createArrayType(t) : createTupleType([t], [elementFlags[i]]); return instantiateMappedType(mappedType, prependTypeMapping(typeVariable, singleton, mapper)); }); @@ -62758,7 +62821,7 @@ function createTypeChecker(host) { } function instantiateMappedTupleType(tupleType, mappedType, mapper) { const elementFlags = tupleType.target.elementFlags; - const elementTypes = map(getTypeArguments(tupleType), (_, i) => instantiateMappedTypeTemplate(mappedType, getStringLiteralType("" + i), !!(elementFlags[i] & 2 /* Optional */), mapper)); + const elementTypes = map(getElementTypes(tupleType), (_, i) => instantiateMappedTypeTemplate(mappedType, getStringLiteralType("" + i), !!(elementFlags[i] & 2 /* Optional */), mapper)); const modifiers = getMappedTypeModifiers(mappedType); const newTupleModifiers = modifiers & 4 /* IncludeOptional */ ? map(elementFlags, (f) => f & 1 /* Required */ ? 2 /* Optional */ : f) : modifiers & 8 /* ExcludeOptional */ ? map(elementFlags, (f) => f & 2 /* Optional */ ? 1 /* Required */ : f) : elementFlags; const newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers); @@ -63944,7 +64007,7 @@ function createTypeChecker(host) { return type; } function getNormalizedTupleType(type, writing) { - const elements = getTypeArguments(type); + const elements = getElementTypes(type); const normalizedElements = sameMap(elements, (t) => t.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(t, writing) : t); return elements !== normalizedElements ? createNormalizedTupleType(type.target, normalizedElements) : type; } @@ -64233,6 +64296,8 @@ function createTypeChecker(host) { return isRelatedTo(source2, target2, 3 /* Both */, reportErrors2); } function isRelatedTo(originalSource, originalTarget, recursionFlags = 3 /* Both */, reportErrors2 = false, headMessage2, intersectionState = 0 /* None */) { + if (originalSource === originalTarget) + return -1 /* True */; if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 402784252 /* Primitive */) { if (relation === comparableRelation && !(originalTarget.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(originalTarget, originalSource, relation) || isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors2 ? reportError : void 0)) { return -1 /* True */; @@ -65451,6 +65516,11 @@ function createTypeChecker(host) { } else { return 0 /* False */; } + } else if (isGenericTupleType(source2) && isTupleType(target2) && !isGenericTupleType(target2)) { + const constraint = getBaseConstraintOrType(source2); + if (constraint !== source2) { + return isRelatedTo(constraint, target2, 1 /* Source */, reportErrors2); + } } else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target2) && getObjectFlags(target2) & 8192 /* FreshLiteral */ && !isEmptyObjectType(source2)) { return 0 /* False */; } @@ -67366,7 +67436,7 @@ function createTypeChecker(host) { return type; } function isPartiallyInferableType(type) { - return !(getObjectFlags(type) & 262144 /* NonInferrableType */) || isObjectLiteralType2(type) && some(getPropertiesOfType(type), (prop) => isPartiallyInferableType(getTypeOfSymbol(prop))) || isTupleType(type) && some(getTypeArguments(type), isPartiallyInferableType); + return !(getObjectFlags(type) & 262144 /* NonInferrableType */) || isObjectLiteralType2(type) && some(getPropertiesOfType(type), (prop) => isPartiallyInferableType(getTypeOfSymbol(prop))) || isTupleType(type) && some(getElementTypes(type), isPartiallyInferableType); } function createReverseMappedType(source, target, constraint) { if (!(getIndexInfoOfType(source, stringType) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) { @@ -67376,7 +67446,7 @@ function createTypeChecker(host) { return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source)); } if (isTupleType(source)) { - const elementTypes = map(getTypeArguments(source), (t) => inferReverseMappedType(t, target, constraint)); + const elementTypes = map(getElementTypes(source), (t) => inferReverseMappedType(t, target, constraint)); const elementFlags = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? sameMap(source.target.elementFlags, (f) => f & 2 /* Optional */ ? 1 /* Required */ : f) : source.target.elementFlags; return createTupleType(elementTypes, elementFlags, source.target.readonly, source.target.labeledElementDeclarations); } @@ -68212,14 +68282,14 @@ function createTypeChecker(host) { const inference = context.inferences[index]; if (!inference.inferredType) { let inferredType; - const signature = context.signature; - if (signature) { - const inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : void 0; - if (inference.contraCandidates) { - const useCovariantType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* 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))); - inferredType = useCovariantType ? inferredCovariantType : getContravariantInference(inference); - } else if (inferredCovariantType) { - inferredType = inferredCovariantType; + let fallbackType; + if (context.signature) { + const inferredCovariantType = inference.candidates ? getCovariantInference(inference, context.signature) : void 0; + const inferredContravariantType = inference.contraCandidates ? getContravariantInference(inference) : void 0; + if (inferredCovariantType || inferredContravariantType) { + const preferCovariantType = inferredCovariantType && (!inferredContravariantType || !(inferredCovariantType.flags & 131072 /* 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)))); + inferredType = preferCovariantType ? inferredCovariantType : inferredContravariantType; + fallbackType = preferCovariantType ? inferredContravariantType : inferredCovariantType; } else if (context.flags & 1 /* NoDefault */) { inferredType = silentNeverType; } else { @@ -68236,7 +68306,7 @@ function createTypeChecker(host) { if (constraint) { const instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper); if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - inference.inferredType = inferredType = instantiatedConstraint; + inference.inferredType = fallbackType && context.compareTypes(fallbackType, getTypeWithThisArgument(instantiatedConstraint, fallbackType)) ? fallbackType : instantiatedConstraint; } } } @@ -70456,7 +70526,7 @@ function createTypeChecker(host) { markAliasReferenced(symbol, node); } const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - const targetSymbol = checkDeprecatedAliasedSymbol(localOrExportSymbol, node); + const targetSymbol = resolveAliasWithDeprecationCheck(localOrExportSymbol, node); if (isDeprecatedSymbol(targetSymbol) && isUncalledFunctionReference(node, targetSymbol) && targetSymbol.declarations) { addDeprecatedSuggestion(node, targetSymbol.declarations, node.escapedText); } @@ -71549,7 +71619,7 @@ function createTypeChecker(host) { return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType2(conditional, contextFlags) : void 0; } function getContextualTypeForChildJsxExpression(node, child, contextFlags) { - const attributesType = getApparentTypeOfContextualType(node.openingElement.tagName, contextFlags); + const attributesType = getApparentTypeOfContextualType(node.openingElement.attributes, contextFlags); const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { return void 0; @@ -71625,6 +71695,7 @@ function createTypeChecker(host) { ); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { + const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); return discriminateTypeByDiscriminableItems( contextualType, concatenate( @@ -71635,7 +71706,14 @@ function createTypeChecker(host) { map( filter(getPropertiesOfType(contextualType), (s) => { var _a; - return !!(s.flags & 16777216 /* Optional */) && !!((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); + if (!(s.flags & 16777216 /* Optional */) || !((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members)) { + return false; + } + const element = node.parent.parent; + if (s.escapedName === jsxChildrenPropertyName && isJsxElement(element) && getSemanticJsxChildren(element.children).length) { + return false; + } + return !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), (s) => [() => undefinedType, s.escapedName] ) @@ -71877,18 +71955,10 @@ function createTypeChecker(host) { function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { const managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { - const declaredManagedType = getDeclaredTypeOfSymbol(managedSym); const ctorType = getStaticTypeOfReferencedJsxConstructor(context); - if (managedSym.flags & 524288 /* TypeAlias */) { - const params = getSymbolLinks(managedSym).typeParameters; - if (length(params) >= 2) { - const args = fillMissingTypeArguments([ctorType, attributesType], params, 2, isInJSFile(context)); - return getTypeAliasInstantiation(managedSym, args); - } - } - if (length(declaredManagedType.typeParameters) >= 2) { - const args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, isInJSFile(context)); - return createTypeReference(declaredManagedType, args); + const result = instantiateAliasOrInterfaceWithDefaults(managedSym, isInJSFile(context), ctorType, attributesType); + if (result) { + return result; } } return attributesType; @@ -72246,7 +72316,7 @@ function createTypeChecker(host) { } return links.immediateTarget; } - function checkObjectLiteral(node, checkMode) { + function checkObjectLiteral(node, checkMode = 0 /* Normal */) { var _a; const inDestructuringPattern = isAssignmentTarget(node); checkGrammarObjectLiteralExpression(node, inDestructuringPattern); @@ -72329,7 +72399,7 @@ function createTypeChecker(host) { prop.links.target = member; member = prop; allPropertiesTable == null ? void 0 : allPropertiesTable.set(prop.escapedName, prop); - if (contextualType && checkMode && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && (memberDecl.kind === 302 /* PropertyAssignment */ || memberDecl.kind === 173 /* MethodDeclaration */) && isContextSensitive(memberDecl)) { + if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && (memberDecl.kind === 302 /* PropertyAssignment */ || memberDecl.kind === 173 /* MethodDeclaration */) && isContextSensitive(memberDecl)) { const inferenceContext = getInferenceContext(node); Debug.assert(inferenceContext); const inferenceNode = memberDecl.kind === 302 /* PropertyAssignment */ ? memberDecl.initializer : memberDecl; @@ -72347,7 +72417,7 @@ function createTypeChecker(host) { hasComputedNumberProperty = false; hasComputedSymbolProperty = false; } - const type = getReducedType(checkExpression(memberDecl.expression)); + const type = getReducedType(checkExpression(memberDecl.expression, checkMode & 2 /* Inferential */)); if (isValidSpreadType(type)) { const mergedType = tryMergeUnionOfObjectTypeAndEmptyObject(type, inConstContext); if (allPropertiesTable) { @@ -72488,7 +72558,7 @@ function createTypeChecker(host) { function checkJsxAttribute(node, checkMode) { return node.initializer ? checkExpressionForMutableLocation(node.initializer, checkMode) : trueType; } - function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode = 0 /* Normal */) { const attributes = openingLikeElement.attributes; const contextualType = getContextualType2(attributes, 0 /* None */); const allAttributesTable = strictNullChecks ? createSymbolTable() : void 0; @@ -72523,7 +72593,7 @@ function createTypeChecker(host) { addDeprecatedSuggestion(attributeDecl.name, prop.declarations, attributeDecl.name.escapedText); } } - if (contextualType && checkMode && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && isContextSensitive(attributeDecl)) { + if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && isContextSensitive(attributeDecl)) { const inferenceContext = getInferenceContext(attributes); Debug.assert(inferenceContext); const inferenceNode = attributeDecl.initializer.expression; @@ -72542,7 +72612,7 @@ function createTypeChecker(host) { ); attributesTable = createSymbolTable(); } - const exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode)); + const exprType = getReducedType(checkExpression(attributeDecl.expression, checkMode & 2 /* Inferential */)); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } @@ -72775,6 +72845,9 @@ function createTypeChecker(host) { function getJsxLibraryManagedAttributes(jsxNamespace) { return jsxNamespace && getSymbol2(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */); } + function getJsxElementTypeSymbol(jsxNamespace) { + return jsxNamespace && getSymbol2(jsxNamespace.exports, JsxNames.ElementType, 788968 /* Type */); + } function getJsxElementPropertiesName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); } @@ -72881,11 +72954,32 @@ function createTypeChecker(host) { } } function getJsxElementTypeTypeAt(location) { - const type = getJsxType(JsxNames.ElementType, location); - if (isErrorType(type)) + const ns = getJsxNamespaceAt(location); + if (!ns) + return void 0; + const sym = getJsxElementTypeSymbol(ns); + if (!sym) + return void 0; + const type = instantiateAliasOrInterfaceWithDefaults(sym, isInJSFile(location)); + if (!type || isErrorType(type)) return void 0; return type; } + function instantiateAliasOrInterfaceWithDefaults(managedSym, inJs, ...typeArguments) { + const declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + if (managedSym.flags & 524288 /* TypeAlias */) { + const params = getSymbolLinks(managedSym).typeParameters; + if (length(params) >= typeArguments.length) { + const args = fillMissingTypeArguments(typeArguments, params, typeArguments.length, inJs); + return length(args) === 0 ? declaredManagedType : getTypeAliasInstantiation(managedSym, args); + } + } + if (length(declaredManagedType.typeParameters) >= typeArguments.length) { + const args = fillMissingTypeArguments(typeArguments, declaredManagedType.typeParameters, typeArguments.length, inJs); + return createTypeReference(declaredManagedType, args); + } + return void 0; + } function getJsxIntrinsicTagNamesAt(location) { const intrinsics = getJsxType(JsxNames.IntrinsicElements, location); return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; @@ -73436,8 +73530,9 @@ function createTypeChecker(host) { addDeprecatedSuggestion(right, [indexInfo.declaration], right.escapedText); } } else { - if (isDeprecatedSymbol(prop) && isUncalledFunctionReference(node, prop) && prop.declarations) { - addDeprecatedSuggestion(right, prop.declarations, right.escapedText); + const targetPropSymbol = resolveAliasWithDeprecationCheck(prop, right); + if (isDeprecatedSymbol(targetPropSymbol) && isUncalledFunctionReference(node, targetPropSymbol) && targetPropSymbol.declarations) { + addDeprecatedSuggestion(right, targetPropSymbol.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, isSelfTypeAccess(left, parentSymbol)); @@ -74132,7 +74227,7 @@ function createTypeChecker(host) { } function getMutableArrayOrTupleType(type) { return type.flags & 1048576 /* Union */ ? mapType(type, getMutableArrayOrTupleType) : type.flags & 1 /* Any */ || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type : isTupleType(type) ? createTupleType( - getTypeArguments(type), + getElementTypes(type), type.target.elementFlags, /*readonly*/ false, @@ -74248,7 +74343,7 @@ function createTypeChecker(host) { if (getJsxNamespaceContainerForImplicitImport(node)) { return true; } - const tagType = isJsxOpeningElement(node) || isJsxSelfClosingElement(node) && !isJsxIntrinsicTagName(node.tagName) ? checkExpression(node.tagName) : void 0; + const tagType = (isJsxOpeningElement(node) || isJsxSelfClosingElement(node)) && !(isJsxIntrinsicTagName(node.tagName) || isJsxNamespacedName(node.tagName)) ? checkExpression(node.tagName) : void 0; if (!tagType) { return true; } @@ -74446,7 +74541,7 @@ function createTypeChecker(host) { const arg = args[i]; const spreadType = arg.kind === 229 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); if (spreadType && isTupleType(spreadType)) { - forEach(getTypeArguments(spreadType), (t, i2) => { + forEach(getElementTypes(spreadType), (t, i2) => { var _a; const flags = spreadType.target.elementFlags[i2]; const syntheticArg = createSyntheticExpression( @@ -75973,6 +76068,8 @@ function createTypeChecker(host) { } return getRegularTypeOfLiteralType(exprType); } + const links = getNodeLinks(node); + links.assertionExpressionType = exprType; checkSourceElement(type); checkNodeDeferred(node); return getTypeFromTypeNode(type); @@ -75994,9 +76091,11 @@ function createTypeChecker(host) { return { type, expression }; } function checkAssertionDeferred(node) { - const { type, expression } = getAssertionTypeAndExpression(node); + const { type } = getAssertionTypeAndExpression(node); const errNode = isParenthesizedExpression(node) ? type : node; - const exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression))); + const links = getNodeLinks(node); + Debug.assertIsDefined(links.assertionExpressionType); + const exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(links.assertionExpressionType)); const targetType = getTypeFromTypeNode(type); if (!isErrorType(targetType)) { addLazyDiagnostic(() => { @@ -76960,6 +77059,10 @@ function createTypeChecker(host) { forEachReturnStatement(func.body, (returnStatement) => { const expr = returnStatement.expression; if (expr) { + if (expr.kind === 212 /* CallExpression */ && expr.expression.kind === 80 /* Identifier */ && checkExpressionCached(expr.expression).symbol === func.symbol) { + hasReturnOfTypeNever = true; + return; + } let type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */); if (functionFlags & 2 /* Async */) { type = unwrapAwaitedType(checkAwaitedType( @@ -78440,7 +78543,7 @@ function createTypeChecker(host) { } function padTupleType(type, pattern) { const patternElements = pattern.elements; - const elementTypes = getTypeArguments(type).slice(); + const elementTypes = getElementTypes(type).slice(); const elementFlags = type.target.elementFlags.slice(); for (let i = getTypeReferenceArity(type); i < patternElements.length; i++) { const e = patternElements[i]; @@ -83713,19 +83816,17 @@ function createTypeChecker(host) { } } if (isImportSpecifier(node)) { - const targetSymbol = checkDeprecatedAliasedSymbol(symbol, node); - if (isDeprecatedAliasedSymbol(targetSymbol) && targetSymbol.declarations) { + const targetSymbol = resolveAliasWithDeprecationCheck(symbol, node); + if (isDeprecatedSymbol(targetSymbol) && targetSymbol.declarations) { addDeprecatedSuggestion(node, targetSymbol.declarations, targetSymbol.escapedName); } } } } - function isDeprecatedAliasedSymbol(symbol) { - return !!symbol.declarations && every(symbol.declarations, (d) => !!(getCombinedNodeFlags(d) & 268435456 /* Deprecated */)); - } - function checkDeprecatedAliasedSymbol(symbol, location) { - if (!(symbol.flags & 2097152 /* Alias */)) + function resolveAliasWithDeprecationCheck(symbol, location) { + if (!(symbol.flags & 2097152 /* Alias */) || isDeprecatedSymbol(symbol) || !getDeclarationOfAliasSymbol(symbol)) { return symbol; + } const targetSymbol = resolveAlias(symbol); if (targetSymbol === unknownSymbol) return targetSymbol; @@ -83735,7 +83836,7 @@ function createTypeChecker(host) { if (target === targetSymbol) break; if (target.declarations && length(target.declarations)) { - if (isDeprecatedAliasedSymbol(target)) { + if (isDeprecatedSymbol(target)) { addDeprecatedSuggestion(location, target.declarations, target.escapedName); break; } else { @@ -84828,7 +84929,7 @@ function createTypeChecker(host) { name, meaning, /*ignoreErrors*/ - false, + true, /*dontResolveAlias*/ true, getHostSignatureFromJSDoc(name) @@ -84839,7 +84940,7 @@ function createTypeChecker(host) { return resolveJSDocMemberName( name, /*ignoreErrors*/ - false, + true, getSymbolOfDeclaration(container) ); } @@ -85692,6 +85793,41 @@ function createTypeChecker(host) { } return void 0; } + function getReferencedValueDeclarations(referenceIn) { + if (!isGeneratedIdentifier(referenceIn)) { + const reference = getParseTreeNode(referenceIn, isIdentifier); + if (reference) { + const symbol = getReferencedValueSymbol(reference); + if (symbol) { + return filter(getExportSymbolOfValueSymbolIfExported(symbol).declarations, (declaration) => { + switch (declaration.kind) { + case 259 /* VariableDeclaration */: + case 168 /* Parameter */: + case 207 /* BindingElement */: + case 171 /* PropertyDeclaration */: + case 302 /* PropertyAssignment */: + case 303 /* ShorthandPropertyAssignment */: + case 305 /* EnumMember */: + case 209 /* ObjectLiteralExpression */: + case 261 /* FunctionDeclaration */: + case 217 /* FunctionExpression */: + case 218 /* ArrowFunction */: + case 262 /* ClassDeclaration */: + case 230 /* ClassExpression */: + case 265 /* EnumDeclaration */: + case 173 /* MethodDeclaration */: + case 176 /* GetAccessor */: + case 177 /* SetAccessor */: + case 266 /* ModuleDeclaration */: + return true; + } + return false; + }); + } + } + } + return void 0; + } function isLiteralConstDeclaration(node) { if (isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node)) { return isFreshLiteralType(getTypeOfSymbol(getSymbolOfDeclaration(node))); @@ -85790,6 +85926,7 @@ function createTypeChecker(host) { }, collectLinkedAliases, getReferencedValueDeclaration, + getReferencedValueDeclarations, getTypeReferenceSerializationKind, isOptionalParameter, moduleExportsSomeValue, @@ -89823,7 +89960,7 @@ function collectExternalModuleInfo(context, sourceFile, resolver, compilerOption case 242 /* VariableStatement */: if (hasSyntacticModifier(node, 1 /* Export */)) { for (const decl of node.declarationList.declarations) { - exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings); } } break; @@ -89885,11 +90022,11 @@ function collectExternalModuleInfo(context, sourceFile, resolver, compilerOption } } } -function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { +function collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings) { if (isBindingPattern(decl.name)) { for (const element of decl.name.elements) { if (!isOmittedExpression(element)) { - exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames, exportedBindings); } } } else if (!isGeneratedIdentifier(decl.name)) { @@ -89897,6 +90034,9 @@ function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { if (!uniqueExports.get(text)) { uniqueExports.set(text, true); exportedNames = append(exportedNames, decl.name); + if (isLocalName(decl.name)) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), decl.name); + } } } return exportedNames; @@ -91021,7 +91161,7 @@ function transformTypeScript(context) { if (promoteToIIFE) { context.startLexicalEnvironment(); } - const moveModifiers = promoteToIIFE || facts & 8 /* IsExportOfNamespace */ || facts & 2 /* HasClassOrConstructorParameterDecorators */ && legacyDecorators || facts & 1 /* HasStaticInitializedProperties */; + const moveModifiers = promoteToIIFE || facts & 8 /* IsExportOfNamespace */; let modifiers = moveModifiers ? visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike) : visitNodes2(node.modifiers, visitor, isModifierLike); if (facts & 2 /* HasClassOrConstructorParameterDecorators */) { modifiers = injectClassTypeMetadata(modifiers, node); @@ -91087,13 +91227,13 @@ function transformTypeScript(context) { } if (moveModifiers) { if (facts & 8 /* IsExportOfNamespace */) { - return demarcateMultiStatementExport( + return [ statement, createExportMemberAssignmentStatement(node) - ); + ]; } if (facts & 32 /* IsDefaultExternalExport */) { - return demarcateMultiStatementExport( + return [ statement, factory2.createExportDefault(factory2.getLocalName( node, @@ -91102,10 +91242,10 @@ function transformTypeScript(context) { /*allowSourceMaps*/ true )) - ); + ]; } if (facts & 16 /* IsNamedExternalExport */ && !promoteToIIFE) { - return demarcateMultiStatementExport( + return [ statement, factory2.createExternalModuleExport(factory2.getLocalName( node, @@ -91114,19 +91254,11 @@ function transformTypeScript(context) { /*allowSourceMaps*/ true )) - ); + ]; } } return statement; } - function demarcateMultiStatementExport(declarationStatement, exportStatement) { - addEmitFlags(declarationStatement, 8388608 /* HasEndOfDeclarationMarker */); - return [ - declarationStatement, - exportStatement, - factory2.createEndOfDeclarationMarker(declarationStatement) - ]; - } function visitClassExpression(node) { let modifiers = visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike); if (classOrConstructorParameterIsDecorated(legacyDecorators, node)) { @@ -91744,14 +91876,14 @@ function transformTypeScript(context) { } const parameterName = getNamespaceParameterName(node); const containerName = getNamespaceContainerName(node); - const exportName = hasSyntacticModifier(node, 1 /* Export */) ? factory2.getExternalModuleOrNamespaceExportName( + const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName( currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true - ) : factory2.getLocalName( + ) : factory2.getDeclarationName( node, /*allowComments*/ false, @@ -91765,7 +91897,7 @@ function transformTypeScript(context) { factory2.createObjectLiteralExpression() ) ); - if (hasNamespaceQualifiedExportName(node)) { + if (isExportOfNamespace(node)) { const localName = factory2.getLocalName( node, /*allowComments*/ @@ -91810,7 +91942,6 @@ function transformTypeScript(context) { setTextRange(enumStatement, node); addEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); - statements.push(factory2.createEndOfDeclarationMarker(node)); return statements; } function transformEnumBody(node, localName) { @@ -91883,9 +92014,6 @@ function transformTypeScript(context) { } return isInstantiatedModule(node, shouldPreserveConstEnums(compilerOptions)); } - function hasNamespaceQualifiedExportName(node) { - return isExportOfNamespace(node) || isExternalModuleExport(node) && moduleKind !== 5 /* ES2015 */ && moduleKind !== 6 /* ES2020 */ && moduleKind !== 7 /* ES2022 */ && moduleKind !== 99 /* ESNext */ && moduleKind !== 4 /* System */; - } function recordEmittedDeclarationInScope(node) { if (!currentScopeFirstDeclarationsOfName) { currentScopeFirstDeclarationsOfName = /* @__PURE__ */ new Map(); @@ -91907,20 +92035,21 @@ function transformTypeScript(context) { return node.name.escapedText; } function addVarForEnumOrModuleDeclaration(statements, node) { + const varDecl = factory2.createVariableDeclaration(factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + )); + const varFlags = currentLexicalScope.kind === 311 /* SourceFile */ ? 0 /* None */ : 1 /* Let */; const statement = factory2.createVariableStatement( visitNodes2(node.modifiers, modifierVisitor, isModifier), - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - factory2.getLocalName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ) - ) - ], currentLexicalScope.kind === 311 /* SourceFile */ ? 0 /* None */ : 1 /* Let */) + factory2.createVariableDeclarationList([varDecl], varFlags) ); + setOriginalNode(varDecl, node); + setSyntheticLeadingComments(varDecl, void 0); + setSyntheticTrailingComments(varDecl, void 0); setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -91930,15 +92059,11 @@ function transformTypeScript(context) { setSourceMapRange(statement, node); } setCommentRange(statement, node); - addEmitFlags(statement, 2048 /* NoTrailingComments */ | 8388608 /* HasEndOfDeclarationMarker */); + addEmitFlags(statement, 2048 /* NoTrailingComments */); statements.push(statement); return true; - } else { - const mergeMarker = factory2.createMergeDeclarationMarker(statement); - setEmitFlags(mergeMarker, 3072 /* NoComments */ | 8388608 /* HasEndOfDeclarationMarker */); - statements.push(mergeMarker); - return false; } + return false; } function visitModuleDeclaration(node) { if (!shouldEmitModuleDeclaration(node)) { @@ -91956,14 +92081,14 @@ function transformTypeScript(context) { } const parameterName = getNamespaceParameterName(node); const containerName = getNamespaceContainerName(node); - const exportName = hasSyntacticModifier(node, 1 /* Export */) ? factory2.getExternalModuleOrNamespaceExportName( + const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName( currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true - ) : factory2.getLocalName( + ) : factory2.getDeclarationName( node, /*allowComments*/ false, @@ -91977,7 +92102,7 @@ function transformTypeScript(context) { factory2.createObjectLiteralExpression() ) ); - if (hasNamespaceQualifiedExportName(node)) { + if (isExportOfNamespace(node)) { const localName = factory2.getLocalName( node, /*allowComments*/ @@ -92022,7 +92147,6 @@ function transformTypeScript(context) { setTextRange(moduleStatement, node); addEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); - statements.push(factory2.createEndOfDeclarationMarker(node)); return statements; } function transformModuleBody(node, namespaceLocalName) { @@ -93608,23 +93732,12 @@ function transformClassFields(context) { getClassLexicalEnvironment().classThis = node.emitNode.classThis; } } - const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); + const isExport = hasSyntacticModifier(node, 1 /* Export */); + const isDefault = hasSyntacticModifier(node, 1024 /* Default */); + let modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); const heritageClauses = visitNodes2(node.heritageClauses, heritageClauseVisitor, isHeritageClause); const { members, prologue } = transformClassMembers(node); - const classDecl = factory2.updateClassDeclaration( - node, - modifiers, - node.name, - /*typeParameters*/ - void 0, - heritageClauses, - members - ); const statements = []; - if (prologue) { - statements.push(factory2.createExpressionStatement(prologue)); - } - statements.push(classDecl); if (pendingClassReferenceAssignment) { getPendingExpressions().unshift(pendingClassReferenceAssignment); } @@ -93637,6 +93750,35 @@ function transformClassFields(context) { addPropertyOrClassStaticBlockStatements(statements, staticProperties, factory2.getInternalName(node)); } } + if (statements.length > 0 && isExport && isDefault) { + modifiers = visitNodes2(modifiers, (node2) => isExportOrDefaultModifier(node2) ? void 0 : node2, isModifier); + statements.push(factory2.createExportAssignment( + /*modifiers*/ + void 0, + /*isExportEquals*/ + false, + factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ) + )); + } + const classDecl = factory2.updateClassDeclaration( + node, + modifiers, + node.name, + /*typeParameters*/ + void 0, + heritageClauses, + members + ); + statements.unshift(classDecl); + if (prologue) { + statements.unshift(factory2.createExpressionStatement(prologue)); + } return statements; } function visitClassExpression(node, referencedName) { @@ -95074,10 +95216,6 @@ function transformLegacyDecorators(context) { true, node ) ? transformClassDeclarationWithClassDecorators(node, node.name) : transformClassDeclarationWithoutClassDecorators(node, node.name); - if (statements.length > 1) { - statements.push(factory2.createEndOfDeclarationMarker(node)); - setEmitFlags(statements[0], getEmitFlags(statements[0]) | 8388608 /* HasEndOfDeclarationMarker */); - } return singleOrMany(statements); } function decoratorContainsPrivateIdentifierInExpression(decorator) { @@ -95150,9 +95288,12 @@ function transformLegacyDecorators(context) { return addRange([updated], decorationStatements); } function transformClassDeclarationWithClassDecorators(node, name) { + const isExport = hasSyntacticModifier(node, 1 /* Export */); + const isDefault = hasSyntacticModifier(node, 1024 /* Default */); + const modifiers = visitNodes2(node.modifiers, (node2) => isExportOrDefaultModifier(node2) || isDecorator(node2) ? void 0 : node2, isModifierLike); const location = moveRangePastModifiers(node); const classAlias = getClassAliasIfNeeded(node); - const declName = languageVersion <= 2 /* ES2015 */ ? factory2.getInternalName( + const declName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName( node, /*allowComments*/ false, @@ -95169,9 +95310,21 @@ function transformLegacyDecorators(context) { let members = visitNodes2(node.members, visitor, isClassElement); let decorationStatements = []; ({ members, decorationStatements } = transformDecoratorsOfClassElements(node, members)); + const assignClassAliasInStaticBlock = languageVersion >= 9 /* ES2022 */ && !!classAlias && some(members, (member) => isPropertyDeclaration(member) && hasSyntacticModifier(member, 32 /* Static */) || isClassStaticBlockDeclaration(member)); + if (assignClassAliasInStaticBlock) { + members = setTextRange(factory2.createNodeArray([ + factory2.createClassStaticBlockDeclaration( + factory2.createBlock([ + factory2.createExpressionStatement( + factory2.createAssignment(classAlias, factory2.createThis()) + ) + ]) + ), + ...members + ]), members); + } const classExpression = factory2.createClassExpression( - /*modifiers*/ - void 0, + modifiers, name && isGeneratedIdentifier(name) ? void 0 : name, /*typeParameters*/ void 0, @@ -95180,18 +95333,23 @@ function transformLegacyDecorators(context) { ); setOriginalNode(classExpression, node); setTextRange(classExpression, location); - const statement = factory2.createVariableStatement( - /*modifiers*/ + const varDecl = factory2.createVariableDeclaration( + declName, + /*exclamationToken*/ void 0, + /*type*/ + void 0, + classAlias && !assignClassAliasInStaticBlock ? factory2.createAssignment(classAlias, classExpression) : classExpression + ); + setOriginalNode(varDecl, node); + let varModifiers; + if (isExport && !isDefault) { + varModifiers = factory2.createModifiersFromModifierFlags(1 /* Export */); + } + const statement = factory2.createVariableStatement( + varModifiers, factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - declName, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - classAlias ? factory2.createAssignment(classAlias, classExpression) : classExpression - ) + varDecl ], 1 /* Let */) ); setOriginalNode(statement, node); @@ -95200,6 +95358,15 @@ function transformLegacyDecorators(context) { const statements = [statement]; addRange(statements, decorationStatements); addConstructorDecorationStatement(statements, node); + if (isExport && isDefault) { + statements.push(factory2.createExportAssignment( + /*modifiers*/ + void 0, + /*isExportEquals*/ + false, + declName + )); + } return statements; } function visitClassExpression(node) { @@ -95376,13 +95543,13 @@ function transformLegacyDecorators(context) { return void 0; } const classAlias = classAliases && classAliases[getOriginalNodeId(node)]; - const localName = languageVersion <= 2 /* ES2015 */ ? factory2.getInternalName( + const localName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName( node, /*allowComments*/ false, /*allowSourceMaps*/ true - ) : factory2.getLocalName( + ) : factory2.getDeclarationName( node, /*allowComments*/ false, @@ -95871,7 +96038,15 @@ function transformESDecorators(context) { function transformClassLike(node, className) { var _a; startLexicalEnvironment(); - const classReference = node.name ?? factory2.getGeneratedNameForNode(node); + const classReference = factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + false, + /*ignoreAssignedName*/ + true + ); const classInfo2 = createClassInfo(node); const classDefinitionStatements = []; let leadingBlockStatements; @@ -96187,6 +96362,7 @@ function transformESDecorators(context) { void 0, iife ); + setOriginalNode(varDecl, node); const varDecls = factory2.createVariableDeclarationList([varDecl], 1 /* Let */); const statement = factory2.createVariableStatement(modifiers, varDecls); setOriginalNode(statement, node); @@ -98511,10 +98687,7 @@ function transformES2018(context) { const exitNonUserCodeExpression = factory2.createAssignment(nonUserCode, factory2.createFalse()); const exitNonUserCodeStatement = factory2.createExpressionStatement(exitNonUserCodeExpression); setSourceMapRange(exitNonUserCodeStatement, node.expression); - const enterNonUserCodeExpression = factory2.createAssignment(nonUserCode, factory2.createTrue()); - const enterNonUserCodeStatement = factory2.createExpressionStatement(enterNonUserCodeExpression); - setSourceMapRange(exitNonUserCodeStatement, node.expression); - const statements = []; + const statements = [iteratorValueStatement, exitNonUserCodeStatement]; const binding = createForOfBindingStatement(factory2, node.initializer, value); statements.push(visitNode(binding, visitor, isStatement)); let bodyLocation; @@ -98527,29 +98700,14 @@ function transformES2018(context) { } else { statements.push(statement); } - const body = setEmitFlags( - setTextRange( - factory2.createBlock( - setTextRange(factory2.createNodeArray(statements), statementsLocation), - /*multiLine*/ - true - ), - bodyLocation + return setTextRange( + factory2.createBlock( + setTextRange(factory2.createNodeArray(statements), statementsLocation), + /*multiLine*/ + true ), - 96 /* NoSourceMap */ | 768 /* NoTokenSourceMaps */ + bodyLocation ); - return factory2.createBlock([ - iteratorValueStatement, - exitNonUserCodeStatement, - factory2.createTryStatement( - body, - /*catchClause*/ - void 0, - factory2.createBlock([ - enterNonUserCodeStatement - ]) - ) - ]); } function createDownlevelAwait(expression) { return enclosingFunctionFlags & 1 /* Generator */ ? factory2.createYieldExpression( @@ -98628,7 +98786,7 @@ function transformES2018(context) { factory2.createLogicalNot(done) ]), /*incrementor*/ - void 0, + factory2.createAssignment(nonUserCode, factory2.createTrue()), /*statement*/ convertForOfStatementHead(node, getValue, nonUserCode) ), @@ -100879,11 +101037,6 @@ function transformES2015(context) { setOriginalNode(exportStatement, statement); statements.push(exportStatement); } - const emitFlags = getEmitFlags(node); - if ((emitFlags & 8388608 /* HasEndOfDeclarationMarker */) === 0) { - statements.push(factory2.createEndOfDeclarationMarker(node)); - setEmitFlags(statement, emitFlags | 8388608 /* HasEndOfDeclarationMarker */); - } return singleOrMany(statements); } function visitClassExpression(node) { @@ -102846,7 +102999,7 @@ function transformES2015(context) { ); const callResult = containsYield ? factory2.createYieldExpression( factory2.createToken(42 /* AsteriskToken */), - setEmitFlags(call, 16777216 /* Iterator */) + setEmitFlags(call, 8388608 /* Iterator */) ) : call; return factory2.createExpressionStatement(callResult); } @@ -102861,7 +103014,7 @@ function transformES2015(context) { ); const callResult = containsYield ? factory2.createYieldExpression( factory2.createToken(42 /* AsteriskToken */), - setEmitFlags(call, 16777216 /* Iterator */) + setEmitFlags(call, 8388608 /* Iterator */) ) : call; if (isSimpleLoop) { statements.push(factory2.createExpressionStatement(callResult)); @@ -104185,7 +104338,7 @@ function transformGenerators(context) { const resumeLabel = defineLabel(); const expression = visitNode(node.expression, visitor, isExpression); if (node.asteriskToken) { - const iterator = (getEmitFlags(node.expression) & 16777216 /* Iterator */) === 0 ? setTextRange(emitHelpers().createValuesHelper(expression), node) : expression; + const iterator = (getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0 ? setTextRange(emitHelpers().createValuesHelper(expression), node) : expression; emitYieldStar( iterator, /*location*/ @@ -105733,7 +105886,6 @@ function transformModule(context) { context.enableSubstitution(303 /* ShorthandPropertyAssignment */); context.enableEmitNotification(311 /* SourceFile */); const moduleInfoMap = []; - const deferredExports = []; let currentSourceFile; let currentModuleInfo; const noSubstitution = []; @@ -106152,16 +106304,56 @@ function transformModule(context) { return visitExportDeclaration(node); case 276 /* ExportAssignment */: return visitExportAssignment(node); + case 261 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 262 /* ClassDeclaration */: + return visitClassDeclaration(node); + default: + return topLevelNestedVisitor(node); + } + } + function topLevelNestedVisitor(node) { + switch (node.kind) { case 242 /* VariableStatement */: return visitVariableStatement(node); case 261 /* FunctionDeclaration */: return visitFunctionDeclaration(node); case 262 /* ClassDeclaration */: return visitClassDeclaration(node); - case 361 /* MergeDeclarationMarker */: - return visitMergeDeclarationMarker(node); - case 362 /* EndOfDeclarationMarker */: - return visitEndOfDeclarationMarker(node); + case 247 /* ForStatement */: + return visitForStatement( + node, + /*isTopLevel*/ + true + ); + case 248 /* ForInStatement */: + return visitForInStatement(node); + case 249 /* ForOfStatement */: + return visitForOfStatement(node); + case 245 /* DoStatement */: + return visitDoStatement(node); + case 246 /* WhileStatement */: + return visitWhileStatement(node); + case 255 /* LabeledStatement */: + return visitLabeledStatement(node); + case 253 /* WithStatement */: + return visitWithStatement(node); + case 244 /* IfStatement */: + return visitIfStatement(node); + case 254 /* SwitchStatement */: + return visitSwitchStatement(node); + case 268 /* CaseBlock */: + return visitCaseBlock(node); + case 295 /* CaseClause */: + return visitCaseClause(node); + case 296 /* DefaultClause */: + return visitDefaultClause(node); + case 257 /* TryStatement */: + return visitTryStatement(node); + case 298 /* CatchClause */: + return visitCatchClause(node); + case 240 /* Block */: + return visitBlock(node); default: return visitor(node); } @@ -106172,7 +106364,11 @@ function transformModule(context) { } switch (node.kind) { case 247 /* ForStatement */: - return visitForStatement(node); + return visitForStatement( + node, + /*isTopLevel*/ + false + ); case 243 /* ExpressionStatement */: return visitExpressionStatement(node); case 216 /* ParenthesizedExpression */: @@ -106257,15 +106453,177 @@ function transformModule(context) { } return visitEachChild(node, visitor, context); } - function visitForStatement(node) { + function visitForStatement(node, isTopLevel) { + if (isTopLevel && node.initializer && isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 3 /* BlockScoped */)) { + const exportStatements = appendExportsOfVariableDeclarationList( + /*statements*/ + void 0, + node.initializer, + /*isForInOrOfInitializer*/ + false + ); + if (exportStatements) { + const statements = []; + const varDeclList = visitNode(node.initializer, discardedValueVisitor, isVariableDeclarationList); + const varStatement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + varDeclList + ); + statements.push(varStatement); + addRange(statements, exportStatements); + const condition = visitNode(node.condition, visitor, isExpression); + const incrementor = visitNode(node.incrementor, discardedValueVisitor, isExpression); + const body = visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context); + statements.push(factory2.updateForStatement( + node, + /*initializer*/ + void 0, + condition, + incrementor, + body + )); + return statements; + } + } return factory2.updateForStatement( node, visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, discardedValueVisitor, isExpression), - visitIterationBody(node.statement, visitor, context) + visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context) ); } + function visitForInStatement(node) { + if (isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 3 /* BlockScoped */)) { + const exportStatements = appendExportsOfVariableDeclarationList( + /*statements*/ + void 0, + node.initializer, + /*isForInOrOfInitializer*/ + true + ); + if (some(exportStatements)) { + const initializer = visitNode(node.initializer, discardedValueVisitor, isForInitializer); + const expression = visitNode(node.expression, visitor, isExpression); + const body = visitIterationBody(node.statement, topLevelNestedVisitor, context); + const mergedBody = isBlock(body) ? factory2.updateBlock(body, [...exportStatements, ...body.statements]) : factory2.createBlock( + [...exportStatements, body], + /*multiLine*/ + true + ); + return factory2.updateForInStatement(node, initializer, expression, mergedBody); + } + } + return factory2.updateForInStatement( + node, + visitNode(node.initializer, discardedValueVisitor, isForInitializer), + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + } + function visitForOfStatement(node) { + if (isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 3 /* BlockScoped */)) { + const exportStatements = appendExportsOfVariableDeclarationList( + /*statements*/ + void 0, + node.initializer, + /*isForInOrOfInitializer*/ + true + ); + const initializer = visitNode(node.initializer, discardedValueVisitor, isForInitializer); + const expression = visitNode(node.expression, visitor, isExpression); + let body = visitIterationBody(node.statement, topLevelNestedVisitor, context); + if (some(exportStatements)) { + body = isBlock(body) ? factory2.updateBlock(body, [...exportStatements, ...body.statements]) : factory2.createBlock( + [...exportStatements, body], + /*multiLine*/ + true + ); + } + return factory2.updateForOfStatement(node, node.awaitModifier, initializer, expression, body); + } + return factory2.updateForOfStatement( + node, + node.awaitModifier, + visitNode(node.initializer, discardedValueVisitor, isForInitializer), + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + } + function visitDoStatement(node) { + return factory2.updateDoStatement( + node, + visitIterationBody(node.statement, topLevelNestedVisitor, context), + visitNode(node.expression, visitor, isExpression) + ); + } + function visitWhileStatement(node) { + return factory2.updateWhileStatement( + node, + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + } + function visitLabeledStatement(node) { + return factory2.updateLabeledStatement( + node, + node.label, + Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) + ); + } + function visitWithStatement(node) { + return factory2.updateWithStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) + ); + } + function visitIfStatement(node) { + return factory2.updateIfStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)), + visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) + ); + } + function visitSwitchStatement(node) { + return factory2.updateSwitchStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock)) + ); + } + function visitCaseBlock(node) { + return factory2.updateCaseBlock( + node, + visitNodes2(node.clauses, topLevelNestedVisitor, isCaseOrDefaultClause) + ); + } + function visitCaseClause(node) { + return factory2.updateCaseClause( + node, + visitNode(node.expression, visitor, isExpression), + visitNodes2(node.statements, topLevelNestedVisitor, isStatement) + ); + } + function visitDefaultClause(node) { + return visitEachChild(node, topLevelNestedVisitor, context); + } + function visitTryStatement(node) { + return visitEachChild(node, topLevelNestedVisitor, context); + } + function visitCatchClause(node) { + return factory2.updateCatchClause( + node, + node.variableDeclaration, + Debug.checkDefined(visitNode(node.block, topLevelNestedVisitor, isBlock)) + ); + } + function visitBlock(node) { + node = visitEachChild(node, topLevelNestedVisitor, context); + return node; + } function visitExpressionStatement(node) { return factory2.updateExpressionStatement( node, @@ -106638,12 +106996,7 @@ function transformModule(context) { ) ); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfImportDeclaration(statements, node); - } + statements = appendExportsOfImportDeclaration(statements, node); return singleOrMany(statements); } function createRequireCall2(importNode) { @@ -106724,12 +107077,7 @@ function transformModule(context) { ); } } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfImportEqualsDeclaration(statements, node); - } + statements = appendExportsOfImportEqualsDeclaration(statements, node); return singleOrMany(statements); } function visitExportDeclaration(node) { @@ -106838,31 +107186,14 @@ function transformModule(context) { if (node.isExportEquals) { return void 0; } - let statements; - const original = node.original; - if (original && hasAssociatedEndOfDeclarationMarker(original)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportStatement( - deferredExports[id], - factory2.createIdentifier("default"), - visitNode(node.expression, visitor, isExpression), - /*location*/ - node, - /*allowComments*/ - true - ); - } else { - statements = appendExportStatement( - statements, - factory2.createIdentifier("default"), - visitNode(node.expression, visitor, isExpression), - /*location*/ - node, - /*allowComments*/ - true - ); - } - return singleOrMany(statements); + return createExportStatement( + factory2.createIdentifier("default"), + visitNode(node.expression, visitor, isExpression), + /*location*/ + node, + /*allowComments*/ + true + ); } function visitFunctionDeclaration(node) { let statements; @@ -106898,12 +107229,7 @@ function transformModule(context) { } else { statements = append(statements, visitEachChild(node, visitor, context)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfHoistedDeclaration(statements, node); - } + statements = appendExportsOfHoistedDeclaration(statements, node); return singleOrMany(statements); } function visitClassDeclaration(node) { @@ -106935,12 +107261,7 @@ function transformModule(context) { } else { statements = append(statements, visitEachChild(node, visitor, context)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfHoistedDeclaration(statements, node); - } + statements = appendExportsOfHoistedDeclaration(statements, node); return singleOrMany(statements); } function visitVariableStatement(node) { @@ -107012,12 +107333,7 @@ function transformModule(context) { } else { statements = append(statements, visitEachChild(node, visitor, context)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); - } else { - statements = appendExportsOfVariableStatement(statements, node); - } + statements = appendExportsOfVariableStatement(statements, node); return singleOrMany(statements); } function createAllExportExpressions(name, value, location) { @@ -107062,25 +107378,6 @@ function transformModule(context) { ); } } - function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 242 /* VariableStatement */) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); - } - return node; - } - function hasAssociatedEndOfDeclarationMarker(node) { - return (getEmitFlags(node) & 8388608 /* HasEndOfDeclarationMarker */) !== 0; - } - function visitEndOfDeclarationMarker(node) { - const id = getOriginalNodeId(node); - const statements = deferredExports[id]; - if (statements) { - delete deferredExports[id]; - return append(statements, node); - } - return node; - } function appendExportsOfImportDeclaration(statements, decl) { if (currentModuleInfo.exportEquals) { return statements; @@ -107119,25 +107416,33 @@ function transformModule(context) { return appendExportsOfDeclaration(statements, decl); } function appendExportsOfVariableStatement(statements, node) { + return appendExportsOfVariableDeclarationList( + statements, + node.declarationList, + /*isForInOrOfInitializer*/ + false + ); + } + function appendExportsOfVariableDeclarationList(statements, node, isForInOrOfInitializer) { if (currentModuleInfo.exportEquals) { return statements; } - for (const decl of node.declarationList.declarations) { - statements = appendExportsOfBindingElement(statements, decl); + for (const decl of node.declarations) { + statements = appendExportsOfBindingElement(statements, decl, isForInOrOfInitializer); } return statements; } - function appendExportsOfBindingElement(statements, decl) { + function appendExportsOfBindingElement(statements, decl, isForInOrOfInitializer) { if (currentModuleInfo.exportEquals) { return statements; } if (isBindingPattern(decl.name)) { for (const element of decl.name.elements) { if (!isOmittedExpression(element)) { - statements = appendExportsOfBindingElement(statements, element); + statements = appendExportsOfBindingElement(statements, element, isForInOrOfInitializer); } } - } else if (!isGeneratedIdentifier(decl.name)) { + } else if (!isGeneratedIdentifier(decl.name) && (!isVariableDeclaration(decl) || decl.initializer || isForInOrOfInitializer)) { statements = appendExportsOfDeclaration(statements, decl); } return statements; @@ -107408,7 +107713,7 @@ function transformModule(context) { return node; } function substituteBinaryExpression(node) { - if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left) && !isDeclarationNameOfEnumOrNamespace(node.left)) { + if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left)) { const exportedNames = getExports(node.left); if (exportedNames) { let expression = node; @@ -107428,9 +107733,24 @@ function transformModule(context) { } function getExports(name) { if (!isGeneratedIdentifier(name)) { - const valueDeclaration = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); - if (valueDeclaration) { - return currentModuleInfo && currentModuleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]; + const importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + return currentModuleInfo == null ? void 0 : currentModuleInfo.exportedBindings[getOriginalNodeId(importDeclaration)]; + } + const bindingsSet = /* @__PURE__ */ new Set(); + const declarations = resolver.getReferencedValueDeclarations(name); + if (declarations) { + for (const declaration of declarations) { + const bindings = currentModuleInfo == null ? void 0 : currentModuleInfo.exportedBindings[getOriginalNodeId(declaration)]; + if (bindings) { + for (const binding of bindings) { + bindingsSet.add(binding); + } + } + } + if (bindingsSet.size) { + return arrayFrom(bindingsSet); + } } } } @@ -107463,7 +107783,6 @@ function transformSystemModule(context) { context.enableSubstitution(235 /* MetaProperty */); context.enableEmitNotification(311 /* SourceFile */); const moduleInfoMap = []; - const deferredExports = []; const exportFunctionsMap = []; const noSubstitutionMap = []; const contextObjectMap = []; @@ -107936,13 +108255,7 @@ function transformSystemModule(context) { if (node.importClause) { hoistVariableDeclaration(getLocalNameForExternalImport(factory2, node, currentSourceFile)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfImportDeclaration(statements, node); - } - return singleOrMany(statements); + return singleOrMany(appendExportsOfImportDeclaration(statements, node)); } function visitExportDeclaration(node) { Debug.assertIsDefined(node); @@ -107952,37 +108265,19 @@ function transformSystemModule(context) { Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); let statements; hoistVariableDeclaration(getLocalNameForExternalImport(factory2, node, currentSourceFile)); - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfImportEqualsDeclaration(statements, node); - } - return singleOrMany(statements); + return singleOrMany(appendExportsOfImportEqualsDeclaration(statements, node)); } function visitExportAssignment(node) { if (node.isExportEquals) { return void 0; } const expression = visitNode(node.expression, visitor, isExpression); - const original = node.original; - if (original && hasAssociatedEndOfDeclarationMarker(original)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportStatement( - deferredExports[id], - factory2.createIdentifier("default"), - expression, - /*allowComments*/ - true - ); - } else { - return createExportStatement( - factory2.createIdentifier("default"), - expression, - /*allowComments*/ - true - ); - } + return createExportStatement( + factory2.createIdentifier("default"), + expression, + /*allowComments*/ + true + ); } function visitFunctionDeclaration(node) { if (hasSyntacticModifier(node, 1 /* Export */)) { @@ -108010,12 +108305,7 @@ function transformSystemModule(context) { } else { hoistedStatements = append(hoistedStatements, visitEachChild(node, visitor, context)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else { - hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); - } + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); return void 0; } function visitClassDeclaration(node) { @@ -108044,12 +108334,7 @@ function transformSystemModule(context) { node ) ); - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfHoistedDeclaration(statements, node); - } + statements = appendExportsOfHoistedDeclaration(statements, node); return singleOrMany(statements); } function visitVariableStatement(node) { @@ -108058,10 +108343,9 @@ function transformSystemModule(context) { } let expressions; const isExportedDeclaration = hasSyntacticModifier(node, 1 /* Export */); - const isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); for (const variable of node.declarationList.declarations) { if (variable.initializer) { - expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration)); + expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration)); } else { hoistBindingElement(variable); } @@ -108070,17 +108354,12 @@ function transformSystemModule(context) { if (expressions) { statements = append(statements, setTextRange(factory2.createExpressionStatement(factory2.inlineExpressions(expressions)), node)); } - if (isMarkedDeclaration) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); - } else { - statements = appendExportsOfVariableStatement( - statements, - node, - /*exportSelf*/ - false - ); - } + statements = appendExportsOfVariableStatement( + statements, + node, + /*exportSelf*/ + false + ); return singleOrMany(statements); } function hoistBindingElement(node) { @@ -108131,31 +108410,6 @@ function transformSystemModule(context) { hoistVariableDeclaration(factory2.cloneNode(name)); return isExportedDeclaration ? createExportExpression(name, preventSubstitution(setTextRange(factory2.createAssignment(name, value), location))) : preventSubstitution(setTextRange(factory2.createAssignment(name, value), location)); } - function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 242 /* VariableStatement */) { - const id = getOriginalNodeId(node); - const isExportedDeclaration = hasSyntacticModifier(node.original, 1 /* Export */); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); - } - return node; - } - function hasAssociatedEndOfDeclarationMarker(node) { - return (getEmitFlags(node) & 8388608 /* HasEndOfDeclarationMarker */) !== 0; - } - function visitEndOfDeclarationMarker(node) { - const id = getOriginalNodeId(node); - const statements = deferredExports[id]; - if (statements) { - delete deferredExports[id]; - return append(statements, node); - } else { - const original = getOriginalNode(node); - if (isModuleOrEnumDeclaration(original)) { - return append(appendExportsOfDeclaration(statements, original), node); - } - } - return node; - } function appendExportsOfImportDeclaration(statements, decl) { if (moduleInfo.exportEquals) { return statements; @@ -108297,6 +108551,8 @@ function transformSystemModule(context) { return visitLabeledStatement(node); case 253 /* WithStatement */: return visitWithStatement(node); + case 244 /* IfStatement */: + return visitIfStatement(node); case 254 /* SwitchStatement */: return visitSwitchStatement(node); case 268 /* CaseBlock */: @@ -108311,10 +108567,6 @@ function transformSystemModule(context) { return visitCatchClause(node); case 240 /* Block */: return visitBlock(node); - case 361 /* MergeDeclarationMarker */: - return visitMergeDeclarationMarker(node); - case 362 /* EndOfDeclarationMarker */: - return visitEndOfDeclarationMarker(node); default: return visitor(node); } @@ -108406,6 +108658,14 @@ function transformSystemModule(context) { Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) ); } + function visitIfStatement(node) { + return factory2.updateIfStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)), + visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) + ); + } function visitSwitchStatement(node) { return factory2.updateSwitchStatement( node, @@ -108720,7 +108980,7 @@ function transformSystemModule(context) { return node; } function substituteBinaryExpression(node) { - if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left) && !isDeclarationNameOfEnumOrNamespace(node.left)) { + if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left)) { const exportedNames = getExports(node.left); if (exportedNames) { let expression = node; @@ -108740,22 +109000,38 @@ function transformSystemModule(context) { } function getExports(name) { let exportedNames; - if (!isGeneratedIdentifier(name)) { - const valueDeclaration = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); - if (valueDeclaration) { - const exportContainer = resolver.getReferencedExportContainer( - name, - /*prefixLocals*/ - false - ); - if (exportContainer && exportContainer.kind === 311 /* SourceFile */) { - exportedNames = append(exportedNames, factory2.getDeclarationName(valueDeclaration)); - } - exportedNames = addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]); + const valueDeclaration = getReferencedDeclaration(name); + if (valueDeclaration) { + const exportContainer = resolver.getReferencedExportContainer( + name, + /*prefixLocals*/ + false + ); + if (exportContainer && exportContainer.kind === 311 /* SourceFile */) { + exportedNames = append(exportedNames, factory2.getDeclarationName(valueDeclaration)); } + exportedNames = addRange(exportedNames, moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]); } return exportedNames; } + function getReferencedDeclaration(name) { + if (!isGeneratedIdentifier(name)) { + const importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) + return importDeclaration; + const valueDeclaration = resolver.getReferencedValueDeclaration(name); + if (valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)])) + return valueDeclaration; + const declarations = resolver.getReferencedValueDeclarations(name); + if (declarations) { + for (const declaration of declarations) { + if (declaration !== valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(declaration)])) + return declaration; + } + } + return valueDeclaration; + } + } function preventSubstitution(node) { if (noSubstitution === void 0) noSubstitution = []; @@ -111168,7 +111444,7 @@ function noEmitNotification(hint, node, callback) { } function transformNodes(resolver, host, factory2, options, nodes, transformers, allowDtsFiles) { var _a, _b; - const enabledSyntaxKindFeatures = new Array(364 /* Count */); + const enabledSyntaxKindFeatures = new Array(362 /* Count */); let lexicalEnvironmentVariableDeclarations; let lexicalEnvironmentFunctionDeclarations; let lexicalEnvironmentStatements; @@ -112112,6 +112388,7 @@ var notImplementedResolver = { // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant getConstantValue: notImplemented, getReferencedValueDeclaration: notImplemented, + getReferencedValueDeclarations: notImplemented, getTypeReferenceSerializationKind: notImplemented, isOptionalParameter: notImplemented, moduleExportsSomeValue: notImplemented, @@ -112970,6 +113247,8 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitJsxSpreadAttribute(node); case 293 /* JsxExpression */: return emitJsxExpression(node); + case 294 /* JsxNamespacedName */: + return emitJsxNamespacedName(node); case 295 /* CaseClause */: return emitCaseClause(node); case 296 /* DefaultClause */: @@ -113065,8 +113344,6 @@ function createPrinter(printerOptions = {}, handlers = {}) { case 353 /* JSDocSeeTag */: return emitJSDocSeeTag(node); case 358 /* NotEmittedStatement */: - case 362 /* EndOfDeclarationMarker */: - case 361 /* MergeDeclarationMarker */: return; } if (isExpression(node)) { @@ -113167,8 +113444,6 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitJsxSelfClosingElement(node); case 287 /* JsxFragment */: return emitJsxFragment(node); - case 294 /* JsxNamespacedName */: - return emitJsxNamespacedName(node); case 357 /* SyntaxList */: return Debug.fail("SyntaxList should not be printed"); case 358 /* NotEmittedStatement */: @@ -113177,10 +113452,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitPartiallyEmittedExpression(node); case 360 /* CommaListExpression */: return emitCommaList(node); - case 361 /* MergeDeclarationMarker */: - case 362 /* EndOfDeclarationMarker */: - return; - case 363 /* SyntheticReferenceExpression */: + case 361 /* SyntheticReferenceExpression */: return Debug.fail("SyntheticReferenceExpression should not be printed"); } } @@ -115502,7 +115774,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } } function emitEmbeddedStatement(parent2, node) { - if (isBlock(node) || getEmitFlags(parent2) & 1 /* SingleLine */) { + if (isBlock(node) || getEmitFlags(parent2) & 1 /* SingleLine */ || preserveSourceNewlines && !getLeadingLineTerminatorCount(parent2, node, 0 /* None */)) { writeSpace(); emit(node); } else { @@ -116003,6 +116275,10 @@ function createPrinter(printerOptions = {}, handlers = {}) { if (!canUseSourceFile || getSourceFileOfNode(node) !== getOriginalNode(sourceFile)) { return idText(node); } + } else if (isJsxNamespacedName(node)) { + if (!canUseSourceFile || getSourceFileOfNode(node) !== getOriginalNode(sourceFile)) { + return getTextOfJsxNamespacedName(node); + } } else { Debug.assertNode(node, isLiteralExpression); if (!canUseSourceFile) { @@ -116014,9 +116290,9 @@ function createPrinter(printerOptions = {}, handlers = {}) { function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) { if (node.kind === 11 /* StringLiteral */ && node.textSourceNode) { const textSourceNode = node.textSourceNode; - if (isIdentifier(textSourceNode) || isPrivateIdentifier(textSourceNode) || isNumericLiteral(textSourceNode)) { + if (isIdentifier(textSourceNode) || isPrivateIdentifier(textSourceNode) || isNumericLiteral(textSourceNode) || isJsxNamespacedName(textSourceNode)) { const text = isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode2(textSourceNode); - return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` : neverAsciiEscape || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? `"${escapeString(text)}"` : `"${escapeNonAsciiString(text)}"`; + return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` : neverAsciiEscape || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? `"${escapeString(text)}"` : `"${escapeNonAsciiString(text)}"`; } else { return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape); } @@ -117352,7 +117628,7 @@ var WatchLogLevel = /* @__PURE__ */ ((WatchLogLevel2) => { WatchLogLevel2[WatchLogLevel2["Verbose"] = 2] = "Verbose"; return WatchLogLevel2; })(WatchLogLevel || {}); -function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo3) { +function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo2) { setSysLog(watchLogLevel === 2 /* Verbose */ ? log : noop); const plainInvokeFactory = { watchFile: (file, callback, pollingInterval, options) => host.watchFile(file, callback, pollingInterval, options), @@ -117390,23 +117666,23 @@ function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo3) { return typeof host.useCaseSensitiveFileNames === "boolean" ? host.useCaseSensitiveFileNames : host.useCaseSensitiveFileNames(); } function createExcludeWatcherWithLogging(file, flags, options, detailInfo1, detailInfo2) { - log(`ExcludeWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3)}`); + log(`ExcludeWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`); return { - close: () => log(`ExcludeWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3)}`) + close: () => log(`ExcludeWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`) }; } function createFileWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) { - log(`FileWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3)}`); + log(`FileWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`); const watcher = triggerInvokingFactory.watchFile(file, cb, flags, options, detailInfo1, detailInfo2); return { close: () => { - log(`FileWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3)}`); + log(`FileWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`); watcher.close(); } }; } function createDirectoryWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) { - const watchInfo = `DirectoryWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3)}`; + const watchInfo = `DirectoryWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`; log(watchInfo); const start2 = timestamp(); const watcher = triggerInvokingFactory.watchDirectory(file, cb, flags, options, detailInfo1, detailInfo2); @@ -117414,7 +117690,7 @@ function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo3) { log(`Elapsed:: ${elapsed}ms ${watchInfo}`); return { close: () => { - const watchInfo2 = `DirectoryWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3)}`; + const watchInfo2 = `DirectoryWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`; log(watchInfo2); const start3 = timestamp(); watcher.close(); @@ -117429,7 +117705,7 @@ function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo3) { void 0, file, (...args) => { - const triggerredInfo = `${key === "watchFile" ? "FileWatcher" : "DirectoryWatcher"}:: Triggered with ${args[0]} ${args[1] !== void 0 ? args[1] : ""}:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3)}`; + const triggerredInfo = `${key === "watchFile" ? "FileWatcher" : "DirectoryWatcher"}:: Triggered with ${args[0]} ${args[1] !== void 0 ? args[1] : ""}:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`; log(triggerredInfo); const start2 = timestamp(); cb.call( @@ -117446,8 +117722,8 @@ function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo3) { detailInfo2 ); } - function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo4) { - return `WatchInfo: ${file} ${flags} ${JSON.stringify(options)} ${getDetailWatchInfo4 ? getDetailWatchInfo4(detailInfo1, detailInfo2) : detailInfo2 === void 0 ? detailInfo1 : `${detailInfo1} ${detailInfo2}`}`; + function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3) { + return `WatchInfo: ${file} ${flags} ${JSON.stringify(options)} ${getDetailWatchInfo3 ? getDetailWatchInfo3(detailInfo1, detailInfo2) : detailInfo2 === void 0 ? detailInfo1 : `${detailInfo1} ${detailInfo2}`}`; } } function getFallbackOptions(options) { @@ -118013,6 +118289,25 @@ function forEachProjectReference(projectReferences, resolvedProjectReferences, c } } var inferredTypesContainingFile = "__inferred type names__.ts"; +function getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName) { + const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : currentDirectory; + return combinePaths(containingDirectory, `__lib_node_modules_lookup_${libFileName}__.ts`); +} +function getLibraryNameFromLibFileName(libFileName) { + const components = libFileName.split("."); + let path = components[1]; + let i = 2; + while (components[i] && components[i] !== "d") { + path += (i === 2 ? "/" : "-") + components[i]; + i++; + } + return "@typescript/lib-" + path; +} +function getLibFileNameFromLibReference(libReference) { + const libName = toFileNameLowerCase(libReference.fileName); + const libFileName = libMap.get(libName); + return { libName, libFileName }; +} function isReferencedFile(reason) { switch (reason == null ? void 0 : reason.kind) { case 3 /* Import */: @@ -118056,7 +118351,7 @@ function getReferencedFileLocation(getSourceFileByPath, ref) { } return { file, pos, end, packageId }; } -function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) { +function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) { if (!program || (hasChangedAutomaticTypeDirectiveNames == null ? void 0 : hasChangedAutomaticTypeDirectiveNames())) return false; if (!arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) @@ -118071,6 +118366,8 @@ function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, const currentOptions = program.getCompilerOptions(); if (!compareDataObjects(currentOptions, newOptions)) return false; + if (program.resolvedLibReferences && forEachEntry(program.resolvedLibReferences, (_value, libFileName) => hasInvalidatedLibResolutions(libFileName))) + return false; if (currentOptions.configFile && newOptions.configFile) return currentOptions.configFile.text === newOptions.configFile.text; return true; @@ -118257,6 +118554,9 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config let fileProcessingDiagnostics; let automaticTypeDirectiveNames; let automaticTypeDirectiveResolutions; + let resolvedLibReferences; + let resolvedLibProcessing; + let packageMap; const maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; let currentNodeModulesDepth = 0; const modulesWithElidedImports = /* @__PURE__ */ new Map(); @@ -118344,6 +118644,14 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config createTypeReferenceResolutionLoader ); } + const hasInvalidatedLibResolutions = host.hasInvalidatedLibResolutions || returnFalse; + let actualResolveLibrary; + if (host.resolveLibrary) { + actualResolveLibrary = host.resolveLibrary.bind(host); + } else { + const libraryResolutionCache = createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + actualResolveLibrary = (libraryName, resolveFrom, options2) => resolveLibrary(libraryName, resolveFrom, options2, host, libraryResolutionCache); + } const packageIdToSourceFile = /* @__PURE__ */ new Map(); let sourceFileToPackageName = /* @__PURE__ */ new Map(); let redirectTargetsMap = createMultiMap(); @@ -118420,7 +118728,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config automaticTypeDirectiveResolutions = createModeAwareCache(); if (automaticTypeDirectiveNames.length) { (_k = tracing) == null ? void 0 : _k.push(tracing.Phase.Program, "processTypeReferences", { count: automaticTypeDirectiveNames.length }); - const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : currentDirectory; const containingFilename = combinePaths(containingDirectory, inferredTypesContainingFile); const resolutions = resolveTypeReferenceDirectiveNamesReusingOldState(automaticTypeDirectiveNames, containingFilename); for (let i = 0; i < automaticTypeDirectiveNames.length; i++) { @@ -118510,6 +118818,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config ); } oldProgram = void 0; + resolvedLibProcessing = void 0; const program = { getRootFileNames: () => rootNames, getSourceFile, @@ -118551,6 +118860,10 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config sourceFileToPackageName, redirectTargetsMap, usesUriStyleNodeCoreModules, + resolvedLibReferences, + getCurrentPackagesMap: () => packageMap, + typesPackageExists, + packageBundlesTypes, isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics2, getProjectReferences, @@ -118591,6 +118904,26 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config measure("Program", "beforeProgram", "afterProgram"); (_p = tracing) == null ? void 0 : _p.pop(); return program; + function getPackagesMap() { + if (packageMap) + return packageMap; + packageMap = /* @__PURE__ */ new Map(); + files.forEach((sf) => { + if (!sf.resolvedModules) + return; + sf.resolvedModules.forEach(({ resolvedModule }) => { + if (resolvedModule == null ? void 0 : resolvedModule.packageId) + packageMap.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!packageMap.get(resolvedModule.packageId.name)); + }); + }); + return packageMap; + } + function typesPackageExists(packageName) { + return getPackagesMap().has(getTypesPackageName(packageName)); + } + function packageBundlesTypes(packageName) { + return !!getPackagesMap().get(packageName); + } function addResolutionDiagnostics(resolution) { var _a2; if (!((_a2 = resolution.resolutionDiagnostics) == null ? void 0 : _a2.length)) @@ -119039,6 +119372,9 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config if (changesAffectingProgramStructure(oldOptions, options)) { return 1 /* SafeModules */; } + if (oldProgram.resolvedLibReferences && forEachEntry(oldProgram.resolvedLibReferences, (resolution, libFileName) => pathForLibFileWorker(libFileName).actual !== resolution.actual)) { + return 1 /* SafeModules */; + } if (host.hasChangedAutomaticTypeDirectiveNames) { if (host.hasChangedAutomaticTypeDirectiveNames()) return 1 /* SafeModules */; @@ -119075,6 +119411,8 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; usesUriStyleNodeCoreModules = oldProgram.usesUriStyleNodeCoreModules; + resolvedLibReferences = oldProgram.resolvedLibReferences; + packageMap = oldProgram.getCurrentPackagesMap(); return 2 /* Completely */; } function getEmitHost(writeFileCallback) { @@ -119184,7 +119522,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config if (!options.lib) { return equalityComparer(file.fileName, getDefaultLibraryFileName()); } else { - return some(options.lib, (libFileName) => equalityComparer(file.fileName, pathForLibFile(libFileName))); + return some(options.lib, (libFileName) => equalityComparer(file.fileName, resolvedLibReferences.get(libFileName).actual)); } } function getTypeChecker() { @@ -119775,11 +120113,10 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } } function getLibFileFromReference(ref) { - const libName = toFileNameLowerCase(ref.fileName); - const libFileName = libMap.get(libName); - if (libFileName) { - return getSourceFile(pathForLibFile(libFileName)); - } + var _a2; + const { libFileName } = getLibFileNameFromLibReference(ref); + const actualFileName = libFileName && ((_a2 = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName)) == null ? void 0 : _a2.actual); + return actualFileName !== void 0 ? getSourceFile(actualFileName) : void 0; } function getSourceFileFromReference(referencingFile, ref) { return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), getSourceFile); @@ -120204,24 +120541,55 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } } function pathForLibFile(libFileName) { - const components = libFileName.split("."); - let path = components[1]; - let i = 2; - while (components[i] && components[i] !== "d") { - path += (i === 2 ? "/" : "-") + components[i]; - i++; + const existing = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName); + if (existing) + return existing.actual; + const result = pathForLibFileWorker(libFileName); + (resolvedLibReferences ?? (resolvedLibReferences = /* @__PURE__ */ new Map())).set(libFileName, result); + return result.actual; + } + function pathForLibFileWorker(libFileName) { + var _a2, _b2, _c2, _d2, _e2; + const existing = resolvedLibProcessing == null ? void 0 : resolvedLibProcessing.get(libFileName); + if (existing) + return existing; + if (structureIsReused !== 0 /* Not */ && oldProgram && !hasInvalidatedLibResolutions(libFileName)) { + const oldResolution = (_a2 = oldProgram.resolvedLibReferences) == null ? void 0 : _a2.get(libFileName); + if (oldResolution) { + if (oldResolution.resolution && isTraceEnabled(options, host)) { + const libraryName2 = getLibraryNameFromLibFileName(libFileName); + const resolveFrom2 = getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName); + trace( + host, + oldResolution.resolution.resolvedModule ? 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, + libraryName2, + getNormalizedAbsolutePath(resolveFrom2, currentDirectory), + (_b2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _b2.resolvedFileName, + ((_c2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _c2.packageId) && packageIdToString(oldResolution.resolution.resolvedModule.packageId) + ); + } + (resolvedLibProcessing ?? (resolvedLibProcessing = /* @__PURE__ */ new Map())).set(libFileName, oldResolution); + return oldResolution; + } } - const resolveFrom = combinePaths(currentDirectory, `__lib_node_modules_lookup_${libFileName}__.ts`); - const localOverrideModuleResult = resolveModuleName("@typescript/lib-" + path, resolveFrom, { moduleResolution: 2 /* Node10 */ }, host, moduleResolutionCache); - if (localOverrideModuleResult == null ? void 0 : localOverrideModuleResult.resolvedModule) { - return localOverrideModuleResult.resolvedModule.resolvedFileName; - } - return combinePaths(defaultLibraryPath, libFileName); + const libraryName = getLibraryNameFromLibFileName(libFileName); + const resolveFrom = getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName); + (_d2 = tracing) == null ? void 0 : _d2.push(tracing.Phase.Program, "resolveLibrary", { resolveFrom }); + mark("beforeResolveLibrary"); + const resolution = actualResolveLibrary(libraryName, resolveFrom, options, libFileName); + mark("afterResolveLibrary"); + measure("ResolveLibrary", "beforeResolveLibrary", "afterResolveLibrary"); + (_e2 = tracing) == null ? void 0 : _e2.pop(); + const result = { + resolution, + actual: resolution.resolvedModule ? resolution.resolvedModule.resolvedFileName : combinePaths(defaultLibraryPath, libFileName) + }; + (resolvedLibProcessing ?? (resolvedLibProcessing = /* @__PURE__ */ new Map())).set(libFileName, result); + return result; } function processLibReferenceDirectives(file) { forEach(file.libReferenceDirectives, (libReference, index) => { - const libName = toFileNameLowerCase(libReference.fileName); - const libFileName = libMap.get(libName); + const { libName, libFileName } = getLibFileNameFromLibReference(libReference); if (libFileName) { processRootFile( pathForLibFile(libFileName), @@ -120347,7 +120715,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config void 0 ); } else { - const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), host.getCurrentDirectory()); + const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), currentDirectory); sourceFile = host.getSourceFile(refPath, 100 /* JSON */); addFileToFilesByName( sourceFile, @@ -121920,7 +122288,10 @@ function createBuilderProgramState(newProgram, oldState) { return; const diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { - state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics); + state.semanticDiagnosticsPerFile.set( + sourceFilePath, + oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : repopulateDiagnostics(diagnostics, newProgram) + ); if (!state.semanticDiagnosticsFromOldState) { state.semanticDiagnosticsFromOldState = /* @__PURE__ */ new Set(); } @@ -121991,6 +122362,33 @@ function getEmitSignatureFromOldSignature(options, oldOptions, oldEmitSignature) isString(oldEmitSignature) ? [oldEmitSignature] : oldEmitSignature[0] ); } +function repopulateDiagnostics(diagnostics, newProgram) { + if (!diagnostics.length) + return diagnostics; + return sameMap(diagnostics, (diag2) => { + if (isString(diag2.messageText)) + return diag2; + const repopulatedChain = convertOrRepopulateDiagnosticMessageChain(diag2.messageText, diag2.file, newProgram, (chain) => { + var _a; + return (_a = chain.repopulateInfo) == null ? void 0 : _a.call(chain); + }); + return repopulatedChain === diag2.messageText ? diag2 : { ...diag2, messageText: repopulatedChain }; + }); +} +function convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo) { + const info = repopulateInfo(chain); + if (info) { + return { + ...createModuleNotFoundChain(sourceFile, newProgram, info.moduleReference, info.mode, info.packageName || info.moduleReference), + next: convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo) + }; + } + const next = convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo); + return next === chain.next ? chain : { ...chain, next }; +} +function convertOrRepopulateDiagnosticMessageChainArray(array, sourceFile, newProgram, repopulateInfo) { + return sameMap(array, (chain) => convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo)); +} function convertToDiagnostics(diagnostics, newProgram) { if (!diagnostics.length) return emptyArray; @@ -122012,9 +122410,11 @@ function convertToDiagnostics(diagnostics, newProgram) { } function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath3) { const { file } = diagnostic; + const sourceFile = file ? newProgram.getSourceFileByPath(toPath3(file)) : void 0; return { ...diagnostic, - file: file ? newProgram.getSourceFileByPath(toPath3(file)) : void 0 + file: sourceFile, + messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertOrRepopulateDiagnosticMessageChain(diagnostic.messageText, sourceFile, newProgram, (chain) => chain.info) }; } function releaseCache(state) { @@ -122556,9 +122956,35 @@ function convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBui const { file } = diagnostic; return { ...diagnostic, - file: file ? relativeToBuildInfo(file.resolvedPath) : void 0 + file: file ? relativeToBuildInfo(file.resolvedPath) : void 0, + messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertToReusableDiagnosticMessageChain(diagnostic.messageText) }; } +function convertToReusableDiagnosticMessageChain(chain) { + if (chain.repopulateInfo) { + return { + info: chain.repopulateInfo(), + next: convertToReusableDiagnosticMessageChainArray(chain.next) + }; + } + const next = convertToReusableDiagnosticMessageChainArray(chain.next); + return next === chain.next ? chain : { ...chain, next }; +} +function convertToReusableDiagnosticMessageChainArray(array) { + if (!array) + return array; + return forEach(array, (chain, index) => { + const reusable = convertToReusableDiagnosticMessageChain(chain); + if (chain === reusable) + return void 0; + const result = index > 0 ? array.slice(0, index - 1) : []; + result.push(reusable); + for (let i = index + 1; i < array.length; i++) { + result.push(convertToReusableDiagnosticMessageChain(array[i])); + } + return result; + }) || array; +} var BuilderProgramKind = /* @__PURE__ */ ((BuilderProgramKind2) => { BuilderProgramKind2[BuilderProgramKind2["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; BuilderProgramKind2[BuilderProgramKind2["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; @@ -123223,6 +123649,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW let failedLookupChecks; let startsWithPathChecks; let isInDirectoryChecks; + let allModuleAndTypeResolutionsAreInvalidated = false; const getCurrentDirectory = memoize(() => resolutionHost.getCurrentDirectory()); const cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); const resolvedModuleNames = /* @__PURE__ */ new Map(); @@ -123238,6 +123665,13 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW resolutionHost.getCompilationSettings(), moduleResolutionCache.getPackageJsonInfoCache() ); + const resolvedLibraries = /* @__PURE__ */ new Map(); + const libraryResolutionCache = createModuleResolutionCache( + getCurrentDirectory(), + resolutionHost.getCanonicalFileName, + getOptionsForLibraryResolution(resolutionHost.getCompilationSettings()), + moduleResolutionCache.getPackageJsonInfoCache() + ); const directoryWatchesOfFailedLookups = /* @__PURE__ */ new Map(); const fileWatchesOfAffectingLocations = /* @__PURE__ */ new Map(); const rootDir = getRootDirectoryOfResolutionCache(rootDirForResolution, getCurrentDirectory); @@ -123254,6 +123688,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW finishCachingPerDirectoryResolution, resolveModuleNameLiterals, resolveTypeReferenceDirectiveReferences, + resolveLibrary: resolveLibrary2, resolveSingleModuleNameWithoutWatching, removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile, @@ -123265,7 +123700,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch, closeTypeRootsWatch, - clear: clear2 + clear: clear2, + onChangesAffectModuleResolution }; function getResolvedModule2(resolution) { return resolution.resolvedModule; @@ -123288,13 +123724,23 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW isInDirectoryChecks = void 0; affectingPathChecks = void 0; affectingPathChecksForFile = void 0; + allModuleAndTypeResolutionsAreInvalidated = false; moduleResolutionCache.clear(); typeReferenceDirectiveResolutionCache.clear(); moduleResolutionCache.update(resolutionHost.getCompilationSettings()); typeReferenceDirectiveResolutionCache.update(resolutionHost.getCompilationSettings()); + libraryResolutionCache.clear(); impliedFormatPackageJsons.clear(); + resolvedLibraries.clear(); hasChangedAutomaticTypeDirectiveNames = false; } + function onChangesAffectModuleResolution() { + allModuleAndTypeResolutionsAreInvalidated = true; + moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); + typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + moduleResolutionCache.update(resolutionHost.getCompilationSettings()); + typeReferenceDirectiveResolutionCache.update(resolutionHost.getCompilationSettings()); + } function startRecordingFilesWithChangedResolutions() { filesWithChangedSetOfUnresolvedImports = []; } @@ -123310,23 +123756,45 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW const value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); return !!value && !!value.length; } - function createHasInvalidatedResolutions(customHasInvalidatedResolutions) { + function createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidatedLibResolutions) { invalidateResolutionsOfFailedLookupLocations(); const collected = filesWithInvalidatedResolutions; filesWithInvalidatedResolutions = void 0; - return (path) => customHasInvalidatedResolutions(path) || !!(collected == null ? void 0 : collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); + return { + hasInvalidatedResolutions: (path) => customHasInvalidatedResolutions(path) || allModuleAndTypeResolutionsAreInvalidated || !!(collected == null ? void 0 : collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path), + hasInvalidatedLibResolutions: (libFileName) => { + var _a; + return customHasInvalidatedLibResolutions(libFileName) || !!((_a = resolvedLibraries == null ? void 0 : resolvedLibraries.get(libFileName)) == null ? void 0 : _a.isInvalidated); + } + }; } function startCachingPerDirectoryResolution() { moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + libraryResolutionCache.clearAllExceptPackageJsonInfoCache(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } + function cleanupLibResolutionWatching(newProgram) { + resolvedLibraries.forEach((resolution, libFileName) => { + var _a; + if (!((_a = newProgram == null ? void 0 : newProgram.resolvedLibReferences) == null ? void 0 : _a.has(libFileName))) { + stopWatchFailedLookupLocationOfResolution( + resolution, + resolutionHost.toPath(getInferredLibraryNameResolveFrom(newProgram.getCompilerOptions(), getCurrentDirectory(), libFileName)), + getResolvedModule2 + ); + resolvedLibraries.delete(libFileName); + } + }); + } function finishCachingPerDirectoryResolution(newProgram, oldProgram) { filesWithInvalidatedNonRelativeUnresolvedImports = void 0; + allModuleAndTypeResolutionsAreInvalidated = false; nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); if (newProgram !== oldProgram) { + cleanupLibResolutionWatching(newProgram); newProgram == null ? void 0 : newProgram.getSourceFiles().forEach((newFile) => { var _a; const expected = isExternalOrCommonJsModule(newFile) ? ((_a = newFile.packageJsonLocations) == null ? void 0 : _a.length) ?? 0 : 0; @@ -123418,6 +123886,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW reusedNames, loader, getResolutionWithResolvedFileName, + deferWatchingNonRelativeResolution, shouldRetryResolution, logChanges }) { @@ -123434,15 +123903,15 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW const name = loader.nameAndMode.getName(entry); const mode = loader.nameAndMode.getMode(entry, containingSourceFile); let resolution = resolutionsInFile.get(name, mode); - if (!seenNamesInFile.has(name, mode) && unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate - hasInvalidatedNonRelativeUnresolvedImport && !isExternalModuleNameRelative(name) && shouldRetryResolution(resolution)) { + 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))) { const existingResolution = resolution; resolution = loader.resolve(name, mode); if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) { resolutionHost.onDiscoveredSymlink(); } resolutionsInFile.set(name, mode, resolution); - watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution); if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName); } @@ -123518,7 +123987,8 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW typeReferenceDirectiveResolutionCache ), getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective2, - shouldRetryResolution: (resolution) => resolution.resolvedTypeReferenceDirective === void 0 + shouldRetryResolution: (resolution) => resolution.resolvedTypeReferenceDirective === void 0, + deferWatchingNonRelativeResolution: false }); } function resolveModuleNameLiterals(moduleLiterals, containingFile, redirectedReference, options, containingSourceFile, reusedNames) { @@ -123537,9 +124007,46 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW ), getResolutionWithResolvedFileName: getResolvedModule2, shouldRetryResolution: (resolution) => !resolution.resolvedModule || !resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension), - logChanges: logChangesWhenResolvingModule + logChanges: logChangesWhenResolvingModule, + deferWatchingNonRelativeResolution: true + // Defer non relative resolution watch because we could be using ambient modules }); } + function resolveLibrary2(libraryName, resolveFrom, options, libFileName) { + var _a; + const host = ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost; + let resolution = resolvedLibraries == null ? void 0 : resolvedLibraries.get(libFileName); + if (!resolution || resolution.isInvalidated) { + const existingResolution = resolution; + resolution = resolveLibrary(libraryName, resolveFrom, options, host, libraryResolutionCache); + const path = resolutionHost.toPath(resolveFrom); + watchFailedLookupLocationsOfExternalModuleResolutions( + libraryName, + resolution, + path, + getResolvedModule2, + /*deferWatchingNonRelativeResolution*/ + false + ); + resolvedLibraries.set(libFileName, resolution); + if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolvedModule2); + } + } else { + if (isTraceEnabled(options, host)) { + const resolved = getResolvedModule2(resolution); + trace( + host, + (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.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, + resolveFrom, + resolved == null ? void 0 : resolved.resolvedFileName, + (resolved == null ? void 0 : resolved.packageId) && packageIdToString(resolved.packageId) + ); + } + } + return resolution; + } function resolveSingleModuleNameWithoutWatching(moduleName, containingFile) { const path = resolutionHost.toPath(containingFile); const resolutionsInFile = resolvedModuleNames.get(path); @@ -123555,7 +124062,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW function isNodeModulesAtTypesDirectory(dirPath) { return endsWith(dirPath, "/node_modules/@types"); } - function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) { + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution) { var _a; if (resolution.refCount) { resolution.refCount++; @@ -123563,7 +124070,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW } else { resolution.refCount = 1; Debug.assert(!((_a = resolution.files) == null ? void 0 : _a.size)); - if (isExternalModuleNameRelative(name)) { + if (!deferWatchingNonRelativeResolution || isExternalModuleNameRelative(name)) { watchFailedLookupLocationOfResolution(resolution); } else { nonRelativeExternalModuleResolutions.add(name, resolution); @@ -123579,45 +124086,51 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW } (resolution.files ?? (resolution.files = /* @__PURE__ */ new Set())).add(filePath); } + function watchFailedLookupLocation(failedLookupLocation, setAtRoot) { + const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + const toWatch = getDirectoryToWatchFailedLookupLocation( + failedLookupLocation, + failedLookupLocationPath, + rootDir, + rootPath, + rootPathComponents, + getCurrentDirectory + ); + if (toWatch) { + const { dir, dirPath, nonRecursive } = toWatch; + if (dirPath === rootPath) { + Debug.assert(nonRecursive); + setAtRoot = true; + } else { + setDirectoryWatcher(dir, dirPath, nonRecursive); + } + } + return setAtRoot; + } function watchFailedLookupLocationOfResolution(resolution) { Debug.assert(!!resolution.refCount); - const { failedLookupLocations, affectingLocations } = resolution; - if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length)) + const { failedLookupLocations, affectingLocations, node10Result } = resolution; + if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length) && !node10Result) return; - if (failedLookupLocations == null ? void 0 : failedLookupLocations.length) + if ((failedLookupLocations == null ? void 0 : failedLookupLocations.length) || node10Result) resolutionsWithFailedLookups.add(resolution); let setAtRoot = false; if (failedLookupLocations) { for (const failedLookupLocation of failedLookupLocations) { - const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - const toWatch = getDirectoryToWatchFailedLookupLocation( - failedLookupLocation, - failedLookupLocationPath, - rootDir, - rootPath, - rootPathComponents, - getCurrentDirectory - ); - if (toWatch) { - const { dir, dirPath, nonRecursive } = toWatch; - if (dirPath === rootPath) { - Debug.assert(nonRecursive); - setAtRoot = true; - } else { - setDirectoryWatcher(dir, dirPath, nonRecursive); - } - } - } - if (setAtRoot) { - setDirectoryWatcher( - rootDir, - rootPath, - /*nonRecursive*/ - true - ); + setAtRoot = watchFailedLookupLocation(failedLookupLocation, setAtRoot); } } - watchAffectingLocationsOfResolution(resolution, !(failedLookupLocations == null ? void 0 : failedLookupLocations.length)); + if (node10Result) + setAtRoot = watchFailedLookupLocation(node10Result, setAtRoot); + if (setAtRoot) { + setDirectoryWatcher( + rootDir, + rootPath, + /*nonRecursive*/ + true + ); + } + watchAffectingLocationsOfResolution(resolution, !(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !node10Result); } function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) { Debug.assert(!!resolution.refCount); @@ -123711,6 +124224,26 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive }); } } + function stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot) { + const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + const toWatch = getDirectoryToWatchFailedLookupLocation( + failedLookupLocation, + failedLookupLocationPath, + rootDir, + rootPath, + rootPathComponents, + getCurrentDirectory + ); + if (toWatch) { + const { dirPath } = toWatch; + if (dirPath === rootPath) { + removeAtRoot = true; + } else { + removeDirectoryWatcher(dirPath); + } + } + return removeAtRoot; + } function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) { Debug.checkDefined(resolution.files).delete(filePath); resolution.refCount--; @@ -123724,31 +124257,18 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW if ((resolutions == null ? void 0 : resolutions.delete(resolution)) && !resolutions.size) resolvedFileToResolution.delete(key); } - const { failedLookupLocations, affectingLocations } = resolution; + const { failedLookupLocations, affectingLocations, node10Result } = resolution; if (resolutionsWithFailedLookups.delete(resolution)) { let removeAtRoot = false; - for (const failedLookupLocation of failedLookupLocations) { - const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - const toWatch = getDirectoryToWatchFailedLookupLocation( - failedLookupLocation, - failedLookupLocationPath, - rootDir, - rootPath, - rootPathComponents, - getCurrentDirectory - ); - if (toWatch) { - const { dirPath } = toWatch; - if (dirPath === rootPath) { - removeAtRoot = true; - } else { - removeDirectoryWatcher(dirPath); - } + if (failedLookupLocations) { + for (const failedLookupLocation of failedLookupLocations) { + removeAtRoot = stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot); } } - if (removeAtRoot) { + if (node10Result) + removeAtRoot = stopWatchFailedLookupLocation(node10Result, removeAtRoot); + if (removeAtRoot) removeDirectoryWatcher(rootPath); - } } else if (affectingLocations == null ? void 0 : affectingLocations.length) { resolutionsWithOnlyAffectingLocations.delete(resolution); } @@ -123843,15 +124363,37 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW return false; } (failedLookupChecks || (failedLookupChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); - const packagePath = parseNodeModuleFromPath(fileOrDirectoryPath); + const packagePath = parseNodeModuleFromPath( + fileOrDirectoryPath, + /*isFolder*/ + true + ); if (packagePath) (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } + function invalidatePackageJsonMap() { + const packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) { + packageJsonMap.forEach((_value, path) => isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : void 0); + } + } function invalidateResolutionsOfFailedLookupLocations() { var _a; + if (allModuleAndTypeResolutionsAreInvalidated) { + affectingPathChecksForFile = void 0; + invalidatePackageJsonMap(); + if (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks || affectingPathChecks) { + invalidateResolutions(resolvedLibraries, canInvalidateFailedLookupResolution); + } + failedLookupChecks = void 0; + startsWithPathChecks = void 0; + isInDirectoryChecks = void 0; + affectingPathChecks = void 0; + return true; + } let invalidated = false; if (affectingPathChecksForFile) { (_a = resolutionHost.getCurrentProgram()) == null ? void 0 : _a.getSourceFiles().forEach((f) => { @@ -123866,10 +124408,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW return invalidated; } invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution) || invalidated; - const packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); - if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) { - packageJsonMap.forEach((_value, path) => isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : void 0); - } + invalidatePackageJsonMap(); failedLookupChecks = void 0; startsWithPathChecks = void 0; isInDirectoryChecks = void 0; @@ -123883,7 +124422,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW return true; if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) return false; - return (_a = resolution.failedLookupLocations) == null ? void 0 : _a.some((location) => isInvalidatedFailedLookup(resolutionHost.toPath(location))); + return ((_a = resolution.failedLookupLocations) == null ? void 0 : _a.some((location) => isInvalidatedFailedLookup(resolutionHost.toPath(location)))) || !!resolution.node10Result && isInvalidatedFailedLookup(resolutionHost.toPath(resolution.node10Result)); } function isInvalidatedFailedLookup(locationPath) { return (failedLookupChecks == null ? void 0 : failedLookupChecks.has(locationPath)) || firstDefinedIterator((startsWithPathChecks == null ? void 0 : startsWithPathChecks.keys()) || [], (fileOrDirectoryPath) => startsWith(locationPath, fileOrDirectoryPath) ? true : void 0) || firstDefinedIterator((isInDirectoryChecks == null ? void 0 : isInDirectoryChecks.keys()) || [], (dirPath) => locationPath.length > dirPath.length && startsWith(locationPath, dirPath) && (isDiskPathRoot(dirPath) || locationPath[dirPath.length] === directorySeparator) ? true : void 0); @@ -124412,7 +124951,9 @@ var WatchType = { 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" + NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation", + TypingInstallerLocationFile: "File location for typing installer", + TypingInstallerLocationDirectory: "Directory location for typing installer" }; function createWatchFactory(host, options) { const watchLogLevel = host.trace ? options.extendedDiagnostics ? 2 /* Verbose */ : options.diagnostics ? 1 /* TriggerOnly */ : 0 /* None */ : 0 /* None */; @@ -124750,9 +125291,11 @@ function createWatchProgram(host) { if (!compilerHost.resolveTypeReferenceDirectiveReferences && !compilerHost.resolveTypeReferenceDirectives) { compilerHost.resolveTypeReferenceDirectiveReferences = resolutionCache.resolveTypeReferenceDirectiveReferences.bind(resolutionCache); } + compilerHost.resolveLibrary = !host.resolveLibrary ? resolutionCache.resolveLibrary.bind(resolutionCache) : host.resolveLibrary.bind(host); compilerHost.getModuleResolutionCache = host.resolveModuleNameLiterals || host.resolveModuleNames ? maybeBind(host, host.getModuleResolutionCache) : () => resolutionCache.getModuleResolutionCache(); const userProvidedResolution = !!host.resolveModuleNameLiterals || !!host.resolveTypeReferenceDirectiveReferences || !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; const customHasInvalidatedResolutions = userProvidedResolution ? maybeBind(host, host.hasInvalidatedResolutions) || returnTrue : returnFalse; + const customHasInvalidLibResolutions = host.resolveLibrary ? maybeBind(host, host.hasInvalidatedLibResolutions) || returnTrue : returnFalse; builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); watchConfigFileWildCardDirectories(); @@ -124813,10 +125356,11 @@ function createWatchProgram(host) { if (hasChangedCompilerOptions) { newLine = updateNewLine(); if (program && changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { - resolutionCache.clear(); + debugger; + resolutionCache.onChangesAffectModuleResolution(); } } - const hasInvalidatedResolutions = resolutionCache.createHasInvalidatedResolutions(customHasInvalidatedResolutions); + const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = resolutionCache.createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidLibResolutions); const { originalReadFile, originalFileExists, @@ -124825,7 +125369,7 @@ function createWatchProgram(host) { originalWriteFile, readFileWithCache } = changeCompilerHostLikeToUseCache(compilerHost, toPath3); - if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, (path) => getSourceVersion(path, readFileWithCache), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, (path) => getSourceVersion(path, readFileWithCache), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { if (reportFileChangeDetectedOnCreateProgram) { reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation); @@ -124846,7 +125390,7 @@ function createWatchProgram(host) { if (reportFileChangeDetectedOnCreateProgram) { reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation); } - createNewProgram(hasInvalidatedResolutions); + createNewProgram(hasInvalidatedResolutions, hasInvalidatedLibResolutions); } reportFileChangeDetectedOnCreateProgram = false; if (host.afterProgramCreate && program !== builderProgram) { @@ -124859,7 +125403,7 @@ function createWatchProgram(host) { compilerHost.writeFile = originalWriteFile; return builderProgram; } - function createNewProgram(hasInvalidatedResolutions) { + function createNewProgram(hasInvalidatedResolutions, hasInvalidatedLibResolutions) { writeLog("CreatingProgramWith::"); writeLog(` roots: ${JSON.stringify(rootFileNames)}`); writeLog(` options: ${JSON.stringify(compilerOptions)}`); @@ -124870,6 +125414,7 @@ function createWatchProgram(host) { hasChangedConfigFileParsingErrors = false; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolutions = hasInvalidatedResolutions; + compilerHost.hasInvalidatedLibResolutions = hasInvalidatedLibResolutions; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; const oldProgram = getCurrentProgram(); builderProgram = createProgram2(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); @@ -125443,6 +125988,7 @@ function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, optio compilerHost.getParsedCommandLine = (fileName) => parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); compilerHost.resolveModuleNameLiterals = maybeBind(host, host.resolveModuleNameLiterals); compilerHost.resolveTypeReferenceDirectiveReferences = maybeBind(host, host.resolveTypeReferenceDirectiveReferences); + compilerHost.resolveLibrary = maybeBind(host, host.resolveLibrary); compilerHost.resolveModuleNames = maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = maybeBind(host, host.resolveTypeReferenceDirectives); compilerHost.getModuleResolutionCache = maybeBind(host, host.getModuleResolutionCache); @@ -125480,6 +126026,23 @@ function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, optio createTypeReferenceResolutionLoader ); } + let libraryResolutionCache; + if (!compilerHost.resolveLibrary) { + libraryResolutionCache = createModuleResolutionCache( + compilerHost.getCurrentDirectory(), + compilerHost.getCanonicalFileName, + /*options*/ + void 0, + moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache() + ); + compilerHost.resolveLibrary = (libraryName, resolveFrom, options2) => resolveLibrary( + libraryName, + resolveFrom, + options2, + host, + libraryResolutionCache + ); + } compilerHost.getBuildInfo = (fileName, configFilePath) => getBuildInfo3( state, fileName, @@ -125511,6 +126074,7 @@ function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, optio compilerHost, moduleResolutionCache, typeReferenceDirectiveResolutionCache, + libraryResolutionCache, // Mutable state buildOrder: void 0, readFileWithCache: (f) => host.readFile(f), @@ -125728,7 +126292,7 @@ function enableCache(state) { function disableCache(state) { if (!state.cache) return; - const { cache, host, compilerHost, extendedConfigCache, moduleResolutionCache, typeReferenceDirectiveResolutionCache } = state; + const { cache, host, compilerHost, extendedConfigCache, moduleResolutionCache, typeReferenceDirectiveResolutionCache, libraryResolutionCache } = state; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -125739,6 +126303,7 @@ function disableCache(state) { extendedConfigCache.clear(); moduleResolutionCache == null ? void 0 : moduleResolutionCache.clear(); typeReferenceDirectiveResolutionCache == null ? void 0 : typeReferenceDirectiveResolutionCache.clear(); + libraryResolutionCache == null ? void 0 : libraryResolutionCache.clear(); state.cache = void 0; } function clearProjectStatus(state, resolved) { @@ -127668,6 +128233,7 @@ var EventTypesRegistry = "event::typesRegistry"; var EventBeginInstallTypes = "event::beginInstallTypes"; var EventEndInstallTypes = "event::endInstallTypes"; var EventInitializationFailed = "event::initializationFailed"; +var ActionWatchTypingLocations = "action::watchTypingLocations"; var Arguments; ((Arguments2) => { Arguments2.GlobalCacheLocation = "--globalTypingsCacheLocation"; @@ -129496,10 +130062,10 @@ function makeImport(defaultImport, namedImports, moduleSpecifier, quotePreferenc function makeStringLiteral(text, quotePreference) { return factory.createStringLiteral(text, quotePreference === 0 /* Single */); } -var QuotePreference = /* @__PURE__ */ ((QuotePreference5) => { - QuotePreference5[QuotePreference5["Single"] = 0] = "Single"; - QuotePreference5[QuotePreference5["Double"] = 1] = "Double"; - return QuotePreference5; +var QuotePreference = /* @__PURE__ */ ((QuotePreference7) => { + QuotePreference7[QuotePreference7["Single"] = 0] = "Single"; + QuotePreference7[QuotePreference7["Double"] = 1] = "Double"; + return QuotePreference7; })(QuotePreference || {}); function quotePreferenceFromString(str, sourceFile) { return isStringDoubleQuoted(str, sourceFile) ? 1 /* Double */ : 0 /* Single */; @@ -130027,7 +130593,12 @@ function getSynthesizedDeepCloneWorker(node, replaceNode) { return visited; } function getSynthesizedDeepClones(nodes, includeTrivia = true) { - return nodes && factory.createNodeArray(nodes.map((n) => getSynthesizedDeepClone(n, includeTrivia)), nodes.hasTrailingComma); + if (nodes) { + const cloned = factory.createNodeArray(nodes.map((n) => getSynthesizedDeepClone(n, includeTrivia)), nodes.hasTrailingComma); + setTextRange(cloned, nodes); + return cloned; + } + return nodes; } function getSynthesizedDeepClonesWithReplacements(nodes, includeTrivia, replaceNode) { return factory.createNodeArray(nodes.map((n) => getSynthesizedDeepCloneWithReplacements(n, includeTrivia, replaceNode)), nodes.hasTrailingComma); @@ -130753,6 +131324,37 @@ function newCaseClauseTracker(checker, clauses) { } } } +function fileShouldUseJavaScriptRequire(file, program, host, preferRequire) { + var _a; + const fileName = typeof file === "string" ? file : file.fileName; + if (!hasJSFileExtension(fileName)) { + return false; + } + const compilerOptions = program.getCompilerOptions(); + const moduleKind = getEmitModuleKind(compilerOptions); + const impliedNodeFormat = typeof file === "string" ? getImpliedNodeFormatForFile(toPath(file, host.getCurrentDirectory(), hostGetCanonicalFileName(host)), (_a = program.getPackageJsonInfoCache) == null ? void 0 : _a.call(program), host, compilerOptions) : file.impliedNodeFormat; + if (impliedNodeFormat === 99 /* ESNext */) { + return false; + } + if (impliedNodeFormat === 1 /* CommonJS */) { + return true; + } + if (compilerOptions.verbatimModuleSyntax && moduleKind === 1 /* CommonJS */) { + return true; + } + if (compilerOptions.verbatimModuleSyntax && emitModuleKindIsNonNodeESM(moduleKind)) { + return false; + } + if (typeof file === "object") { + if (file.commonJsModuleIndicator) { + return true; + } + if (file.externalModuleIndicator) { + return false; + } + } + return preferRequire; +} // src/services/exportInfoMap.ts var ImportKind = /* @__PURE__ */ ((ImportKind2) => { @@ -134894,6 +135496,5099 @@ function cleanText(text) { return text.replace(/\\?(\r?\n|\r|\u2028|\u2029)/g, ""); } +// src/services/_namespaces/ts.refactor.ts +var ts_refactor_exports = {}; +__export(ts_refactor_exports, { + addExportToChanges: () => addExportToChanges, + addExports: () => addExports, + addNewFileToTsconfig: () => addNewFileToTsconfig, + addOrRemoveBracesToArrowFunction: () => ts_refactor_addOrRemoveBracesToArrowFunction_exports, + convertArrowFunctionOrFunctionExpression: () => ts_refactor_convertArrowFunctionOrFunctionExpression_exports, + convertParamsToDestructuredObject: () => ts_refactor_convertParamsToDestructuredObject_exports, + convertStringOrTemplateLiteral: () => ts_refactor_convertStringOrTemplateLiteral_exports, + convertToOptionalChainExpression: () => ts_refactor_convertToOptionalChainExpression_exports, + createNewFileName: () => createNewFileName, + createOldFileImportsFromTargetFile: () => createOldFileImportsFromTargetFile, + deleteMovedStatements: () => deleteMovedStatements, + deleteUnusedImports: () => deleteUnusedImports, + deleteUnusedOldImports: () => deleteUnusedOldImports, + doChangeNamedToNamespaceOrDefault: () => doChangeNamedToNamespaceOrDefault, + extractSymbol: () => ts_refactor_extractSymbol_exports, + filterImport: () => filterImport, + forEachImportInStatement: () => forEachImportInStatement, + generateGetAccessorAndSetAccessor: () => ts_refactor_generateGetAccessorAndSetAccessor_exports, + getApplicableRefactors: () => getApplicableRefactors, + getEditsForRefactor: () => getEditsForRefactor, + getStatementsToMove: () => getStatementsToMove, + getTopLevelDeclarationStatement: () => getTopLevelDeclarationStatement, + getUsageInfo: () => getUsageInfo, + inferFunctionReturnType: () => ts_refactor_inferFunctionReturnType_exports, + isRefactorErrorInfo: () => isRefactorErrorInfo, + isTopLevelDeclaration: () => isTopLevelDeclaration, + makeImportOrRequire: () => makeImportOrRequire, + moduleSpecifierFromImport: () => moduleSpecifierFromImport, + nameOfTopLevelDeclaration: () => nameOfTopLevelDeclaration, + refactorKindBeginsWith: () => refactorKindBeginsWith, + registerRefactor: () => registerRefactor, + updateImportsInOtherFiles: () => updateImportsInOtherFiles +}); + +// src/services/refactorProvider.ts +var refactors = /* @__PURE__ */ new Map(); +function registerRefactor(name, refactor) { + refactors.set(name, refactor); +} +function getApplicableRefactors(context, includeInteractiveActions) { + return arrayFrom(flatMapIterator(refactors.values(), (refactor) => { + var _a; + return context.cancellationToken && context.cancellationToken.isCancellationRequested() || !((_a = refactor.kinds) == null ? void 0 : _a.some((kind) => refactorKindBeginsWith(kind, context.kind))) ? void 0 : refactor.getAvailableActions(context, includeInteractiveActions); + })); +} +function getEditsForRefactor(context, refactorName13, actionName2, interactiveRefactorArguments) { + const refactor = refactors.get(refactorName13); + return refactor && refactor.getEditsForAction(context, actionName2, interactiveRefactorArguments); +} + +// src/services/refactors/convertExport.ts +var refactorName = "Convert export"; +var defaultToNamedAction = { + name: "Convert default export to named export", + description: Diagnostics.Convert_default_export_to_named_export.message, + kind: "refactor.rewrite.export.named" +}; +var namedToDefaultAction = { + name: "Convert named export to default export", + description: Diagnostics.Convert_named_export_to_default_export.message, + kind: "refactor.rewrite.export.default" +}; +registerRefactor(refactorName, { + kinds: [ + defaultToNamedAction.kind, + namedToDefaultAction.kind + ], + getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndDefaultExports(context) { + const info = getInfo2(context, context.triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + const action = info.wasDefault ? defaultToNamedAction : namedToDefaultAction; + return [{ name: refactorName, description: action.description, actions: [action] }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [ + { name: refactorName, description: Diagnostics.Convert_default_export_to_named_export.message, actions: [ + { ...defaultToNamedAction, notApplicableReason: info.error }, + { ...namedToDefaultAction, notApplicableReason: info.error } + ] } + ]; + } + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndDefaultExports(context, actionName2) { + Debug.assert(actionName2 === defaultToNamedAction.name || actionName2 === namedToDefaultAction.name, "Unexpected action name"); + const info = getInfo2(context); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange(context.file, context.program, info, t, context.cancellationToken)); + return { edits, renameFilename: void 0, renameLocation: void 0 }; + } +}); +function getInfo2(context, considerPartialSpans = true) { + const { file, program } = context; + const span = getRefactorContextSpan(context); + const token = getTokenAtPosition(file, span.start); + const exportNode = !!(token.parent && getSyntacticModifierFlags(token.parent) & 1 /* Export */) && considerPartialSpans ? token.parent : getParentNodeInSpan(token, file, span); + if (!exportNode || !isSourceFile(exportNode.parent) && !(isModuleBlock(exportNode.parent) && isAmbientModule(exportNode.parent.parent))) { + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_export_statement) }; + } + const checker = program.getTypeChecker(); + const exportingModuleSymbol = getExportingModuleSymbol(exportNode.parent, checker); + const flags = getSyntacticModifierFlags(exportNode) || (isExportAssignment(exportNode) && !exportNode.isExportEquals ? 1025 /* ExportDefault */ : 0 /* None */); + const wasDefault = !!(flags & 1024 /* Default */); + if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { + return { error: getLocaleSpecificMessage(Diagnostics.This_file_already_has_a_default_export) }; + } + const noSymbolError = (id) => isIdentifier(id) && checker.getSymbolAtLocation(id) ? void 0 : { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_named_export) }; + switch (exportNode.kind) { + case 261 /* FunctionDeclaration */: + case 262 /* ClassDeclaration */: + case 263 /* InterfaceDeclaration */: + case 265 /* EnumDeclaration */: + case 264 /* TypeAliasDeclaration */: + case 266 /* ModuleDeclaration */: { + const node = exportNode; + if (!node.name) + return void 0; + return noSymbolError(node.name) || { exportNode: node, exportName: node.name, wasDefault, exportingModuleSymbol }; + } + case 242 /* VariableStatement */: { + const vs = exportNode; + if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { + return void 0; + } + const decl = first(vs.declarationList.declarations); + if (!decl.initializer) + return void 0; + Debug.assert(!wasDefault, "Can't have a default flag here"); + return noSymbolError(decl.name) || { exportNode: vs, exportName: decl.name, wasDefault, exportingModuleSymbol }; + } + case 276 /* ExportAssignment */: { + const node = exportNode; + if (node.isExportEquals) + return void 0; + return noSymbolError(node.expression) || { exportNode: node, exportName: node.expression, wasDefault, exportingModuleSymbol }; + } + default: + return void 0; + } +} +function doChange(exportingSourceFile, program, info, changes, cancellationToken) { + changeExport(exportingSourceFile, info, changes, program.getTypeChecker()); + changeImports(program, info, changes, cancellationToken); +} +function changeExport(exportingSourceFile, { wasDefault, exportNode, exportName }, changes, checker) { + if (wasDefault) { + if (isExportAssignment(exportNode) && !exportNode.isExportEquals) { + const exp = exportNode.expression; + const spec = makeExportSpecifier(exp.text, exp.text); + changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createNamedExports([spec]) + )); + } else { + changes.delete(exportingSourceFile, Debug.checkDefined(findModifier(exportNode, 90 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + } + } else { + const exportKeyword = Debug.checkDefined(findModifier(exportNode, 95 /* ExportKeyword */), "Should find an export keyword in modifier list"); + switch (exportNode.kind) { + case 261 /* FunctionDeclaration */: + case 262 /* ClassDeclaration */: + case 263 /* InterfaceDeclaration */: + changes.insertNodeAfter(exportingSourceFile, exportKeyword, factory.createToken(90 /* DefaultKeyword */)); + break; + case 242 /* VariableStatement */: + const decl = first(exportNode.declarationList.declarations); + if (!ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile) && !decl.type) { + changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDefault(Debug.checkDefined(decl.initializer, "Initializer was previously known to be present"))); + break; + } + case 265 /* EnumDeclaration */: + case 264 /* TypeAliasDeclaration */: + case 266 /* ModuleDeclaration */: + changes.deleteModifier(exportingSourceFile, exportKeyword); + changes.insertNodeAfter(exportingSourceFile, exportNode, factory.createExportDefault(factory.createIdentifier(exportName.text))); + break; + default: + Debug.fail(`Unexpected exportNode kind ${exportNode.kind}`); + } + } +} +function changeImports(program, { wasDefault, exportName, exportingModuleSymbol }, changes, cancellationToken) { + const checker = program.getTypeChecker(); + const exportSymbol = Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol"); + ts_FindAllReferences_exports.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, (ref) => { + if (exportName === ref) + return; + const importingSourceFile = ref.getSourceFile(); + if (wasDefault) { + changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); + } else { + changeNamedToDefaultImport(importingSourceFile, ref, changes); + } + }); +} +function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { + const { parent: parent2 } = ref; + switch (parent2.kind) { + case 210 /* PropertyAccessExpression */: + changes.replaceNode(importingSourceFile, ref, factory.createIdentifier(exportName)); + break; + case 275 /* ImportSpecifier */: + case 280 /* ExportSpecifier */: { + const spec = parent2; + changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); + break; + } + case 272 /* ImportClause */: { + const clause = parent2; + Debug.assert(clause.name === ref, "Import clause name should match provided ref"); + const spec = makeImportSpecifier(exportName, ref.text); + const { namedBindings } = clause; + if (!namedBindings) { + changes.replaceNode(importingSourceFile, ref, factory.createNamedImports([spec])); + } else if (namedBindings.kind === 273 /* NamespaceImport */) { + changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); + const quotePreference = isStringLiteral(clause.parent.moduleSpecifier) ? quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; + const newImport = makeImport( + /*defaultImport*/ + void 0, + [makeImportSpecifier(exportName, ref.text)], + clause.parent.moduleSpecifier, + quotePreference + ); + changes.insertNodeAfter(importingSourceFile, clause.parent, newImport); + } else { + changes.delete(importingSourceFile, ref); + changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec); + } + break; + } + case 204 /* ImportType */: + const importTypeNode = parent2; + changes.replaceNode(importingSourceFile, parent2, factory.createImportTypeNode(importTypeNode.argument, importTypeNode.assertions, factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); + break; + default: + Debug.failBadSyntaxKind(parent2); + } +} +function changeNamedToDefaultImport(importingSourceFile, ref, changes) { + const parent2 = ref.parent; + switch (parent2.kind) { + case 210 /* PropertyAccessExpression */: + changes.replaceNode(importingSourceFile, ref, factory.createIdentifier("default")); + break; + case 275 /* ImportSpecifier */: { + const defaultImport = factory.createIdentifier(parent2.name.text); + if (parent2.parent.elements.length === 1) { + changes.replaceNode(importingSourceFile, parent2.parent, defaultImport); + } else { + changes.delete(importingSourceFile, parent2); + changes.insertNodeBefore(importingSourceFile, parent2.parent, defaultImport); + } + break; + } + case 280 /* ExportSpecifier */: { + changes.replaceNode(importingSourceFile, parent2, makeExportSpecifier("default", parent2.name.text)); + break; + } + default: + Debug.assertNever(parent2, `Unexpected parent kind ${parent2.kind}`); + } +} +function makeImportSpecifier(propertyName, name) { + return factory.createImportSpecifier( + /*isTypeOnly*/ + false, + propertyName === name ? void 0 : factory.createIdentifier(propertyName), + factory.createIdentifier(name) + ); +} +function makeExportSpecifier(propertyName, name) { + return factory.createExportSpecifier( + /*isTypeOnly*/ + false, + propertyName === name ? void 0 : factory.createIdentifier(propertyName), + factory.createIdentifier(name) + ); +} +function getExportingModuleSymbol(parent2, checker) { + if (isSourceFile(parent2)) { + return parent2.symbol; + } + const symbol = parent2.parent.symbol; + if (symbol.valueDeclaration && isExternalModuleAugmentation(symbol.valueDeclaration)) { + return checker.getMergedSymbol(symbol); + } + return symbol; +} + +// src/services/refactors/convertImport.ts +var refactorName2 = "Convert import"; +var actions = { + [0 /* Named */]: { + name: "Convert namespace import to named imports", + description: Diagnostics.Convert_namespace_import_to_named_imports.message, + kind: "refactor.rewrite.import.named" + }, + [2 /* Namespace */]: { + name: "Convert named imports to namespace import", + description: Diagnostics.Convert_named_imports_to_namespace_import.message, + kind: "refactor.rewrite.import.namespace" + }, + [1 /* Default */]: { + name: "Convert named imports to default import", + description: Diagnostics.Convert_named_imports_to_default_import.message, + kind: "refactor.rewrite.import.default" + } +}; +registerRefactor(refactorName2, { + kinds: getOwnValues(actions).map((a) => a.kind), + getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndNamespacedImports(context) { + const info = getImportConversionInfo(context, context.triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + const action = actions[info.convertTo]; + return [{ name: refactorName2, description: action.description, actions: [action] }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return getOwnValues(actions).map((action) => ({ + name: refactorName2, + description: action.description, + actions: [{ ...action, notApplicableReason: info.error }] + })); + } + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndNamespacedImports(context, actionName2) { + Debug.assert(some(getOwnValues(actions), (action) => action.name === actionName2), "Unexpected action name"); + const info = getImportConversionInfo(context); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange2(context.file, context.program, t, info)); + return { edits, renameFilename: void 0, renameLocation: void 0 }; + } +}); +function getImportConversionInfo(context, considerPartialSpans = true) { + const { file } = context; + const span = getRefactorContextSpan(context); + const token = getTokenAtPosition(file, span.start); + const importDecl = considerPartialSpans ? findAncestor(token, isImportDeclaration) : getParentNodeInSpan(token, file, span); + if (!importDecl || !isImportDeclaration(importDecl)) + return { error: "Selection is not an import declaration." }; + const end = span.start + span.length; + const nextToken = findNextToken(importDecl, importDecl.parent, file); + if (nextToken && end > nextToken.getStart()) + return void 0; + const { importClause } = importDecl; + if (!importClause) { + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_import_clause) }; + } + if (!importClause.namedBindings) { + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_namespace_import_or_named_imports) }; + } + if (importClause.namedBindings.kind === 273 /* NamespaceImport */) { + return { convertTo: 0 /* Named */, import: importClause.namedBindings }; + } + const shouldUseDefault = getShouldUseDefault(context.program, importClause); + return shouldUseDefault ? { convertTo: 1 /* Default */, import: importClause.namedBindings } : { convertTo: 2 /* Namespace */, import: importClause.namedBindings }; +} +function getShouldUseDefault(program, importClause) { + return getAllowSyntheticDefaultImports(program.getCompilerOptions()) && isExportEqualsModule(importClause.parent.moduleSpecifier, program.getTypeChecker()); +} +function doChange2(sourceFile, program, changes, info) { + const checker = program.getTypeChecker(); + if (info.convertTo === 0 /* Named */) { + doChangeNamespaceToNamed(sourceFile, checker, changes, info.import, getAllowSyntheticDefaultImports(program.getCompilerOptions())); + } else { + doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, info.import, info.convertTo === 1 /* Default */); + } +} +function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { + let usedAsNamespaceOrDefault = false; + const nodesToReplace = []; + const conflictingNames = /* @__PURE__ */ new Map(); + ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, (id) => { + if (!isPropertyAccessOrQualifiedName(id.parent)) { + usedAsNamespaceOrDefault = true; + } else { + const exportName = getRightOfPropertyAccessOrQualifiedName(id.parent).text; + if (checker.resolveName( + exportName, + id, + 67108863 /* All */, + /*excludeGlobals*/ + true + )) { + conflictingNames.set(exportName, true); + } + Debug.assert(getLeftOfPropertyAccessOrQualifiedName(id.parent) === id, "Parent expression should match id"); + nodesToReplace.push(id.parent); + } + }); + const exportNameToImportName = /* @__PURE__ */ new Map(); + for (const propertyAccessOrQualifiedName of nodesToReplace) { + const exportName = getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName).text; + let importName = exportNameToImportName.get(exportName); + if (importName === void 0) { + exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? getUniqueName(exportName, sourceFile) : exportName); + } + changes.replaceNode(sourceFile, propertyAccessOrQualifiedName, factory.createIdentifier(importName)); + } + const importSpecifiers = []; + exportNameToImportName.forEach((name, propertyName) => { + importSpecifiers.push(factory.createImportSpecifier( + /*isTypeOnly*/ + false, + name === propertyName ? void 0 : factory.createIdentifier(propertyName), + factory.createIdentifier(name) + )); + }); + const importDecl = toConvert.parent.parent; + if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) { + changes.insertNodeAfter(sourceFile, importDecl, updateImport( + importDecl, + /*defaultImportName*/ + void 0, + importSpecifiers + )); + } else { + changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? factory.createIdentifier(toConvert.name.text) : void 0, importSpecifiers)); + } +} +function getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { + return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.name : propertyAccessOrQualifiedName.right; +} +function getLeftOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { + return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.expression : propertyAccessOrQualifiedName.left; +} +function doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, toConvert, shouldUseDefault = getShouldUseDefault(program, toConvert.parent)) { + const checker = program.getTypeChecker(); + const importDecl = toConvert.parent.parent; + const { moduleSpecifier } = importDecl; + const toConvertSymbols = /* @__PURE__ */ new Set(); + toConvert.elements.forEach((namedImport) => { + const symbol = checker.getSymbolAtLocation(namedImport.name); + if (symbol) { + toConvertSymbols.add(symbol); + } + }); + const preferredName = moduleSpecifier && isStringLiteral(moduleSpecifier) ? ts_codefix_exports.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 99 /* ESNext */) : "module"; + function hasNamespaceNameConflict(namedImport) { + return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(namedImport.name, checker, sourceFile, (id) => { + const symbol = checker.resolveName( + preferredName, + id, + 67108863 /* All */, + /*excludeGlobals*/ + true + ); + if (symbol) { + if (toConvertSymbols.has(symbol)) { + return isExportSpecifier(id.parent); + } + return true; + } + return false; + }); + } + const namespaceNameConflicts = toConvert.elements.some(hasNamespaceNameConflict); + const namespaceImportName = namespaceNameConflicts ? getUniqueName(preferredName, sourceFile) : preferredName; + const neededNamedImports = /* @__PURE__ */ new Set(); + for (const element of toConvert.elements) { + const propertyName = (element.propertyName || element.name).text; + ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, (id) => { + const access = factory.createPropertyAccessExpression(factory.createIdentifier(namespaceImportName), propertyName); + if (isShorthandPropertyAssignment(id.parent)) { + changes.replaceNode(sourceFile, id.parent, factory.createPropertyAssignment(id.text, access)); + } else if (isExportSpecifier(id.parent)) { + neededNamedImports.add(element); + } else { + changes.replaceNode(sourceFile, id, access); + } + }); + } + changes.replaceNode(sourceFile, toConvert, shouldUseDefault ? factory.createIdentifier(namespaceImportName) : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName))); + if (neededNamedImports.size) { + const newNamedImports = 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*/ + void 0, + newNamedImports + )); + } +} +function isExportEqualsModule(moduleSpecifier, checker) { + const externalModule = checker.resolveExternalModuleName(moduleSpecifier); + if (!externalModule) + return false; + const exportEquals = checker.resolveExternalModuleSymbol(externalModule); + return externalModule !== exportEquals; +} +function updateImport(old, defaultImportName, elements) { + return factory.createImportDeclaration( + /*modifiers*/ + void 0, + factory.createImportClause( + /*isTypeOnly*/ + false, + defaultImportName, + elements && elements.length ? factory.createNamedImports(elements) : void 0 + ), + old.moduleSpecifier, + /*assertClause*/ + void 0 + ); +} + +// src/services/refactors/extractType.ts +var refactorName3 = "Extract type"; +var extractToTypeAliasAction = { + name: "Extract to type alias", + description: getLocaleSpecificMessage(Diagnostics.Extract_to_type_alias), + kind: "refactor.extract.type" +}; +var extractToInterfaceAction = { + name: "Extract to interface", + description: getLocaleSpecificMessage(Diagnostics.Extract_to_interface), + kind: "refactor.extract.interface" +}; +var extractToTypeDefAction = { + name: "Extract to typedef", + description: getLocaleSpecificMessage(Diagnostics.Extract_to_typedef), + kind: "refactor.extract.typedef" +}; +registerRefactor(refactorName3, { + kinds: [ + extractToTypeAliasAction.kind, + extractToInterfaceAction.kind, + extractToTypeDefAction.kind + ], + getAvailableActions: function getRefactorActionsToExtractType(context) { + const info = getRangeToExtract(context, context.triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + return [{ + name: refactorName3, + description: getLocaleSpecificMessage(Diagnostics.Extract_type), + actions: info.isJS ? [extractToTypeDefAction] : append([extractToTypeAliasAction], info.typeElements && extractToInterfaceAction) + }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorName3, + description: getLocaleSpecificMessage(Diagnostics.Extract_type), + actions: [ + { ...extractToTypeDefAction, notApplicableReason: info.error }, + { ...extractToTypeAliasAction, notApplicableReason: info.error }, + { ...extractToInterfaceAction, notApplicableReason: info.error } + ] + }]; + } + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToExtractType(context, actionName2) { + const { file } = context; + const info = getRangeToExtract(context); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected to find a range to extract"); + const name = getUniqueName("NewType", file); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (changes) => { + switch (actionName2) { + case extractToTypeAliasAction.name: + Debug.assert(!info.isJS, "Invalid actionName/JS combo"); + return doTypeAliasChange(changes, file, name, info); + case extractToTypeDefAction.name: + Debug.assert(info.isJS, "Invalid actionName/JS combo"); + return doTypedefChange(changes, context, file, name, info); + case extractToInterfaceAction.name: + Debug.assert(!info.isJS && !!info.typeElements, "Invalid actionName/JS combo"); + return doInterfaceChange(changes, file, name, info); + default: + Debug.fail("Unexpected action name"); + } + }); + const renameFilename = file.fileName; + const renameLocation = getRenameLocation( + edits, + renameFilename, + name, + /*preferLastLocation*/ + false + ); + return { edits, renameFilename, renameLocation }; + } +}); +function getRangeToExtract(context, considerEmptySpans = true) { + const { file, startPosition } = context; + const isJS = isSourceFileJS(file); + const current = getTokenAtPosition(file, startPosition); + 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))); + if (!selection || !isTypeNode(selection)) + return { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) }; + const checker = context.program.getTypeChecker(); + const enclosingNode = getEnclosingNode(selection, isJS); + if (enclosingNode === void 0) + return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }; + const typeParameters = collectTypeParameters(checker, selection, enclosingNode, file); + if (!typeParameters) + return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }; + const typeElements = flattenTypeLiteralNodeReference(checker, selection); + return { isJS, selection, enclosingNode, typeParameters, typeElements }; +} +function flattenTypeLiteralNodeReference(checker, node) { + if (!node) + return void 0; + if (isIntersectionTypeNode(node)) { + const result = []; + const seen = /* @__PURE__ */ new Map(); + for (const type of node.types) { + const flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type); + if (!flattenedTypeMembers || !flattenedTypeMembers.every((type2) => type2.name && addToSeen(seen, getNameFromPropertyName(type2.name)))) { + return void 0; + } + addRange(result, flattenedTypeMembers); + } + return result; + } else if (isParenthesizedTypeNode(node)) { + return flattenTypeLiteralNodeReference(checker, node.type); + } else if (isTypeLiteralNode(node)) { + return node.members; + } + return void 0; +} +function rangeContainsSkipTrivia(r1, node, file) { + return rangeContainsStartEnd(r1, skipTrivia(file.text, node.pos), node.end); +} +function collectTypeParameters(checker, selection, enclosingNode, file) { + const result = []; + return visitor(selection) ? void 0 : result; + function visitor(node) { + if (isTypeReferenceNode(node)) { + if (isIdentifier(node.typeName)) { + const typeName = node.typeName; + const symbol = checker.resolveName( + typeName.text, + typeName, + 262144 /* TypeParameter */, + /*excludeGlobals*/ + true + ); + for (const decl of (symbol == null ? void 0 : symbol.declarations) || emptyArray) { + if (isTypeParameterDeclaration(decl) && decl.getSourceFile() === file) { + if (decl.name.escapedText === typeName.escapedText && rangeContainsSkipTrivia(decl, selection, file)) { + return true; + } + if (rangeContainsSkipTrivia(enclosingNode, decl, file) && !rangeContainsSkipTrivia(selection, decl, file)) { + pushIfUnique(result, decl); + break; + } + } + } + } + } else if (isInferTypeNode(node)) { + const conditionalTypeNode = findAncestor(node, (n) => isConditionalTypeNode(n) && rangeContainsSkipTrivia(n.extendsType, node, file)); + if (!conditionalTypeNode || !rangeContainsSkipTrivia(selection, conditionalTypeNode, file)) { + return true; + } + } else if (isTypePredicateNode(node) || isThisTypeNode(node)) { + const functionLikeNode = findAncestor(node.parent, isFunctionLike); + if (functionLikeNode && functionLikeNode.type && rangeContainsSkipTrivia(functionLikeNode.type, node, file) && !rangeContainsSkipTrivia(selection, functionLikeNode, file)) { + return true; + } + } else if (isTypeQueryNode(node)) { + if (isIdentifier(node.exprName)) { + const symbol = checker.resolveName( + node.exprName.text, + node.exprName, + 111551 /* Value */, + /*excludeGlobals*/ + false + ); + if ((symbol == null ? void 0 : symbol.valueDeclaration) && rangeContainsSkipTrivia(enclosingNode, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) { + return true; + } + } else { + if (isThisIdentifier(node.exprName.left) && !rangeContainsSkipTrivia(selection, node.parent, file)) { + return true; + } + } + } + if (file && isTupleTypeNode(node) && getLineAndCharacterOfPosition(file, node.pos).line === getLineAndCharacterOfPosition(file, node.end).line) { + setEmitFlags(node, 1 /* SingleLine */); + } + return forEachChild(node, visitor); + } +} +function doTypeAliasChange(changes, file, name, info) { + const { enclosingNode, selection, typeParameters } = info; + const newTypeNode = factory.createTypeAliasDeclaration( + /*modifiers*/ + void 0, + name, + typeParameters.map((id) => factory.updateTypeParameterDeclaration( + id, + id.modifiers, + id.name, + id.constraint, + /*defaultType*/ + void 0 + )), + selection + ); + changes.insertNodeBefore( + file, + enclosingNode, + ignoreSourceNewlines(newTypeNode), + /*blankLineBetween*/ + true + ); + changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( + id.name, + /*typeArguments*/ + void 0 + ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace }); +} +function doInterfaceChange(changes, file, name, info) { + var _a; + const { enclosingNode, selection, typeParameters, typeElements } = info; + const newTypeNode = factory.createInterfaceDeclaration( + /*modifiers*/ + void 0, + name, + typeParameters, + /*heritageClauses*/ + void 0, + typeElements + ); + setTextRange(newTypeNode, (_a = typeElements[0]) == null ? void 0 : _a.parent); + changes.insertNodeBefore( + file, + enclosingNode, + ignoreSourceNewlines(newTypeNode), + /*blankLineBetween*/ + true + ); + changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( + id.name, + /*typeArguments*/ + void 0 + ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace }); +} +function doTypedefChange(changes, context, file, name, info) { + var _a; + const { enclosingNode, selection, typeParameters } = info; + setEmitFlags(selection, 3072 /* NoComments */ | 4096 /* NoNestedComments */); + const node = factory.createJSDocTypedefTag( + factory.createIdentifier("typedef"), + factory.createJSDocTypeExpression(selection), + factory.createIdentifier(name) + ); + const templates = []; + forEach(typeParameters, (typeParameter) => { + const constraint = getEffectiveConstraintOfTypeParameter(typeParameter); + const parameter = factory.createTypeParameterDeclaration( + /*modifiers*/ + void 0, + typeParameter.name + ); + const template = factory.createJSDocTemplateTag( + factory.createIdentifier("template"), + constraint && cast(constraint, isJSDocTypeExpression), + [parameter] + ); + templates.push(template); + }); + const jsDoc = factory.createJSDocComment( + /*comment*/ + void 0, + factory.createNodeArray(concatenate(templates, [node])) + ); + if (isJSDoc(enclosingNode)) { + const pos = enclosingNode.getStart(file); + const newLineCharacter = getNewLineOrDefaultFromHost(context.host, (_a = context.formatContext) == null ? void 0 : _a.options); + changes.insertNodeAt(file, enclosingNode.getStart(file), jsDoc, { + suffix: newLineCharacter + newLineCharacter + file.text.slice(getPrecedingNonSpaceCharacterPosition(file.text, pos - 1), pos) + }); + } else { + changes.insertNodeBefore( + file, + enclosingNode, + jsDoc, + /*blankLineBetween*/ + true + ); + } + changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( + id.name, + /*typeArguments*/ + void 0 + )))); +} +function getEnclosingNode(node, isJS) { + return findAncestor(node, isStatement) || (isJS ? findAncestor(node, isJSDoc) : void 0); +} + +// src/services/refactors/helpers.ts +function isRefactorErrorInfo(info) { + return info.error !== void 0; +} +function refactorKindBeginsWith(known, requested) { + if (!requested) + return true; + return known.substr(0, requested.length) === requested; +} + +// src/services/refactors/moveToNewFile.ts +var refactorName4 = "Move to a new file"; +var description = getLocaleSpecificMessage(Diagnostics.Move_to_a_new_file); +var moveToNewFileAction = { + name: refactorName4, + description, + kind: "refactor.move.newFile" +}; +registerRefactor(refactorName4, { + kinds: [moveToNewFileAction.kind], + getAvailableActions: function getRefactorActionsToMoveToNewFile(context) { + const statements = getStatementsToMove(context); + if (context.preferences.allowTextChangesInNewFiles && statements) { + return [{ name: refactorName4, description, actions: [moveToNewFileAction] }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorName4, + description, + actions: [{ ...moveToNewFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] + }]; + } + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToMoveToNewFile(context, actionName2) { + Debug.assert(actionName2 === refactorName4, "Wrong refactor invoked"); + const statements = Debug.checkDefined(getStatementsToMove(context)); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange3(context.file, context.program, statements, t, context.host, context.preferences, context)); + return { edits, renameFilename: void 0, renameLocation: void 0 }; + } +}); +function doChange3(oldFile, program, toMove, changes, host, preferences, context) { + const checker = program.getTypeChecker(); + const usage = getUsageInfo(oldFile, toMove.all, checker); + const newFilename = createNewFileName(oldFile, program, context, host); + changes.createNewFile(oldFile, newFilename, getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences)); + addNewFileToTsconfig(program, changes, oldFile.fileName, newFilename, hostGetCanonicalFileName(host)); +} +function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences) { + const checker = program.getTypeChecker(); + const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective); + if (oldFile.externalModuleIndicator === void 0 && oldFile.commonJsModuleIndicator === void 0 && usage.oldImportsNeededByTargetFile.size === 0) { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return [...prologueDirectives, ...toMove.all]; + } + const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(newFilename, program, host, !!oldFile.commonJsModuleIndicator); + const quotePreference = getQuotePreference(oldFile, preferences); + const importsFromNewFile = createOldFileImportsFromTargetFile(oldFile, usage.oldFileImportsFromTargetFile, newFilename, program, host, useEsModuleSyntax, quotePreference); + if (importsFromNewFile) { + insertImports( + changes, + oldFile, + importsFromNewFile, + /*blankLineBetween*/ + true, + preferences + ); + } + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, newFilename, quotePreference); + const imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference); + const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromTargetFile, useEsModuleSyntax); + if (imports.length && body.length) { + return [ + ...prologueDirectives, + ...imports, + 4 /* NewLineTrivia */, + ...body + ]; + } + return [ + ...prologueDirectives, + ...imports, + ...body + ]; +} +function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference) { + const copiedOldImports = []; + for (const oldStatement of oldFile.statements) { + forEachImportInStatement(oldStatement, (i) => { + append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); + }); + } + let oldFileDefault; + const oldFileNamedImports = []; + const markSeenTop = nodeSeenTracker(); + newFileImportsFromOldFile.forEach((symbol) => { + if (!symbol.declarations) { + return; + } + for (const decl of symbol.declarations) { + if (!isTopLevelDeclaration(decl)) + continue; + const name = nameOfTopLevelDeclaration(decl); + if (!name) + continue; + const top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) { + addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); + } + if (hasSyntacticModifier(decl, 1024 /* Default */)) { + oldFileDefault = name; + } else { + oldFileNamedImports.push(name.text); + } + } + }); + append(copiedOldImports, makeImportOrRequire(oldFile, oldFileDefault, oldFileNamedImports, getBaseFileName(oldFile.fileName), program, host, useEsModuleSyntax, quotePreference)); + return copiedOldImports; +} + +// src/services/refactors/moveToFile.ts +var refactorNameForMoveToFile = "Move to file"; +var description2 = getLocaleSpecificMessage(Diagnostics.Move_to_file); +var moveToFileAction = { + name: "Move to file", + description: description2, + kind: "refactor.move.file" +}; +registerRefactor(refactorNameForMoveToFile, { + kinds: [moveToFileAction.kind], + getAvailableActions: function getRefactorActionsToMoveToFile(context, interactiveRefactorArguments) { + const statements = getStatementsToMove(context); + if (!interactiveRefactorArguments) { + return emptyArray; + } + if (context.preferences.allowTextChangesInNewFiles && statements) { + return [{ name: refactorNameForMoveToFile, description: description2, actions: [moveToFileAction] }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorNameForMoveToFile, + description: description2, + actions: [{ ...moveToFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] + }]; + } + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToMoveToFile(context, actionName2, interactiveRefactorArguments) { + Debug.assert(actionName2 === refactorNameForMoveToFile, "Wrong refactor invoked"); + const statements = Debug.checkDefined(getStatementsToMove(context)); + Debug.assert(interactiveRefactorArguments, "No interactive refactor arguments available"); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange4(context, context.file, interactiveRefactorArguments.targetFile, context.program, statements, t, context.host, context.preferences)); + return { edits, renameFilename: void 0, renameLocation: void 0 }; + } +}); +function doChange4(context, oldFile, targetFile, program, toMove, changes, host, preferences) { + var _a; + const checker = program.getTypeChecker(); + const usage = getUsageInfo(oldFile, toMove.all, checker); + if (!host.fileExists(targetFile) || host.fileExists(targetFile) && ((_a = program.getSourceFile(targetFile)) == null ? void 0 : _a.statements.length) === 0) { + changes.createNewFile(oldFile, targetFile, getNewStatementsAndRemoveFromOldFile2(oldFile, targetFile, usage, changes, toMove, program, host, preferences)); + addNewFileToTsconfig(program, changes, oldFile.fileName, targetFile, hostGetCanonicalFileName(host)); + } else { + const targetSourceFile = Debug.checkDefined(program.getSourceFile(targetFile)); + const importAdder = ts_codefix_exports.createImportAdder(targetSourceFile, context.program, context.preferences, context.host); + getNewStatementsAndRemoveFromOldFile2(oldFile, targetSourceFile, usage, changes, toMove, program, host, preferences, importAdder); + } +} +function getNewStatementsAndRemoveFromOldFile2(oldFile, targetFile, usage, changes, toMove, program, host, preferences, importAdder) { + const checker = program.getTypeChecker(); + const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective); + if (oldFile.externalModuleIndicator === void 0 && oldFile.commonJsModuleIndicator === void 0 && usage.oldImportsNeededByTargetFile.size === 0 && usage.targetFileImportsFromOldFile.size === 0 && typeof targetFile === "string") { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return [...prologueDirectives, ...toMove.all]; + } + const targetFileName = typeof targetFile === "string" ? targetFile : targetFile.fileName; + const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(targetFileName, program, host, !!oldFile.commonJsModuleIndicator); + const quotePreference = getQuotePreference(oldFile, preferences); + const importsFromTargetFile = createOldFileImportsFromTargetFile(oldFile, usage.oldFileImportsFromTargetFile, targetFileName, program, host, useEsModuleSyntax, quotePreference); + if (importsFromTargetFile) { + insertImports( + changes, + oldFile, + importsFromTargetFile, + /*blankLineBetween*/ + true, + preferences + ); + } + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, targetFileName, quotePreference); + const imports = getTargetFileImportsAndAddExportInOldFile(oldFile, targetFileName, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference, importAdder); + const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromTargetFile, useEsModuleSyntax); + if (typeof targetFile !== "string") { + if (targetFile.statements.length > 0) { + changes.insertNodesAfter(targetFile, targetFile.statements[targetFile.statements.length - 1], body); + } + if (imports.length > 0) { + insertImports( + changes, + targetFile, + imports, + /*blankLineBetween*/ + true, + preferences + ); + } + } + if (importAdder) { + importAdder.writeFixes(changes); + } + if (imports.length && body.length) { + return [ + ...prologueDirectives, + ...imports, + 4 /* NewLineTrivia */, + ...body + ]; + } + return [ + ...prologueDirectives, + ...imports, + ...body + ]; +} +function getTargetFileImportsAndAddExportInOldFile(oldFile, targetFile, importsToCopy, targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference, importAdder) { + const copiedOldImports = []; + if (importAdder) { + importsToCopy.forEach((isValidTypeOnlyUseSite, symbol) => { + try { + importAdder.addImportFromExportedSymbol(skipAlias(symbol, checker), isValidTypeOnlyUseSite); + } catch { + for (const oldStatement of oldFile.statements) { + forEachImportInStatement(oldStatement, (i) => { + append(copiedOldImports, filterImport(i, factory.createStringLiteral(moduleSpecifierFromImport(i).text), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); + }); + } + } + }); + } else { + const targetSourceFile = program.getSourceFile(targetFile); + for (const oldStatement of oldFile.statements) { + forEachImportInStatement(oldStatement, (i) => { + var _a, _b; + const moduleSpecifier = moduleSpecifierFromImport(i); + const resolved = (_a = oldFile.resolvedModules) == null ? void 0 : _a.get(moduleSpecifier.text, getModeForUsageLocation(oldFile, moduleSpecifier)); + const fileName = (_b = resolved == null ? void 0 : resolved.resolvedModule) == null ? void 0 : _b.resolvedFileName; + if (fileName && targetSourceFile) { + const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), targetSourceFile, targetSourceFile.path, fileName, createModuleSpecifierResolutionHost(program, host)); + append(copiedOldImports, filterImport(i, makeStringLiteral(newModuleSpecifier, quotePreference), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); + } else { + append(copiedOldImports, filterImport(i, factory.createStringLiteral(moduleSpecifierFromImport(i).text), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); + } + }); + } + } + const targetFileSourceFile = program.getSourceFile(targetFile); + let oldFileDefault; + const oldFileNamedImports = []; + const markSeenTop = nodeSeenTracker(); + targetFileImportsFromOldFile.forEach((symbol) => { + if (!symbol.declarations) { + return; + } + for (const decl of symbol.declarations) { + if (!isTopLevelDeclaration(decl)) + continue; + const name = nameOfTopLevelDeclaration(decl); + if (!name) + continue; + const top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) { + addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); + } + if (importAdder && checker.isUnknownSymbol(symbol)) { + importAdder.addImportFromExportedSymbol(skipAlias(symbol, checker)); + } else { + if (hasSyntacticModifier(decl, 1024 /* Default */)) { + oldFileDefault = name; + } else { + oldFileNamedImports.push(name.text); + } + } + } + }); + 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)); +} +function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { + const cfg = program.getCompilerOptions().configFile; + if (!cfg) + return; + const newFileAbsolutePath = normalizePath(combinePaths(oldFileName, "..", newFileNameWithExtension)); + 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) => 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); + } +} +function deleteMovedStatements(sourceFile, moved, changes) { + for (const { first: first2, afterLast } of moved) { + changes.deleteNodeRangeExcludingEnd(sourceFile, first2, afterLast); + } +} +function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { + for (const statement of oldFile.statements) { + if (contains(toMove, statement)) + continue; + forEachImportInStatement(statement, (i) => deleteUnusedImports(oldFile, i, changes, (name) => toDelete.has(checker.getSymbolAtLocation(name)))); + } +} +function updateImportsInOtherFiles(changes, program, host, oldFile, movedSymbols, targetFileName, quotePreference) { + const checker = program.getTypeChecker(); + for (const sourceFile of program.getSourceFiles()) { + if (sourceFile === oldFile) + continue; + for (const statement of sourceFile.statements) { + forEachImportInStatement(statement, (importNode) => { + if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) + return; + const shouldMove = (name) => { + const symbol = isBindingElement(name.parent) ? getPropertySymbolFromBindingElement(checker, name.parent) : skipAlias(checker.getSymbolAtLocation(name), checker); + return !!symbol && movedSymbols.has(symbol); + }; + deleteUnusedImports(sourceFile, importNode, changes, shouldMove); + const pathToTargetFileWithExtension = resolvePath(getDirectoryPath(oldFile.path), targetFileName); + const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToTargetFileWithExtension, createModuleSpecifierResolutionHost(program, host)); + const newImportDeclaration = filterImport(importNode, makeStringLiteral(newModuleSpecifier, quotePreference), shouldMove); + if (newImportDeclaration) + changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + const ns = getNamespaceLikeImport(importNode); + if (ns) + updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, ns, importNode, quotePreference); + }); + } + } +} +function getNamespaceLikeImport(node) { + switch (node.kind) { + case 271 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 273 /* NamespaceImport */ ? node.importClause.namedBindings.name : void 0; + case 270 /* ImportEqualsDeclaration */: + return node.name; + case 259 /* VariableDeclaration */: + return tryCast(node.name, isIdentifier); + default: + return Debug.assertNever(node, `Unexpected node kind ${node.kind}`); + } +} +function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, oldImportId, oldImportNode, quotePreference) { + const preferredNewNamespaceName = ts_codefix_exports.moduleSpecifierToValidIdentifier(newModuleSpecifier, 99 /* ESNext */); + let needUniqueName = false; + const toChange = []; + ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, (ref) => { + if (!isPropertyAccessExpression(ref.parent)) + return; + needUniqueName = needUniqueName || !!checker.resolveName( + preferredNewNamespaceName, + ref, + 67108863 /* All */, + /*excludeGlobals*/ + true + ); + if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) { + toChange.push(ref); + } + }); + if (toChange.length) { + const newNamespaceName = needUniqueName ? getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; + for (const ref of toChange) { + changes.replaceNode(sourceFile, ref, factory.createIdentifier(newNamespaceName)); + } + changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, preferredNewNamespaceName, newModuleSpecifier, quotePreference)); + } +} +function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier, quotePreference) { + const newNamespaceId = factory.createIdentifier(newNamespaceName); + const newModuleString = makeStringLiteral(newModuleSpecifier, quotePreference); + switch (node.kind) { + case 271 /* ImportDeclaration */: + return factory.createImportDeclaration( + /*modifiers*/ + void 0, + factory.createImportClause( + /*isTypeOnly*/ + false, + /*name*/ + void 0, + factory.createNamespaceImport(newNamespaceId) + ), + newModuleString, + /*assertClause*/ + void 0 + ); + case 270 /* ImportEqualsDeclaration */: + return factory.createImportEqualsDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + newNamespaceId, + factory.createExternalModuleReference(newModuleString) + ); + case 259 /* VariableDeclaration */: + return factory.createVariableDeclaration( + newNamespaceId, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + createRequireCall(newModuleString) + ); + default: + return Debug.assertNever(node, `Unexpected node kind ${node.kind}`); + } +} +function createRequireCall(moduleSpecifier) { + return factory.createCallExpression( + factory.createIdentifier("require"), + /*typeArguments*/ + void 0, + [moduleSpecifier] + ); +} +function moduleSpecifierFromImport(i) { + return i.kind === 271 /* ImportDeclaration */ ? i.moduleSpecifier : i.kind === 270 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]; +} +function forEachImportInStatement(statement, cb) { + if (isImportDeclaration(statement)) { + if (isStringLiteral(statement.moduleSpecifier)) + cb(statement); + } else if (isImportEqualsDeclaration(statement)) { + if (isExternalModuleReference(statement.moduleReference) && isStringLiteralLike(statement.moduleReference.expression)) { + cb(statement); + } + } else if (isVariableStatement(statement)) { + for (const decl of statement.declarationList.declarations) { + if (decl.initializer && isRequireCall( + decl.initializer, + /*requireStringLiteralLikeArgument*/ + true + )) { + cb(decl); + } + } + } +} +function createOldFileImportsFromTargetFile(sourceFile, targetFileNeedExport, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference) { + let defaultImport; + const imports = []; + targetFileNeedExport.forEach((symbol) => { + if (symbol.escapedName === "default" /* Default */) { + defaultImport = factory.createIdentifier(symbolNameNoDefault(symbol)); + } else { + imports.push(symbol.name); + } + }); + return makeImportOrRequire(sourceFile, defaultImport, imports, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference); +} +function makeImportOrRequire(sourceFile, defaultImport, imports, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference) { + const pathToTargetFile = resolvePath(getDirectoryPath(sourceFile.path), targetFileNameWithExtension); + const pathToTargetFileWithCorrectExtension = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToTargetFile, createModuleSpecifierResolutionHost(program, host)); + if (useEs6Imports) { + const specifiers = imports.map((i) => factory.createImportSpecifier( + /*isTypeOnly*/ + false, + /*propertyName*/ + void 0, + factory.createIdentifier(i) + )); + return makeImportIfNecessary(defaultImport, specifiers, pathToTargetFileWithCorrectExtension, quotePreference); + } else { + Debug.assert(!defaultImport, "No default import should exist"); + const bindingElements = imports.map((i) => factory.createBindingElement( + /*dotDotDotToken*/ + void 0, + /*propertyName*/ + void 0, + i + )); + return bindingElements.length ? makeVariableStatement( + factory.createObjectBindingPattern(bindingElements), + /*type*/ + void 0, + createRequireCall(makeStringLiteral(pathToTargetFileWithCorrectExtension, quotePreference)) + ) : void 0; + } +} +function makeVariableStatement(name, type, initializer, flags = 2 /* Const */) { + return factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList([factory.createVariableDeclaration( + name, + /*exclamationToken*/ + void 0, + type, + initializer + )], flags) + ); +} +function addExports(sourceFile, toMove, needExport, useEs6Exports) { + return flatMap(toMove, (statement) => { + if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, (d) => { + var _a; + return needExport.has(Debug.checkDefined((_a = tryCast(d, canHaveSymbol)) == null ? void 0 : _a.symbol)); + })) { + const exports = addExport(getSynthesizedDeepClone(statement), useEs6Exports); + if (exports) + return exports; + } + return getSynthesizedDeepClone(statement); + }); +} +function isExported(sourceFile, decl, useEs6Exports, name) { + var _a; + if (useEs6Exports) { + return !isExpressionStatement(decl) && hasSyntacticModifier(decl, 1 /* Export */) || !!(name && sourceFile.symbol && ((_a = sourceFile.symbol.exports) == null ? void 0 : _a.has(name.escapedText))); + } + return !!sourceFile.symbol && !!sourceFile.symbol.exports && getNamesToExportInCommonJS(decl).some((name2) => sourceFile.symbol.exports.has(escapeLeadingUnderscores(name2))); +} +function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { + switch (importDecl.kind) { + case 271 /* ImportDeclaration */: + deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); + break; + case 270 /* ImportEqualsDeclaration */: + if (isUnused(importDecl.name)) { + changes.delete(sourceFile, importDecl); + } + break; + case 259 /* VariableDeclaration */: + deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); + break; + default: + Debug.assertNever(importDecl, `Unexpected import decl kind ${importDecl.kind}`); + } +} +function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { + if (!importDecl.importClause) + return; + const { name, namedBindings } = importDecl.importClause; + const defaultUnused = !name || isUnused(name); + const namedBindingsUnused = !namedBindings || (namedBindings.kind === 273 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every((e) => isUnused(e.name))); + if (defaultUnused && namedBindingsUnused) { + changes.delete(sourceFile, importDecl); + } else { + if (name && defaultUnused) { + changes.delete(sourceFile, name); + } + if (namedBindings) { + if (namedBindingsUnused) { + changes.replaceNode( + sourceFile, + importDecl.importClause, + factory.updateImportClause( + importDecl.importClause, + importDecl.importClause.isTypeOnly, + name, + /*namedBindings*/ + void 0 + ) + ); + } else if (namedBindings.kind === 274 /* NamedImports */) { + for (const element of namedBindings.elements) { + if (isUnused(element.name)) + changes.delete(sourceFile, element); + } + } + } + } +} +function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { + const { name } = varDecl; + switch (name.kind) { + case 80 /* 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 + ); + } else { + changes.delete(sourceFile, name); + } + } + break; + case 206 /* ArrayBindingPattern */: + break; + case 205 /* 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 + ); + } else { + for (const element of name.elements) { + if (isIdentifier(element.name) && isUnused(element.name)) { + changes.delete(sourceFile, element.name); + } + } + } + break; + } +} +function isTopLevelDeclarationStatement(node) { + Debug.assert(isSourceFile(node.parent), "Node parent should be a SourceFile"); + return isNonVariableTopLevelDeclaration(node) || isVariableStatement(node); +} +function addExport(decl, useEs6Exports) { + return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); +} +function addEs6Export(d) { + const modifiers = canHaveModifiers(d) ? concatenate([factory.createModifier(95 /* ExportKeyword */)], getModifiers(d)) : void 0; + switch (d.kind) { + case 261 /* FunctionDeclaration */: + return factory.updateFunctionDeclaration(d, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + case 262 /* ClassDeclaration */: + const decorators = canHaveDecorators(d) ? getDecorators(d) : void 0; + return factory.updateClassDeclaration(d, concatenate(decorators, modifiers), d.name, d.typeParameters, d.heritageClauses, d.members); + case 242 /* VariableStatement */: + return factory.updateVariableStatement(d, modifiers, d.declarationList); + case 266 /* ModuleDeclaration */: + return factory.updateModuleDeclaration(d, modifiers, d.name, d.body); + case 265 /* EnumDeclaration */: + return factory.updateEnumDeclaration(d, modifiers, d.name, d.members); + case 264 /* TypeAliasDeclaration */: + return factory.updateTypeAliasDeclaration(d, modifiers, d.name, d.typeParameters, d.type); + case 263 /* InterfaceDeclaration */: + return factory.updateInterfaceDeclaration(d, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 270 /* ImportEqualsDeclaration */: + return factory.updateImportEqualsDeclaration(d, modifiers, d.isTypeOnly, d.name, d.moduleReference); + case 243 /* ExpressionStatement */: + return Debug.fail(); + default: + return Debug.assertNever(d, `Unexpected declaration kind ${d.kind}`); + } +} +function addCommonjsExport(decl) { + return [decl, ...getNamesToExportInCommonJS(decl).map(createExportAssignment)]; +} +function createExportAssignment(name) { + return factory.createExpressionStatement( + factory.createBinaryExpression( + factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(name)), + 64 /* EqualsToken */, + factory.createIdentifier(name) + ) + ); +} +function getNamesToExportInCommonJS(decl) { + switch (decl.kind) { + case 261 /* FunctionDeclaration */: + case 262 /* ClassDeclaration */: + return [decl.name.text]; + case 242 /* VariableStatement */: + return mapDefined(decl.declarationList.declarations, (d) => isIdentifier(d.name) ? d.name.text : void 0); + case 266 /* ModuleDeclaration */: + case 265 /* EnumDeclaration */: + case 264 /* TypeAliasDeclaration */: + case 263 /* InterfaceDeclaration */: + case 270 /* ImportEqualsDeclaration */: + return emptyArray; + case 243 /* ExpressionStatement */: + return Debug.fail("Can't export an ExpressionStatement"); + default: + return Debug.assertNever(decl, `Unexpected decl kind ${decl.kind}`); + } +} +function filterImport(i, moduleSpecifier, keep) { + switch (i.kind) { + case 271 /* ImportDeclaration */: { + const clause = i.importClause; + if (!clause) + return void 0; + const defaultImport = clause.name && keep(clause.name) ? clause.name : void 0; + const namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); + return defaultImport || namedBindings ? factory.createImportDeclaration( + /*modifiers*/ + void 0, + factory.createImportClause(clause.isTypeOnly, defaultImport, namedBindings), + getSynthesizedDeepClone(moduleSpecifier), + /*assertClause*/ + void 0 + ) : void 0; + } + case 270 /* ImportEqualsDeclaration */: + return keep(i.name) ? i : void 0; + case 259 /* VariableDeclaration */: { + const name = filterBindingName(i.name, keep); + return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : void 0; + } + default: + return Debug.assertNever(i, `Unexpected import kind ${i.kind}`); + } +} +function filterNamedBindings(namedBindings, keep) { + if (namedBindings.kind === 273 /* NamespaceImport */) { + return keep(namedBindings.name) ? namedBindings : void 0; + } else { + const newElements = namedBindings.elements.filter((e) => keep(e.name)); + return newElements.length ? factory.createNamedImports(newElements) : void 0; + } +} +function filterBindingName(name, keep) { + switch (name.kind) { + case 80 /* Identifier */: + return keep(name) ? name : void 0; + case 206 /* ArrayBindingPattern */: + return name; + case 205 /* ObjectBindingPattern */: { + const newElements = name.elements.filter((prop) => prop.propertyName || !isIdentifier(prop.name) || keep(prop.name)); + return newElements.length ? factory.createObjectBindingPattern(newElements) : void 0; + } + } +} +function nameOfTopLevelDeclaration(d) { + return isExpressionStatement(d) ? tryCast(d.expression.left.name, isIdentifier) : tryCast(d.name, isIdentifier); +} +function getTopLevelDeclarationStatement(d) { + switch (d.kind) { + case 259 /* VariableDeclaration */: + return d.parent.parent; + case 207 /* BindingElement */: + return getTopLevelDeclarationStatement( + cast(d.parent.parent, (p) => isVariableDeclaration(p) || isBindingElement(p)) + ); + default: + return d; + } +} +function addExportToChanges(sourceFile, decl, name, changes, useEs6Exports) { + if (isExported(sourceFile, decl, useEs6Exports, name)) + return; + if (useEs6Exports) { + if (!isExpressionStatement(decl)) + changes.insertExportModifier(sourceFile, decl); + } else { + const names = getNamesToExportInCommonJS(decl); + if (names.length !== 0) + changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); + } +} +function createNewFileName(oldFile, program, context, host) { + const checker = program.getTypeChecker(); + const toMove = getStatementsToMove(context); + let usage; + if (toMove) { + usage = getUsageInfo(oldFile, toMove.all, checker); + 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, + currentDirectory, + host + ) + ) + extension; + return newFileName; + } + return ""; +} +function getRangeToMove(context) { + const { file } = context; + const range = createTextRangeFromSpan(getRefactorContextSpan(context)); + const { statements } = file; + const startNodeIndex = findIndex(statements, (s) => s.end > range.pos); + if (startNodeIndex === -1) + return void 0; + const startStatement = statements[startNodeIndex]; + if (isNamedDeclaration(startStatement) && startStatement.name && rangeContainsRange(startStatement.name, range)) { + return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; + } + if (range.pos > startStatement.getStart(file)) + return void 0; + const afterEndNodeIndex = findIndex(statements, (s) => s.end > range.end, startNodeIndex); + if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) + return void 0; + return { + toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), + afterLast: afterEndNodeIndex === -1 ? void 0 : statements[afterEndNodeIndex] + }; +} +function getStatementsToMove(context) { + const rangeToMove = getRangeToMove(context); + if (rangeToMove === void 0) + return void 0; + const all = []; + const ranges = []; + const { toMove, afterLast } = rangeToMove; + getRangesWhere(toMove, isAllowedStatementToMove, (start2, afterEndIndex) => { + for (let i = start2; i < afterEndIndex; i++) + all.push(toMove[i]); + ranges.push({ first: toMove[start2], afterLast }); + }); + return all.length === 0 ? void 0 : { all, ranges }; +} +function isAllowedStatementToMove(statement) { + return !isPureImport(statement) && !isPrologueDirective(statement); +} +function isPureImport(node) { + switch (node.kind) { + case 271 /* ImportDeclaration */: + return true; + case 270 /* ImportEqualsDeclaration */: + return !hasSyntacticModifier(node, 1 /* Export */); + case 242 /* VariableStatement */: + return node.declarationList.declarations.every((d) => !!d.initializer && isRequireCall( + d.initializer, + /*requireStringLiteralLikeArgument*/ + true + )); + default: + return false; + } +} +function getUsageInfo(oldFile, toMove, checker) { + const movedSymbols = /* @__PURE__ */ new Set(); + const oldImportsNeededByTargetFile = /* @__PURE__ */ new Map(); + const targetFileImportsFromOldFile = /* @__PURE__ */ new Set(); + const containsJsx = find(toMove, (statement) => !!(statement.transformFlags & 2 /* ContainsJsx */)); + const jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx); + if (jsxNamespaceSymbol) { + oldImportsNeededByTargetFile.set(jsxNamespaceSymbol, false); + } + for (const statement of toMove) { + forEachTopLevelDeclaration(statement, (decl) => { + movedSymbols.add(Debug.checkDefined(isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here")); + }); + } + for (const statement of toMove) { + forEachReference(statement, checker, (symbol, isValidTypeOnlyUseSite) => { + if (!symbol.declarations) + return; + for (const decl of symbol.declarations) { + if (isInImport(decl)) { + const prevIsTypeOnly = oldImportsNeededByTargetFile.get(symbol); + oldImportsNeededByTargetFile.set(symbol, prevIsTypeOnly === void 0 ? isValidTypeOnlyUseSite : prevIsTypeOnly && isValidTypeOnlyUseSite); + } else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) { + targetFileImportsFromOldFile.add(symbol); + } + } + }); + } + const unusedImportsFromOldFile = new Set(oldImportsNeededByTargetFile.keys()); + const oldFileImportsFromTargetFile = /* @__PURE__ */ new Set(); + for (const statement of oldFile.statements) { + if (contains(toMove, statement)) + continue; + if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) { + unusedImportsFromOldFile.delete(jsxNamespaceSymbol); + } + forEachReference(statement, checker, (symbol) => { + if (movedSymbols.has(symbol)) + oldFileImportsFromTargetFile.add(symbol); + unusedImportsFromOldFile.delete(symbol); + }); + } + return { movedSymbols, targetFileImportsFromOldFile, oldFileImportsFromTargetFile, oldImportsNeededByTargetFile, unusedImportsFromOldFile }; + function getJsxNamespaceSymbol(containsJsx2) { + if (containsJsx2 === void 0) { + return void 0; + } + const jsxNamespace = checker.getJsxNamespace(containsJsx2); + const jsxNamespaceSymbol2 = checker.resolveName( + jsxNamespace, + containsJsx2, + 1920 /* Namespace */, + /*excludeGlobals*/ + true + ); + return !!jsxNamespaceSymbol2 && some(jsxNamespaceSymbol2.declarations, isInImport) ? jsxNamespaceSymbol2 : void 0; + } +} +function makeUniqueFilename(proposedFilename, extension, inDirectory, host) { + let newFilename = proposedFilename; + for (let i = 1; ; i++) { + const name = combinePaths(inDirectory, newFilename + extension); + if (!host.fileExists(name)) + return newFilename; + newFilename = `${proposedFilename}.${i}`; + } +} +function inferNewFileName(importsFromNewFile, movedSymbols) { + return forEachKey(importsFromNewFile, symbolNameNoDefault) || forEachKey(movedSymbols, symbolNameNoDefault) || "newFile"; +} +function forEachReference(node, checker, onReference) { + node.forEachChild(function cb(node2) { + if (isIdentifier(node2) && !isDeclarationName(node2)) { + const sym = checker.getSymbolAtLocation(node2); + if (sym) + onReference(sym, isValidTypeOnlyAliasUseSite(node2)); + } else { + node2.forEachChild(cb); + } + }); +} +function forEachTopLevelDeclaration(statement, cb) { + switch (statement.kind) { + case 261 /* FunctionDeclaration */: + case 262 /* ClassDeclaration */: + case 266 /* ModuleDeclaration */: + case 265 /* EnumDeclaration */: + case 264 /* TypeAliasDeclaration */: + case 263 /* InterfaceDeclaration */: + case 270 /* ImportEqualsDeclaration */: + return cb(statement); + case 242 /* VariableStatement */: + return firstDefined(statement.declarationList.declarations, (decl) => forEachTopLevelDeclarationInBindingName(decl.name, cb)); + case 243 /* ExpressionStatement */: { + const { expression } = statement; + return isBinaryExpression(expression) && getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : void 0; + } + } +} +function isInImport(decl) { + switch (decl.kind) { + case 270 /* ImportEqualsDeclaration */: + case 275 /* ImportSpecifier */: + case 272 /* ImportClause */: + case 273 /* NamespaceImport */: + return true; + case 259 /* VariableDeclaration */: + return isVariableDeclarationInImport(decl); + case 207 /* BindingElement */: + return isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); + default: + return false; + } +} +function isVariableDeclarationInImport(decl) { + return isSourceFile(decl.parent.parent.parent) && !!decl.initializer && isRequireCall( + decl.initializer, + /*requireStringLiteralLikeArgument*/ + true + ); +} +function isTopLevelDeclaration(node) { + return isNonVariableTopLevelDeclaration(node) && isSourceFile(node.parent) || isVariableDeclaration(node) && isSourceFile(node.parent.parent.parent); +} +function sourceFileOfTopLevelDeclaration(node) { + return isVariableDeclaration(node) ? node.parent.parent.parent : node.parent; +} +function forEachTopLevelDeclarationInBindingName(name, cb) { + switch (name.kind) { + case 80 /* Identifier */: + return cb(cast(name.parent, (x) => isVariableDeclaration(x) || isBindingElement(x))); + case 206 /* ArrayBindingPattern */: + case 205 /* ObjectBindingPattern */: + return firstDefined(name.elements, (em) => isOmittedExpression(em) ? void 0 : forEachTopLevelDeclarationInBindingName(em.name, cb)); + default: + return Debug.assertNever(name, `Unexpected name kind ${name.kind}`); + } +} +function isNonVariableTopLevelDeclaration(node) { + switch (node.kind) { + case 261 /* FunctionDeclaration */: + case 262 /* ClassDeclaration */: + case 266 /* ModuleDeclaration */: + case 265 /* EnumDeclaration */: + case 264 /* TypeAliasDeclaration */: + case 263 /* InterfaceDeclaration */: + case 270 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } +} + +// src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts +var ts_refactor_addOrRemoveBracesToArrowFunction_exports = {}; + +// src/services/refactors/convertOverloadListToSingleSignature.ts +var refactorName5 = "Convert overload list to single signature"; +var refactorDescription = Diagnostics.Convert_overload_list_to_single_signature.message; +var functionOverloadAction = { + name: refactorName5, + description: refactorDescription, + kind: "refactor.rewrite.function.overloadList" +}; +registerRefactor(refactorName5, { + kinds: [functionOverloadAction.kind], + getEditsForAction: getRefactorEditsToConvertOverloadsToOneSignature, + getAvailableActions: getRefactorActionsToConvertOverloadsToOneSignature +}); +function getRefactorActionsToConvertOverloadsToOneSignature(context) { + const { file, startPosition, program } = context; + const info = getConvertableOverloadListAtPosition(file, startPosition, program); + if (!info) + return emptyArray; + return [{ + name: refactorName5, + description: refactorDescription, + actions: [functionOverloadAction] + }]; +} +function getRefactorEditsToConvertOverloadsToOneSignature(context) { + const { file, startPosition, program } = context; + const signatureDecls = getConvertableOverloadListAtPosition(file, startPosition, program); + if (!signatureDecls) + return void 0; + const checker = program.getTypeChecker(); + const lastDeclaration = signatureDecls[signatureDecls.length - 1]; + let updated = lastDeclaration; + switch (lastDeclaration.kind) { + case 172 /* MethodSignature */: { + updated = factory.updateMethodSignature( + lastDeclaration, + lastDeclaration.modifiers, + lastDeclaration.name, + lastDeclaration.questionToken, + lastDeclaration.typeParameters, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.type + ); + break; + } + case 173 /* MethodDeclaration */: { + updated = factory.updateMethodDeclaration( + lastDeclaration, + lastDeclaration.modifiers, + lastDeclaration.asteriskToken, + lastDeclaration.name, + lastDeclaration.questionToken, + lastDeclaration.typeParameters, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.type, + lastDeclaration.body + ); + break; + } + case 178 /* CallSignature */: { + updated = factory.updateCallSignature( + lastDeclaration, + lastDeclaration.typeParameters, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.type + ); + break; + } + case 175 /* Constructor */: { + updated = factory.updateConstructorDeclaration( + lastDeclaration, + lastDeclaration.modifiers, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.body + ); + break; + } + case 179 /* ConstructSignature */: { + updated = factory.updateConstructSignature( + lastDeclaration, + lastDeclaration.typeParameters, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.type + ); + break; + } + case 261 /* FunctionDeclaration */: { + updated = factory.updateFunctionDeclaration( + lastDeclaration, + lastDeclaration.modifiers, + lastDeclaration.asteriskToken, + lastDeclaration.name, + lastDeclaration.typeParameters, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.type, + lastDeclaration.body + ); + break; + } + default: + return Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring"); + } + if (updated === lastDeclaration) { + return; + } + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => { + t.replaceNodeRange(file, signatureDecls[0], signatureDecls[signatureDecls.length - 1], updated); + }); + return { renameFilename: void 0, renameLocation: void 0, edits }; + function getNewParametersForCombinedSignature(signatureDeclarations) { + const lastSig = signatureDeclarations[signatureDeclarations.length - 1]; + if (isFunctionLikeDeclaration(lastSig) && lastSig.body) { + signatureDeclarations = signatureDeclarations.slice(0, signatureDeclarations.length - 1); + } + return factory.createNodeArray([ + factory.createParameterDeclaration( + /*modifiers*/ + void 0, + factory.createToken(26 /* DotDotDotToken */), + "args", + /*questionToken*/ + void 0, + factory.createUnionTypeNode(map(signatureDeclarations, convertSignatureParametersToTuple)) + ) + ]); + } + function convertSignatureParametersToTuple(decl) { + const members = map(decl.parameters, convertParameterToNamedTupleMember); + return setEmitFlags(factory.createTupleTypeNode(members), some(members, (m) => !!length(getSyntheticLeadingComments(m))) ? 0 /* None */ : 1 /* SingleLine */); + } + function convertParameterToNamedTupleMember(p) { + Debug.assert(isIdentifier(p.name)); + const result = setTextRange(factory.createNamedTupleMember( + p.dotDotDotToken, + p.name, + p.questionToken, + p.type || factory.createKeywordTypeNode(133 /* AnyKeyword */) + ), p); + const parameterDocComment = p.symbol && p.symbol.getDocumentationComment(checker); + if (parameterDocComment) { + const newComment = displayPartsToString(parameterDocComment); + if (newComment.length) { + setSyntheticLeadingComments(result, [{ + text: `* +${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} + `, + kind: 3 /* MultiLineCommentTrivia */, + pos: -1, + end: -1, + hasTrailingNewLine: true, + hasLeadingNewline: true + }]); + } + } + return result; + } +} +function isConvertableSignatureDeclaration(d) { + switch (d.kind) { + case 172 /* MethodSignature */: + case 173 /* MethodDeclaration */: + case 178 /* CallSignature */: + case 175 /* Constructor */: + case 179 /* ConstructSignature */: + case 261 /* FunctionDeclaration */: + return true; + } + return false; +} +function getConvertableOverloadListAtPosition(file, startPosition, program) { + const node = getTokenAtPosition(file, startPosition); + const containingDecl = findAncestor(node, isConvertableSignatureDeclaration); + if (!containingDecl) { + return; + } + if (isFunctionLikeDeclaration(containingDecl) && containingDecl.body && rangeContainsPosition(containingDecl.body, startPosition)) { + return; + } + const checker = program.getTypeChecker(); + const signatureSymbol = containingDecl.symbol; + if (!signatureSymbol) { + return; + } + const decls = signatureSymbol.declarations; + if (length(decls) <= 1) { + return; + } + if (!every(decls, (d) => getSourceFileOfNode(d) === file)) { + return; + } + if (!isConvertableSignatureDeclaration(decls[0])) { + return; + } + const kindOne = decls[0].kind; + if (!every(decls, (d) => d.kind === kindOne)) { + return; + } + const signatureDecls = decls; + if (some(signatureDecls, (d) => !!d.typeParameters || some(d.parameters, (p) => !!p.modifiers || !isIdentifier(p.name)))) { + return; + } + const signatures = mapDefined(signatureDecls, (d) => checker.getSignatureFromDeclaration(d)); + if (length(signatures) !== length(decls)) { + return; + } + const returnOne = checker.getReturnTypeOfSignature(signatures[0]); + if (!every(signatures, (s) => checker.getReturnTypeOfSignature(s) === returnOne)) { + return; + } + return signatureDecls; +} + +// src/services/refactors/addOrRemoveBracesToArrowFunction.ts +var refactorName6 = "Add or remove braces in an arrow function"; +var refactorDescription2 = Diagnostics.Add_or_remove_braces_in_an_arrow_function.message; +var addBracesAction = { + name: "Add braces to arrow function", + description: Diagnostics.Add_braces_to_arrow_function.message, + kind: "refactor.rewrite.arrow.braces.add" +}; +var removeBracesAction = { + name: "Remove braces from arrow function", + description: Diagnostics.Remove_braces_from_arrow_function.message, + kind: "refactor.rewrite.arrow.braces.remove" +}; +registerRefactor(refactorName6, { + kinds: [removeBracesAction.kind], + getEditsForAction: getRefactorEditsToRemoveFunctionBraces, + getAvailableActions: getRefactorActionsToRemoveFunctionBraces +}); +function getRefactorActionsToRemoveFunctionBraces(context) { + const { file, startPosition, triggerReason } = context; + const info = getConvertibleArrowFunctionAtPosition(file, startPosition, triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + return [{ + name: refactorName6, + description: refactorDescription2, + actions: [ + info.addBraces ? addBracesAction : removeBracesAction + ] + }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorName6, + description: refactorDescription2, + actions: [ + { ...addBracesAction, notApplicableReason: info.error }, + { ...removeBracesAction, notApplicableReason: info.error } + ] + }]; + } + return emptyArray; +} +function getRefactorEditsToRemoveFunctionBraces(context, actionName2) { + const { file, startPosition } = context; + const info = getConvertibleArrowFunctionAtPosition(file, startPosition); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const { expression, returnStatement, func } = info; + let body; + if (actionName2 === addBracesAction.name) { + const returnStatement2 = factory.createReturnStatement(expression); + body = factory.createBlock( + [returnStatement2], + /*multiLine*/ + true + ); + copyLeadingComments( + expression, + returnStatement2, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + true + ); + } else if (actionName2 === removeBracesAction.name && returnStatement) { + const actualExpression = expression || factory.createVoidZero(); + body = needsParentheses(actualExpression) ? factory.createParenthesizedExpression(actualExpression) : actualExpression; + copyTrailingAsLeadingComments( + returnStatement, + body, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + copyLeadingComments( + returnStatement, + body, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + copyTrailingComments( + returnStatement, + body, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + } else { + Debug.fail("invalid action"); + } + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => { + t.replaceNode(file, func.body, body); + }); + return { renameFilename: void 0, renameLocation: void 0, edits }; +} +function getConvertibleArrowFunctionAtPosition(file, startPosition, considerFunctionBodies = true, kind) { + const node = getTokenAtPosition(file, startPosition); + const func = getContainingFunction(node); + if (!func) { + return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_a_containing_arrow_function) + }; + } + if (!isArrowFunction(func)) { + return { + error: getLocaleSpecificMessage(Diagnostics.Containing_function_is_not_an_arrow_function) + }; + } + if (!rangeContainsRange(func, node) || rangeContainsRange(func.body, node) && !considerFunctionBodies) { + return void 0; + } + if (refactorKindBeginsWith(addBracesAction.kind, kind) && isExpression(func.body)) { + return { func, addBraces: true, expression: func.body }; + } else if (refactorKindBeginsWith(removeBracesAction.kind, kind) && isBlock(func.body) && func.body.statements.length === 1) { + const firstStatement = first(func.body.statements); + if (isReturnStatement(firstStatement)) { + return { func, addBraces: false, expression: firstStatement.expression, returnStatement: firstStatement }; + } + } + return void 0; +} + +// src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts +var ts_refactor_convertArrowFunctionOrFunctionExpression_exports = {}; + +// src/services/refactors/convertArrowFunctionOrFunctionExpression.ts +var refactorName7 = "Convert arrow function or function expression"; +var refactorDescription3 = getLocaleSpecificMessage(Diagnostics.Convert_arrow_function_or_function_expression); +var toAnonymousFunctionAction = { + name: "Convert to anonymous function", + description: getLocaleSpecificMessage(Diagnostics.Convert_to_anonymous_function), + kind: "refactor.rewrite.function.anonymous" +}; +var toNamedFunctionAction = { + name: "Convert to named function", + description: getLocaleSpecificMessage(Diagnostics.Convert_to_named_function), + kind: "refactor.rewrite.function.named" +}; +var toArrowFunctionAction = { + name: "Convert to arrow function", + description: getLocaleSpecificMessage(Diagnostics.Convert_to_arrow_function), + kind: "refactor.rewrite.function.arrow" +}; +registerRefactor(refactorName7, { + kinds: [ + toAnonymousFunctionAction.kind, + toNamedFunctionAction.kind, + toArrowFunctionAction.kind + ], + getEditsForAction: getRefactorEditsToConvertFunctionExpressions, + getAvailableActions: getRefactorActionsToConvertFunctionExpressions +}); +function getRefactorActionsToConvertFunctionExpressions(context) { + const { file, startPosition, program, kind } = context; + const info = getFunctionInfo(file, startPosition, program); + if (!info) + return emptyArray; + const { selectedVariableDeclaration, func } = info; + const possibleActions = []; + const errors = []; + if (refactorKindBeginsWith(toNamedFunctionAction.kind, kind)) { + const error = selectedVariableDeclaration || isArrowFunction(func) && isVariableDeclaration(func.parent) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_named_function); + if (error) { + errors.push({ ...toNamedFunctionAction, notApplicableReason: error }); + } else { + possibleActions.push(toNamedFunctionAction); + } + } + if (refactorKindBeginsWith(toAnonymousFunctionAction.kind, kind)) { + const error = !selectedVariableDeclaration && isArrowFunction(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_anonymous_function); + if (error) { + errors.push({ ...toAnonymousFunctionAction, notApplicableReason: error }); + } else { + possibleActions.push(toAnonymousFunctionAction); + } + } + if (refactorKindBeginsWith(toArrowFunctionAction.kind, kind)) { + const error = isFunctionExpression(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_arrow_function); + if (error) { + errors.push({ ...toArrowFunctionAction, notApplicableReason: error }); + } else { + possibleActions.push(toArrowFunctionAction); + } + } + return [{ + name: refactorName7, + description: refactorDescription3, + actions: possibleActions.length === 0 && context.preferences.provideRefactorNotApplicableReason ? errors : possibleActions + }]; +} +function getRefactorEditsToConvertFunctionExpressions(context, actionName2) { + const { file, startPosition, program } = context; + const info = getFunctionInfo(file, startPosition, program); + if (!info) + return void 0; + const { func } = info; + const edits = []; + switch (actionName2) { + case toAnonymousFunctionAction.name: + edits.push(...getEditInfoForConvertToAnonymousFunction(context, func)); + break; + case toNamedFunctionAction.name: + const variableInfo = getVariableInfo(func); + if (!variableInfo) + return void 0; + edits.push(...getEditInfoForConvertToNamedFunction(context, func, variableInfo)); + break; + case toArrowFunctionAction.name: + if (!isFunctionExpression(func)) + return void 0; + edits.push(...getEditInfoForConvertToArrowFunction(context, func)); + break; + default: + return Debug.fail("invalid action"); + } + return { renameFilename: void 0, renameLocation: void 0, edits }; +} +function containingThis(node) { + let containsThis = false; + node.forEachChild(function checkThis(child) { + if (isThis(child)) { + containsThis = true; + return; + } + if (!isClassLike(child) && !isFunctionDeclaration(child) && !isFunctionExpression(child)) { + forEachChild(child, checkThis); + } + }); + return containsThis; +} +function getFunctionInfo(file, startPosition, program) { + const token = getTokenAtPosition(file, startPosition); + const typeChecker = program.getTypeChecker(); + const func = tryGetFunctionFromVariableDeclaration(file, typeChecker, token.parent); + if (func && !containingThis(func.body) && !typeChecker.containsArgumentsReference(func)) { + return { selectedVariableDeclaration: true, func }; + } + const maybeFunc = getContainingFunction(token); + if (maybeFunc && (isFunctionExpression(maybeFunc) || isArrowFunction(maybeFunc)) && !rangeContainsRange(maybeFunc.body, token) && !containingThis(maybeFunc.body) && !typeChecker.containsArgumentsReference(maybeFunc)) { + if (isFunctionExpression(maybeFunc) && isFunctionReferencedInFile(file, typeChecker, maybeFunc)) + return void 0; + return { selectedVariableDeclaration: false, func: maybeFunc }; + } + return void 0; +} +function isSingleVariableDeclaration(parent2) { + return isVariableDeclaration(parent2) || isVariableDeclarationList(parent2) && parent2.declarations.length === 1; +} +function tryGetFunctionFromVariableDeclaration(sourceFile, typeChecker, parent2) { + if (!isSingleVariableDeclaration(parent2)) { + return void 0; + } + const variableDeclaration = isVariableDeclaration(parent2) ? parent2 : first(parent2.declarations); + const initializer = variableDeclaration.initializer; + if (initializer && (isArrowFunction(initializer) || isFunctionExpression(initializer) && !isFunctionReferencedInFile(sourceFile, typeChecker, initializer))) { + return initializer; + } + return void 0; +} +function convertToBlock(body) { + if (isExpression(body)) { + const returnStatement = factory.createReturnStatement(body); + const file = body.getSourceFile(); + setTextRange(returnStatement, body); + suppressLeadingAndTrailingTrivia(returnStatement); + copyTrailingAsLeadingComments( + body, + returnStatement, + file, + /*commentKind*/ + void 0, + /*hasTrailingNewLine*/ + true + ); + return factory.createBlock( + [returnStatement], + /*multiLine*/ + true + ); + } else { + return body; + } +} +function getVariableInfo(func) { + const variableDeclaration = func.parent; + if (!isVariableDeclaration(variableDeclaration) || !isVariableDeclarationInVariableStatement(variableDeclaration)) + return void 0; + const variableDeclarationList = variableDeclaration.parent; + const statement = variableDeclarationList.parent; + if (!isVariableDeclarationList(variableDeclarationList) || !isVariableStatement(statement) || !isIdentifier(variableDeclaration.name)) + return void 0; + return { variableDeclaration, variableDeclarationList, statement, name: variableDeclaration.name }; +} +function getEditInfoForConvertToAnonymousFunction(context, func) { + const { file } = context; + const body = convertToBlock(func.body); + const newNode = factory.createFunctionExpression( + func.modifiers, + func.asteriskToken, + /*name*/ + void 0, + func.typeParameters, + func.parameters, + func.type, + body + ); + return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode)); +} +function getEditInfoForConvertToNamedFunction(context, func, variableInfo) { + const { file } = context; + const body = convertToBlock(func.body); + const { variableDeclaration, variableDeclarationList, statement, name } = variableInfo; + suppressLeadingTrivia(statement); + const modifiersFlags = getCombinedModifierFlags(variableDeclaration) & 1 /* Export */ | getEffectiveModifierFlags(func); + const modifiers = factory.createModifiersFromModifierFlags(modifiersFlags); + const newNode = factory.createFunctionDeclaration(length(modifiers) ? modifiers : void 0, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); + if (variableDeclarationList.declarations.length === 1) { + return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, statement, newNode)); + } else { + return ts_textChanges_exports.ChangeTracker.with(context, (t) => { + t.delete(file, variableDeclaration); + t.insertNodeAfter(file, statement, newNode); + }); + } +} +function getEditInfoForConvertToArrowFunction(context, func) { + const { file } = context; + const statements = func.body.statements; + const head = statements[0]; + let body; + if (canBeConvertedToExpression(func.body, head)) { + body = head.expression; + suppressLeadingAndTrailingTrivia(body); + copyComments(head, body); + } else { + body = func.body; + } + const newNode = factory.createArrowFunction(func.modifiers, func.typeParameters, func.parameters, func.type, factory.createToken(39 /* EqualsGreaterThanToken */), body); + return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode)); +} +function canBeConvertedToExpression(body, head) { + return body.statements.length === 1 && (isReturnStatement(head) && !!head.expression); +} +function isFunctionReferencedInFile(sourceFile, typeChecker, node) { + return !!node.name && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(node.name, typeChecker, sourceFile); +} + +// src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts +var ts_refactor_convertParamsToDestructuredObject_exports = {}; + +// src/services/refactors/convertParamsToDestructuredObject.ts +var refactorName8 = "Convert parameters to destructured object"; +var minimumParameterLength = 1; +var refactorDescription4 = getLocaleSpecificMessage(Diagnostics.Convert_parameters_to_destructured_object); +var toDestructuredAction = { + name: refactorName8, + description: refactorDescription4, + kind: "refactor.rewrite.parameters.toDestructured" +}; +registerRefactor(refactorName8, { + kinds: [toDestructuredAction.kind], + getEditsForAction: getRefactorEditsToConvertParametersToDestructuredObject, + getAvailableActions: getRefactorActionsToConvertParametersToDestructuredObject +}); +function getRefactorActionsToConvertParametersToDestructuredObject(context) { + const { file, startPosition } = context; + const isJSFile = isSourceFileJS(file); + if (isJSFile) + return emptyArray; + const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker()); + if (!functionDeclaration) + return emptyArray; + return [{ + name: refactorName8, + description: refactorDescription4, + actions: [toDestructuredAction] + }]; +} +function getRefactorEditsToConvertParametersToDestructuredObject(context, actionName2) { + Debug.assert(actionName2 === refactorName8, "Unexpected action name"); + const { file, startPosition, program, cancellationToken, host } = context; + const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); + if (!functionDeclaration || !cancellationToken) + return void 0; + const groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken); + if (groupedReferences.valid) { + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange5(file, program, host, t, functionDeclaration, groupedReferences)); + return { renameFilename: void 0, renameLocation: void 0, edits }; + } + return { edits: [] }; +} +function doChange5(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { + const signature = groupedReferences.signature; + const newFunctionDeclarationParams = map(createNewParameters(functionDeclaration, program, host), (param) => getSynthesizedDeepClone(param)); + if (signature) { + const newSignatureParams = map(createNewParameters(signature, program, host), (param) => getSynthesizedDeepClone(param)); + replaceParameters(signature, newSignatureParams); + } + replaceParameters(functionDeclaration, newFunctionDeclarationParams); + const functionCalls = sortAndDeduplicate( + groupedReferences.functionCalls, + /*comparer*/ + (a, b) => compareValues(a.pos, b.pos) + ); + for (const call of functionCalls) { + if (call.arguments && call.arguments.length) { + const newArgument = getSynthesizedDeepClone( + createNewArgument(functionDeclaration, call.arguments), + /*includeTrivia*/ + true + ); + changes.replaceNodeRange( + getSourceFileOfNode(call), + first(call.arguments), + last(call.arguments), + newArgument, + { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include } + ); + } + } + function replaceParameters(declarationOrSignature, parameterDeclarations) { + changes.replaceNodeRangeWithNodes( + sourceFile, + first(declarationOrSignature.parameters), + last(declarationOrSignature.parameters), + parameterDeclarations, + { + joiner: ", ", + // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter + indentation: 0, + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include + } + ); + } +} +function getGroupedReferences(functionDeclaration, program, cancellationToken) { + const functionNames = getFunctionNames(functionDeclaration); + const classNames = isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : []; + const names = deduplicate([...functionNames, ...classNames], equateValues); + const checker = program.getTypeChecker(); + const references = flatMap( + names, + /*mapfn*/ + (name) => ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken) + ); + const groupedReferences = groupReferences(references); + if (!every( + groupedReferences.declarations, + /*callback*/ + (decl) => contains(names, decl) + )) { + groupedReferences.valid = false; + } + return groupedReferences; + function groupReferences(referenceEntries) { + const classReferences = { accessExpressions: [], typeUsages: [] }; + const groupedReferences2 = { functionCalls: [], declarations: [], classReferences, valid: true }; + const functionSymbols = map(functionNames, getSymbolTargetAtLocation); + const classSymbols = map(classNames, getSymbolTargetAtLocation); + const isConstructor = isConstructorDeclaration(functionDeclaration); + const contextualSymbols = map(functionNames, (name) => getSymbolForContextualType(name, checker)); + for (const entry of referenceEntries) { + if (entry.kind === ts_FindAllReferences_exports.EntryKind.Span) { + groupedReferences2.valid = false; + continue; + } + if (contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) { + if (isValidMethodSignature(entry.node.parent)) { + groupedReferences2.signature = entry.node.parent; + continue; + } + const call = entryToFunctionCall(entry); + if (call) { + groupedReferences2.functionCalls.push(call); + continue; + } + } + const contextualSymbol = getSymbolForContextualType(entry.node, checker); + if (contextualSymbol && contains(contextualSymbols, contextualSymbol)) { + const decl = entryToDeclaration(entry); + if (decl) { + groupedReferences2.declarations.push(decl); + continue; + } + } + if (contains(functionSymbols, getSymbolTargetAtLocation(entry.node)) || isNewExpressionTarget(entry.node)) { + const importOrExportReference = entryToImportOrExport(entry); + if (importOrExportReference) { + continue; + } + const decl = entryToDeclaration(entry); + if (decl) { + groupedReferences2.declarations.push(decl); + continue; + } + const call = entryToFunctionCall(entry); + if (call) { + groupedReferences2.functionCalls.push(call); + continue; + } + } + if (isConstructor && contains(classSymbols, getSymbolTargetAtLocation(entry.node))) { + const importOrExportReference = entryToImportOrExport(entry); + if (importOrExportReference) { + continue; + } + const decl = entryToDeclaration(entry); + if (decl) { + groupedReferences2.declarations.push(decl); + continue; + } + const accessExpression = entryToAccessExpression(entry); + if (accessExpression) { + classReferences.accessExpressions.push(accessExpression); + continue; + } + if (isClassDeclaration(functionDeclaration.parent)) { + const type = entryToType(entry); + if (type) { + classReferences.typeUsages.push(type); + continue; + } + } + } + groupedReferences2.valid = false; + } + return groupedReferences2; + } + function getSymbolTargetAtLocation(node) { + const symbol = checker.getSymbolAtLocation(node); + return symbol && getSymbolTarget(symbol, checker); + } +} +function getSymbolForContextualType(node, checker) { + const element = getContainingObjectLiteralElement(node); + if (element) { + const contextualType = checker.getContextualTypeForObjectLiteralElement(element); + const symbol = contextualType == null ? void 0 : contextualType.getSymbol(); + if (symbol && !(getCheckFlags(symbol) & 6 /* Synthetic */)) { + return symbol; + } + } +} +function entryToImportOrExport(entry) { + const node = entry.node; + if (isImportSpecifier(node.parent) || isImportClause(node.parent) || isImportEqualsDeclaration(node.parent) || isNamespaceImport(node.parent)) { + return node; + } + if (isExportSpecifier(node.parent) || isExportAssignment(node.parent)) { + return node; + } + return void 0; +} +function entryToDeclaration(entry) { + if (isDeclaration(entry.node.parent)) { + return entry.node; + } + return void 0; +} +function entryToFunctionCall(entry) { + if (entry.node.parent) { + const functionReference = entry.node; + const parent2 = functionReference.parent; + switch (parent2.kind) { + case 212 /* CallExpression */: + case 213 /* NewExpression */: + const callOrNewExpression = tryCast(parent2, isCallOrNewExpression); + if (callOrNewExpression && callOrNewExpression.expression === functionReference) { + return callOrNewExpression; + } + break; + case 210 /* PropertyAccessExpression */: + const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); + if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { + const callOrNewExpression2 = tryCast(propertyAccessExpression.parent, isCallOrNewExpression); + if (callOrNewExpression2 && callOrNewExpression2.expression === propertyAccessExpression) { + return callOrNewExpression2; + } + } + break; + case 211 /* ElementAccessExpression */: + const elementAccessExpression = tryCast(parent2, isElementAccessExpression); + if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { + const callOrNewExpression2 = tryCast(elementAccessExpression.parent, isCallOrNewExpression); + if (callOrNewExpression2 && callOrNewExpression2.expression === elementAccessExpression) { + return callOrNewExpression2; + } + } + break; + } + } + return void 0; +} +function entryToAccessExpression(entry) { + if (entry.node.parent) { + const reference = entry.node; + const parent2 = reference.parent; + switch (parent2.kind) { + case 210 /* PropertyAccessExpression */: + const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); + if (propertyAccessExpression && propertyAccessExpression.expression === reference) { + return propertyAccessExpression; + } + break; + case 211 /* ElementAccessExpression */: + const elementAccessExpression = tryCast(parent2, isElementAccessExpression); + if (elementAccessExpression && elementAccessExpression.expression === reference) { + return elementAccessExpression; + } + break; + } + } + return void 0; +} +function entryToType(entry) { + const reference = entry.node; + if (getMeaningFromLocation(reference) === 2 /* Type */ || isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) { + return reference; + } + return void 0; +} +function getFunctionDeclarationAtPosition(file, startPosition, checker) { + const node = getTouchingToken(file, startPosition); + const functionDeclaration = getContainingFunctionDeclaration(node); + if (isTopLevelJSDoc(node)) + return void 0; + if (functionDeclaration && isValidFunctionDeclaration(functionDeclaration, checker) && rangeContainsRange(functionDeclaration, node) && !(functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node))) + return functionDeclaration; + return void 0; +} +function isTopLevelJSDoc(node) { + const containingJSDoc = findAncestor(node, isJSDocNode); + if (containingJSDoc) { + const containingNonJSDoc = findAncestor(containingJSDoc, (n) => !isJSDocNode(n)); + return !!containingNonJSDoc && isFunctionLikeDeclaration(containingNonJSDoc); + } + return false; +} +function isValidMethodSignature(node) { + return isMethodSignature(node) && (isInterfaceDeclaration(node.parent) || isTypeLiteralNode(node.parent)); +} +function isValidFunctionDeclaration(functionDeclaration, checker) { + var _a; + if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) + return false; + switch (functionDeclaration.kind) { + case 261 /* FunctionDeclaration */: + return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); + case 173 /* MethodDeclaration */: + if (isObjectLiteralExpression(functionDeclaration.parent)) { + const contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); + return ((_a = contextualSymbol == null ? void 0 : contextualSymbol.declarations) == null ? void 0 : _a.length) === 1 && isSingleImplementation(functionDeclaration, checker); + } + return isSingleImplementation(functionDeclaration, checker); + case 175 /* Constructor */: + if (isClassDeclaration(functionDeclaration.parent)) { + return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker); + } else { + return isValidVariableDeclaration(functionDeclaration.parent.parent) && isSingleImplementation(functionDeclaration, checker); + } + case 217 /* FunctionExpression */: + case 218 /* ArrowFunction */: + return isValidVariableDeclaration(functionDeclaration.parent); + } + return false; +} +function isSingleImplementation(functionDeclaration, checker) { + return !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); +} +function hasNameOrDefault(functionOrClassDeclaration) { + if (!functionOrClassDeclaration.name) { + const defaultKeyword = findModifier(functionOrClassDeclaration, 90 /* DefaultKeyword */); + return !!defaultKeyword; + } + return true; +} +function isValidParameterNodeArray(parameters, checker) { + return getRefactorableParametersLength(parameters) >= minimumParameterLength && every( + parameters, + /*callback*/ + (paramDecl) => isValidParameterDeclaration(paramDecl, checker) + ); +} +function isValidParameterDeclaration(parameterDeclaration, checker) { + if (isRestParameter(parameterDeclaration)) { + const type = checker.getTypeAtLocation(parameterDeclaration); + if (!checker.isArrayType(type) && !checker.isTupleType(type)) + return false; + } + return !parameterDeclaration.modifiers && isIdentifier(parameterDeclaration.name); +} +function isValidVariableDeclaration(node) { + return isVariableDeclaration(node) && isVarConst(node) && isIdentifier(node.name) && !node.type; +} +function hasThisParameter(parameters) { + return parameters.length > 0 && isThis(parameters[0].name); +} +function getRefactorableParametersLength(parameters) { + if (hasThisParameter(parameters)) { + return parameters.length - 1; + } + return parameters.length; +} +function getRefactorableParameters(parameters) { + if (hasThisParameter(parameters)) { + parameters = factory.createNodeArray(parameters.slice(1), parameters.hasTrailingComma); + } + return parameters; +} +function createPropertyOrShorthandAssignment(name, initializer) { + if (isIdentifier(initializer) && getTextOfIdentifierOrLiteral(initializer) === name) { + return factory.createShorthandPropertyAssignment(name); + } + return factory.createPropertyAssignment(name, initializer); +} +function createNewArgument(functionDeclaration, functionArguments) { + const parameters = getRefactorableParameters(functionDeclaration.parameters); + const hasRestParameter2 = isRestParameter(last(parameters)); + const nonRestArguments = hasRestParameter2 ? functionArguments.slice(0, parameters.length - 1) : functionArguments; + const properties = map(nonRestArguments, (arg, i) => { + const parameterName = getParameterName(parameters[i]); + const property = createPropertyOrShorthandAssignment(parameterName, arg); + suppressLeadingAndTrailingTrivia(property.name); + if (isPropertyAssignment(property)) + suppressLeadingAndTrailingTrivia(property.initializer); + copyComments(arg, property); + return property; + }); + if (hasRestParameter2 && functionArguments.length >= parameters.length) { + const restArguments = functionArguments.slice(parameters.length - 1); + const restProperty = factory.createPropertyAssignment(getParameterName(last(parameters)), factory.createArrayLiteralExpression(restArguments)); + properties.push(restProperty); + } + const objectLiteral = factory.createObjectLiteralExpression( + properties, + /*multiLine*/ + false + ); + return objectLiteral; +} +function createNewParameters(functionDeclaration, program, host) { + const checker = program.getTypeChecker(); + const refactorableParameters = getRefactorableParameters(functionDeclaration.parameters); + const bindingElements = map(refactorableParameters, createBindingElementFromParameterDeclaration); + const objectParameterName = factory.createObjectBindingPattern(bindingElements); + const objectParameterType = createParameterTypeNode(refactorableParameters); + let objectInitializer; + if (every(refactorableParameters, isOptionalParameter)) { + objectInitializer = factory.createObjectLiteralExpression(); + } + const objectParameter = factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + objectParameterName, + /*questionToken*/ + void 0, + objectParameterType, + objectInitializer + ); + if (hasThisParameter(functionDeclaration.parameters)) { + const thisParameter = functionDeclaration.parameters[0]; + const newThisParameter = factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + thisParameter.name, + /*questionToken*/ + void 0, + thisParameter.type + ); + suppressLeadingAndTrailingTrivia(newThisParameter.name); + copyComments(thisParameter.name, newThisParameter.name); + if (thisParameter.type) { + suppressLeadingAndTrailingTrivia(newThisParameter.type); + copyComments(thisParameter.type, newThisParameter.type); + } + return factory.createNodeArray([newThisParameter, objectParameter]); + } + return factory.createNodeArray([objectParameter]); + function createBindingElementFromParameterDeclaration(parameterDeclaration) { + const element = factory.createBindingElement( + /*dotDotDotToken*/ + void 0, + /*propertyName*/ + void 0, + getParameterName(parameterDeclaration), + isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? factory.createArrayLiteralExpression() : parameterDeclaration.initializer + ); + suppressLeadingAndTrailingTrivia(element); + if (parameterDeclaration.initializer && element.initializer) { + copyComments(parameterDeclaration.initializer, element.initializer); + } + return element; + } + function createParameterTypeNode(parameters) { + const members = map(parameters, createPropertySignatureFromParameterDeclaration); + const typeNode = addEmitFlags(factory.createTypeLiteralNode(members), 1 /* SingleLine */); + return typeNode; + } + function createPropertySignatureFromParameterDeclaration(parameterDeclaration) { + let parameterType = parameterDeclaration.type; + if (!parameterType && (parameterDeclaration.initializer || isRestParameter(parameterDeclaration))) { + parameterType = getTypeNode3(parameterDeclaration); + } + const propertySignature = factory.createPropertySignature( + /*modifiers*/ + void 0, + getParameterName(parameterDeclaration), + isOptionalParameter(parameterDeclaration) ? factory.createToken(58 /* QuestionToken */) : parameterDeclaration.questionToken, + parameterType + ); + suppressLeadingAndTrailingTrivia(propertySignature); + copyComments(parameterDeclaration.name, propertySignature.name); + if (parameterDeclaration.type && propertySignature.type) { + copyComments(parameterDeclaration.type, propertySignature.type); + } + return propertySignature; + } + function getTypeNode3(node) { + const type = checker.getTypeAtLocation(node); + return getTypeNodeIfAccessible(type, node, program, host); + } + function isOptionalParameter(parameterDeclaration) { + if (isRestParameter(parameterDeclaration)) { + const type = checker.getTypeAtLocation(parameterDeclaration); + return !checker.isTupleType(type); + } + return checker.isOptionalParameter(parameterDeclaration); + } +} +function getParameterName(paramDeclaration) { + return getTextOfIdentifierOrLiteral(paramDeclaration.name); +} +function getClassNames(constructorDeclaration) { + switch (constructorDeclaration.parent.kind) { + case 262 /* ClassDeclaration */: + const classDeclaration = constructorDeclaration.parent; + if (classDeclaration.name) + return [classDeclaration.name]; + const defaultModifier = Debug.checkDefined( + findModifier(classDeclaration, 90 /* DefaultKeyword */), + "Nameless class declaration should be a default export" + ); + return [defaultModifier]; + case 230 /* ClassExpression */: + const classExpression = constructorDeclaration.parent; + const variableDeclaration = constructorDeclaration.parent.parent; + const className = classExpression.name; + if (className) + return [className, variableDeclaration.name]; + return [variableDeclaration.name]; + } +} +function getFunctionNames(functionDeclaration) { + switch (functionDeclaration.kind) { + case 261 /* FunctionDeclaration */: + if (functionDeclaration.name) + return [functionDeclaration.name]; + const defaultModifier = Debug.checkDefined( + findModifier(functionDeclaration, 90 /* DefaultKeyword */), + "Nameless function declaration should be a default export" + ); + return [defaultModifier]; + case 173 /* MethodDeclaration */: + return [functionDeclaration.name]; + case 175 /* Constructor */: + const ctrKeyword = Debug.checkDefined( + findChildOfKind(functionDeclaration, 137 /* ConstructorKeyword */, functionDeclaration.getSourceFile()), + "Constructor declaration should have constructor keyword" + ); + if (functionDeclaration.parent.kind === 230 /* ClassExpression */) { + const variableDeclaration = functionDeclaration.parent.parent; + return [variableDeclaration.name, ctrKeyword]; + } + return [ctrKeyword]; + case 218 /* ArrowFunction */: + return [functionDeclaration.parent.name]; + case 217 /* FunctionExpression */: + if (functionDeclaration.name) + return [functionDeclaration.name, functionDeclaration.parent.name]; + return [functionDeclaration.parent.name]; + default: + return Debug.assertNever(functionDeclaration, `Unexpected function declaration kind ${functionDeclaration.kind}`); + } +} + +// src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts +var ts_refactor_convertStringOrTemplateLiteral_exports = {}; + +// src/services/refactors/convertStringOrTemplateLiteral.ts +var refactorName9 = "Convert to template string"; +var refactorDescription5 = getLocaleSpecificMessage(Diagnostics.Convert_to_template_string); +var convertStringAction = { + name: refactorName9, + description: refactorDescription5, + kind: "refactor.rewrite.string" +}; +registerRefactor(refactorName9, { + kinds: [convertStringAction.kind], + getEditsForAction: getRefactorEditsToConvertToTemplateString, + getAvailableActions: getRefactorActionsToConvertToTemplateString +}); +function getRefactorActionsToConvertToTemplateString(context) { + const { file, startPosition } = context; + const node = getNodeOrParentOfParentheses(file, startPosition); + const maybeBinary = getParentBinaryExpression(node); + const refactorInfo = { name: refactorName9, description: refactorDescription5, actions: [] }; + if (isBinaryExpression(maybeBinary) && treeToArray(maybeBinary).isValidConcatenation) { + refactorInfo.actions.push(convertStringAction); + return [refactorInfo]; + } else if (context.preferences.provideRefactorNotApplicableReason) { + refactorInfo.actions.push({ + ...convertStringAction, + notApplicableReason: getLocaleSpecificMessage(Diagnostics.Can_only_convert_string_concatenation) + }); + return [refactorInfo]; + } + return emptyArray; +} +function getNodeOrParentOfParentheses(file, startPosition) { + const node = getTokenAtPosition(file, startPosition); + const nestedBinary = getParentBinaryExpression(node); + const isNonStringBinary = !treeToArray(nestedBinary).isValidConcatenation; + if (isNonStringBinary && isParenthesizedExpression(nestedBinary.parent) && isBinaryExpression(nestedBinary.parent.parent)) { + return nestedBinary.parent.parent; + } + return node; +} +function getRefactorEditsToConvertToTemplateString(context, actionName2) { + const { file, startPosition } = context; + const node = getNodeOrParentOfParentheses(file, startPosition); + switch (actionName2) { + case refactorDescription5: + return { edits: getEditsForToTemplateLiteral(context, node) }; + default: + return Debug.fail("invalid action"); + } +} +function getEditsForToTemplateLiteral(context, node) { + const maybeBinary = getParentBinaryExpression(node); + const file = context.file; + const templateLiteral = nodesToTemplate(treeToArray(maybeBinary), file); + const trailingCommentRanges = getTrailingCommentRanges(file.text, maybeBinary.end); + if (trailingCommentRanges) { + const lastComment = trailingCommentRanges[trailingCommentRanges.length - 1]; + const trailingRange = { pos: trailingCommentRanges[0].pos, end: lastComment.end }; + return ts_textChanges_exports.ChangeTracker.with(context, (t) => { + t.deleteRange(file, trailingRange); + t.replaceNode(file, maybeBinary, templateLiteral); + }); + } else { + return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, maybeBinary, templateLiteral)); + } +} +function isNotEqualsOperator(node) { + return node.operatorToken.kind !== 64 /* EqualsToken */; +} +function getParentBinaryExpression(expr) { + const container = findAncestor(expr.parent, (n) => { + switch (n.kind) { + case 210 /* PropertyAccessExpression */: + case 211 /* ElementAccessExpression */: + return false; + case 227 /* TemplateExpression */: + case 225 /* BinaryExpression */: + return !(isBinaryExpression(n.parent) && isNotEqualsOperator(n.parent)); + default: + return "quit"; + } + }); + return container || expr; +} +function treeToArray(current) { + const loop = (current2) => { + if (!isBinaryExpression(current2)) { + return { + nodes: [current2], + operators: [], + validOperators: true, + hasString: isStringLiteral(current2) || isNoSubstitutionTemplateLiteral(current2) + }; + } + const { nodes: nodes2, operators: operators2, hasString: leftHasString, validOperators: leftOperatorValid } = loop(current2.left); + if (!(leftHasString || isStringLiteral(current2.right) || isTemplateExpression(current2.right))) { + return { nodes: [current2], operators: [], hasString: false, validOperators: true }; + } + const currentOperatorValid = current2.operatorToken.kind === 40 /* PlusToken */; + const validOperators2 = leftOperatorValid && currentOperatorValid; + nodes2.push(current2.right); + operators2.push(current2.operatorToken); + return { nodes: nodes2, operators: operators2, hasString: true, validOperators: validOperators2 }; + }; + const { nodes, operators, validOperators, hasString } = loop(current); + return { nodes, operators, isValidConcatenation: validOperators && hasString }; +} +var copyTrailingOperatorComments = (operators, file) => (index, targetNode) => { + if (index < operators.length) { + copyTrailingComments( + operators[index], + targetNode, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + } +}; +var copyCommentFromMultiNode = (nodes, file, copyOperatorComments) => (indexes, targetNode) => { + while (indexes.length > 0) { + const index = indexes.shift(); + copyTrailingComments( + nodes[index], + targetNode, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + copyOperatorComments(index, targetNode); + } +}; +function escapeRawStringForTemplate(s) { + return s.replace(/\\.|[$`]/g, (m) => m[0] === "\\" ? m : "\\" + m); +} +function getRawTextOfTemplate(node) { + const rightShaving = isTemplateHead(node) || isTemplateMiddle(node) ? -2 : -1; + return getTextOfNode(node).slice(1, rightShaving); +} +function concatConsecutiveString(index, nodes) { + const indexes = []; + let text = "", rawText = ""; + while (index < nodes.length) { + const node = nodes[index]; + if (isStringLiteralLike(node)) { + text += node.text; + rawText += escapeRawStringForTemplate(getTextOfNode(node).slice(1, -1)); + indexes.push(index); + index++; + } else if (isTemplateExpression(node)) { + text += node.head.text; + rawText += getRawTextOfTemplate(node.head); + break; + } else { + break; + } + } + return [index, text, rawText, indexes]; +} +function nodesToTemplate({ nodes, operators }, file) { + const copyOperatorComments = copyTrailingOperatorComments(operators, file); + const copyCommentFromStringLiterals = copyCommentFromMultiNode(nodes, file, copyOperatorComments); + const [begin, headText, rawHeadText, headIndexes] = concatConsecutiveString(0, nodes); + if (begin === nodes.length) { + const noSubstitutionTemplateLiteral = factory.createNoSubstitutionTemplateLiteral(headText, rawHeadText); + copyCommentFromStringLiterals(headIndexes, noSubstitutionTemplateLiteral); + return noSubstitutionTemplateLiteral; + } + const templateSpans = []; + const templateHead = factory.createTemplateHead(headText, rawHeadText); + copyCommentFromStringLiterals(headIndexes, templateHead); + for (let i = begin; i < nodes.length; i++) { + const currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); + copyOperatorComments(i, currentNode); + const [newIndex, subsequentText, rawSubsequentText, stringIndexes] = concatConsecutiveString(i + 1, nodes); + i = newIndex - 1; + const isLast = i === nodes.length - 1; + if (isTemplateExpression(currentNode)) { + const spans = map(currentNode.templateSpans, (span, index) => { + copyExpressionComments(span); + 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)); + }); + templateSpans.push(...spans); + } else { + const templatePart = isLast ? factory.createTemplateTail(subsequentText, rawSubsequentText) : factory.createTemplateMiddle(subsequentText, rawSubsequentText); + copyCommentFromStringLiterals(stringIndexes, templatePart); + templateSpans.push(factory.createTemplateSpan(currentNode, templatePart)); + } + } + return factory.createTemplateExpression(templateHead, templateSpans); +} +function copyExpressionComments(node) { + const file = node.getSourceFile(); + copyTrailingComments( + node, + node.expression, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + copyTrailingAsLeadingComments( + node.expression, + node.expression, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); +} +function getExpressionFromParenthesesOrExpression(node) { + if (isParenthesizedExpression(node)) { + copyExpressionComments(node); + node = node.expression; + } + return node; +} + +// src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts +var ts_refactor_convertToOptionalChainExpression_exports = {}; + +// src/services/refactors/convertToOptionalChainExpression.ts +var refactorName10 = "Convert to optional chain expression"; +var convertToOptionalChainExpressionMessage = getLocaleSpecificMessage(Diagnostics.Convert_to_optional_chain_expression); +var toOptionalChainAction = { + name: refactorName10, + description: convertToOptionalChainExpressionMessage, + kind: "refactor.rewrite.expression.optionalChain" +}; +registerRefactor(refactorName10, { + kinds: [toOptionalChainAction.kind], + getEditsForAction: getRefactorEditsToConvertToOptionalChain, + getAvailableActions: getRefactorActionsToConvertToOptionalChain +}); +function getRefactorActionsToConvertToOptionalChain(context) { + const info = getInfo3(context, context.triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + return [{ + name: refactorName10, + description: convertToOptionalChainExpressionMessage, + actions: [toOptionalChainAction] + }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorName10, + description: convertToOptionalChainExpressionMessage, + actions: [{ ...toOptionalChainAction, notApplicableReason: info.error }] + }]; + } + return emptyArray; +} +function getRefactorEditsToConvertToOptionalChain(context, actionName2) { + const info = getInfo3(context); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const edits = ts_textChanges_exports.ChangeTracker.with( + context, + (t) => doChange6(context.file, context.program.getTypeChecker(), t, info, actionName2) + ); + return { edits, renameFilename: void 0, renameLocation: void 0 }; +} +function isValidExpression(node) { + return isBinaryExpression(node) || isConditionalExpression(node); +} +function isValidStatement(node) { + return isExpressionStatement(node) || isReturnStatement(node) || isVariableStatement(node); +} +function isValidExpressionOrStatement(node) { + return isValidExpression(node) || isValidStatement(node); +} +function getInfo3(context, considerEmptySpans = true) { + const { file, program } = context; + const span = getRefactorContextSpan(context); + const forEmptySpan = span.length === 0; + if (forEmptySpan && !considerEmptySpans) + return void 0; + const startToken = getTokenAtPosition(file, span.start); + const endToken = findTokenOnLeftOfPosition(file, span.start + span.length); + const adjustedSpan = createTextSpanFromBounds(startToken.pos, endToken && endToken.end >= startToken.pos ? endToken.getEnd() : startToken.getEnd()); + const parent2 = forEmptySpan ? getValidParentNodeOfEmptySpan(startToken) : getValidParentNodeContainingSpan(startToken, adjustedSpan); + const expression = parent2 && isValidExpressionOrStatement(parent2) ? getExpression(parent2) : void 0; + if (!expression) + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; + const checker = program.getTypeChecker(); + return isConditionalExpression(expression) ? getConditionalInfo(expression, checker) : getBinaryInfo(expression); +} +function getConditionalInfo(expression, checker) { + const condition = expression.condition; + const finalExpression = getFinalExpressionInChain(expression.whenTrue); + if (!finalExpression || checker.isNullableType(checker.getTypeAtLocation(finalExpression))) { + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; + } + if ((isPropertyAccessExpression(condition) || isIdentifier(condition)) && getMatchingStart(condition, finalExpression.expression)) { + return { finalExpression, occurrences: [condition], expression }; + } else if (isBinaryExpression(condition)) { + const occurrences = getOccurrencesInExpression(finalExpression.expression, condition); + return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) }; + } +} +function getBinaryInfo(expression) { + if (expression.operatorToken.kind !== 56 /* AmpersandAmpersandToken */) { + return { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_logical_AND_access_chains) }; + } + const finalExpression = getFinalExpressionInChain(expression.right); + if (!finalExpression) + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; + const occurrences = getOccurrencesInExpression(finalExpression.expression, expression.left); + return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) }; +} +function getOccurrencesInExpression(matchTo, expression) { + const occurrences = []; + while (isBinaryExpression(expression) && expression.operatorToken.kind === 56 /* AmpersandAmpersandToken */) { + const match = getMatchingStart(skipParentheses(matchTo), skipParentheses(expression.right)); + if (!match) { + break; + } + occurrences.push(match); + matchTo = match; + expression = expression.left; + } + const finalMatch = getMatchingStart(matchTo, expression); + if (finalMatch) { + occurrences.push(finalMatch); + } + return occurrences.length > 0 ? occurrences : void 0; +} +function getMatchingStart(chain, subchain) { + if (!isIdentifier(subchain) && !isPropertyAccessExpression(subchain) && !isElementAccessExpression(subchain)) { + return void 0; + } + return chainStartsWith(chain, subchain) ? subchain : void 0; +} +function chainStartsWith(chain, subchain) { + while (isCallExpression(chain) || isPropertyAccessExpression(chain) || isElementAccessExpression(chain)) { + if (getTextOfChainNode(chain) === getTextOfChainNode(subchain)) + break; + chain = chain.expression; + } + while (isPropertyAccessExpression(chain) && isPropertyAccessExpression(subchain) || isElementAccessExpression(chain) && isElementAccessExpression(subchain)) { + if (getTextOfChainNode(chain) !== getTextOfChainNode(subchain)) + return false; + chain = chain.expression; + subchain = subchain.expression; + } + return isIdentifier(chain) && isIdentifier(subchain) && chain.getText() === subchain.getText(); +} +function getTextOfChainNode(node) { + if (isIdentifier(node) || isStringOrNumericLiteralLike(node)) { + return node.getText(); + } + if (isPropertyAccessExpression(node)) { + return getTextOfChainNode(node.name); + } + if (isElementAccessExpression(node)) { + return getTextOfChainNode(node.argumentExpression); + } + return void 0; +} +function getValidParentNodeContainingSpan(node, span) { + while (node.parent) { + if (isValidExpressionOrStatement(node) && span.length !== 0 && node.end >= span.start + span.length) { + return node; + } + node = node.parent; + } + return void 0; +} +function getValidParentNodeOfEmptySpan(node) { + while (node.parent) { + if (isValidExpressionOrStatement(node) && !isValidExpressionOrStatement(node.parent)) { + return node; + } + node = node.parent; + } + return void 0; +} +function getExpression(node) { + if (isValidExpression(node)) { + return node; + } + if (isVariableStatement(node)) { + const variable = getSingleVariableOfVariableStatement(node); + const initializer = variable == null ? void 0 : variable.initializer; + return initializer && isValidExpression(initializer) ? initializer : void 0; + } + return node.expression && isValidExpression(node.expression) ? node.expression : void 0; +} +function getFinalExpressionInChain(node) { + node = skipParentheses(node); + if (isBinaryExpression(node)) { + return getFinalExpressionInChain(node.left); + } else if ((isPropertyAccessExpression(node) || isElementAccessExpression(node) || isCallExpression(node)) && !isOptionalChain(node)) { + return node; + } + return void 0; +} +function convertOccurrences(checker, toConvert, occurrences) { + if (isPropertyAccessExpression(toConvert) || isElementAccessExpression(toConvert) || isCallExpression(toConvert)) { + const chain = convertOccurrences(checker, toConvert.expression, occurrences); + const lastOccurrence = occurrences.length > 0 ? occurrences[occurrences.length - 1] : void 0; + const isOccurrence = (lastOccurrence == null ? void 0 : lastOccurrence.getText()) === toConvert.expression.getText(); + if (isOccurrence) + occurrences.pop(); + if (isCallExpression(toConvert)) { + return isOccurrence ? factory.createCallChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.typeArguments, toConvert.arguments) : factory.createCallChain(chain, toConvert.questionDotToken, toConvert.typeArguments, toConvert.arguments); + } else if (isPropertyAccessExpression(toConvert)) { + return isOccurrence ? factory.createPropertyAccessChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.name) : factory.createPropertyAccessChain(chain, toConvert.questionDotToken, toConvert.name); + } else if (isElementAccessExpression(toConvert)) { + return isOccurrence ? factory.createElementAccessChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.argumentExpression) : factory.createElementAccessChain(chain, toConvert.questionDotToken, toConvert.argumentExpression); + } + } + return toConvert; +} +function doChange6(sourceFile, checker, changes, info, _actionName) { + const { finalExpression, occurrences, expression } = info; + const firstOccurrence = occurrences[occurrences.length - 1]; + const convertedChain = convertOccurrences(checker, finalExpression, occurrences); + if (convertedChain && (isPropertyAccessExpression(convertedChain) || isElementAccessExpression(convertedChain) || isCallExpression(convertedChain))) { + if (isBinaryExpression(expression)) { + changes.replaceNodeRange(sourceFile, firstOccurrence, finalExpression, convertedChain); + } else if (isConditionalExpression(expression)) { + changes.replaceNode( + sourceFile, + expression, + factory.createBinaryExpression(convertedChain, factory.createToken(61 /* QuestionQuestionToken */), expression.whenFalse) + ); + } + } +} + +// src/services/_namespaces/ts.refactor.extractSymbol.ts +var ts_refactor_extractSymbol_exports = {}; +__export(ts_refactor_extractSymbol_exports, { + Messages: () => Messages, + RangeFacts: () => RangeFacts, + getRangeToExtract: () => getRangeToExtract2, + getRefactorActionsToExtractSymbol: () => getRefactorActionsToExtractSymbol, + getRefactorEditsToExtractSymbol: () => getRefactorEditsToExtractSymbol +}); + +// src/services/refactors/extractSymbol.ts +var refactorName11 = "Extract Symbol"; +var extractConstantAction = { + name: "Extract Constant", + description: getLocaleSpecificMessage(Diagnostics.Extract_constant), + kind: "refactor.extract.constant" +}; +var extractFunctionAction = { + name: "Extract Function", + description: getLocaleSpecificMessage(Diagnostics.Extract_function), + kind: "refactor.extract.function" +}; +registerRefactor(refactorName11, { + kinds: [ + extractConstantAction.kind, + extractFunctionAction.kind + ], + getEditsForAction: getRefactorEditsToExtractSymbol, + getAvailableActions: getRefactorActionsToExtractSymbol +}); +function getRefactorActionsToExtractSymbol(context) { + const requestedRefactor = context.kind; + const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context), context.triggerReason === "invoked"); + const targetRange = rangeToExtract.targetRange; + if (targetRange === void 0) { + if (!rangeToExtract.errors || rangeToExtract.errors.length === 0 || !context.preferences.provideRefactorNotApplicableReason) { + return emptyArray; + } + const errors = []; + if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { + errors.push({ + name: refactorName11, + description: extractFunctionAction.description, + actions: [{ ...extractFunctionAction, notApplicableReason: getStringError(rangeToExtract.errors) }] + }); + } + if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { + errors.push({ + name: refactorName11, + description: extractConstantAction.description, + actions: [{ ...extractConstantAction, notApplicableReason: getStringError(rangeToExtract.errors) }] + }); + } + return errors; + } + const extractions = getPossibleExtractions(targetRange, context); + if (extractions === void 0) { + return emptyArray; + } + const functionActions = []; + const usedFunctionNames = /* @__PURE__ */ new Map(); + let innermostErrorFunctionAction; + const constantActions = []; + const usedConstantNames = /* @__PURE__ */ new Map(); + let innermostErrorConstantAction; + let i = 0; + for (const { functionExtraction, constantExtraction } of extractions) { + if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { + const description3 = functionExtraction.description; + if (functionExtraction.errors.length === 0) { + if (!usedFunctionNames.has(description3)) { + usedFunctionNames.set(description3, true); + functionActions.push({ + description: description3, + name: `function_scope_${i}`, + kind: extractFunctionAction.kind + }); + } + } else if (!innermostErrorFunctionAction) { + innermostErrorFunctionAction = { + description: description3, + name: `function_scope_${i}`, + notApplicableReason: getStringError(functionExtraction.errors), + kind: extractFunctionAction.kind + }; + } + } + if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { + const description3 = constantExtraction.description; + if (constantExtraction.errors.length === 0) { + if (!usedConstantNames.has(description3)) { + usedConstantNames.set(description3, true); + constantActions.push({ + description: description3, + name: `constant_scope_${i}`, + kind: extractConstantAction.kind + }); + } + } else if (!innermostErrorConstantAction) { + innermostErrorConstantAction = { + description: description3, + name: `constant_scope_${i}`, + notApplicableReason: getStringError(constantExtraction.errors), + kind: extractConstantAction.kind + }; + } + } + i++; + } + const infos = []; + if (functionActions.length) { + infos.push({ + name: refactorName11, + description: getLocaleSpecificMessage(Diagnostics.Extract_function), + actions: functionActions + }); + } else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorFunctionAction) { + infos.push({ + name: refactorName11, + description: getLocaleSpecificMessage(Diagnostics.Extract_function), + actions: [innermostErrorFunctionAction] + }); + } + if (constantActions.length) { + infos.push({ + name: refactorName11, + description: getLocaleSpecificMessage(Diagnostics.Extract_constant), + actions: constantActions + }); + } else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorConstantAction) { + infos.push({ + name: refactorName11, + description: getLocaleSpecificMessage(Diagnostics.Extract_constant), + actions: [innermostErrorConstantAction] + }); + } + return infos.length ? infos : emptyArray; + function getStringError(errors) { + let error = errors[0].messageText; + if (typeof error !== "string") { + error = error.messageText; + } + return error; + } +} +function getRefactorEditsToExtractSymbol(context, actionName2) { + const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context)); + const targetRange = rangeToExtract.targetRange; + const parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName2); + if (parsedFunctionIndexMatch) { + const index = +parsedFunctionIndexMatch[1]; + Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index"); + return getFunctionExtractionAtIndex(targetRange, context, index); + } + const parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName2); + if (parsedConstantIndexMatch) { + const index = +parsedConstantIndexMatch[1]; + Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index"); + return getConstantExtractionAtIndex(targetRange, context, index); + } + Debug.fail("Unrecognized action name"); +} +var Messages; +((Messages2) => { + function createMessage(message) { + return { message, code: 0, category: 3 /* Message */, key: message }; + } + Messages2.cannotExtractRange = createMessage("Cannot extract range."); + Messages2.cannotExtractImport = createMessage("Cannot extract import statement."); + Messages2.cannotExtractSuper = createMessage("Cannot extract super call."); + Messages2.cannotExtractJSDoc = createMessage("Cannot extract JSDoc."); + Messages2.cannotExtractEmpty = createMessage("Cannot extract empty range."); + Messages2.expressionExpected = createMessage("expression expected."); + Messages2.uselessConstantType = createMessage("No reason to extract constant of type."); + Messages2.statementOrExpressionExpected = createMessage("Statement or expression expected."); + Messages2.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); + Messages2.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); + Messages2.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); + Messages2.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); + Messages2.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); + Messages2.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); + Messages2.cannotExtractIdentifier = createMessage("Select more than a single identifier."); + Messages2.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); + Messages2.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); + Messages2.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); + Messages2.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); + Messages2.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); + Messages2.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); + Messages2.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); + Messages2.cannotExtractFunctionsContainingThisToMethod = createMessage("Cannot extract functions containing this to method"); +})(Messages || (Messages = {})); +var RangeFacts = /* @__PURE__ */ ((RangeFacts2) => { + RangeFacts2[RangeFacts2["None"] = 0] = "None"; + RangeFacts2[RangeFacts2["HasReturn"] = 1] = "HasReturn"; + RangeFacts2[RangeFacts2["IsGenerator"] = 2] = "IsGenerator"; + RangeFacts2[RangeFacts2["IsAsyncFunction"] = 4] = "IsAsyncFunction"; + RangeFacts2[RangeFacts2["UsesThis"] = 8] = "UsesThis"; + RangeFacts2[RangeFacts2["UsesThisInFunction"] = 16] = "UsesThisInFunction"; + RangeFacts2[RangeFacts2["InStaticRegion"] = 32] = "InStaticRegion"; + return RangeFacts2; +})(RangeFacts || {}); +function getRangeToExtract2(sourceFile, span, invoked = true) { + const { length: length2 } = span; + if (length2 === 0 && !invoked) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractEmpty)] }; + } + const cursorRequest = length2 === 0 && invoked; + const startToken = findFirstNonJsxWhitespaceToken(sourceFile, span.start); + const endToken = findTokenOnLeftOfPosition(sourceFile, textSpanEnd(span)); + const adjustedSpan = startToken && endToken && invoked ? getAdjustedSpanFromNodes(startToken, endToken, sourceFile) : span; + const start2 = cursorRequest ? getExtractableParent(startToken) : getParentNodeInSpan(startToken, sourceFile, adjustedSpan); + const end = cursorRequest ? start2 : getParentNodeInSpan(endToken, sourceFile, adjustedSpan); + let rangeFacts = 0 /* None */; + let thisNode; + if (!start2 || !end) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + } + if (start2.flags & 8388608 /* JSDoc */) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractJSDoc)] }; + } + if (start2.parent !== end.parent) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + } + if (start2 !== end) { + if (!isBlockLike(start2.parent)) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + } + const statements = []; + for (const statement of start2.parent.statements) { + if (statement === start2 || statements.length) { + const errors2 = checkNode(statement); + if (errors2) { + return { errors: errors2 }; + } + statements.push(statement); + } + if (statement === end) { + break; + } + } + if (!statements.length) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + } + return { targetRange: { range: statements, facts: rangeFacts, thisNode } }; + } + if (isReturnStatement(start2) && !start2.expression) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + } + const node = refineNode(start2); + const errors = checkRootNode(node) || checkNode(node); + if (errors) { + return { errors }; + } + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, thisNode } }; + function refineNode(node2) { + if (isReturnStatement(node2)) { + if (node2.expression) { + return node2.expression; + } + } else if (isVariableStatement(node2) || isVariableDeclarationList(node2)) { + const declarations = isVariableStatement(node2) ? node2.declarationList.declarations : node2.declarations; + let numInitializers = 0; + let lastInitializer; + for (const declaration of declarations) { + if (declaration.initializer) { + numInitializers++; + lastInitializer = declaration.initializer; + } + } + if (numInitializers === 1) { + return lastInitializer; + } + } else if (isVariableDeclaration(node2)) { + if (node2.initializer) { + return node2.initializer; + } + } + return node2; + } + function checkRootNode(node2) { + if (isIdentifier(isExpressionStatement(node2) ? node2.expression : node2)) { + return [createDiagnosticForNode(node2, Messages.cannotExtractIdentifier)]; + } + return void 0; + } + function checkForStaticContext(nodeToCheck, containingClass) { + let current = nodeToCheck; + while (current !== containingClass) { + if (current.kind === 171 /* PropertyDeclaration */) { + if (isStatic(current)) { + rangeFacts |= 32 /* InStaticRegion */; + } + break; + } else if (current.kind === 168 /* Parameter */) { + const ctorOrMethod = getContainingFunction(current); + if (ctorOrMethod.kind === 175 /* Constructor */) { + rangeFacts |= 32 /* InStaticRegion */; + } + break; + } else if (current.kind === 173 /* MethodDeclaration */) { + if (isStatic(current)) { + rangeFacts |= 32 /* InStaticRegion */; + } + } + current = current.parent; + } + } + function checkNode(nodeToCheck) { + let PermittedJumps; + ((PermittedJumps2) => { + PermittedJumps2[PermittedJumps2["None"] = 0] = "None"; + PermittedJumps2[PermittedJumps2["Break"] = 1] = "Break"; + PermittedJumps2[PermittedJumps2["Continue"] = 2] = "Continue"; + PermittedJumps2[PermittedJumps2["Return"] = 4] = "Return"; + })(PermittedJumps || (PermittedJumps = {})); + Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (1)"); + Debug.assert(!positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (2)"); + if (!isStatement(nodeToCheck) && !(isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck)) && !isStringLiteralJsxAttribute(nodeToCheck)) { + return [createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)]; + } + if (nodeToCheck.flags & 16777216 /* Ambient */) { + return [createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)]; + } + const containingClass = getContainingClass(nodeToCheck); + if (containingClass) { + checkForStaticContext(nodeToCheck, containingClass); + } + let errors2; + let permittedJumps = 4 /* Return */; + let seenLabels; + visit(nodeToCheck); + if (rangeFacts & 8 /* UsesThis */) { + const container = getThisContainer( + nodeToCheck, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ); + if (container.kind === 261 /* FunctionDeclaration */ || container.kind === 173 /* MethodDeclaration */ && container.parent.kind === 209 /* ObjectLiteralExpression */ || container.kind === 217 /* FunctionExpression */) { + rangeFacts |= 16 /* UsesThisInFunction */; + } + } + return errors2; + function visit(node2) { + if (errors2) { + return true; + } + if (isDeclaration(node2)) { + const declaringNode = node2.kind === 259 /* VariableDeclaration */ ? node2.parent.parent : node2; + if (hasSyntacticModifier(declaringNode, 1 /* Export */)) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity)); + return true; + } + } + switch (node2.kind) { + case 271 /* ImportDeclaration */: + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractImport)); + return true; + case 276 /* ExportAssignment */: + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity)); + return true; + case 108 /* SuperKeyword */: + if (node2.parent.kind === 212 /* CallExpression */) { + const containingClass2 = getContainingClass(node2); + if (containingClass2 === void 0 || containingClass2.pos < span.start || containingClass2.end >= span.start + span.length) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractSuper)); + return true; + } + } else { + rangeFacts |= 8 /* UsesThis */; + thisNode = node2; + } + break; + case 218 /* ArrowFunction */: + forEachChild(node2, function check(n) { + if (isThis(n)) { + rangeFacts |= 8 /* UsesThis */; + thisNode = node2; + } else if (isClassLike(n) || isFunctionLike(n) && !isArrowFunction(n)) { + return false; + } else { + forEachChild(n, check); + } + }); + case 262 /* ClassDeclaration */: + case 261 /* FunctionDeclaration */: + if (isSourceFile(node2.parent) && node2.parent.externalModuleIndicator === void 0) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.functionWillNotBeVisibleInTheNewScope)); + } + case 230 /* ClassExpression */: + case 217 /* FunctionExpression */: + case 173 /* MethodDeclaration */: + case 175 /* Constructor */: + case 176 /* GetAccessor */: + case 177 /* SetAccessor */: + return false; + } + const savedPermittedJumps = permittedJumps; + switch (node2.kind) { + case 244 /* IfStatement */: + permittedJumps &= ~4 /* Return */; + break; + case 257 /* TryStatement */: + permittedJumps = 0 /* None */; + break; + case 240 /* Block */: + if (node2.parent && node2.parent.kind === 257 /* TryStatement */ && node2.parent.finallyBlock === node2) { + permittedJumps = 4 /* Return */; + } + break; + case 296 /* DefaultClause */: + case 295 /* CaseClause */: + permittedJumps |= 1 /* Break */; + break; + default: + if (isIterationStatement( + node2, + /*lookInLabeledStatements*/ + false + )) { + permittedJumps |= 1 /* Break */ | 2 /* Continue */; + } + break; + } + switch (node2.kind) { + case 196 /* ThisType */: + case 110 /* ThisKeyword */: + rangeFacts |= 8 /* UsesThis */; + thisNode = node2; + break; + case 255 /* LabeledStatement */: { + const label = node2.label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + forEachChild(node2, visit); + seenLabels.pop(); + break; + } + case 251 /* BreakStatement */: + case 250 /* ContinueStatement */: { + const label = node2.label; + if (label) { + if (!contains(seenLabels, label.escapedText)) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); + } + } else { + if (!(permittedJumps & (node2.kind === 251 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); + } + } + break; + } + case 222 /* AwaitExpression */: + rangeFacts |= 4 /* IsAsyncFunction */; + break; + case 228 /* YieldExpression */: + rangeFacts |= 2 /* IsGenerator */; + break; + case 252 /* ReturnStatement */: + if (permittedJumps & 4 /* Return */) { + rangeFacts |= 1 /* HasReturn */; + } else { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalReturnStatement)); + } + break; + default: + forEachChild(node2, visit); + break; + } + permittedJumps = savedPermittedJumps; + } + } +} +function getAdjustedSpanFromNodes(startNode2, endNode2, sourceFile) { + const start2 = startNode2.getStart(sourceFile); + let end = endNode2.getEnd(); + if (sourceFile.text.charCodeAt(end) === 59 /* semicolon */) { + end++; + } + return { start: start2, length: end - start2 }; +} +function getStatementOrExpressionRange(node) { + if (isStatement(node)) { + return [node]; + } + if (isExpressionNode(node)) { + return isExpressionStatement(node.parent) ? [node.parent] : node; + } + if (isStringLiteralJsxAttribute(node)) { + return node; + } + return void 0; +} +function isScope(node) { + return isArrowFunction(node) ? isFunctionBody(node.body) : isFunctionLikeDeclaration(node) || isSourceFile(node) || isModuleBlock(node) || isClassLike(node); +} +function collectEnclosingScopes(range) { + let current = isReadonlyArray(range.range) ? first(range.range) : range.range; + if (range.facts & 8 /* UsesThis */ && !(range.facts & 16 /* UsesThisInFunction */)) { + const containingClass = getContainingClass(current); + if (containingClass) { + const containingFunction = findAncestor(current, isFunctionLikeDeclaration); + return containingFunction ? [containingFunction, containingClass] : [containingClass]; + } + } + const scopes = []; + while (true) { + current = current.parent; + if (current.kind === 168 /* Parameter */) { + current = findAncestor(current, (parent2) => isFunctionLikeDeclaration(parent2)).parent; + } + if (isScope(current)) { + scopes.push(current); + if (current.kind === 311 /* SourceFile */) { + return scopes; + } + } + } +} +function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { + const { scopes, readsAndWrites: { target, usagesPerScope, functionErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); + Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + context.cancellationToken.throwIfCancellationRequested(); + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); +} +function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { + const { scopes, readsAndWrites: { target, usagesPerScope, constantErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); + Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); + context.cancellationToken.throwIfCancellationRequested(); + const expression = isExpression(target) ? target : target.statements[0].expression; + return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context); +} +function getPossibleExtractions(targetRange, context) { + const { scopes, readsAndWrites: { functionErrorsPerScope, constantErrorsPerScope } } = getPossibleExtractionsWorker(targetRange, context); + const extractions = scopes.map((scope, i) => { + const functionDescriptionPart = getDescriptionForFunctionInScope(scope); + const constantDescriptionPart = getDescriptionForConstantInScope(scope); + const scopeDescription = isFunctionLikeDeclaration(scope) ? getDescriptionForFunctionLikeDeclaration(scope) : isClassLike(scope) ? getDescriptionForClassLikeDeclaration(scope) : getDescriptionForModuleLikeDeclaration(scope); + let functionDescription; + let constantDescription; + if (scopeDescription === 1 /* Global */) { + functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]); + constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]); + } else if (scopeDescription === 0 /* Module */) { + functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]); + constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]); + } else { + functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]); + constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]); + } + if (i === 0 && !isClassLike(scope)) { + constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]); + } + return { + functionExtraction: { + description: functionDescription, + errors: functionErrorsPerScope[i] + }, + constantExtraction: { + description: constantDescription, + errors: constantErrorsPerScope[i] + } + }; + }); + return extractions; +} +function getPossibleExtractionsWorker(targetRange, context) { + const { file: sourceFile } = context; + const scopes = collectEnclosingScopes(targetRange); + const enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); + const readsAndWrites = collectReadsAndWrites( + targetRange, + scopes, + enclosingTextRange, + sourceFile, + context.program.getTypeChecker(), + context.cancellationToken + ); + return { scopes, readsAndWrites }; +} +function getDescriptionForFunctionInScope(scope) { + return isFunctionLikeDeclaration(scope) ? "inner function" : isClassLike(scope) ? "method" : "function"; +} +function getDescriptionForConstantInScope(scope) { + return isClassLike(scope) ? "readonly field" : "constant"; +} +function getDescriptionForFunctionLikeDeclaration(scope) { + switch (scope.kind) { + case 175 /* Constructor */: + return "constructor"; + case 217 /* FunctionExpression */: + case 261 /* FunctionDeclaration */: + return scope.name ? `function '${scope.name.text}'` : ANONYMOUS; + case 218 /* ArrowFunction */: + return "arrow function"; + case 173 /* MethodDeclaration */: + return `method '${scope.name.getText()}'`; + case 176 /* GetAccessor */: + return `'get ${scope.name.getText()}'`; + case 177 /* SetAccessor */: + return `'set ${scope.name.getText()}'`; + default: + Debug.assertNever(scope, `Unexpected scope kind ${scope.kind}`); + } +} +function getDescriptionForClassLikeDeclaration(scope) { + return scope.kind === 262 /* ClassDeclaration */ ? scope.name ? `class '${scope.name.text}'` : "anonymous class declaration" : scope.name ? `class expression '${scope.name.text}'` : "anonymous class expression"; +} +function getDescriptionForModuleLikeDeclaration(scope) { + return scope.kind === 267 /* ModuleBlock */ ? `namespace '${scope.parent.name.getText()}'` : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; +} +function extractFunctionInScope(node, scope, { usages: usagesInScope, typeParameterUsages, substitutions }, exposedVariableDeclarations, range, context) { + const checker = context.program.getTypeChecker(); + const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); + const importAdder = ts_codefix_exports.createImportAdder(context.file, context.program, context.preferences, context.host); + const file = scope.getSourceFile(); + const functionNameText = getUniqueName(isClassLike(scope) ? "newMethod" : "newFunction", file); + const isJS = isInJSFile(scope); + const functionName = factory.createIdentifier(functionNameText); + let returnType; + const parameters = []; + const callArguments = []; + let writes; + usagesInScope.forEach((usage, name) => { + let typeNode; + if (!isJS) { + let type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); + type = checker.getBaseTypeOfLiteralType(type); + typeNode = ts_codefix_exports.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */); + } + const paramDecl = factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + /*name*/ + name, + /*questionToken*/ + void 0, + typeNode + ); + parameters.push(paramDecl); + if (usage.usage === 2 /* Write */) { + (writes || (writes = [])).push(usage); + } + callArguments.push(factory.createIdentifier(name)); + }); + const typeParametersAndDeclarations = arrayFrom(typeParameterUsages.values(), (type) => ({ type, declaration: getFirstDeclarationBeforePosition(type, context.startPosition) })); + const sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); + const typeParameters = sortedTypeParametersAndDeclarations.length === 0 ? void 0 : mapDefined(sortedTypeParametersAndDeclarations, ({ declaration }) => declaration); + const callTypeArguments = typeParameters !== void 0 ? typeParameters.map((decl) => factory.createTypeReferenceNode( + decl.name, + /*typeArguments*/ + void 0 + )) : void 0; + if (isExpression(node) && !isJS) { + const contextualType = checker.getContextualType(node); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); + } + const { body, returnValueProperty } = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & 1 /* HasReturn */)); + suppressLeadingAndTrailingTrivia(body); + let newFunction; + const callThis = !!(range.facts & 16 /* UsesThisInFunction */); + if (isClassLike(scope)) { + const modifiers = isJS ? [] : [factory.createModifier(123 /* PrivateKeyword */)]; + if (range.facts & 32 /* InStaticRegion */) { + modifiers.push(factory.createModifier(126 /* StaticKeyword */)); + } + if (range.facts & 4 /* IsAsyncFunction */) { + modifiers.push(factory.createModifier(134 /* AsyncKeyword */)); + } + newFunction = factory.createMethodDeclaration( + modifiers.length ? modifiers : void 0, + range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0, + functionName, + /*questionToken*/ + void 0, + typeParameters, + parameters, + returnType, + body + ); + } else { + if (callThis) { + parameters.unshift( + factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + /*name*/ + "this", + /*questionToken*/ + void 0, + checker.typeToTypeNode( + checker.getTypeAtLocation(range.thisNode), + scope, + 1 /* NoTruncation */ + ), + /*initializer*/ + void 0 + ) + ); + } + newFunction = factory.createFunctionDeclaration( + range.facts & 4 /* IsAsyncFunction */ ? [factory.createToken(134 /* AsyncKeyword */)] : void 0, + range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0, + functionName, + typeParameters, + parameters, + returnType, + body + ); + } + const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); + const minInsertionPos = (isReadonlyArray(range.range) ? last(range.range) : range.range).end; + const nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); + if (nodeToInsertBefore) { + changeTracker.insertNodeBefore( + context.file, + nodeToInsertBefore, + newFunction, + /*blankLineBetween*/ + true + ); + } else { + changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); + } + importAdder.writeFixes(changeTracker); + const newNodes = []; + const called = getCalledExpression(scope, range, functionNameText); + if (callThis) { + callArguments.unshift(factory.createIdentifier("this")); + } + let call = factory.createCallExpression( + callThis ? factory.createPropertyAccessExpression( + called, + "call" + ) : called, + callTypeArguments, + // Note that no attempt is made to take advantage of type argument inference + callArguments + ); + if (range.facts & 2 /* IsGenerator */) { + call = factory.createYieldExpression(factory.createToken(42 /* AsteriskToken */), call); + } + if (range.facts & 4 /* IsAsyncFunction */) { + call = factory.createAwaitExpression(call); + } + if (isInJSXContent(node)) { + call = factory.createJsxExpression( + /*dotDotDotToken*/ + void 0, + call + ); + } + if (exposedVariableDeclarations.length && !writes) { + Debug.assert(!returnValueProperty, "Expected no returnValueProperty"); + Debug.assert(!(range.facts & 1 /* HasReturn */), "Expected RangeFacts.HasReturn flag to be unset"); + if (exposedVariableDeclarations.length === 1) { + const variableDeclaration = exposedVariableDeclarations[0]; + newNodes.push(factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + getSynthesizedDeepClone(variableDeclaration.name), + /*exclamationToken*/ + void 0, + /*type*/ + getSynthesizedDeepClone(variableDeclaration.type), + /*initializer*/ + call + )], + variableDeclaration.parent.flags + ) + )); + } else { + const bindingElements = []; + const typeElements = []; + let commonNodeFlags = exposedVariableDeclarations[0].parent.flags; + let sawExplicitType = false; + for (const variableDeclaration of exposedVariableDeclarations) { + bindingElements.push(factory.createBindingElement( + /*dotDotDotToken*/ + void 0, + /*propertyName*/ + void 0, + /*name*/ + getSynthesizedDeepClone(variableDeclaration.name) + )); + const variableType = checker.typeToTypeNode( + checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), + scope, + 1 /* NoTruncation */ + ); + typeElements.push(factory.createPropertySignature( + /*modifiers*/ + void 0, + /*name*/ + variableDeclaration.symbol.name, + /*questionToken*/ + void 0, + /*type*/ + variableType + )); + sawExplicitType = sawExplicitType || variableDeclaration.type !== void 0; + commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; + } + const typeLiteral = sawExplicitType ? factory.createTypeLiteralNode(typeElements) : void 0; + if (typeLiteral) { + setEmitFlags(typeLiteral, 1 /* SingleLine */); + } + newNodes.push(factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + factory.createObjectBindingPattern(bindingElements), + /*exclamationToken*/ + void 0, + /*type*/ + typeLiteral, + /*initializer*/ + call + )], + commonNodeFlags + ) + )); + } + } else if (exposedVariableDeclarations.length || writes) { + if (exposedVariableDeclarations.length) { + for (const variableDeclaration of exposedVariableDeclarations) { + let flags = variableDeclaration.parent.flags; + if (flags & 2 /* Const */) { + flags = flags & ~2 /* Const */ | 1 /* Let */; + } + newNodes.push(factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + variableDeclaration.symbol.name, + /*exclamationToken*/ + void 0, + getTypeDeepCloneUnionUndefined(variableDeclaration.type) + )], + flags + ) + )); + } + } + if (returnValueProperty) { + newNodes.push(factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + returnValueProperty, + /*exclamationToken*/ + void 0, + getTypeDeepCloneUnionUndefined(returnType) + )], + 1 /* Let */ + ) + )); + } + const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (returnValueProperty) { + assignments.unshift(factory.createShorthandPropertyAssignment(returnValueProperty)); + } + if (assignments.length === 1) { + Debug.assert(!returnValueProperty, "Shouldn't have returnValueProperty here"); + newNodes.push(factory.createExpressionStatement(factory.createAssignment(assignments[0].name, call))); + if (range.facts & 1 /* HasReturn */) { + newNodes.push(factory.createReturnStatement()); + } + } else { + newNodes.push(factory.createExpressionStatement(factory.createAssignment(factory.createObjectLiteralExpression(assignments), call))); + if (returnValueProperty) { + newNodes.push(factory.createReturnStatement(factory.createIdentifier(returnValueProperty))); + } + } + } else { + if (range.facts & 1 /* HasReturn */) { + newNodes.push(factory.createReturnStatement(call)); + } else if (isReadonlyArray(range.range)) { + newNodes.push(factory.createExpressionStatement(call)); + } else { + newNodes.push(call); + } + } + if (isReadonlyArray(range.range)) { + changeTracker.replaceNodeRangeWithNodes(context.file, first(range.range), last(range.range), newNodes); + } else { + changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes); + } + const edits = changeTracker.getChanges(); + const renameRange = isReadonlyArray(range.range) ? first(range.range) : range.range; + const renameFilename = renameRange.getSourceFile().fileName; + const renameLocation = getRenameLocation( + edits, + renameFilename, + functionNameText, + /*preferLastLocation*/ + false + ); + return { renameFilename, renameLocation, edits }; + function getTypeDeepCloneUnionUndefined(typeNode) { + if (typeNode === void 0) { + return void 0; + } + const clone2 = getSynthesizedDeepClone(typeNode); + let withoutParens = clone2; + while (isParenthesizedTypeNode(withoutParens)) { + withoutParens = withoutParens.type; + } + return isUnionTypeNode(withoutParens) && find(withoutParens.types, (t) => t.kind === 157 /* UndefinedKeyword */) ? clone2 : factory.createUnionTypeNode([clone2, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); + } +} +function extractConstantInScope(node, scope, { substitutions }, rangeFacts, context) { + const checker = context.program.getTypeChecker(); + const file = scope.getSourceFile(); + const localNameText = isPropertyAccessExpression(node) && !isClassLike(scope) && !checker.resolveName( + node.name.text, + node, + 111551 /* Value */, + /*excludeGlobals*/ + false + ) && !isPrivateIdentifier(node.name) && !identifierToKeywordKind(node.name) ? node.name.text : getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file); + const isJS = isInJSFile(scope); + let variableType = isJS || !checker.isContextSensitive(node) ? void 0 : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); + let initializer = transformConstantInitializer(skipParentheses(node), substitutions); + ({ variableType, initializer } = transformFunctionInitializerAndType(variableType, initializer)); + suppressLeadingAndTrailingTrivia(initializer); + const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); + if (isClassLike(scope)) { + Debug.assert(!isJS, "Cannot extract to a JS class"); + const modifiers = []; + modifiers.push(factory.createModifier(123 /* PrivateKeyword */)); + if (rangeFacts & 32 /* InStaticRegion */) { + modifiers.push(factory.createModifier(126 /* StaticKeyword */)); + } + modifiers.push(factory.createModifier(148 /* ReadonlyKeyword */)); + const newVariable = factory.createPropertyDeclaration( + modifiers, + localNameText, + /*questionOrExclamationToken*/ + void 0, + variableType, + initializer + ); + let localReference = factory.createPropertyAccessExpression( + rangeFacts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.getText()) : factory.createThis(), + factory.createIdentifier(localNameText) + ); + if (isInJSXContent(node)) { + localReference = factory.createJsxExpression( + /*dotDotDotToken*/ + void 0, + localReference + ); + } + const maxInsertionPos = node.pos; + const nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); + changeTracker.insertNodeBefore( + context.file, + nodeToInsertBefore, + newVariable, + /*blankLineBetween*/ + true + ); + changeTracker.replaceNode(context.file, node, localReference); + } else { + const newVariableDeclaration = factory.createVariableDeclaration( + localNameText, + /*exclamationToken*/ + void 0, + variableType, + initializer + ); + const oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); + if (oldVariableDeclaration) { + changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); + const localReference = factory.createIdentifier(localNameText); + changeTracker.replaceNode(context.file, node, localReference); + } else if (node.parent.kind === 243 /* ExpressionStatement */ && scope === findAncestor(node, isScope)) { + const newVariableStatement = factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */) + ); + changeTracker.replaceNode(context.file, node.parent, newVariableStatement); + } else { + const newVariableStatement = factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */) + ); + const nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); + if (nodeToInsertBefore.pos === 0) { + changeTracker.insertNodeAtTopOfFile( + context.file, + newVariableStatement, + /*blankLineBetween*/ + false + ); + } else { + changeTracker.insertNodeBefore( + context.file, + nodeToInsertBefore, + newVariableStatement, + /*blankLineBetween*/ + false + ); + } + if (node.parent.kind === 243 /* ExpressionStatement */) { + changeTracker.delete(context.file, node.parent); + } else { + let localReference = factory.createIdentifier(localNameText); + if (isInJSXContent(node)) { + localReference = factory.createJsxExpression( + /*dotDotDotToken*/ + void 0, + localReference + ); + } + changeTracker.replaceNode(context.file, node, localReference); + } + } + } + const edits = changeTracker.getChanges(); + const renameFilename = node.getSourceFile().fileName; + const renameLocation = getRenameLocation( + edits, + renameFilename, + localNameText, + /*preferLastLocation*/ + true + ); + return { renameFilename, renameLocation, edits }; + function transformFunctionInitializerAndType(variableType2, initializer2) { + if (variableType2 === void 0) + return { variableType: variableType2, initializer: initializer2 }; + if (!isFunctionExpression(initializer2) && !isArrowFunction(initializer2) || !!initializer2.typeParameters) + return { variableType: variableType2, initializer: initializer2 }; + const functionType = checker.getTypeAtLocation(node); + const functionSignature = singleOrUndefined(checker.getSignaturesOfType(functionType, 0 /* Call */)); + if (!functionSignature) + return { variableType: variableType2, initializer: initializer2 }; + if (!!functionSignature.getTypeParameters()) + return { variableType: variableType2, initializer: initializer2 }; + const parameters = []; + let hasAny = false; + for (const p of initializer2.parameters) { + if (p.type) { + parameters.push(p); + } else { + 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, 1 /* NoTruncation */), + p.initializer + )); + } + } + if (hasAny) + return { variableType: variableType2, initializer: initializer2 }; + variableType2 = void 0; + if (isArrowFunction(initializer2)) { + initializer2 = factory.updateArrowFunction( + initializer2, + canHaveModifiers(node) ? getModifiers(node) : void 0, + initializer2.typeParameters, + parameters, + initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), + initializer2.equalsGreaterThanToken, + initializer2.body + ); + } else { + if (functionSignature && !!functionSignature.thisParameter) { + const firstParameter = firstOrUndefined(parameters); + if (!firstParameter || isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this") { + const thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node); + parameters.splice(0, 0, factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "this", + /*questionToken*/ + void 0, + checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */) + )); + } + } + initializer2 = factory.updateFunctionExpression( + initializer2, + canHaveModifiers(node) ? getModifiers(node) : void 0, + initializer2.asteriskToken, + initializer2.name, + initializer2.typeParameters, + parameters, + initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), + initializer2.body + ); + } + return { variableType: variableType2, initializer: initializer2 }; + } +} +function getContainingVariableDeclarationIfInList(node, scope) { + let prevNode; + while (node !== void 0 && node !== scope) { + if (isVariableDeclaration(node) && node.initializer === prevNode && isVariableDeclarationList(node.parent) && node.parent.declarations.length > 1) { + return node; + } + prevNode = node; + node = node.parent; + } +} +function getFirstDeclarationBeforePosition(type, position) { + let firstDeclaration; + const symbol = type.symbol; + if (symbol && symbol.declarations) { + for (const declaration of symbol.declarations) { + if ((firstDeclaration === void 0 || declaration.pos < firstDeclaration.pos) && declaration.pos < position) { + firstDeclaration = declaration; + } + } + } + return firstDeclaration; +} +function compareTypesByDeclarationOrder({ type: type1, declaration: declaration1 }, { type: type2, declaration: declaration2 }) { + return compareProperties(declaration1, declaration2, "pos", compareValues) || compareStringsCaseSensitive( + type1.symbol ? type1.symbol.getName() : "", + type2.symbol ? type2.symbol.getName() : "" + ) || compareValues(type1.id, type2.id); +} +function getCalledExpression(scope, range, functionNameText) { + const functionReference = factory.createIdentifier(functionNameText); + if (isClassLike(scope)) { + const lhs = range.facts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.text) : factory.createThis(); + return factory.createPropertyAccessExpression(lhs, functionReference); + } else { + return functionReference; + } +} +function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn2) { + const hasWritesOrVariableDeclarations = writes !== void 0 || exposedVariableDeclarations.length > 0; + if (isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { + return { body: factory.createBlock( + body.statements, + /*multiLine*/ + true + ), returnValueProperty: void 0 }; + } + let returnValueProperty; + let ignoreReturns = false; + const statements = factory.createNodeArray(isBlock(body) ? body.statements.slice(0) : [isStatement(body) ? body : factory.createReturnStatement(skipParentheses(body))]); + if (hasWritesOrVariableDeclarations || substitutions.size) { + const rewrittenStatements = visitNodes2(statements, visitor, isStatement).slice(); + if (hasWritesOrVariableDeclarations && !hasReturn2 && isStatement(body)) { + const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (assignments.length === 1) { + rewrittenStatements.push(factory.createReturnStatement(assignments[0].name)); + } else { + rewrittenStatements.push(factory.createReturnStatement(factory.createObjectLiteralExpression(assignments))); + } + } + return { body: factory.createBlock( + rewrittenStatements, + /*multiLine*/ + true + ), returnValueProperty }; + } else { + return { body: factory.createBlock( + statements, + /*multiLine*/ + true + ), returnValueProperty: void 0 }; + } + function visitor(node) { + if (!ignoreReturns && isReturnStatement(node) && hasWritesOrVariableDeclarations) { + const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (node.expression) { + if (!returnValueProperty) { + returnValueProperty = "__return"; + } + assignments.unshift(factory.createPropertyAssignment(returnValueProperty, visitNode(node.expression, visitor, isExpression))); + } + if (assignments.length === 1) { + return factory.createReturnStatement(assignments[0].name); + } else { + return factory.createReturnStatement(factory.createObjectLiteralExpression(assignments)); + } + } else { + const oldIgnoreReturns = ignoreReturns; + ignoreReturns = ignoreReturns || isFunctionLikeDeclaration(node) || isClassLike(node); + const substitution = substitutions.get(getNodeId(node).toString()); + const result = substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext); + ignoreReturns = oldIgnoreReturns; + return result; + } + } +} +function transformConstantInitializer(initializer, substitutions) { + return substitutions.size ? visitor(initializer) : initializer; + function visitor(node) { + const substitution = substitutions.get(getNodeId(node).toString()); + return substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext); + } +} +function getStatementsOrClassElements(scope) { + if (isFunctionLikeDeclaration(scope)) { + const body = scope.body; + if (isBlock(body)) { + return body.statements; + } + } else if (isModuleBlock(scope) || isSourceFile(scope)) { + return scope.statements; + } else if (isClassLike(scope)) { + return scope.members; + } else { + assertType(scope); + } + return emptyArray; +} +function getNodeToInsertFunctionBefore(minPos, scope) { + return find(getStatementsOrClassElements(scope), (child) => child.pos >= minPos && isFunctionLikeDeclaration(child) && !isConstructorDeclaration(child)); +} +function getNodeToInsertPropertyBefore(maxPos, scope) { + const members = scope.members; + Debug.assert(members.length > 0, "Found no members"); + let prevMember; + let allProperties = true; + for (const member of members) { + if (member.pos > maxPos) { + return prevMember || members[0]; + } + if (allProperties && !isPropertyDeclaration(member)) { + if (prevMember !== void 0) { + return member; + } + allProperties = false; + } + prevMember = member; + } + if (prevMember === void 0) + return Debug.fail(); + return prevMember; +} +function getNodeToInsertConstantBefore(node, scope) { + Debug.assert(!isClassLike(scope)); + let prevScope; + for (let curr = node; curr !== scope; curr = curr.parent) { + if (isScope(curr)) { + prevScope = curr; + } + } + for (let curr = (prevScope || node).parent; ; curr = curr.parent) { + if (isBlockLike(curr)) { + let prevStatement; + for (const statement of curr.statements) { + if (statement.pos > node.pos) { + break; + } + prevStatement = statement; + } + if (!prevStatement && isCaseClause(curr)) { + Debug.assert(isSwitchStatement(curr.parent.parent), "Grandparent isn't a switch statement"); + return curr.parent.parent; + } + return Debug.checkDefined(prevStatement, "prevStatement failed to get set"); + } + Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); + } +} +function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { + const variableAssignments = map(exposedVariableDeclarations, (v) => factory.createShorthandPropertyAssignment(v.symbol.name)); + const writeAssignments = map(writes, (w) => factory.createShorthandPropertyAssignment(w.symbol.name)); + return variableAssignments === void 0 ? writeAssignments : writeAssignments === void 0 ? variableAssignments : variableAssignments.concat(writeAssignments); +} +function isReadonlyArray(v) { + return isArray(v); +} +function getEnclosingTextRange(targetRange, sourceFile) { + return isReadonlyArray(targetRange.range) ? { pos: first(targetRange.range).getStart(sourceFile), end: last(targetRange.range).getEnd() } : targetRange.range; +} +function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { + const allTypeParameterUsages = /* @__PURE__ */ new Map(); + const usagesPerScope = []; + const substitutionsPerScope = []; + const functionErrorsPerScope = []; + const constantErrorsPerScope = []; + const visibleDeclarationsInExtractedRange = []; + const exposedVariableSymbolSet = /* @__PURE__ */ new Map(); + const exposedVariableDeclarations = []; + let firstExposedNonVariableDeclaration; + const expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && isExpressionStatement(targetRange.range[0]) ? targetRange.range[0].expression : void 0; + let expressionDiagnostic; + if (expression === void 0) { + const statements = targetRange.range; + const start2 = first(statements).getStart(); + const end = last(statements).end; + expressionDiagnostic = createFileDiagnostic(sourceFile, start2, end - start2, Messages.expressionExpected); + } else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) { + expressionDiagnostic = createDiagnosticForNode(expression, Messages.uselessConstantType); + } + for (const scope of scopes) { + usagesPerScope.push({ usages: /* @__PURE__ */ new Map(), typeParameterUsages: /* @__PURE__ */ new Map(), substitutions: /* @__PURE__ */ new Map() }); + substitutionsPerScope.push(/* @__PURE__ */ new Map()); + functionErrorsPerScope.push([]); + const constantErrors = []; + if (expressionDiagnostic) { + constantErrors.push(expressionDiagnostic); + } + if (isClassLike(scope) && isInJSFile(scope)) { + constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); + } + if (isArrowFunction(scope) && !isBlock(scope.body)) { + constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction)); + } + constantErrorsPerScope.push(constantErrors); + } + const seenUsages = /* @__PURE__ */ new Map(); + const target = isReadonlyArray(targetRange.range) ? factory.createBlock(targetRange.range) : targetRange.range; + const unmodifiedNode = isReadonlyArray(targetRange.range) ? first(targetRange.range) : targetRange.range; + const inGenericContext = isInGenericContext(unmodifiedNode); + collectUsages(target); + if (inGenericContext && !isReadonlyArray(targetRange.range) && !isJsxAttribute(targetRange.range)) { + const contextualType = checker.getContextualType(targetRange.range); + recordTypeParameterUsages(contextualType); + } + if (allTypeParameterUsages.size > 0) { + const seenTypeParameterUsages = /* @__PURE__ */ new Map(); + let i = 0; + for (let curr = unmodifiedNode; curr !== void 0 && i < scopes.length; curr = curr.parent) { + if (curr === scopes[i]) { + seenTypeParameterUsages.forEach((typeParameter, id) => { + usagesPerScope[i].typeParameterUsages.set(id, typeParameter); + }); + i++; + } + if (isDeclarationWithTypeParameters(curr)) { + for (const typeParameterDecl of getEffectiveTypeParameterDeclarations(curr)) { + const typeParameter = checker.getTypeAtLocation(typeParameterDecl); + if (allTypeParameterUsages.has(typeParameter.id.toString())) { + seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter); + } + } + } + } + Debug.assert(i === scopes.length, "Should have iterated all scopes"); + } + if (visibleDeclarationsInExtractedRange.length) { + const containingLexicalScopeOfExtraction = isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : getEnclosingBlockScopeContainer(scopes[0]); + forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } + for (let i = 0; i < scopes.length; i++) { + const scopeUsages = usagesPerScope[i]; + if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { + const errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + constantErrorsPerScope[i].push(createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); + } + if (targetRange.facts & 16 /* UsesThisInFunction */ && isClassLike(scopes[i])) { + functionErrorsPerScope[i].push(createDiagnosticForNode(targetRange.thisNode, Messages.cannotExtractFunctionsContainingThisToMethod)); + } + let hasWrite = false; + let readonlyClassPropertyWrite; + usagesPerScope[i].usages.forEach((value) => { + if (value.usage === 2 /* Write */) { + hasWrite = true; + if (value.symbol.flags & 106500 /* ClassMember */ && value.symbol.valueDeclaration && hasEffectiveModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) { + readonlyClassPropertyWrite = value.symbol.valueDeclaration; + } + } + }); + Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0, "No variable declarations expected if something was extracted"); + if (hasWrite && !isReadonlyArray(targetRange.range)) { + const diag2 = createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression); + functionErrorsPerScope[i].push(diag2); + constantErrorsPerScope[i].push(diag2); + } else if (readonlyClassPropertyWrite && i > 0) { + const diag2 = createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor); + functionErrorsPerScope[i].push(diag2); + constantErrorsPerScope[i].push(diag2); + } else if (firstExposedNonVariableDeclaration) { + const diag2 = createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity); + functionErrorsPerScope[i].push(diag2); + constantErrorsPerScope[i].push(diag2); + } + } + return { target, usagesPerScope, functionErrorsPerScope, constantErrorsPerScope, exposedVariableDeclarations }; + function isInGenericContext(node) { + return !!findAncestor(node, (n) => isDeclarationWithTypeParameters(n) && getEffectiveTypeParameterDeclarations(n).length !== 0); + } + function recordTypeParameterUsages(type) { + const symbolWalker = checker.getSymbolWalker(() => (cancellationToken.throwIfCancellationRequested(), true)); + const { visitedTypes } = symbolWalker.walkType(type); + for (const visitedType of visitedTypes) { + if (visitedType.isTypeParameter()) { + allTypeParameterUsages.set(visitedType.id.toString(), visitedType); + } + } + } + function collectUsages(node, valueUsage = 1 /* Read */) { + if (inGenericContext) { + const type = checker.getTypeAtLocation(node); + recordTypeParameterUsages(type); + } + if (isDeclaration(node) && node.symbol) { + visibleDeclarationsInExtractedRange.push(node); + } + if (isAssignmentExpression(node)) { + collectUsages(node.left, 2 /* Write */); + collectUsages(node.right); + } else if (isUnaryExpressionWithWrite(node)) { + collectUsages(node.operand, 2 /* Write */); + } else if (isPropertyAccessExpression(node) || isElementAccessExpression(node)) { + forEachChild(node, collectUsages); + } else if (isIdentifier(node)) { + if (!node.parent) { + return; + } + if (isQualifiedName(node.parent) && node !== node.parent.left) { + return; + } + if (isPropertyAccessExpression(node.parent) && node !== node.parent.expression) { + return; + } + recordUsage( + node, + valueUsage, + /*isTypeNode*/ + isPartOfTypeNode(node) + ); + } else { + forEachChild(node, collectUsages); + } + } + function recordUsage(n, usage, isTypeNode2) { + const symbolId = recordUsagebySymbol(n, usage, isTypeNode2); + if (symbolId) { + for (let i = 0; i < scopes.length; i++) { + const substitution = substitutionsPerScope[i].get(symbolId); + if (substitution) { + usagesPerScope[i].substitutions.set(getNodeId(n).toString(), substitution); + } + } + } + } + function recordUsagebySymbol(identifier, usage, isTypeName) { + const symbol = getSymbolReferencedByIdentifier(identifier); + if (!symbol) { + return void 0; + } + const symbolId = getSymbolId(symbol).toString(); + const lastUsage = seenUsages.get(symbolId); + if (lastUsage && lastUsage >= usage) { + return symbolId; + } + seenUsages.set(symbolId, usage); + if (lastUsage) { + for (const perScope of usagesPerScope) { + const prevEntry = perScope.usages.get(identifier.text); + if (prevEntry) { + perScope.usages.set(identifier.text, { usage, symbol, node: identifier }); + } + } + return symbolId; + } + const decls = symbol.getDeclarations(); + const declInFile = decls && find(decls, (d) => d.getSourceFile() === sourceFile); + if (!declInFile) { + return void 0; + } + if (rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) { + return void 0; + } + if (targetRange.facts & 2 /* IsGenerator */ && usage === 2 /* Write */) { + const diag2 = createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators); + for (const errors of functionErrorsPerScope) { + errors.push(diag2); + } + for (const errors of constantErrorsPerScope) { + errors.push(diag2); + } + } + for (let i = 0; i < scopes.length; i++) { + const scope = scopes[i]; + const resolvedSymbol = checker.resolveName( + symbol.name, + scope, + symbol.flags, + /*excludeGlobals*/ + false + ); + if (resolvedSymbol === symbol) { + continue; + } + if (!substitutionsPerScope[i].has(symbolId)) { + const substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName); + if (substitution) { + substitutionsPerScope[i].set(symbolId, substitution); + } else if (isTypeName) { + if (!(symbol.flags & 262144 /* TypeParameter */)) { + const diag2 = createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope); + functionErrorsPerScope[i].push(diag2); + constantErrorsPerScope[i].push(diag2); + } + } else { + usagesPerScope[i].usages.set(identifier.text, { usage, symbol, node: identifier }); + } + } + } + return symbolId; + } + function checkForUsedDeclarations(node) { + if (node === targetRange.range || isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0) { + return; + } + const sym = isIdentifier(node) ? getSymbolReferencedByIdentifier(node) : checker.getSymbolAtLocation(node); + if (sym) { + const decl = find(visibleDeclarationsInExtractedRange, (d) => d.symbol === sym); + if (decl) { + if (isVariableDeclaration(decl)) { + const idString = decl.symbol.id.toString(); + if (!exposedVariableSymbolSet.has(idString)) { + exposedVariableDeclarations.push(decl); + exposedVariableSymbolSet.set(idString, true); + } + } else { + firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; + } + } + } + forEachChild(node, checkForUsedDeclarations); + } + function getSymbolReferencedByIdentifier(identifier) { + return identifier.parent && isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier ? checker.getShorthandAssignmentValueSymbol(identifier.parent) : checker.getSymbolAtLocation(identifier); + } + function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode2) { + if (!symbol) { + return void 0; + } + const decls = symbol.getDeclarations(); + if (decls && decls.some((d) => d.parent === scopeDecl)) { + return factory.createIdentifier(symbol.name); + } + const prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode2); + if (prefix === void 0) { + return void 0; + } + return isTypeNode2 ? factory.createQualifiedName(prefix, factory.createIdentifier(symbol.name)) : factory.createPropertyAccessExpression(prefix, symbol.name); + } +} +function getExtractableParent(node) { + return findAncestor(node, (node2) => node2.parent && isExtractableExpression(node2) && !isBinaryExpression(node2.parent)); +} +function isExtractableExpression(node) { + const { parent: parent2 } = node; + switch (parent2.kind) { + case 305 /* EnumMember */: + return false; + } + switch (node.kind) { + case 11 /* StringLiteral */: + return parent2.kind !== 271 /* ImportDeclaration */ && parent2.kind !== 275 /* ImportSpecifier */; + case 229 /* SpreadElement */: + case 205 /* ObjectBindingPattern */: + case 207 /* BindingElement */: + return false; + case 80 /* Identifier */: + return parent2.kind !== 207 /* BindingElement */ && parent2.kind !== 275 /* ImportSpecifier */ && parent2.kind !== 280 /* ExportSpecifier */; + } + return true; +} +function isBlockLike(node) { + switch (node.kind) { + case 240 /* Block */: + case 311 /* SourceFile */: + case 267 /* ModuleBlock */: + case 295 /* CaseClause */: + return true; + default: + return false; + } +} +function isInJSXContent(node) { + return isStringLiteralJsxAttribute(node) || (isJsxElement(node) || isJsxSelfClosingElement(node) || isJsxFragment(node)) && (isJsxElement(node.parent) || isJsxFragment(node.parent)); +} +function isStringLiteralJsxAttribute(node) { + return isStringLiteral(node) && node.parent && isJsxAttribute(node.parent); +} + +// src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts +var ts_refactor_generateGetAccessorAndSetAccessor_exports = {}; + +// src/services/refactors/generateGetAccessorAndSetAccessor.ts +var actionName = "Generate 'get' and 'set' accessors"; +var actionDescription = Diagnostics.Generate_get_and_set_accessors.message; +var generateGetSetAction = { + name: actionName, + description: actionDescription, + kind: "refactor.rewrite.property.generateAccessors" +}; +registerRefactor(actionName, { + kinds: [generateGetSetAction.kind], + getEditsForAction: function getRefactorActionsToGenerateGetAndSetAccessors(context, actionName2) { + if (!context.endPosition) + return void 0; + const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const edits = ts_codefix_exports.generateAccessorFromProperty(context.file, context.program, context.startPosition, context.endPosition, context, actionName2); + if (!edits) + return void 0; + const renameFilename = context.file.fileName; + const nameNeedRename = info.renameAccessor ? info.accessorName : info.fieldName; + const renameLocationOffset = isIdentifier(nameNeedRename) ? 0 : -1; + const renameLocation = renameLocationOffset + getRenameLocation( + edits, + renameFilename, + nameNeedRename.text, + /*preferLastLocation*/ + isParameter(info.declaration) + ); + return { renameFilename, renameLocation, edits }; + }, + getAvailableActions(context) { + if (!context.endPosition) + return emptyArray; + const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition, context.triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + return [{ + name: actionName, + description: actionDescription, + actions: [generateGetSetAction] + }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: actionName, + description: actionDescription, + actions: [{ ...generateGetSetAction, notApplicableReason: info.error }] + }]; + } + return emptyArray; + } +}); + +// src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts +var ts_refactor_inferFunctionReturnType_exports = {}; + +// src/services/refactors/inferFunctionReturnType.ts +var refactorName12 = "Infer function return type"; +var refactorDescription6 = Diagnostics.Infer_function_return_type.message; +var inferReturnTypeAction = { + name: refactorName12, + description: refactorDescription6, + kind: "refactor.rewrite.function.returnType" +}; +registerRefactor(refactorName12, { + kinds: [inferReturnTypeAction.kind], + getEditsForAction: getRefactorEditsToInferReturnType, + getAvailableActions: getRefactorActionsToInferReturnType +}); +function getRefactorEditsToInferReturnType(context) { + const info = getInfo4(context); + if (info && !isRefactorErrorInfo(info)) { + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange7(context.file, t, info.declaration, info.returnTypeNode)); + return { renameFilename: void 0, renameLocation: void 0, edits }; + } + return void 0; +} +function getRefactorActionsToInferReturnType(context) { + const info = getInfo4(context); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + return [{ + name: refactorName12, + description: refactorDescription6, + actions: [inferReturnTypeAction] + }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorName12, + description: refactorDescription6, + actions: [{ ...inferReturnTypeAction, notApplicableReason: info.error }] + }]; + } + return emptyArray; +} +function doChange7(sourceFile, changes, declaration, typeNode) { + const closeParen = findChildOfKind(declaration, 22 /* CloseParenToken */, sourceFile); + const needParens = isArrowFunction(declaration) && closeParen === void 0; + const endNode2 = needParens ? first(declaration.parameters) : closeParen; + if (endNode2) { + if (needParens) { + changes.insertNodeBefore(sourceFile, endNode2, factory.createToken(21 /* OpenParenToken */)); + changes.insertNodeAfter(sourceFile, endNode2, factory.createToken(22 /* CloseParenToken */)); + } + changes.insertNodeAt(sourceFile, endNode2.end, typeNode, { prefix: ": " }); + } +} +function getInfo4(context) { + if (isInJSFile(context.file) || !refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind)) + return; + const token = getTokenAtPosition(context.file, context.startPosition); + const declaration = findAncestor(token, (n) => isBlock(n) || n.parent && isArrowFunction(n.parent) && (n.kind === 39 /* EqualsGreaterThanToken */ || n.parent.body === n) ? "quit" : isConvertibleDeclaration(n)); + if (!declaration || !declaration.body || declaration.type) { + return { error: getLocaleSpecificMessage(Diagnostics.Return_type_must_be_inferred_from_a_function) }; + } + const typeChecker = context.program.getTypeChecker(); + const returnType = tryGetReturnType(typeChecker, declaration); + if (!returnType) { + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_determine_function_return_type) }; + } + const returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */); + if (returnTypeNode) { + return { declaration, returnTypeNode }; + } +} +function isConvertibleDeclaration(node) { + switch (node.kind) { + case 261 /* FunctionDeclaration */: + case 217 /* FunctionExpression */: + case 218 /* ArrowFunction */: + case 173 /* MethodDeclaration */: + return true; + default: + return false; + } +} +function tryGetReturnType(typeChecker, node) { + if (typeChecker.isImplementationOfOverload(node)) { + const signatures = typeChecker.getTypeAtLocation(node).getCallSignatures(); + if (signatures.length > 1) { + return typeChecker.getUnionType(mapDefined(signatures, (s) => s.getReturnType())); + } + } + const signature = typeChecker.getSignatureFromDeclaration(node); + if (signature) { + return typeChecker.getReturnTypeOfSignature(signature); + } +} + // src/services/classifier2020.ts var TokenEncodingConsts = /* @__PURE__ */ ((TokenEncodingConsts2) => { TokenEncodingConsts2[TokenEncodingConsts2["typeOffset"] = 8] = "typeOffset"; @@ -136082,6 +141777,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h const rootFileNames = host.getScriptFileNames().slice(); const newSettings = host.getCompilationSettings() || getDefaultCompilerOptions2(); const hasInvalidatedResolutions = host.hasInvalidatedResolutions || returnFalse; + const hasInvalidatedLibResolutions = maybeBind(host, host.hasInvalidatedLibResolutions) || returnFalse; const hasChangedAutomaticTypeDirectiveNames = maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames); const projectReferences = (_b = host.getProjectReferences) == null ? void 0 : _b.call(host); let parsedCommandLines; @@ -136112,6 +141808,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h onReleaseOldSourceFile, onReleaseParsedCommandLine, hasInvalidatedResolutions, + hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, trace: maybeBind(host, host.trace), resolveModuleNames: maybeBind(host, host.resolveModuleNames), @@ -136120,6 +141817,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h resolveTypeReferenceDirectives: maybeBind(host, host.resolveTypeReferenceDirectives), resolveModuleNameLiterals: maybeBind(host, host.resolveModuleNameLiterals), resolveTypeReferenceDirectiveReferences: maybeBind(host, host.resolveTypeReferenceDirectiveReferences), + resolveLibrary: maybeBind(host, host.resolveLibrary), useSourceOfProjectReferenceRedirect: maybeBind(host, host.useSourceOfProjectReferenceRedirect), getParsedCommandLine }; @@ -136141,7 +141839,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h onUnRecoverableConfigFileDiagnostic: noop }; const documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); - if (isProgramUptoDate(program, rootFileNames, newSettings, (_path, fileName) => host.getScriptVersion(fileName), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + if (isProgramUptoDate(program, rootFileNames, newSettings, (_path, fileName) => host.getScriptVersion(fileName), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { return; } const options = { @@ -136445,7 +142143,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h const sourceFile = getValidSourceFile(fileName); return DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } - function findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) { + function findRenameLocations(fileName, position, findInStrings, findInComments, preferences) { synchronizeHostData(); const sourceFile = getValidSourceFile(fileName); const node = getAdjustedRenameLocation(getTouchingPropertyName(sourceFile, position)); @@ -136462,11 +142160,13 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h }; }); } else { + const quotePreference = getQuotePreference(sourceFile, preferences ?? emptyOptions); + const providePrefixAndSuffixTextForRename = typeof preferences === "boolean" ? preferences : preferences == null ? void 0 : preferences.providePrefixAndSuffixTextForRename; return getReferencesWorker2( node, position, { findInStrings, findInComments, providePrefixAndSuffixTextForRename, use: ts_FindAllReferences_exports.FindReferencesUse.Rename }, - (entry, originalNode, checker) => ts_FindAllReferences_exports.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false) + (entry, originalNode, checker) => ts_FindAllReferences_exports.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false, quotePreference) ); } } @@ -136711,6 +142411,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h const token = findPrecedingToken(position, sourceFile); if (!token || token.parent.kind === 311 /* SourceFile */) return void 0; + const jsxTagWordPattern = "[a-zA-Z0-9:\\-\\._$]*"; if (isJsxFragment(token.parent.parent)) { const openFragment = token.parent.parent.openingFragment; const closeFragment = token.parent.parent.closingFragment; @@ -136720,7 +142421,10 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h const closePos = closeFragment.getStart(sourceFile) + 2; if (position !== openPos && position !== closePos) return void 0; - return { ranges: [{ start: openPos, length: 0 }, { start: closePos, length: 0 }] }; + return { + ranges: [{ start: openPos, length: 0 }, { start: closePos, length: 0 }], + wordPattern: jsxTagWordPattern + }; } else { const tag = findAncestor( token.parent, @@ -136746,7 +142450,8 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h if (openingTagText !== closeTag.tagName.getText(sourceFile)) return void 0; return { - ranges: [{ start: openTagStart, length: openTagEnd - openTagStart }, { start: closeTagStart, length: closeTagEnd - closeTagStart }] + ranges: [{ start: openTagStart, length: openTagEnd - openTagStart }, { start: closeTagStart, length: closeTagEnd - closeTagStart }], + wordPattern: jsxTagWordPattern }; } } @@ -137048,15 +142753,24 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h function getSmartSelectionRange2(fileName, position) { return ts_SmartSelectionRange_exports.getSmartSelectionRange(position, syntaxTreeCache.getCurrentSourceFile(fileName)); } - function getApplicableRefactors2(fileName, positionOrRange, preferences = emptyOptions, triggerReason, kind) { + function getApplicableRefactors2(fileName, positionOrRange, preferences = emptyOptions, triggerReason, kind, includeInteractiveActions) { synchronizeHostData(); const file = getValidSourceFile(fileName); - return ts_refactor_exports.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences, emptyOptions, triggerReason, kind)); + return ts_refactor_exports.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences, emptyOptions, triggerReason, kind), includeInteractiveActions); } - function getEditsForRefactor2(fileName, formatOptions, positionOrRange, refactorName13, actionName2, preferences = emptyOptions) { + function getMoveToRefactoringFileSuggestions(fileName, positionOrRange, preferences = emptyOptions) { + synchronizeHostData(); + const sourceFile = getValidSourceFile(fileName); + const allFiles = Debug.checkDefined(program.getSourceFiles()); + const extension = extensionFromPath(fileName); + const files = mapDefined(allFiles, (file) => !(program == null ? void 0 : program.isSourceFileFromExternalLibrary(sourceFile)) && !(sourceFile === getValidSourceFile(file.fileName) || extension === ".ts" /* Ts */ && extensionFromPath(file.fileName) === ".d.ts" /* Dts */ || extension === ".d.ts" /* Dts */ && startsWith(getBaseFileName(file.fileName), "lib.") && extensionFromPath(file.fileName) === ".d.ts" /* Dts */) && extension === extensionFromPath(file.fileName) ? file.fileName : void 0); + const newFileName = createNewFileName(sourceFile, program, getRefactorContext(sourceFile, positionOrRange, preferences, emptyOptions), host); + return { newFileName, files }; + } + function getEditsForRefactor2(fileName, formatOptions, positionOrRange, refactorName13, actionName2, preferences = emptyOptions, interactiveRefactorArguments) { synchronizeHostData(); const file = getValidSourceFile(fileName); - return ts_refactor_exports.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName13, actionName2); + return ts_refactor_exports.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName13, actionName2, interactiveRefactorArguments); } function toLineColumnOffset(fileName, position) { if (position === 0) { @@ -137143,6 +142857,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h updateIsDefinitionOfReferencedSymbols, getApplicableRefactors: getApplicableRefactors2, getEditsForRefactor: getEditsForRefactor2, + getMoveToRefactoringFileSuggestions, toLineColumnOffset, getSourceMapper: () => sourceMapper, clearSourceMapperCache: () => sourceMapper.clearCache(), @@ -137774,10 +143489,10 @@ var LanguageServiceShimObject = class extends ShimBase { () => this.languageService.getSmartSelectionRange(fileName, position) ); } - findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) { + findRenameLocations(fileName, position, findInStrings, findInComments, preferences) { return this.forwardJSONCall( - `findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments}, ${providePrefixAndSuffixTextForRename})`, - () => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) + `findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments})`, + () => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, preferences) ); } /// GET BRACE MATCHING @@ -139226,10 +144941,10 @@ __export(ts_codefix_exports, { // src/services/codeFixProvider.ts var errorCodeToFixes = createMultiMap(); var fixIdToRegistration = /* @__PURE__ */ new Map(); -function createCodeFixActionWithoutFixAll(fixName8, changes, description2) { +function createCodeFixActionWithoutFixAll(fixName8, changes, description3) { return createCodeFixActionWorker( fixName8, - diagnosticToString(description2), + diagnosticToString(description3), changes, /*fixId*/ void 0, @@ -139237,14 +144952,14 @@ function createCodeFixActionWithoutFixAll(fixName8, changes, description2) { void 0 ); } -function createCodeFixAction(fixName8, changes, description2, fixId52, fixAllDescription, command) { - return createCodeFixActionWorker(fixName8, diagnosticToString(description2), changes, fixId52, diagnosticToString(fixAllDescription), command); +function createCodeFixAction(fixName8, changes, description3, fixId52, fixAllDescription, command) { + return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId52, diagnosticToString(fixAllDescription), command); } -function createCodeFixActionMaybeFixAll(fixName8, changes, description2, fixId52, fixAllDescription, command) { - return createCodeFixActionWorker(fixName8, diagnosticToString(description2), changes, fixId52, fixAllDescription && diagnosticToString(fixAllDescription), command); +function createCodeFixActionMaybeFixAll(fixName8, changes, description3, fixId52, fixAllDescription, command) { + return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId52, fixAllDescription && diagnosticToString(fixAllDescription), command); } -function createCodeFixActionWorker(fixName8, description2, changes, fixId52, fixAllDescription, command) { - return { fixName: fixName8, description: description2, changes, fixId: fixId52, fixAllDescription, commands: command ? [command] : void 0 }; +function createCodeFixActionWorker(fixName8, description3, changes, fixId52, fixAllDescription, command) { + return { fixName: fixName8, description: description3, changes, fixId: fixId52, fixAllDescription, commands: command ? [command] : void 0 }; } function registerCodeFix(reg) { for (const error of reg.errorCodes) { @@ -139944,14 +145659,14 @@ registerCodeFix({ const decl = getDeclaration(context.sourceFile, context.span.start); if (!decl) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange(t, context.sourceFile, decl)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange8(t, context.sourceFile, decl)); return [createCodeFixAction(fixId8, changes, Diagnostics.Annotate_with_type_from_JSDoc, fixId8, Diagnostics.Annotate_everything_with_types_from_JSDoc)]; }, fixIds: [fixId8], getAllCodeActions: (context) => codeFixAll(context, errorCodes9, (changes, diag2) => { const decl = getDeclaration(diag2.file, diag2.start); if (decl) - doChange(changes, diag2.file, decl); + doChange8(changes, diag2.file, decl); }) }); function getDeclaration(file, pos) { @@ -139964,7 +145679,7 @@ function parameterShouldGetTypeFromJSDoc(node) { function hasUsableJSDoc(decl) { return isFunctionLikeDeclaration(decl) ? decl.parameters.some(hasUsableJSDoc) || !decl.type && !!getJSDocReturnType(decl) : !decl.type && !!getJSDocType(decl); } -function doChange(changes, sourceFile, decl) { +function doChange8(changes, sourceFile, decl) { if (isFunctionLikeDeclaration(decl) && (getJSDocReturnType(decl) || decl.parameters.some((p) => !!getJSDocType(p)))) { if (!decl.typeParameters) { const typeParameters = getJSDocTypeParameterDeclarations(decl); @@ -140111,13 +145826,13 @@ var errorCodes10 = [Diagnostics.This_constructor_function_may_be_converted_to_a_ registerCodeFix({ errorCodes: errorCodes10, getCodeActions(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange2(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange9(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())); return [createCodeFixAction(fixId9, changes, Diagnostics.Convert_function_to_an_ES2015_class, fixId9, Diagnostics.Convert_all_constructor_functions_to_classes)]; }, fixIds: [fixId9], - getAllCodeActions: (context) => codeFixAll(context, errorCodes10, (changes, err) => doChange2(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())) + getAllCodeActions: (context) => codeFixAll(context, errorCodes10, (changes, err) => doChange9(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())) }); -function doChange2(changes, sourceFile, position, checker, preferences, compilerOptions) { +function doChange9(changes, sourceFile, position, checker, preferences, compilerOptions) { const ctorSymbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, position)); if (!ctorSymbol || !ctorSymbol.valueDeclaration || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { return void 0; @@ -141450,7 +147165,7 @@ function replaceImportUseSites(nodeOrNodes, useSitesToUnqualify) { function convertSingleImport(name, moduleSpecifier, checker, identifiers, target, quotePreference) { switch (name.kind) { case 205 /* ObjectBindingPattern */: { - const importSpecifiers = mapAllOrFail(name.elements, (e) => e.dotDotDotToken || e.initializer || e.propertyName && !isIdentifier(e.propertyName) || !isIdentifier(e.name) ? void 0 : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text)); + const importSpecifiers = mapAllOrFail(name.elements, (e) => e.dotDotDotToken || e.initializer || e.propertyName && !isIdentifier(e.propertyName) || !isIdentifier(e.name) ? void 0 : makeImportSpecifier2(e.propertyName && e.propertyName.text, e.name.text)); if (importSpecifiers) { return convertedImports([makeImport( /*defaultImport*/ @@ -141588,12 +147303,12 @@ function makeSingleImport(localName, propertyName, moduleSpecifier, quotePrefere ) : makeImport( /*defaultImport*/ void 0, - [makeImportSpecifier(propertyName, localName)], + [makeImportSpecifier2(propertyName, localName)], moduleSpecifier, quotePreference ); } -function makeImportSpecifier(propertyName, name) { +function makeImportSpecifier2(propertyName, name) { return factory.createImportSpecifier( /*isTypeOnly*/ false, @@ -141643,7 +147358,7 @@ registerCodeFix({ const qualifiedName = getQualifiedName(context.sourceFile, context.span.start); if (!qualifiedName) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange3(t, context.sourceFile, qualifiedName)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange10(t, context.sourceFile, qualifiedName)); const newText = `${qualifiedName.left.text}["${qualifiedName.right.text}"]`; return [createCodeFixAction(fixId11, changes, [Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId11, Diagnostics.Rewrite_all_as_indexed_access_types)]; }, @@ -141651,7 +147366,7 @@ registerCodeFix({ getAllCodeActions: (context) => codeFixAll(context, errorCodes12, (changes, diag2) => { const q = getQualifiedName(diag2.file, diag2.start); if (q) { - doChange3(changes, diag2.file, q); + doChange10(changes, diag2.file, q); } }) }); @@ -141660,7 +147375,7 @@ function getQualifiedName(sourceFile, pos) { Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); return isIdentifier(qualifiedName.left) ? qualifiedName : void 0; } -function doChange3(changeTracker, sourceFile, qualifiedName) { +function doChange10(changeTracker, sourceFile, qualifiedName) { const rightText = qualifiedName.right.text; const replacement = factory.createIndexedAccessTypeNode( factory.createTypeReferenceNode( @@ -141761,7 +147476,7 @@ registerCodeFix({ getCodeActions: function getCodeActionsToConvertToTypeOnlyImport(context) { const declaration = getDeclaration2(context.sourceFile, context.span.start); if (declaration) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange4(t, context.sourceFile, declaration)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange11(t, context.sourceFile, declaration)); return [createCodeFixAction(fixId13, changes, Diagnostics.Convert_to_type_only_import, fixId13, Diagnostics.Convert_all_imports_not_used_as_a_value_to_type_only_imports)]; } return void 0; @@ -141771,7 +147486,7 @@ registerCodeFix({ return codeFixAll(context, errorCodes14, (changes, diag2) => { const declaration = getDeclaration2(diag2.file, diag2.start); if (declaration) { - doChange4(changes, diag2.file, declaration); + doChange11(changes, diag2.file, declaration); } }); } @@ -141780,7 +147495,7 @@ function getDeclaration2(sourceFile, pos) { const { parent: parent2 } = getTokenAtPosition(sourceFile, pos); return isImportSpecifier(parent2) || isImportDeclaration(parent2) && parent2.importClause ? parent2 : void 0; } -function doChange4(changes, sourceFile, declaration) { +function doChange11(changes, sourceFile, declaration) { if (isImportSpecifier(declaration)) { changes.replaceNode(sourceFile, declaration, factory.updateImportSpecifier( declaration, @@ -141882,7 +147597,7 @@ registerCodeFix({ ); if (!node) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange5(t, node, context.sourceFile)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange12(t, node, context.sourceFile)); if (changes.length > 0) { return [ createCodeFixAction( @@ -141898,10 +147613,10 @@ registerCodeFix({ getAllCodeActions: (context) => codeFixAll(context, errorCodes15, (changes, diag2) => { const node = getTokenAtPosition(diag2.file, diag2.start); if (node) - doChange5(changes, node, diag2.file); + doChange12(changes, node, diag2.file); }) }); -function doChange5(changes, node, sourceFile) { +function doChange12(changes, node, sourceFile) { if (isJSDocTypedefTag(node)) { fixSingleTypeDef(changes, node, sourceFile); } @@ -142015,23 +147730,23 @@ registerCodeFix({ errorCodes: errorCodes16, getCodeActions: function getCodeActionsToConvertLiteralTypeToMappedType(context) { const { sourceFile, span } = context; - const info = getInfo2(sourceFile, span.start); + const info = getInfo5(sourceFile, span.start); if (!info) { return void 0; } const { name, constraint } = info; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange6(t, sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange13(t, sourceFile, info)); return [createCodeFixAction(fixId15, changes, [Diagnostics.Convert_0_to_1_in_0, constraint, name], fixId15, Diagnostics.Convert_all_type_literals_to_mapped_type)]; }, fixIds: [fixId15], getAllCodeActions: (context) => codeFixAll(context, errorCodes16, (changes, diag2) => { - const info = getInfo2(diag2.file, diag2.start); + const info = getInfo5(diag2.file, diag2.start); if (info) { - doChange6(changes, diag2.file, info); + doChange13(changes, diag2.file, info); } }) }); -function getInfo2(sourceFile, pos) { +function getInfo5(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); if (isIdentifier(token)) { const propertySignature = cast(token.parent.parent, isPropertySignature); @@ -142045,7 +147760,7 @@ function getInfo2(sourceFile, pos) { } return void 0; } -function doChange6(changes, sourceFile, { container, typeNode, constraint, name }) { +function doChange13(changes, sourceFile, { container, typeNode, constraint, name }) { changes.replaceNode(sourceFile, container, factory.createMappedTypeNode( /*readonlyToken*/ void 0, @@ -142460,8 +148175,8 @@ function getImportFixForSymbol(sourceFile, exportInfos, program, position, isVal const packageJsonImportFilter = createPackageJsonImportFilter(sourceFile, preferences, host); return getBestFix(getImportFixes(exportInfos, position, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes, sourceFile, program, packageJsonImportFilter, host); } -function codeFixActionToCodeAction({ description: description2, changes, commands }) { - return { description: description2, changes, commands }; +function codeFixActionToCodeAction({ description: description3, changes, commands }) { + return { description: description3, changes, commands }; } function getAllExportInfoForSymbol(importingFile, symbol, symbolName2, moduleSymbol, preferCapitalized, program, host, preferences, cancellationToken) { const getChecker = createGetChecker(program, host); @@ -143392,7 +149107,7 @@ registerCodeFix({ errorCodes: errorCodes19, getCodeActions(context) { const { sourceFile, span, program, preferences, host } = context; - const info = getInfo3(program, sourceFile, span); + const info = getInfo6(program, sourceFile, span); if (info === void 0) return; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingConstraint(t, program, preferences, host, sourceFile, info)); @@ -143404,7 +149119,7 @@ registerCodeFix({ const seen = /* @__PURE__ */ new Map(); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { eachDiagnostic(context, errorCodes19, (diag2) => { - const info = getInfo3(program, diag2.file, createTextSpan(diag2.start, diag2.length)); + const info = getInfo6(program, diag2.file, createTextSpan(diag2.start, diag2.length)); if (info) { if (addToSeen(seen, getNodeId(info.declaration))) { return addMissingConstraint(changes, program, preferences, host, diag2.file, info); @@ -143415,7 +149130,7 @@ registerCodeFix({ })); } }); -function getInfo3(program, sourceFile, span) { +function getInfo6(program, sourceFile, span) { const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3) => diag3.start === span.start && diag3.length === span.length); if (diag2 === void 0 || diag2.relatedInformation === void 0) return; @@ -143651,12 +149366,12 @@ registerCodeFix({ getCodeActions(context) { const { sourceFile, span, preferences } = context; const property = getPropertyAccessExpression(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange7(t, context.sourceFile, property, preferences)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange14(t, context.sourceFile, property, preferences)); return [createCodeFixAction(fixId18, changes, [Diagnostics.Use_element_access_for_0, property.name.text], fixId18, Diagnostics.Use_element_access_for_all_undeclared_properties)]; }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes21, (changes, diag2) => doChange7(changes, diag2.file, getPropertyAccessExpression(diag2.file, diag2.start), context.preferences)) + getAllCodeActions: (context) => codeFixAll(context, errorCodes21, (changes, diag2) => doChange14(changes, diag2.file, getPropertyAccessExpression(diag2.file, diag2.start), context.preferences)) }); -function doChange7(changes, sourceFile, node, preferences) { +function doChange14(changes, sourceFile, node, preferences) { const quotePreference = getQuotePreference(sourceFile, preferences); const argumentsExpression = factory.createStringLiteral(node.name.text, quotePreference === 0 /* Single */); changes.replaceNode( @@ -143678,16 +149393,16 @@ registerCodeFix({ const { sourceFile, program, span } = context; let diagnostic; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => { - diagnostic = doChange8(t, sourceFile, span.start, program.getTypeChecker()); + diagnostic = doChange15(t, sourceFile, span.start, program.getTypeChecker()); }); return diagnostic ? [createCodeFixAction(fixId19, changes, diagnostic, fixId19, Diagnostics.Fix_all_implicit_this_errors)] : emptyArray; }, fixIds: [fixId19], getAllCodeActions: (context) => codeFixAll(context, errorCodes22, (changes, diag2) => { - doChange8(changes, diag2.file, diag2.start, context.program.getTypeChecker()); + doChange15(changes, diag2.file, diag2.start, context.program.getTypeChecker()); }) }); -function doChange8(changes, sourceFile, pos, checker) { +function doChange15(changes, sourceFile, pos, checker) { const token = getTokenAtPosition(sourceFile, pos); if (!isThis(token)) return void 0; @@ -143739,10 +149454,10 @@ registerCodeFix({ fixIds: [fixId20], getCodeActions(context) { const { sourceFile, span, program } = context; - const info = getInfo4(sourceFile, span.start, program); + const info = getInfo7(sourceFile, span.start, program); if (info === void 0) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange9(t, program, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange16(t, program, info)); return [createCodeFixAction(fixId20, changes, [Diagnostics.Export_0_from_module_1, info.exportName.node.text, info.moduleSpecifier], fixId20, Diagnostics.Export_all_referenced_locals)]; }, getAllCodeActions(context) { @@ -143750,7 +149465,7 @@ registerCodeFix({ return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { const exports = /* @__PURE__ */ new Map(); eachDiagnostic(context, errorCodes23, (diag2) => { - const info = getInfo4(diag2.file, diag2.start, program); + const info = getInfo7(diag2.file, diag2.start, program); if (info === void 0) return void 0; const { exportName, node, moduleSourceFile } = info; @@ -143786,7 +149501,7 @@ registerCodeFix({ })); } }); -function getInfo4(sourceFile, pos, program) { +function getInfo7(sourceFile, pos, program) { var _a; const token = getTokenAtPosition(sourceFile, pos); if (isIdentifier(token)) { @@ -143822,7 +149537,7 @@ function getInfo4(sourceFile, pos, program) { } return void 0; } -function doChange9(changes, program, { exportName, node, moduleSourceFile }) { +function doChange16(changes, program, { exportName, node, moduleSourceFile }) { const exportDeclaration = tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly); if (exportDeclaration) { updateExport(changes, program, moduleSourceFile, exportDeclaration, [exportName]); @@ -143916,7 +149631,7 @@ registerCodeFix({ getCodeActions: function getCodeActionsToFixIncorrectNamedTupleSyntax(context) { const { sourceFile, span } = context; const namedTupleMember = getNamedTupleMember(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange10(t, sourceFile, namedTupleMember)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange17(t, sourceFile, namedTupleMember)); return [createCodeFixAction(fixId21, changes, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels, fixId21, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels)]; }, fixIds: [fixId21] @@ -143925,7 +149640,7 @@ function getNamedTupleMember(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); return findAncestor(token, (t) => t.kind === 201 /* NamedTupleMember */); } -function doChange10(changes, sourceFile, namedTupleMember) { +function doChange17(changes, sourceFile, namedTupleMember) { if (!namedTupleMember) { return; } @@ -143975,23 +149690,23 @@ registerCodeFix({ errorCodes: errorCodes25, getCodeActions(context) { const { sourceFile, errorCode } = context; - const info = getInfo5(sourceFile, context.span.start, context, errorCode); + const info = getInfo8(sourceFile, context.span.start, context, errorCode); if (!info) return void 0; const { node, suggestedSymbol } = info; const target = getEmitScriptTarget(context.host.getCompilationSettings()); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange11(t, sourceFile, node, suggestedSymbol, target)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange18(t, sourceFile, node, suggestedSymbol, target)); return [createCodeFixAction("spelling", changes, [Diagnostics.Change_spelling_to_0, symbolName(suggestedSymbol)], fixId22, Diagnostics.Fix_all_detected_spelling_errors)]; }, fixIds: [fixId22], getAllCodeActions: (context) => codeFixAll(context, errorCodes25, (changes, diag2) => { - const info = getInfo5(diag2.file, diag2.start, context, diag2.code); + const info = getInfo8(diag2.file, diag2.start, context, diag2.code); const target = getEmitScriptTarget(context.host.getCompilationSettings()); if (info) - doChange11(changes, context.sourceFile, info.node, info.suggestedSymbol, target); + doChange18(changes, context.sourceFile, info.node, info.suggestedSymbol, target); }) }); -function getInfo5(sourceFile, pos, context, errorCode) { +function getInfo8(sourceFile, pos, context, errorCode) { const node = getTokenAtPosition(sourceFile, pos); const parent2 = node.parent; if ((errorCode === Diagnostics.No_overload_matches_this_call.code || errorCode === Diagnostics.Type_0_is_not_assignable_to_type_1.code) && !isJsxAttribute(parent2)) @@ -144040,7 +149755,7 @@ function getInfo5(sourceFile, pos, context, errorCode) { } return suggestedSymbol === void 0 ? void 0 : { node, suggestedSymbol }; } -function doChange11(changes, sourceFile, node, suggestedSymbol, target) { +function doChange18(changes, sourceFile, node, suggestedSymbol, target) { const suggestion = symbolName(suggestedSymbol); if (!isIdentifierText(suggestion, target) && isPropertyAccessExpression(node.parent)) { const valDecl = suggestedSymbol.valueDeclaration; @@ -144090,7 +149805,7 @@ registerCodeFix({ fixIds: [fixIdAddReturnStatement, fixRemoveBracesFromArrowFunctionBody, fixIdWrapTheBlockWithParen], getCodeActions: function getCodeActionsToCorrectReturnValue(context) { const { program, sourceFile, span: { start: start2 }, errorCode } = context; - const info = getInfo6(program.getTypeChecker(), sourceFile, start2, errorCode); + const info = getInfo9(program.getTypeChecker(), sourceFile, start2, errorCode); if (!info) return void 0; if (info.kind === 0 /* MissingReturnStatement */) { @@ -144103,7 +149818,7 @@ registerCodeFix({ } }, getAllCodeActions: (context) => codeFixAll(context, errorCodes26, (changes, diag2) => { - const info = getInfo6(context.program.getTypeChecker(), diag2.file, diag2.start, diag2.code); + const info = getInfo9(context.program.getTypeChecker(), diag2.file, diag2.start, diag2.code); if (!info) return void 0; switch (context.fixId) { @@ -144226,7 +149941,7 @@ function checkFixedAssignableTo(checker, declaration, exprType, type, isFunction } return checker.isTypeAssignableTo(exprType, type); } -function getInfo6(checker, sourceFile, position, errorCode) { +function getInfo9(checker, sourceFile, position, errorCode) { const node = getTokenAtPosition(sourceFile, position); if (!node.parent) return void 0; @@ -144347,7 +150062,7 @@ registerCodeFix({ errorCodes: errorCodes27, getCodeActions(context) { const typeChecker = context.program.getTypeChecker(); - const info = getInfo7(context.sourceFile, context.span.start, context.errorCode, typeChecker, context.program); + const info = getInfo10(context.sourceFile, context.span.start, context.errorCode, typeChecker, context.program); if (!info) { return void 0; } @@ -144377,7 +150092,7 @@ registerCodeFix({ const typeDeclToMembers = /* @__PURE__ */ new Map(); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { eachDiagnostic(context, errorCodes27, (diag2) => { - const info = getInfo7(diag2.file, diag2.start, diag2.code, checker, context.program); + const info = getInfo10(diag2.file, diag2.start, diag2.code, checker, context.program); if (!info || !addToSeen(seen, getNodeId(info.parentDeclaration) + "#" + info.token.text)) { return; } @@ -144424,7 +150139,7 @@ registerCodeFix({ })); } }); -function getInfo7(sourceFile, tokenPos, errorCode, checker, program) { +function getInfo10(sourceFile, tokenPos, errorCode, checker, program) { var _a; const token = getTokenAtPosition(sourceFile, tokenPos); const parent2 = token.parent; @@ -145098,7 +150813,7 @@ registerCodeFix({ if (!nodes) return void 0; const { constructor, superCall } = nodes; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange12(t, sourceFile, constructor, superCall)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange19(t, sourceFile, constructor, superCall)); return [createCodeFixAction(fixId26, changes, Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId26, Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)]; }, fixIds: [fixId26], @@ -145111,12 +150826,12 @@ registerCodeFix({ return; const { constructor, superCall } = nodes; if (addToSeen(seenClasses, getNodeId(constructor.parent))) { - doChange12(changes, sourceFile, constructor, superCall); + doChange19(changes, sourceFile, constructor, superCall); } }); } }); -function doChange12(changes, sourceFile, constructor, superCall) { +function doChange19(changes, sourceFile, constructor, superCall) { changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall); changes.delete(sourceFile, superCall); } @@ -145140,18 +150855,18 @@ registerCodeFix({ getCodeActions(context) { const { sourceFile, span } = context; const ctr = getNode(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange13(t, sourceFile, ctr)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange20(t, sourceFile, ctr)); return [createCodeFixAction(fixId27, changes, Diagnostics.Add_missing_super_call, fixId27, Diagnostics.Add_all_missing_super_calls)]; }, fixIds: [fixId27], - getAllCodeActions: (context) => codeFixAll(context, errorCodes32, (changes, diag2) => doChange13(changes, context.sourceFile, getNode(diag2.file, diag2.start))) + getAllCodeActions: (context) => codeFixAll(context, errorCodes32, (changes, diag2) => doChange20(changes, context.sourceFile, getNode(diag2.file, diag2.start))) }); function getNode(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); Debug.assert(isConstructorDeclaration(token.parent), "token should be at the constructor declaration"); return token.parent; } -function doChange13(changes, sourceFile, ctr) { +function doChange20(changes, sourceFile, ctr) { const superCall = factory.createExpressionStatement(factory.createCallExpression( factory.createSuper(), /*typeArguments*/ @@ -145174,7 +150889,7 @@ registerCodeFix({ } const changes = ts_textChanges_exports.ChangeTracker.with( context, - (changeTracker) => doChange14(changeTracker, configFile) + (changeTracker) => doChange21(changeTracker, configFile) ); return [ createCodeFixActionWithoutFixAll(fixID, changes, Diagnostics.Enable_the_jsx_flag_in_your_configuration_file) @@ -145186,10 +150901,10 @@ registerCodeFix({ if (configFile === void 0) { return void 0; } - doChange14(changes, configFile); + doChange21(changes, configFile); }) }); -function doChange14(changeTracker, configFile) { +function doChange21(changeTracker, configFile) { setJsonCompilerOptionValue(changeTracker, configFile, "jsx", factory.createStringLiteral("react")); } @@ -145202,24 +150917,24 @@ registerCodeFix({ errorCodes: errorCodes34, getCodeActions(context) { const { sourceFile, span, program } = context; - const info = getInfo8(program, sourceFile, span); + const info = getInfo11(program, sourceFile, span); if (info === void 0) return; const { suggestion, expression, arg } = info; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange15(t, sourceFile, arg, expression)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange22(t, sourceFile, arg, expression)); return [createCodeFixAction(fixId28, changes, [Diagnostics.Use_0, suggestion], fixId28, Diagnostics.Use_Number_isNaN_in_all_conditions)]; }, fixIds: [fixId28], getAllCodeActions: (context) => { return codeFixAll(context, errorCodes34, (changes, diag2) => { - const info = getInfo8(context.program, diag2.file, createTextSpan(diag2.start, diag2.length)); + const info = getInfo11(context.program, diag2.file, createTextSpan(diag2.start, diag2.length)); if (info) { - doChange15(changes, diag2.file, info.arg, info.expression); + doChange22(changes, diag2.file, info.arg, info.expression); } }); } }); -function getInfo8(program, sourceFile, span) { +function getInfo11(program, sourceFile, span) { const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3) => diag3.start === span.start && diag3.length === span.length); if (diag2 === void 0 || diag2.relatedInformation === void 0) return; @@ -145234,7 +150949,7 @@ function getInfo8(program, sourceFile, span) { } return void 0; } -function doChange15(changes, sourceFile, arg, expression) { +function doChange22(changes, sourceFile, arg, expression) { const callExpression = factory.createCallExpression( factory.createPropertyAccessExpression(factory.createIdentifier("Number"), factory.createIdentifier("isNaN")), /*typeArguments*/ @@ -145304,12 +151019,12 @@ registerCodeFix({ getCodeActions(context) { const { sourceFile, span } = context; const property = getProperty2(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange16(t, context.sourceFile, property)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange23(t, context.sourceFile, property)); return [createCodeFixAction(fixId29, changes, [Diagnostics.Change_0_to_1, "=", ":"], fixId29, [Diagnostics.Switch_each_misused_0_to_1, "=", ":"])]; }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes35, (changes, diag2) => doChange16(changes, diag2.file, getProperty2(diag2.file, diag2.start))) + getAllCodeActions: (context) => codeFixAll(context, errorCodes35, (changes, diag2) => doChange23(changes, diag2.file, getProperty2(diag2.file, diag2.start))) }); -function doChange16(changes, sourceFile, node) { +function doChange23(changes, sourceFile, node) { changes.replaceNode(sourceFile, node, factory.createPropertyAssignment(node.name, node.objectAssignmentInitializer)); } function getProperty2(sourceFile, pos) { @@ -145370,27 +151085,27 @@ registerCodeFix({ errorCodes: errorCodes37, getCodeActions(context) { const { sourceFile } = context; - const info = getInfo9(sourceFile, context.span.start, context.errorCode); + const info = getInfo12(sourceFile, context.span.start, context.errorCode); if (!info) { return void 0; } - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange17(t, sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange24(t, sourceFile, info)); return [createCodeFixAction(fixId31, changes, [Diagnostics.Add_0_to_unresolved_variable, info.className || "this"], fixId31, Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name)]; }, fixIds: [fixId31], getAllCodeActions: (context) => codeFixAll(context, errorCodes37, (changes, diag2) => { - const info = getInfo9(diag2.file, diag2.start, diag2.code); + const info = getInfo12(diag2.file, diag2.start, diag2.code); if (info) - doChange17(changes, context.sourceFile, info); + doChange24(changes, context.sourceFile, info); }) }); -function getInfo9(sourceFile, pos, diagCode) { +function getInfo12(sourceFile, pos, diagCode) { const node = getTokenAtPosition(sourceFile, pos); if (isIdentifier(node) || isPrivateIdentifier(node)) { return { node, className: diagCode === didYouMeanStaticMemberCode ? getContainingClass(node).name.text : void 0 }; } } -function doChange17(changes, sourceFile, { node, className }) { +function doChange24(changes, sourceFile, { node, className }) { suppressLeadingAndTrailingTrivia(node); changes.replaceNode(sourceFile, node, factory.createPropertyAccessExpression(className ? factory.createIdentifier(className) : factory.createThis(), node)); } @@ -145407,7 +151122,7 @@ registerCodeFix({ fixIds: [fixIdExpression, fixIdHtmlEntity], getCodeActions(context) { const { sourceFile, preferences, span } = context; - const changeToExpression = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange18( + const changeToExpression = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange25( t, preferences, sourceFile, @@ -145415,7 +151130,7 @@ registerCodeFix({ /*useHtmlEntity*/ false )); - const changeToHtmlEntity = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange18( + const changeToHtmlEntity = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange25( t, preferences, sourceFile, @@ -145429,7 +151144,7 @@ registerCodeFix({ ]; }, getAllCodeActions(context) { - return codeFixAll(context, errorCodes38, (changes, diagnostic) => doChange18(changes, context.preferences, diagnostic.file, diagnostic.start, context.fixId === fixIdHtmlEntity)); + return codeFixAll(context, errorCodes38, (changes, diagnostic) => doChange25(changes, context.preferences, diagnostic.file, diagnostic.start, context.fixId === fixIdHtmlEntity)); } }); var htmlEntity = { @@ -145439,7 +151154,7 @@ var htmlEntity = { function isValidCharacter(character) { return hasProperty(htmlEntity, character); } -function doChange18(changes, preferences, sourceFile, start2, useHtmlEntity) { +function doChange25(changes, preferences, sourceFile, start2, useHtmlEntity) { const character = sourceFile.getText()[start2]; if (!isValidCharacter(character)) { return; @@ -145460,7 +151175,7 @@ registerCodeFix({ getCodeActions: function getCodeActionsToFixUnmatchedParameter(context) { const { sourceFile, span } = context; const actions2 = []; - const info = getInfo10(sourceFile, span.start); + const info = getInfo13(sourceFile, span.start); if (info) { append(actions2, getDeleteAction(context, info)); append(actions2, getRenameAction(context, info)); @@ -145472,7 +151187,7 @@ registerCodeFix({ const tagsToSignature = /* @__PURE__ */ new Map(); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { eachDiagnostic(context, errorCodes39, ({ file, start: start2 }) => { - const info = getInfo10(file, start2); + const info = getInfo13(file, start2); if (info) { tagsToSignature.set(info.signature, append(tagsToSignature.get(info.signature), info.jsDocParameterTag)); } @@ -145522,7 +151237,7 @@ function getRenameAction(context, { name, jsDocHost, signature, jsDocParameterTa const changes = ts_textChanges_exports.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]); } -function getInfo10(sourceFile, pos) { +function getInfo13(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); if (token.parent && isJSDocParameterTag(token.parent) && isIdentifier(token.parent.name)) { const jsDocParameterTag = token.parent; @@ -145933,13 +151648,13 @@ registerCodeFix({ const syntacticDiagnostics = context.program.getSyntacticDiagnostics(context.sourceFile, context.cancellationToken); if (syntacticDiagnostics.length) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange19(t, context.sourceFile, context.span.start, context.span.length, context.errorCode)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange26(t, context.sourceFile, context.span.start, context.span.length, context.errorCode)); return [createCodeFixAction(fixId33, changes, Diagnostics.Remove_unreachable_code, fixId33, Diagnostics.Remove_all_unreachable_code)]; }, fixIds: [fixId33], - getAllCodeActions: (context) => codeFixAll(context, errorCodes42, (changes, diag2) => doChange19(changes, diag2.file, diag2.start, diag2.length, diag2.code)) + getAllCodeActions: (context) => codeFixAll(context, errorCodes42, (changes, diag2) => doChange26(changes, diag2.file, diag2.start, diag2.length, diag2.code)) }); -function doChange19(changes, sourceFile, start2, length2, errorCode) { +function doChange26(changes, sourceFile, start2, length2, errorCode) { const token = getTokenAtPosition(sourceFile, start2); const statement = findAncestor(token, isStatement); if (statement.getStart(sourceFile) !== token.getStart(sourceFile)) { @@ -145994,13 +151709,13 @@ var errorCodes43 = [Diagnostics.Unused_label.code]; registerCodeFix({ errorCodes: errorCodes43, getCodeActions(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange20(t, context.sourceFile, context.span.start)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange27(t, context.sourceFile, context.span.start)); return [createCodeFixAction(fixId34, changes, Diagnostics.Remove_unused_label, fixId34, Diagnostics.Remove_all_unused_labels)]; }, fixIds: [fixId34], - getAllCodeActions: (context) => codeFixAll(context, errorCodes43, (changes, diag2) => doChange20(changes, diag2.file, diag2.start)) + getAllCodeActions: (context) => codeFixAll(context, errorCodes43, (changes, diag2) => doChange27(changes, diag2.file, diag2.start)) }); -function doChange20(changes, sourceFile, start2) { +function doChange27(changes, sourceFile, start2) { const token = getTokenAtPosition(sourceFile, start2); const labeledStatement = cast(token.parent, isLabeledStatement); const pos = token.getStart(sourceFile); @@ -146027,7 +151742,7 @@ registerCodeFix({ getCodeActions(context) { const { sourceFile } = context; const checker = context.program.getTypeChecker(); - const info = getInfo11(sourceFile, context.span.start, checker); + const info = getInfo14(sourceFile, context.span.start, checker); if (!info) return void 0; const { typeNode, type } = info; @@ -146038,7 +151753,7 @@ registerCodeFix({ } return actions2; function fix(type2, fixId52, fixAllDescription) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange21(t, sourceFile, typeNode, type2, checker)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange28(t, sourceFile, typeNode, type2, checker)); return createCodeFixAction("jdocTypes", changes, [Diagnostics.Change_0_to_1, original, checker.typeToString(type2)], fixId52, fixAllDescription); } }, @@ -146047,16 +151762,16 @@ registerCodeFix({ const { fixId: fixId52, program, sourceFile } = context; const checker = program.getTypeChecker(); return codeFixAll(context, errorCodes44, (changes, err) => { - const info = getInfo11(err.file, err.start, checker); + const info = getInfo14(err.file, err.start, checker); if (!info) return; const { typeNode, type } = info; const fixedType = typeNode.kind === 320 /* JSDocNullableType */ && fixId52 === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; - doChange21(changes, sourceFile, typeNode, fixedType, checker); + doChange28(changes, sourceFile, typeNode, fixedType, checker); }); } }); -function doChange21(changes, sourceFile, oldTypeNode, newType, checker) { +function doChange28(changes, sourceFile, oldTypeNode, newType, checker) { changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode( newType, /*enclosingDeclaration*/ @@ -146065,7 +151780,7 @@ function doChange21(changes, sourceFile, oldTypeNode, newType, checker) { void 0 )); } -function getInfo11(sourceFile, pos, checker) { +function getInfo14(sourceFile, pos, checker) { const decl = findAncestor(getTokenAtPosition(sourceFile, pos), isTypeContainer); const typeNode = decl && decl.type; return typeNode && { typeNode, type: getType(checker, typeNode) }; @@ -146119,16 +151834,16 @@ registerCodeFix({ const callName = getCallName(sourceFile, span.start); if (!callName) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange22(t, context.sourceFile, callName)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange29(t, context.sourceFile, callName)); return [createCodeFixAction(fixId35, changes, Diagnostics.Add_missing_call_parentheses, fixId35, Diagnostics.Add_all_missing_call_parentheses)]; }, getAllCodeActions: (context) => codeFixAll(context, errorCodes45, (changes, diag2) => { const callName = getCallName(diag2.file, diag2.start); if (callName) - doChange22(changes, diag2.file, callName); + doChange29(changes, diag2.file, callName); }) }); -function doChange22(changes, sourceFile, name) { +function doChange29(changes, sourceFile, name) { changes.replaceNodeWithText(sourceFile, name, `${name.text}()`); } function getCallName(sourceFile, start2) { @@ -146160,7 +151875,7 @@ registerCodeFix({ const nodes = getNodes3(sourceFile, span.start); if (!nodes) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange23(t, sourceFile, nodes)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange30(t, sourceFile, nodes)); return [createCodeFixAction(fixId36, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId36, Diagnostics.Add_all_missing_async_modifiers)]; }, fixIds: [fixId36], @@ -146170,7 +151885,7 @@ registerCodeFix({ const nodes = getNodes3(diag2.file, diag2.start); if (!nodes || !addToSeen(seen, getNodeId(nodes.insertBefore))) return; - doChange23(changes, context.sourceFile, nodes); + doChange30(changes, context.sourceFile, nodes); }); } }); @@ -146209,7 +151924,7 @@ function getNodes3(sourceFile, start2) { returnType: getReturnType(containingFunction) }; } -function doChange23(changes, sourceFile, { insertBefore, returnType }) { +function doChange30(changes, sourceFile, { insertBefore, returnType }) { if (returnType) { const entityName = getEntityNameFromTypeNode(returnType); if (!entityName || entityName.kind !== 80 /* Identifier */ || entityName.text !== "Promise") { @@ -146228,14 +151943,14 @@ var fixId37 = "fixPropertyOverrideAccessor"; registerCodeFix({ errorCodes: errorCodes47, getCodeActions(context) { - const edits = doChange24(context.sourceFile, context.span.start, context.span.length, context.errorCode, context); + const edits = doChange31(context.sourceFile, context.span.start, context.span.length, context.errorCode, context); if (edits) { return [createCodeFixAction(fixId37, edits, Diagnostics.Generate_get_and_set_accessors, fixId37, Diagnostics.Generate_get_and_set_accessors_for_all_overriding_properties)]; } }, fixIds: [fixId37], getAllCodeActions: (context) => codeFixAll(context, errorCodes47, (changes, diag2) => { - const edits = doChange24(diag2.file, diag2.start, diag2.length, diag2.code, context); + const edits = doChange31(diag2.file, diag2.start, diag2.length, diag2.code, context); if (edits) { for (const edit of edits) { changes.pushRaw(context.sourceFile, edit); @@ -146243,7 +151958,7 @@ registerCodeFix({ } }) }); -function doChange24(file, start2, length2, code, context) { +function doChange31(file, start2, length2, code, context) { let startPosition; let endPosition; if (code === Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property.code) { @@ -146313,7 +152028,7 @@ registerCodeFix({ const token = getTokenAtPosition(sourceFile, start2); let declaration; const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => { - declaration = doChange25( + declaration = doChange32( changes2, sourceFile, token, @@ -146334,7 +152049,7 @@ registerCodeFix({ const { sourceFile, program, cancellationToken, host, preferences } = context; const markSeen = nodeSeenTracker(); return codeFixAll(context, errorCodes48, (changes, err) => { - doChange25(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences); + doChange32(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences); }); } }); @@ -146373,7 +152088,7 @@ function mapSuggestionDiagnostic(errorCode) { } return errorCode; } -function doChange25(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, preferences) { +function doChange32(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, preferences) { if (!isParameterPropertyModifier(token.kind) && token.kind !== 80 /* Identifier */ && token.kind !== 26 /* DotDotDotToken */ && token.kind !== 110 /* ThisKeyword */) { return void 0; } @@ -147282,12 +152997,12 @@ registerCodeFix({ getCodeActions: function getCodeActionsToFixReturnTypeInAsyncFunction(context) { const { sourceFile, program, span } = context; const checker = program.getTypeChecker(); - const info = getInfo12(sourceFile, program.getTypeChecker(), span.start); + const info = getInfo15(sourceFile, program.getTypeChecker(), span.start); if (!info) { return void 0; } const { returnTypeNode, returnType, promisedTypeNode, promisedType } = info; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange26(t, sourceFile, returnTypeNode, promisedTypeNode)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange33(t, sourceFile, returnTypeNode, promisedTypeNode)); return [createCodeFixAction( fixId39, changes, @@ -147301,13 +153016,13 @@ registerCodeFix({ )]; }, getAllCodeActions: (context) => codeFixAll(context, errorCodes49, (changes, diag2) => { - const info = getInfo12(diag2.file, context.program.getTypeChecker(), diag2.start); + const info = getInfo15(diag2.file, context.program.getTypeChecker(), diag2.start); if (info) { - doChange26(changes, diag2.file, info.returnTypeNode, info.promisedTypeNode); + doChange33(changes, diag2.file, info.returnTypeNode, info.promisedTypeNode); } }) }); -function getInfo12(sourceFile, checker, pos) { +function getInfo15(sourceFile, checker, pos) { if (isInJSFile(sourceFile)) { return void 0; } @@ -147330,7 +153045,7 @@ function getInfo12(sourceFile, checker, pos) { return { returnTypeNode, returnType, promisedTypeNode, promisedType }; } } -function doChange26(changes, sourceFile, returnTypeNode, promisedTypeNode) { +function doChange33(changes, sourceFile, returnTypeNode, promisedTypeNode) { changes.replaceNode(sourceFile, returnTypeNode, factory.createTypeReferenceNode("Promise", [promisedTypeNode])); } @@ -148350,7 +154065,7 @@ var errorCodes51 = [Diagnostics.Property_0_has_no_initializer_and_is_not_definit registerCodeFix({ errorCodes: errorCodes51, getCodeActions: function getCodeActionsForStrictClassInitializationErrors(context) { - const info = getInfo13(context.sourceFile, context.span.start); + const info = getInfo16(context.sourceFile, context.span.start); if (!info) return; const result = []; @@ -148362,7 +154077,7 @@ registerCodeFix({ fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], getAllCodeActions: (context) => { return codeFixAll(context, errorCodes51, (changes, diag2) => { - const info = getInfo13(diag2.file, diag2.start); + const info = getInfo16(diag2.file, diag2.start); if (!info) return; switch (context.fixId) { @@ -148385,7 +154100,7 @@ registerCodeFix({ }); } }); -function getInfo13(sourceFile, pos) { +function getInfo16(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); if (isIdentifier(token) && isPropertyDeclaration(token.parent)) { const type = getEffectiveTypeAnnotationNode(token.parent); @@ -148496,22 +154211,22 @@ var errorCodes52 = [Diagnostics.require_call_may_be_converted_to_an_import.code] registerCodeFix({ errorCodes: errorCodes52, getCodeActions(context) { - const info = getInfo14(context.sourceFile, context.program, context.span.start); + const info = getInfo17(context.sourceFile, context.program, context.span.start); if (!info) { return void 0; } - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange27(t, context.sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange34(t, context.sourceFile, info)); return [createCodeFixAction(fixId41, changes, Diagnostics.Convert_require_to_import, fixId41, Diagnostics.Convert_all_require_to_import)]; }, fixIds: [fixId41], getAllCodeActions: (context) => codeFixAll(context, errorCodes52, (changes, diag2) => { - const info = getInfo14(diag2.file, context.program, diag2.start); + const info = getInfo17(diag2.file, context.program, diag2.start); if (info) { - doChange27(changes, context.sourceFile, info); + doChange34(changes, context.sourceFile, info); } }) }); -function doChange27(changes, sourceFile, info) { +function doChange34(changes, sourceFile, info) { const { allowSyntheticDefaults, defaultImportName, namedImports, statement, required } = info; changes.replaceNode(sourceFile, statement, defaultImportName && !allowSyntheticDefaults ? factory.createImportEqualsDeclaration( /*modifiers*/ @@ -148534,7 +154249,7 @@ function doChange27(changes, sourceFile, info) { void 0 )); } -function getInfo14(sourceFile, program, pos) { +function getInfo17(sourceFile, program, pos) { const { parent: parent2 } = getTokenAtPosition(sourceFile, pos); if (!isRequireCall( parent2, @@ -148581,20 +154296,20 @@ registerCodeFix({ errorCodes: errorCodes53, getCodeActions(context) { const { sourceFile, span: { start: start2 } } = context; - const info = getInfo15(sourceFile, start2); + const info = getInfo18(sourceFile, start2); if (!info) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange28(t, sourceFile, info, context.preferences)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange35(t, sourceFile, info, context.preferences)); return [createCodeFixAction(fixId42, changes, Diagnostics.Convert_to_default_import, fixId42, Diagnostics.Convert_all_to_default_imports)]; }, fixIds: [fixId42], getAllCodeActions: (context) => codeFixAll(context, errorCodes53, (changes, diag2) => { - const info = getInfo15(diag2.file, diag2.start); + const info = getInfo18(diag2.file, diag2.start); if (info) - doChange28(changes, diag2.file, info, context.preferences); + doChange35(changes, diag2.file, info, context.preferences); }) }); -function getInfo15(sourceFile, pos) { +function getInfo18(sourceFile, pos) { const name = getTokenAtPosition(sourceFile, pos); if (!isIdentifier(name)) return void 0; @@ -148606,7 +154321,7 @@ function getInfo15(sourceFile, pos) { return { importNode, name, moduleSpecifier: importNode.moduleSpecifier }; } } -function doChange28(changes, sourceFile, info, preferences) { +function doChange35(changes, sourceFile, info, preferences) { changes.replaceNode(sourceFile, info.importNode, makeImport( info.name, /*namedImports*/ @@ -148652,11 +154367,11 @@ registerCodeFix({ getCodeActions: function getCodeActionsToAddMissingTypeof(context) { const { sourceFile, span } = context; const importType = getImportTypeNode(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange29(t, sourceFile, importType)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange36(t, sourceFile, importType)); return [createCodeFixAction(fixId44, changes, Diagnostics.Add_missing_typeof, fixId44, Diagnostics.Add_missing_typeof)]; }, fixIds: [fixId44], - getAllCodeActions: (context) => codeFixAll(context, errorCodes55, (changes, diag2) => doChange29(changes, context.sourceFile, getImportTypeNode(diag2.file, diag2.start))) + getAllCodeActions: (context) => codeFixAll(context, errorCodes55, (changes, diag2) => doChange36(changes, context.sourceFile, getImportTypeNode(diag2.file, diag2.start))) }); function getImportTypeNode(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); @@ -148664,7 +154379,7 @@ function getImportTypeNode(sourceFile, pos) { Debug.assert(token.parent.kind === 204 /* ImportType */, "Token parent should be an ImportType"); return token.parent; } -function doChange29(changes, sourceFile, importType) { +function doChange36(changes, sourceFile, importType) { const newTypeNode = factory.updateImportTypeNode( importType, importType.argument, @@ -148687,7 +154402,7 @@ registerCodeFix({ const node = findNodeToFix(sourceFile, span.start); if (!node) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange30(t, sourceFile, node)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange37(t, sourceFile, node)); return [createCodeFixAction(fixID2, changes, Diagnostics.Wrap_in_JSX_fragment, fixID2, Diagnostics.Wrap_all_unparented_JSX_in_JSX_fragment)]; }, fixIds: [fixID2], @@ -148695,7 +154410,7 @@ registerCodeFix({ const node = findNodeToFix(context.sourceFile, diag2.start); if (!node) return void 0; - doChange30(changes, context.sourceFile, node); + doChange37(changes, context.sourceFile, node); }) }); function findNodeToFix(sourceFile, pos) { @@ -148711,7 +154426,7 @@ function findNodeToFix(sourceFile, pos) { return void 0; return binaryExpr; } -function doChange30(changeTracker, sf, node) { +function doChange37(changeTracker, sf, node) { const jsx = flattenInvalidBinaryExpr(node); if (jsx) changeTracker.replaceNode(sf, node, factory.createJsxFragment(factory.createJsxOpeningFragment(), jsx, factory.createJsxJsxClosingFragment())); @@ -148742,21 +154457,21 @@ registerCodeFix({ errorCodes: errorCodes57, getCodeActions: function getCodeActionsToConvertToMappedTypeObject(context) { const { sourceFile, span } = context; - const info = getInfo16(sourceFile, span.start); + const info = getInfo19(sourceFile, span.start); if (!info) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange31(t, sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange38(t, sourceFile, info)); const name = idText(info.container.name); return [createCodeFixAction(fixId45, changes, [Diagnostics.Convert_0_to_mapped_object_type, name], fixId45, [Diagnostics.Convert_0_to_mapped_object_type, name])]; }, fixIds: [fixId45], getAllCodeActions: (context) => codeFixAll(context, errorCodes57, (changes, diag2) => { - const info = getInfo16(diag2.file, diag2.start); + const info = getInfo19(diag2.file, diag2.start); if (info) - doChange31(changes, diag2.file, info); + doChange38(changes, diag2.file, info); }) }); -function getInfo16(sourceFile, pos) { +function getInfo19(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); const indexSignature = tryCast(token.parent.parent, isIndexSignatureDeclaration); if (!indexSignature) @@ -148769,7 +154484,7 @@ function getInfo16(sourceFile, pos) { function createTypeAliasFromInterface(declaration, type) { return factory.createTypeAliasDeclaration(declaration.modifiers, declaration.name, declaration.typeParameters, type); } -function doChange31(changes, sourceFile, { indexSignature, container }) { +function doChange38(changes, sourceFile, { indexSignature, container }) { const members = isInterfaceDeclaration(container) ? container.members : container.type.members; const otherMembers = members.filter((member) => !isIndexSignatureDeclaration(member)); const parameter = first(indexSignature.parameters); @@ -148920,10 +154635,10 @@ registerCodeFix({ errorCodes: errorCodes61, getCodeActions: function getCodeActionsToConvertConstToLet(context) { const { sourceFile, span, program } = context; - const info = getInfo17(sourceFile, span.start, program); + const info = getInfo20(sourceFile, span.start, program); if (info === void 0) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange32(t, sourceFile, info.token)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange39(t, sourceFile, info.token)); return [createCodeFixActionMaybeFixAll(fixId49, changes, Diagnostics.Convert_const_to_let, fixId49, Diagnostics.Convert_all_const_to_let)]; }, getAllCodeActions: (context) => { @@ -148931,10 +154646,10 @@ registerCodeFix({ const seen = /* @__PURE__ */ new Map(); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { eachDiagnostic(context, errorCodes61, (diag2) => { - const info = getInfo17(diag2.file, diag2.start, program); + const info = getInfo20(diag2.file, diag2.start, program); if (info) { if (addToSeen(seen, getSymbolId(info.symbol))) { - return doChange32(changes, diag2.file, info.token); + return doChange39(changes, diag2.file, info.token); } } return void 0; @@ -148943,7 +154658,7 @@ registerCodeFix({ }, fixIds: [fixId49] }); -function getInfo17(sourceFile, pos, program) { +function getInfo20(sourceFile, pos, program) { var _a; const checker = program.getTypeChecker(); const symbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, pos)); @@ -148957,7 +154672,7 @@ function getInfo17(sourceFile, pos, program) { return; return { symbol, token: constToken }; } -function doChange32(changes, sourceFile, token) { +function doChange39(changes, sourceFile, token) { changes.replaceNode(sourceFile, token, factory.createToken(121 /* LetKeyword */)); } @@ -148969,10 +154684,10 @@ registerCodeFix({ errorCodes: errorCodes62, getCodeActions(context) { const { sourceFile } = context; - const info = getInfo18(sourceFile, context.span.start, context.errorCode); + const info = getInfo21(sourceFile, context.span.start, context.errorCode); if (!info) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange33(t, sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange40(t, sourceFile, info)); return [createCodeFixAction( fixId50, changes, @@ -148983,16 +154698,16 @@ registerCodeFix({ }, fixIds: [fixId50], getAllCodeActions: (context) => codeFixAll(context, errorCodes62, (changes, diag2) => { - const info = getInfo18(diag2.file, diag2.start, diag2.code); + const info = getInfo21(diag2.file, diag2.start, diag2.code); if (info) - doChange33(changes, context.sourceFile, info); + doChange40(changes, context.sourceFile, info); }) }); -function getInfo18(sourceFile, pos, _) { +function getInfo21(sourceFile, pos, _) { const node = getTokenAtPosition(sourceFile, pos); return node.kind === 27 /* SemicolonToken */ && node.parent && (isObjectLiteralExpression(node.parent) || isArrayLiteralExpression(node.parent)) ? { node } : void 0; } -function doChange33(changes, sourceFile, { node }) { +function doChange40(changes, sourceFile, { node }) { const newNode = factory.createToken(28 /* CommaToken */); changes.replaceNode(sourceFile, node, newNode); } @@ -149622,11 +155337,11 @@ function getJSDocParamAnnotation(paramName, initializer, dotDotDotToken, isJs, i } } const dotDotDot = !isObject && dotDotDotToken ? "..." : ""; - const description2 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : ""; - return `@param {${dotDotDot}${type}} ${paramName} ${description2}`; + const description3 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : ""; + return `@param {${dotDotDot}${type}} ${paramName} ${description3}`; } else { - const description2 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : ""; - return `@param ${paramName} ${description2}`; + const description3 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : ""; + return `@param ${paramName} ${description3}`; } } function getJSDocParamNameWithInitializer(paramName, initializer) { @@ -150960,7 +156675,7 @@ function getContextualType(previousToken, position, sourceFile, checker) { ) : isEqualityOperatorKind(previousToken.kind) && isBinaryExpression(parent2) && isEqualityOperatorKind(parent2.operatorToken.kind) ? ( // completion at `x ===/**/` should be for the right side checker.getTypeAtLocation(parent2.left) - ) : checker.getContextualType(previousToken); + ) : checker.getContextualType(previousToken, 4 /* Completions */) || checker.getContextualType(previousToken); } } function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { @@ -152135,7 +157850,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, return true; } } - return isDeclarationName(contextToken2) && !isShorthandPropertyAssignment(contextToken2.parent) && !isJsxAttribute(contextToken2.parent) && !((isClassLike(contextToken2.parent) || isInterfaceDeclaration(contextToken2.parent)) && (contextToken2 !== previousToken || position > previousToken.end)); + return isDeclarationName(contextToken2) && !isShorthandPropertyAssignment(contextToken2.parent) && !isJsxAttribute(contextToken2.parent) && !((isClassLike(contextToken2.parent) || isInterfaceDeclaration(contextToken2.parent) || isTypeParameterDeclaration(contextToken2.parent)) && (contextToken2 !== previousToken || position > previousToken.end)); } function isPreviousPropertyDeclarationTerminated(contextToken2, position2) { return contextToken2.kind !== 64 /* EqualsToken */ && (contextToken2.kind === 27 /* SemicolonToken */ || !positionsAreOnSameLine(contextToken2.end, position2, sourceFile)); @@ -154512,8 +160227,8 @@ function getDefinitionKindAndDisplayParts(symbol, checker, node) { const { displayParts, symbolKind } = ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning); return { displayParts, kind: symbolKind }; } -function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText) { - return { ...entryToDocumentSpan(entry), ...providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker) }; +function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText, quotePreference) { + return { ...entryToDocumentSpan(entry), ...providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker, quotePreference) }; } function toReferencedSymbolEntry(entry, symbol) { const referenceEntry = toReferenceEntry(entry); @@ -154549,7 +160264,7 @@ function entryToDocumentSpan(entry) { }; } } -function getPrefixAndSuffixText(entry, originalNode, checker) { +function getPrefixAndSuffixText(entry, originalNode, checker, quotePreference) { if (entry.kind !== 0 /* Span */ && isIdentifier(originalNode)) { const { node, kind } = entry; const parent2 = node.parent; @@ -154580,6 +160295,10 @@ function getPrefixAndSuffixText(entry, originalNode, checker) { return originalNode === entry.node || checker.getSymbolAtLocation(originalNode) === checker.getSymbolAtLocation(entry.node) ? { prefixText: name + " as " } : { suffixText: " as " + name }; } } + if (entry.kind !== 0 /* Span */ && isNumericLiteral(entry.node) && isAccessExpression(entry.node.parent)) { + const quote2 = getQuoteFromPreference(quotePreference); + return { prefixText: quote2, suffixText: quote2 }; + } return emptyOptions; } function toImplementationLocation(entry, checker) { @@ -158302,4928 +164021,6 @@ function tryGetFunctionOpenToken(node, body, sourceFile) { return findChildOfKind(body, 19 /* OpenBraceToken */, sourceFile); } -// src/services/_namespaces/ts.refactor.ts -var ts_refactor_exports = {}; -__export(ts_refactor_exports, { - addOrRemoveBracesToArrowFunction: () => ts_refactor_addOrRemoveBracesToArrowFunction_exports, - convertArrowFunctionOrFunctionExpression: () => ts_refactor_convertArrowFunctionOrFunctionExpression_exports, - convertParamsToDestructuredObject: () => ts_refactor_convertParamsToDestructuredObject_exports, - convertStringOrTemplateLiteral: () => ts_refactor_convertStringOrTemplateLiteral_exports, - convertToOptionalChainExpression: () => ts_refactor_convertToOptionalChainExpression_exports, - doChangeNamedToNamespaceOrDefault: () => doChangeNamedToNamespaceOrDefault, - extractSymbol: () => ts_refactor_extractSymbol_exports, - generateGetAccessorAndSetAccessor: () => ts_refactor_generateGetAccessorAndSetAccessor_exports, - getApplicableRefactors: () => getApplicableRefactors, - getEditsForRefactor: () => getEditsForRefactor, - inferFunctionReturnType: () => ts_refactor_inferFunctionReturnType_exports, - isRefactorErrorInfo: () => isRefactorErrorInfo, - refactorKindBeginsWith: () => refactorKindBeginsWith, - registerRefactor: () => registerRefactor -}); - -// src/services/refactorProvider.ts -var refactors = /* @__PURE__ */ new Map(); -function registerRefactor(name, refactor) { - refactors.set(name, refactor); -} -function getApplicableRefactors(context) { - return arrayFrom(flatMapIterator(refactors.values(), (refactor) => { - var _a; - return context.cancellationToken && context.cancellationToken.isCancellationRequested() || !((_a = refactor.kinds) == null ? void 0 : _a.some((kind) => refactorKindBeginsWith(kind, context.kind))) ? void 0 : refactor.getAvailableActions(context); - })); -} -function getEditsForRefactor(context, refactorName13, actionName2) { - const refactor = refactors.get(refactorName13); - return refactor && refactor.getEditsForAction(context, actionName2); -} - -// src/services/refactors/convertExport.ts -var refactorName = "Convert export"; -var defaultToNamedAction = { - name: "Convert default export to named export", - description: Diagnostics.Convert_default_export_to_named_export.message, - kind: "refactor.rewrite.export.named" -}; -var namedToDefaultAction = { - name: "Convert named export to default export", - description: Diagnostics.Convert_named_export_to_default_export.message, - kind: "refactor.rewrite.export.default" -}; -registerRefactor(refactorName, { - kinds: [ - defaultToNamedAction.kind, - namedToDefaultAction.kind - ], - getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndDefaultExports(context) { - const info = getInfo19(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - const action = info.wasDefault ? defaultToNamedAction : namedToDefaultAction; - return [{ name: refactorName, description: action.description, actions: [action] }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [ - { name: refactorName, description: Diagnostics.Convert_default_export_to_named_export.message, actions: [ - { ...defaultToNamedAction, notApplicableReason: info.error }, - { ...namedToDefaultAction, notApplicableReason: info.error } - ] } - ]; - } - return emptyArray; - }, - getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndDefaultExports(context, actionName2) { - Debug.assert(actionName2 === defaultToNamedAction.name || actionName2 === namedToDefaultAction.name, "Unexpected action name"); - const info = getInfo19(context); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange34(context.file, context.program, info, t, context.cancellationToken)); - return { edits, renameFilename: void 0, renameLocation: void 0 }; - } -}); -function getInfo19(context, considerPartialSpans = true) { - const { file, program } = context; - const span = getRefactorContextSpan(context); - const token = getTokenAtPosition(file, span.start); - const exportNode = !!(token.parent && getSyntacticModifierFlags(token.parent) & 1 /* Export */) && considerPartialSpans ? token.parent : getParentNodeInSpan(token, file, span); - if (!exportNode || !isSourceFile(exportNode.parent) && !(isModuleBlock(exportNode.parent) && isAmbientModule(exportNode.parent.parent))) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_export_statement) }; - } - const checker = program.getTypeChecker(); - const exportingModuleSymbol = getExportingModuleSymbol(exportNode.parent, checker); - const flags = getSyntacticModifierFlags(exportNode) || (isExportAssignment(exportNode) && !exportNode.isExportEquals ? 1025 /* ExportDefault */ : 0 /* None */); - const wasDefault = !!(flags & 1024 /* Default */); - if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { - return { error: getLocaleSpecificMessage(Diagnostics.This_file_already_has_a_default_export) }; - } - const noSymbolError = (id) => isIdentifier(id) && checker.getSymbolAtLocation(id) ? void 0 : { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_named_export) }; - switch (exportNode.kind) { - case 261 /* FunctionDeclaration */: - case 262 /* ClassDeclaration */: - case 263 /* InterfaceDeclaration */: - case 265 /* EnumDeclaration */: - case 264 /* TypeAliasDeclaration */: - case 266 /* ModuleDeclaration */: { - const node = exportNode; - if (!node.name) - return void 0; - return noSymbolError(node.name) || { exportNode: node, exportName: node.name, wasDefault, exportingModuleSymbol }; - } - case 242 /* VariableStatement */: { - const vs = exportNode; - if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { - return void 0; - } - const decl = first(vs.declarationList.declarations); - if (!decl.initializer) - return void 0; - Debug.assert(!wasDefault, "Can't have a default flag here"); - return noSymbolError(decl.name) || { exportNode: vs, exportName: decl.name, wasDefault, exportingModuleSymbol }; - } - case 276 /* ExportAssignment */: { - const node = exportNode; - if (node.isExportEquals) - return void 0; - return noSymbolError(node.expression) || { exportNode: node, exportName: node.expression, wasDefault, exportingModuleSymbol }; - } - default: - return void 0; - } -} -function doChange34(exportingSourceFile, program, info, changes, cancellationToken) { - changeExport(exportingSourceFile, info, changes, program.getTypeChecker()); - changeImports(program, info, changes, cancellationToken); -} -function changeExport(exportingSourceFile, { wasDefault, exportNode, exportName }, changes, checker) { - if (wasDefault) { - if (isExportAssignment(exportNode) && !exportNode.isExportEquals) { - const exp = exportNode.expression; - const spec = makeExportSpecifier(exp.text, exp.text); - changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports([spec]) - )); - } else { - changes.delete(exportingSourceFile, Debug.checkDefined(findModifier(exportNode, 90 /* DefaultKeyword */), "Should find a default keyword in modifier list")); - } - } else { - const exportKeyword = Debug.checkDefined(findModifier(exportNode, 95 /* ExportKeyword */), "Should find an export keyword in modifier list"); - switch (exportNode.kind) { - case 261 /* FunctionDeclaration */: - case 262 /* ClassDeclaration */: - case 263 /* InterfaceDeclaration */: - changes.insertNodeAfter(exportingSourceFile, exportKeyword, factory.createToken(90 /* DefaultKeyword */)); - break; - case 242 /* VariableStatement */: - const decl = first(exportNode.declarationList.declarations); - if (!ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile) && !decl.type) { - changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDefault(Debug.checkDefined(decl.initializer, "Initializer was previously known to be present"))); - break; - } - case 265 /* EnumDeclaration */: - case 264 /* TypeAliasDeclaration */: - case 266 /* ModuleDeclaration */: - changes.deleteModifier(exportingSourceFile, exportKeyword); - changes.insertNodeAfter(exportingSourceFile, exportNode, factory.createExportDefault(factory.createIdentifier(exportName.text))); - break; - default: - Debug.fail(`Unexpected exportNode kind ${exportNode.kind}`); - } - } -} -function changeImports(program, { wasDefault, exportName, exportingModuleSymbol }, changes, cancellationToken) { - const checker = program.getTypeChecker(); - const exportSymbol = Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol"); - ts_FindAllReferences_exports.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, (ref) => { - if (exportName === ref) - return; - const importingSourceFile = ref.getSourceFile(); - if (wasDefault) { - changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); - } else { - changeNamedToDefaultImport(importingSourceFile, ref, changes); - } - }); -} -function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { - const { parent: parent2 } = ref; - switch (parent2.kind) { - case 210 /* PropertyAccessExpression */: - changes.replaceNode(importingSourceFile, ref, factory.createIdentifier(exportName)); - break; - case 275 /* ImportSpecifier */: - case 280 /* ExportSpecifier */: { - const spec = parent2; - changes.replaceNode(importingSourceFile, spec, makeImportSpecifier2(exportName, spec.name.text)); - break; - } - case 272 /* ImportClause */: { - const clause = parent2; - Debug.assert(clause.name === ref, "Import clause name should match provided ref"); - const spec = makeImportSpecifier2(exportName, ref.text); - const { namedBindings } = clause; - if (!namedBindings) { - changes.replaceNode(importingSourceFile, ref, factory.createNamedImports([spec])); - } else if (namedBindings.kind === 273 /* NamespaceImport */) { - changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); - const quotePreference = isStringLiteral(clause.parent.moduleSpecifier) ? quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; - const newImport = makeImport( - /*defaultImport*/ - void 0, - [makeImportSpecifier2(exportName, ref.text)], - clause.parent.moduleSpecifier, - quotePreference - ); - changes.insertNodeAfter(importingSourceFile, clause.parent, newImport); - } else { - changes.delete(importingSourceFile, ref); - changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec); - } - break; - } - case 204 /* ImportType */: - const importTypeNode = parent2; - changes.replaceNode(importingSourceFile, parent2, factory.createImportTypeNode(importTypeNode.argument, importTypeNode.assertions, factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); - break; - default: - Debug.failBadSyntaxKind(parent2); - } -} -function changeNamedToDefaultImport(importingSourceFile, ref, changes) { - const parent2 = ref.parent; - switch (parent2.kind) { - case 210 /* PropertyAccessExpression */: - changes.replaceNode(importingSourceFile, ref, factory.createIdentifier("default")); - break; - case 275 /* ImportSpecifier */: { - const defaultImport = factory.createIdentifier(parent2.name.text); - if (parent2.parent.elements.length === 1) { - changes.replaceNode(importingSourceFile, parent2.parent, defaultImport); - } else { - changes.delete(importingSourceFile, parent2); - changes.insertNodeBefore(importingSourceFile, parent2.parent, defaultImport); - } - break; - } - case 280 /* ExportSpecifier */: { - changes.replaceNode(importingSourceFile, parent2, makeExportSpecifier("default", parent2.name.text)); - break; - } - default: - Debug.assertNever(parent2, `Unexpected parent kind ${parent2.kind}`); - } -} -function makeImportSpecifier2(propertyName, name) { - return factory.createImportSpecifier( - /*isTypeOnly*/ - false, - propertyName === name ? void 0 : factory.createIdentifier(propertyName), - factory.createIdentifier(name) - ); -} -function makeExportSpecifier(propertyName, name) { - return factory.createExportSpecifier( - /*isTypeOnly*/ - false, - propertyName === name ? void 0 : factory.createIdentifier(propertyName), - factory.createIdentifier(name) - ); -} -function getExportingModuleSymbol(parent2, checker) { - if (isSourceFile(parent2)) { - return parent2.symbol; - } - const symbol = parent2.parent.symbol; - if (symbol.valueDeclaration && isExternalModuleAugmentation(symbol.valueDeclaration)) { - return checker.getMergedSymbol(symbol); - } - return symbol; -} - -// src/services/refactors/convertImport.ts -var refactorName2 = "Convert import"; -var actions = { - [0 /* Named */]: { - name: "Convert namespace import to named imports", - description: Diagnostics.Convert_namespace_import_to_named_imports.message, - kind: "refactor.rewrite.import.named" - }, - [2 /* Namespace */]: { - name: "Convert named imports to namespace import", - description: Diagnostics.Convert_named_imports_to_namespace_import.message, - kind: "refactor.rewrite.import.namespace" - }, - [1 /* Default */]: { - name: "Convert named imports to default import", - description: Diagnostics.Convert_named_imports_to_default_import.message, - kind: "refactor.rewrite.import.default" - } -}; -registerRefactor(refactorName2, { - kinds: getOwnValues(actions).map((a) => a.kind), - getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndNamespacedImports(context) { - const info = getImportConversionInfo(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - const action = actions[info.convertTo]; - return [{ name: refactorName2, description: action.description, actions: [action] }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return getOwnValues(actions).map((action) => ({ - name: refactorName2, - description: action.description, - actions: [{ ...action, notApplicableReason: info.error }] - })); - } - return emptyArray; - }, - getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndNamespacedImports(context, actionName2) { - Debug.assert(some(getOwnValues(actions), (action) => action.name === actionName2), "Unexpected action name"); - const info = getImportConversionInfo(context); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange35(context.file, context.program, t, info)); - return { edits, renameFilename: void 0, renameLocation: void 0 }; - } -}); -function getImportConversionInfo(context, considerPartialSpans = true) { - const { file } = context; - const span = getRefactorContextSpan(context); - const token = getTokenAtPosition(file, span.start); - const importDecl = considerPartialSpans ? findAncestor(token, isImportDeclaration) : getParentNodeInSpan(token, file, span); - if (!importDecl || !isImportDeclaration(importDecl)) - return { error: "Selection is not an import declaration." }; - const end = span.start + span.length; - const nextToken = findNextToken(importDecl, importDecl.parent, file); - if (nextToken && end > nextToken.getStart()) - return void 0; - const { importClause } = importDecl; - if (!importClause) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_import_clause) }; - } - if (!importClause.namedBindings) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_namespace_import_or_named_imports) }; - } - if (importClause.namedBindings.kind === 273 /* NamespaceImport */) { - return { convertTo: 0 /* Named */, import: importClause.namedBindings }; - } - const shouldUseDefault = getShouldUseDefault(context.program, importClause); - return shouldUseDefault ? { convertTo: 1 /* Default */, import: importClause.namedBindings } : { convertTo: 2 /* Namespace */, import: importClause.namedBindings }; -} -function getShouldUseDefault(program, importClause) { - return getAllowSyntheticDefaultImports(program.getCompilerOptions()) && isExportEqualsModule(importClause.parent.moduleSpecifier, program.getTypeChecker()); -} -function doChange35(sourceFile, program, changes, info) { - const checker = program.getTypeChecker(); - if (info.convertTo === 0 /* Named */) { - doChangeNamespaceToNamed(sourceFile, checker, changes, info.import, getAllowSyntheticDefaultImports(program.getCompilerOptions())); - } else { - doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, info.import, info.convertTo === 1 /* Default */); - } -} -function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { - let usedAsNamespaceOrDefault = false; - const nodesToReplace = []; - const conflictingNames = /* @__PURE__ */ new Map(); - ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, (id) => { - if (!isPropertyAccessOrQualifiedName(id.parent)) { - usedAsNamespaceOrDefault = true; - } else { - const exportName = getRightOfPropertyAccessOrQualifiedName(id.parent).text; - if (checker.resolveName( - exportName, - id, - 67108863 /* All */, - /*excludeGlobals*/ - true - )) { - conflictingNames.set(exportName, true); - } - Debug.assert(getLeftOfPropertyAccessOrQualifiedName(id.parent) === id, "Parent expression should match id"); - nodesToReplace.push(id.parent); - } - }); - const exportNameToImportName = /* @__PURE__ */ new Map(); - for (const propertyAccessOrQualifiedName of nodesToReplace) { - const exportName = getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName).text; - let importName = exportNameToImportName.get(exportName); - if (importName === void 0) { - exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? getUniqueName(exportName, sourceFile) : exportName); - } - changes.replaceNode(sourceFile, propertyAccessOrQualifiedName, factory.createIdentifier(importName)); - } - const importSpecifiers = []; - exportNameToImportName.forEach((name, propertyName) => { - importSpecifiers.push(factory.createImportSpecifier( - /*isTypeOnly*/ - false, - name === propertyName ? void 0 : factory.createIdentifier(propertyName), - factory.createIdentifier(name) - )); - }); - const importDecl = toConvert.parent.parent; - if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) { - changes.insertNodeAfter(sourceFile, importDecl, updateImport( - importDecl, - /*defaultImportName*/ - void 0, - importSpecifiers - )); - } else { - changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? factory.createIdentifier(toConvert.name.text) : void 0, importSpecifiers)); - } -} -function getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { - return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.name : propertyAccessOrQualifiedName.right; -} -function getLeftOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { - return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.expression : propertyAccessOrQualifiedName.left; -} -function doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, toConvert, shouldUseDefault = getShouldUseDefault(program, toConvert.parent)) { - const checker = program.getTypeChecker(); - const importDecl = toConvert.parent.parent; - const { moduleSpecifier } = importDecl; - const toConvertSymbols = /* @__PURE__ */ new Set(); - toConvert.elements.forEach((namedImport) => { - const symbol = checker.getSymbolAtLocation(namedImport.name); - if (symbol) { - toConvertSymbols.add(symbol); - } - }); - const preferredName = moduleSpecifier && isStringLiteral(moduleSpecifier) ? ts_codefix_exports.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 99 /* ESNext */) : "module"; - function hasNamespaceNameConflict(namedImport) { - return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(namedImport.name, checker, sourceFile, (id) => { - const symbol = checker.resolveName( - preferredName, - id, - 67108863 /* All */, - /*excludeGlobals*/ - true - ); - if (symbol) { - if (toConvertSymbols.has(symbol)) { - return isExportSpecifier(id.parent); - } - return true; - } - return false; - }); - } - const namespaceNameConflicts = toConvert.elements.some(hasNamespaceNameConflict); - const namespaceImportName = namespaceNameConflicts ? getUniqueName(preferredName, sourceFile) : preferredName; - const neededNamedImports = /* @__PURE__ */ new Set(); - for (const element of toConvert.elements) { - const propertyName = (element.propertyName || element.name).text; - ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, (id) => { - const access = factory.createPropertyAccessExpression(factory.createIdentifier(namespaceImportName), propertyName); - if (isShorthandPropertyAssignment(id.parent)) { - changes.replaceNode(sourceFile, id.parent, factory.createPropertyAssignment(id.text, access)); - } else if (isExportSpecifier(id.parent)) { - neededNamedImports.add(element); - } else { - changes.replaceNode(sourceFile, id, access); - } - }); - } - changes.replaceNode(sourceFile, toConvert, shouldUseDefault ? factory.createIdentifier(namespaceImportName) : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName))); - if (neededNamedImports.size) { - const newNamedImports = 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*/ - void 0, - newNamedImports - )); - } -} -function isExportEqualsModule(moduleSpecifier, checker) { - const externalModule = checker.resolveExternalModuleName(moduleSpecifier); - if (!externalModule) - return false; - const exportEquals = checker.resolveExternalModuleSymbol(externalModule); - return externalModule !== exportEquals; -} -function updateImport(old, defaultImportName, elements) { - return factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - /*isTypeOnly*/ - false, - defaultImportName, - elements && elements.length ? factory.createNamedImports(elements) : void 0 - ), - old.moduleSpecifier, - /*assertClause*/ - void 0 - ); -} - -// src/services/refactors/extractType.ts -var refactorName3 = "Extract type"; -var extractToTypeAliasAction = { - name: "Extract to type alias", - description: getLocaleSpecificMessage(Diagnostics.Extract_to_type_alias), - kind: "refactor.extract.type" -}; -var extractToInterfaceAction = { - name: "Extract to interface", - description: getLocaleSpecificMessage(Diagnostics.Extract_to_interface), - kind: "refactor.extract.interface" -}; -var extractToTypeDefAction = { - name: "Extract to typedef", - description: getLocaleSpecificMessage(Diagnostics.Extract_to_typedef), - kind: "refactor.extract.typedef" -}; -registerRefactor(refactorName3, { - kinds: [ - extractToTypeAliasAction.kind, - extractToInterfaceAction.kind, - extractToTypeDefAction.kind - ], - getAvailableActions: function getRefactorActionsToExtractType(context) { - const info = getRangeToExtract(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - return [{ - name: refactorName3, - description: getLocaleSpecificMessage(Diagnostics.Extract_type), - actions: info.isJS ? [extractToTypeDefAction] : append([extractToTypeAliasAction], info.typeElements && extractToInterfaceAction) - }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorName3, - description: getLocaleSpecificMessage(Diagnostics.Extract_type), - actions: [ - { ...extractToTypeDefAction, notApplicableReason: info.error }, - { ...extractToTypeAliasAction, notApplicableReason: info.error }, - { ...extractToInterfaceAction, notApplicableReason: info.error } - ] - }]; - } - return emptyArray; - }, - getEditsForAction: function getRefactorEditsToExtractType(context, actionName2) { - const { file } = context; - const info = getRangeToExtract(context); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected to find a range to extract"); - const name = getUniqueName("NewType", file); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (changes) => { - switch (actionName2) { - case extractToTypeAliasAction.name: - Debug.assert(!info.isJS, "Invalid actionName/JS combo"); - return doTypeAliasChange(changes, file, name, info); - case extractToTypeDefAction.name: - Debug.assert(info.isJS, "Invalid actionName/JS combo"); - return doTypedefChange(changes, context, file, name, info); - case extractToInterfaceAction.name: - Debug.assert(!info.isJS && !!info.typeElements, "Invalid actionName/JS combo"); - return doInterfaceChange(changes, file, name, info); - default: - Debug.fail("Unexpected action name"); - } - }); - const renameFilename = file.fileName; - const renameLocation = getRenameLocation( - edits, - renameFilename, - name, - /*preferLastLocation*/ - false - ); - return { edits, renameFilename, renameLocation }; - } -}); -function getRangeToExtract(context, considerEmptySpans = true) { - const { file, startPosition } = context; - const isJS = isSourceFileJS(file); - const current = getTokenAtPosition(file, startPosition); - 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))); - if (!selection || !isTypeNode(selection)) - return { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) }; - const checker = context.program.getTypeChecker(); - const enclosingNode = getEnclosingNode(selection, isJS); - if (enclosingNode === void 0) - return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }; - const typeParameters = collectTypeParameters(checker, selection, enclosingNode, file); - if (!typeParameters) - return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }; - const typeElements = flattenTypeLiteralNodeReference(checker, selection); - return { isJS, selection, enclosingNode, typeParameters, typeElements }; -} -function flattenTypeLiteralNodeReference(checker, node) { - if (!node) - return void 0; - if (isIntersectionTypeNode(node)) { - const result = []; - const seen = /* @__PURE__ */ new Map(); - for (const type of node.types) { - const flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type); - if (!flattenedTypeMembers || !flattenedTypeMembers.every((type2) => type2.name && addToSeen(seen, getNameFromPropertyName(type2.name)))) { - return void 0; - } - addRange(result, flattenedTypeMembers); - } - return result; - } else if (isParenthesizedTypeNode(node)) { - return flattenTypeLiteralNodeReference(checker, node.type); - } else if (isTypeLiteralNode(node)) { - return node.members; - } - return void 0; -} -function rangeContainsSkipTrivia(r1, node, file) { - return rangeContainsStartEnd(r1, skipTrivia(file.text, node.pos), node.end); -} -function collectTypeParameters(checker, selection, enclosingNode, file) { - const result = []; - return visitor(selection) ? void 0 : result; - function visitor(node) { - if (isTypeReferenceNode(node)) { - if (isIdentifier(node.typeName)) { - const typeName = node.typeName; - const symbol = checker.resolveName( - typeName.text, - typeName, - 262144 /* TypeParameter */, - /*excludeGlobals*/ - true - ); - for (const decl of (symbol == null ? void 0 : symbol.declarations) || emptyArray) { - if (isTypeParameterDeclaration(decl) && decl.getSourceFile() === file) { - if (decl.name.escapedText === typeName.escapedText && rangeContainsSkipTrivia(decl, selection, file)) { - return true; - } - if (rangeContainsSkipTrivia(enclosingNode, decl, file) && !rangeContainsSkipTrivia(selection, decl, file)) { - pushIfUnique(result, decl); - break; - } - } - } - } - } else if (isInferTypeNode(node)) { - const conditionalTypeNode = findAncestor(node, (n) => isConditionalTypeNode(n) && rangeContainsSkipTrivia(n.extendsType, node, file)); - if (!conditionalTypeNode || !rangeContainsSkipTrivia(selection, conditionalTypeNode, file)) { - return true; - } - } else if (isTypePredicateNode(node) || isThisTypeNode(node)) { - const functionLikeNode = findAncestor(node.parent, isFunctionLike); - if (functionLikeNode && functionLikeNode.type && rangeContainsSkipTrivia(functionLikeNode.type, node, file) && !rangeContainsSkipTrivia(selection, functionLikeNode, file)) { - return true; - } - } else if (isTypeQueryNode(node)) { - if (isIdentifier(node.exprName)) { - const symbol = checker.resolveName( - node.exprName.text, - node.exprName, - 111551 /* Value */, - /*excludeGlobals*/ - false - ); - if ((symbol == null ? void 0 : symbol.valueDeclaration) && rangeContainsSkipTrivia(enclosingNode, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) { - return true; - } - } else { - if (isThisIdentifier(node.exprName.left) && !rangeContainsSkipTrivia(selection, node.parent, file)) { - return true; - } - } - } - if (file && isTupleTypeNode(node) && getLineAndCharacterOfPosition(file, node.pos).line === getLineAndCharacterOfPosition(file, node.end).line) { - setEmitFlags(node, 1 /* SingleLine */); - } - return forEachChild(node, visitor); - } -} -function doTypeAliasChange(changes, file, name, info) { - const { enclosingNode, selection, typeParameters } = info; - const newTypeNode = factory.createTypeAliasDeclaration( - /*modifiers*/ - void 0, - name, - typeParameters.map((id) => factory.updateTypeParameterDeclaration( - id, - id.modifiers, - id.name, - id.constraint, - /*defaultType*/ - void 0 - )), - selection - ); - changes.insertNodeBefore( - file, - enclosingNode, - ignoreSourceNewlines(newTypeNode), - /*blankLineBetween*/ - true - ); - changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( - id.name, - /*typeArguments*/ - void 0 - ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace }); -} -function doInterfaceChange(changes, file, name, info) { - var _a; - const { enclosingNode, selection, typeParameters, typeElements } = info; - const newTypeNode = factory.createInterfaceDeclaration( - /*modifiers*/ - void 0, - name, - typeParameters, - /*heritageClauses*/ - void 0, - typeElements - ); - setTextRange(newTypeNode, (_a = typeElements[0]) == null ? void 0 : _a.parent); - changes.insertNodeBefore( - file, - enclosingNode, - ignoreSourceNewlines(newTypeNode), - /*blankLineBetween*/ - true - ); - changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( - id.name, - /*typeArguments*/ - void 0 - ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace }); -} -function doTypedefChange(changes, context, file, name, info) { - var _a; - const { enclosingNode, selection, typeParameters } = info; - setEmitFlags(selection, 3072 /* NoComments */ | 4096 /* NoNestedComments */); - const node = factory.createJSDocTypedefTag( - factory.createIdentifier("typedef"), - factory.createJSDocTypeExpression(selection), - factory.createIdentifier(name) - ); - const templates = []; - forEach(typeParameters, (typeParameter) => { - const constraint = getEffectiveConstraintOfTypeParameter(typeParameter); - const parameter = factory.createTypeParameterDeclaration( - /*modifiers*/ - void 0, - typeParameter.name - ); - const template = factory.createJSDocTemplateTag( - factory.createIdentifier("template"), - constraint && cast(constraint, isJSDocTypeExpression), - [parameter] - ); - templates.push(template); - }); - const jsDoc = factory.createJSDocComment( - /*comment*/ - void 0, - factory.createNodeArray(concatenate(templates, [node])) - ); - if (isJSDoc(enclosingNode)) { - const pos = enclosingNode.getStart(file); - const newLineCharacter = getNewLineOrDefaultFromHost(context.host, (_a = context.formatContext) == null ? void 0 : _a.options); - changes.insertNodeAt(file, enclosingNode.getStart(file), jsDoc, { - suffix: newLineCharacter + newLineCharacter + file.text.slice(getPrecedingNonSpaceCharacterPosition(file.text, pos - 1), pos) - }); - } else { - changes.insertNodeBefore( - file, - enclosingNode, - jsDoc, - /*blankLineBetween*/ - true - ); - } - changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( - id.name, - /*typeArguments*/ - void 0 - )))); -} -function getEnclosingNode(node, isJS) { - return findAncestor(node, isStatement) || (isJS ? findAncestor(node, isJSDoc) : void 0); -} - -// src/services/refactors/helpers.ts -function isRefactorErrorInfo(info) { - return info.error !== void 0; -} -function refactorKindBeginsWith(known, requested) { - if (!requested) - return true; - return known.substr(0, requested.length) === requested; -} - -// src/services/refactors/moveToNewFile.ts -var refactorName4 = "Move to a new file"; -var description = getLocaleSpecificMessage(Diagnostics.Move_to_a_new_file); -var moveToNewFileAction = { - name: refactorName4, - description, - kind: "refactor.move.newFile" -}; -registerRefactor(refactorName4, { - kinds: [moveToNewFileAction.kind], - getAvailableActions: function getRefactorActionsToMoveToNewFile(context) { - const statements = getStatementsToMove(context); - if (context.preferences.allowTextChangesInNewFiles && statements) { - return [{ name: refactorName4, description, actions: [moveToNewFileAction] }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorName4, - description, - actions: [{ ...moveToNewFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] - }]; - } - return emptyArray; - }, - getEditsForAction: function getRefactorEditsToMoveToNewFile(context, actionName2) { - Debug.assert(actionName2 === refactorName4, "Wrong refactor invoked"); - const statements = Debug.checkDefined(getStatementsToMove(context)); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange36(context.file, context.program, statements, t, context.host, context.preferences)); - return { edits, renameFilename: void 0, renameLocation: void 0 }; - } -}); -function getRangeToMove(context) { - const { file } = context; - const range = createTextRangeFromSpan(getRefactorContextSpan(context)); - const { statements } = file; - const startNodeIndex = findIndex(statements, (s) => s.end > range.pos); - if (startNodeIndex === -1) - return void 0; - const startStatement = statements[startNodeIndex]; - if (isNamedDeclaration(startStatement) && startStatement.name && rangeContainsRange(startStatement.name, range)) { - return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; - } - if (range.pos > startStatement.getStart(file)) - return void 0; - const afterEndNodeIndex = findIndex(statements, (s) => s.end > range.end, startNodeIndex); - if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) - return void 0; - return { - toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), - afterLast: afterEndNodeIndex === -1 ? void 0 : statements[afterEndNodeIndex] - }; -} -function doChange36(oldFile, program, toMove, changes, host, preferences) { - const checker = program.getTypeChecker(); - const usage = getUsageInfo(oldFile, toMove.all, checker); - 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.oldFileImportsFromNewFile, usage.movedSymbols), - extension, - currentDirectory, - host - ) - ) + extension; - changes.createNewFile(oldFile, newFilename, getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences)); - addNewFileToTsconfig(program, changes, oldFile.fileName, newFilename, hostGetCanonicalFileName(host)); -} -function getStatementsToMove(context) { - const rangeToMove = getRangeToMove(context); - if (rangeToMove === void 0) - return void 0; - const all = []; - const ranges = []; - const { toMove, afterLast } = rangeToMove; - getRangesWhere(toMove, isAllowedStatementToMove, (start2, afterEndIndex) => { - for (let i = start2; i < afterEndIndex; i++) - all.push(toMove[i]); - ranges.push({ first: toMove[start2], afterLast }); - }); - return all.length === 0 ? void 0 : { all, ranges }; -} -function isAllowedStatementToMove(statement) { - return !isPureImport(statement) && !isPrologueDirective(statement); -} -function isPureImport(node) { - switch (node.kind) { - case 271 /* ImportDeclaration */: - return true; - case 270 /* ImportEqualsDeclaration */: - return !hasSyntacticModifier(node, 1 /* Export */); - case 242 /* VariableStatement */: - return node.declarationList.declarations.every((d) => !!d.initializer && isRequireCall( - d.initializer, - /*requireStringLiteralLikeArgument*/ - true - )); - default: - return false; - } -} -function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { - const cfg = program.getCompilerOptions().configFile; - if (!cfg) - return; - const newFileAbsolutePath = normalizePath(combinePaths(oldFileName, "..", newFileNameWithExtension)); - 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) => 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); - } -} -function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences) { - const checker = program.getTypeChecker(); - const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective); - if (oldFile.externalModuleIndicator === void 0 && oldFile.commonJsModuleIndicator === void 0 && usage.oldImportsNeededByNewFile.size() === 0) { - deleteMovedStatements(oldFile, toMove.ranges, changes); - return [...prologueDirectives, ...toMove.all]; - } - const useEsModuleSyntax = !!oldFile.externalModuleIndicator; - const quotePreference = getQuotePreference(oldFile, preferences); - const importsFromNewFile = createOldFileImportsFromNewFile(oldFile, usage.oldFileImportsFromNewFile, newFilename, program, host, useEsModuleSyntax, quotePreference); - if (importsFromNewFile) { - insertImports( - changes, - oldFile, - importsFromNewFile, - /*blankLineBetween*/ - true, - preferences - ); - } - deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); - deleteMovedStatements(oldFile, toMove.ranges, changes); - updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, newFilename, quotePreference); - const imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference); - const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEsModuleSyntax); - if (imports.length && body.length) { - return [ - ...prologueDirectives, - ...imports, - 4 /* NewLineTrivia */, - ...body - ]; - } - return [ - ...prologueDirectives, - ...imports, - ...body - ]; -} -function deleteMovedStatements(sourceFile, moved, changes) { - for (const { first: first2, afterLast } of moved) { - changes.deleteNodeRangeExcludingEnd(sourceFile, first2, afterLast); - } -} -function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { - for (const statement of oldFile.statements) { - if (contains(toMove, statement)) - continue; - forEachImportInStatement(statement, (i) => deleteUnusedImports(oldFile, i, changes, (name) => toDelete.has(checker.getSymbolAtLocation(name)))); - } -} -function updateImportsInOtherFiles(changes, program, host, oldFile, movedSymbols, newFilename, quotePreference) { - const checker = program.getTypeChecker(); - for (const sourceFile of program.getSourceFiles()) { - if (sourceFile === oldFile) - continue; - for (const statement of sourceFile.statements) { - forEachImportInStatement(statement, (importNode) => { - if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) - return; - const shouldMove = (name) => { - const symbol = isBindingElement(name.parent) ? getPropertySymbolFromBindingElement(checker, name.parent) : skipAlias(checker.getSymbolAtLocation(name), checker); - return !!symbol && movedSymbols.has(symbol); - }; - deleteUnusedImports(sourceFile, importNode, changes, shouldMove); - const pathToNewFileWithExtension = resolvePath(getDirectoryPath(oldFile.path), newFilename); - const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToNewFileWithExtension, createModuleSpecifierResolutionHost(program, host)); - const newImportDeclaration = filterImport(importNode, makeStringLiteral(newModuleSpecifier, quotePreference), shouldMove); - if (newImportDeclaration) - changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); - const ns = getNamespaceLikeImport(importNode); - if (ns) - updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, ns, importNode, quotePreference); - }); - } - } -} -function getNamespaceLikeImport(node) { - switch (node.kind) { - case 271 /* ImportDeclaration */: - return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 273 /* NamespaceImport */ ? node.importClause.namedBindings.name : void 0; - case 270 /* ImportEqualsDeclaration */: - return node.name; - case 259 /* VariableDeclaration */: - return tryCast(node.name, isIdentifier); - default: - return Debug.assertNever(node, `Unexpected node kind ${node.kind}`); - } -} -function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, oldImportId, oldImportNode, quotePreference) { - const preferredNewNamespaceName = ts_codefix_exports.moduleSpecifierToValidIdentifier(newModuleSpecifier, 99 /* ESNext */); - let needUniqueName = false; - const toChange = []; - ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, (ref) => { - if (!isPropertyAccessExpression(ref.parent)) - return; - needUniqueName = needUniqueName || !!checker.resolveName( - preferredNewNamespaceName, - ref, - 67108863 /* All */, - /*excludeGlobals*/ - true - ); - if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) { - toChange.push(ref); - } - }); - if (toChange.length) { - const newNamespaceName = needUniqueName ? getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; - for (const ref of toChange) { - changes.replaceNode(sourceFile, ref, factory.createIdentifier(newNamespaceName)); - } - changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, preferredNewNamespaceName, newModuleSpecifier, quotePreference)); - } -} -function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier, quotePreference) { - const newNamespaceId = factory.createIdentifier(newNamespaceName); - const newModuleString = makeStringLiteral(newModuleSpecifier, quotePreference); - switch (node.kind) { - case 271 /* ImportDeclaration */: - return factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - /*isTypeOnly*/ - false, - /*name*/ - void 0, - factory.createNamespaceImport(newNamespaceId) - ), - newModuleString, - /*assertClause*/ - void 0 - ); - case 270 /* ImportEqualsDeclaration */: - return factory.createImportEqualsDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - newNamespaceId, - factory.createExternalModuleReference(newModuleString) - ); - case 259 /* VariableDeclaration */: - return factory.createVariableDeclaration( - newNamespaceId, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - createRequireCall(newModuleString) - ); - default: - return Debug.assertNever(node, `Unexpected node kind ${node.kind}`); - } -} -function moduleSpecifierFromImport(i) { - return i.kind === 271 /* ImportDeclaration */ ? i.moduleSpecifier : i.kind === 270 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]; -} -function forEachImportInStatement(statement, cb) { - if (isImportDeclaration(statement)) { - if (isStringLiteral(statement.moduleSpecifier)) - cb(statement); - } else if (isImportEqualsDeclaration(statement)) { - if (isExternalModuleReference(statement.moduleReference) && isStringLiteralLike(statement.moduleReference.expression)) { - cb(statement); - } - } else if (isVariableStatement(statement)) { - for (const decl of statement.declarationList.declarations) { - if (decl.initializer && isRequireCall( - decl.initializer, - /*requireStringLiteralLikeArgument*/ - true - )) { - cb(decl); - } - } - } -} -function createOldFileImportsFromNewFile(sourceFile, newFileNeedExport, newFileNameWithExtension, program, host, useEs6Imports, quotePreference) { - let defaultImport; - const imports = []; - newFileNeedExport.forEach((symbol) => { - if (symbol.escapedName === "default" /* Default */) { - defaultImport = factory.createIdentifier(symbolNameNoDefault(symbol)); - } else { - imports.push(symbol.name); - } - }); - return makeImportOrRequire(sourceFile, defaultImport, imports, newFileNameWithExtension, program, host, useEs6Imports, quotePreference); -} -function makeImportOrRequire(sourceFile, defaultImport, imports, newFileNameWithExtension, program, host, useEs6Imports, quotePreference) { - const pathToNewFile = resolvePath(getDirectoryPath(sourceFile.path), newFileNameWithExtension); - const pathToNewFileWithCorrectExtension = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToNewFile, createModuleSpecifierResolutionHost(program, host)); - if (useEs6Imports) { - const specifiers = imports.map((i) => factory.createImportSpecifier( - /*isTypeOnly*/ - false, - /*propertyName*/ - void 0, - factory.createIdentifier(i) - )); - return makeImportIfNecessary(defaultImport, specifiers, pathToNewFileWithCorrectExtension, quotePreference); - } else { - Debug.assert(!defaultImport, "No default import should exist"); - const bindingElements = imports.map((i) => factory.createBindingElement( - /*dotDotDotToken*/ - void 0, - /*propertyName*/ - void 0, - i - )); - return bindingElements.length ? makeVariableStatement( - factory.createObjectBindingPattern(bindingElements), - /*type*/ - void 0, - createRequireCall(makeStringLiteral(pathToNewFileWithCorrectExtension, quotePreference)) - ) : void 0; - } -} -function makeVariableStatement(name, type, initializer, flags = 2 /* Const */) { - return factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([factory.createVariableDeclaration( - name, - /*exclamationToken*/ - void 0, - type, - initializer - )], flags) - ); -} -function createRequireCall(moduleSpecifier) { - return factory.createCallExpression( - factory.createIdentifier("require"), - /*typeArguments*/ - void 0, - [moduleSpecifier] - ); -} -function addExports(sourceFile, toMove, needExport, useEs6Exports) { - return flatMap(toMove, (statement) => { - if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, (d) => { - var _a; - return needExport.has(Debug.checkDefined((_a = tryCast(d, canHaveSymbol)) == null ? void 0 : _a.symbol)); - })) { - const exports = addExport(statement, useEs6Exports); - if (exports) - return exports; - } - return statement; - }); -} -function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { - switch (importDecl.kind) { - case 271 /* ImportDeclaration */: - deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); - break; - case 270 /* ImportEqualsDeclaration */: - if (isUnused(importDecl.name)) { - changes.delete(sourceFile, importDecl); - } - break; - case 259 /* VariableDeclaration */: - deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); - break; - default: - Debug.assertNever(importDecl, `Unexpected import decl kind ${importDecl.kind}`); - } -} -function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { - if (!importDecl.importClause) - return; - const { name, namedBindings } = importDecl.importClause; - const defaultUnused = !name || isUnused(name); - const namedBindingsUnused = !namedBindings || (namedBindings.kind === 273 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every((e) => isUnused(e.name))); - if (defaultUnused && namedBindingsUnused) { - changes.delete(sourceFile, importDecl); - } else { - if (name && defaultUnused) { - changes.delete(sourceFile, name); - } - if (namedBindings) { - if (namedBindingsUnused) { - changes.replaceNode( - sourceFile, - importDecl.importClause, - factory.updateImportClause( - importDecl.importClause, - importDecl.importClause.isTypeOnly, - name, - /*namedBindings*/ - void 0 - ) - ); - } else if (namedBindings.kind === 274 /* NamedImports */) { - for (const element of namedBindings.elements) { - if (isUnused(element.name)) - changes.delete(sourceFile, element); - } - } - } - } -} -function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { - const { name } = varDecl; - switch (name.kind) { - case 80 /* 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 - ); - } else { - changes.delete(sourceFile, name); - } - } - break; - case 206 /* ArrayBindingPattern */: - break; - case 205 /* 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 - ); - } else { - for (const element of name.elements) { - if (isIdentifier(element.name) && isUnused(element.name)) { - changes.delete(sourceFile, element.name); - } - } - } - break; - } -} -function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference) { - const copiedOldImports = []; - for (const oldStatement of oldFile.statements) { - forEachImportInStatement(oldStatement, (i) => { - append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); - }); - } - let oldFileDefault; - const oldFileNamedImports = []; - const markSeenTop = nodeSeenTracker(); - newFileImportsFromOldFile.forEach((symbol) => { - if (!symbol.declarations) { - return; - } - for (const decl of symbol.declarations) { - if (!isTopLevelDeclaration(decl)) - continue; - const name = nameOfTopLevelDeclaration(decl); - if (!name) - continue; - const top = getTopLevelDeclarationStatement(decl); - if (markSeenTop(top)) { - addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); - } - if (hasSyntacticModifier(decl, 1024 /* Default */)) { - oldFileDefault = name; - } else { - oldFileNamedImports.push(name.text); - } - } - }); - append(copiedOldImports, makeImportOrRequire(oldFile, oldFileDefault, oldFileNamedImports, getBaseFileName(oldFile.fileName), program, host, useEsModuleSyntax, quotePreference)); - return copiedOldImports; -} -function makeUniqueFilename(proposedFilename, extension, inDirectory, host) { - let newFilename = proposedFilename; - for (let i = 1; ; i++) { - const name = combinePaths(inDirectory, newFilename + extension); - if (!host.fileExists(name)) - return newFilename; - newFilename = `${proposedFilename}.${i}`; - } -} -function inferNewFilename(importsFromNewFile, movedSymbols) { - return importsFromNewFile.forEachEntry(symbolNameNoDefault) || movedSymbols.forEachEntry(symbolNameNoDefault) || "newFile"; -} -function getUsageInfo(oldFile, toMove, checker) { - const movedSymbols = new SymbolSet(); - const oldImportsNeededByNewFile = new SymbolSet(); - const newFileImportsFromOldFile = new SymbolSet(); - const containsJsx = find(toMove, (statement) => !!(statement.transformFlags & 2 /* ContainsJsx */)); - const jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx); - if (jsxNamespaceSymbol) { - oldImportsNeededByNewFile.add(jsxNamespaceSymbol); - } - for (const statement of toMove) { - forEachTopLevelDeclaration(statement, (decl) => { - movedSymbols.add(Debug.checkDefined(isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here")); - }); - } - for (const statement of toMove) { - forEachReference(statement, checker, (symbol) => { - if (!symbol.declarations) - return; - for (const decl of symbol.declarations) { - if (isInImport(decl)) { - oldImportsNeededByNewFile.add(symbol); - } else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) { - newFileImportsFromOldFile.add(symbol); - } - } - }); - } - const unusedImportsFromOldFile = oldImportsNeededByNewFile.clone(); - const oldFileImportsFromNewFile = new SymbolSet(); - for (const statement of oldFile.statements) { - if (contains(toMove, statement)) - continue; - if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) { - unusedImportsFromOldFile.delete(jsxNamespaceSymbol); - } - forEachReference(statement, checker, (symbol) => { - if (movedSymbols.has(symbol)) - oldFileImportsFromNewFile.add(symbol); - unusedImportsFromOldFile.delete(symbol); - }); - } - return { movedSymbols, newFileImportsFromOldFile, oldFileImportsFromNewFile, oldImportsNeededByNewFile, unusedImportsFromOldFile }; - function getJsxNamespaceSymbol(containsJsx2) { - if (containsJsx2 === void 0) { - return void 0; - } - const jsxNamespace = checker.getJsxNamespace(containsJsx2); - const jsxNamespaceSymbol2 = checker.resolveName( - jsxNamespace, - containsJsx2, - 1920 /* Namespace */, - /*excludeGlobals*/ - true - ); - return !!jsxNamespaceSymbol2 && some(jsxNamespaceSymbol2.declarations, isInImport) ? jsxNamespaceSymbol2 : void 0; - } -} -function isInImport(decl) { - switch (decl.kind) { - case 270 /* ImportEqualsDeclaration */: - case 275 /* ImportSpecifier */: - case 272 /* ImportClause */: - case 273 /* NamespaceImport */: - return true; - case 259 /* VariableDeclaration */: - return isVariableDeclarationInImport(decl); - case 207 /* BindingElement */: - return isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); - default: - return false; - } -} -function isVariableDeclarationInImport(decl) { - return isSourceFile(decl.parent.parent.parent) && !!decl.initializer && isRequireCall( - decl.initializer, - /*requireStringLiteralLikeArgument*/ - true - ); -} -function filterImport(i, moduleSpecifier, keep) { - switch (i.kind) { - case 271 /* ImportDeclaration */: { - const clause = i.importClause; - if (!clause) - return void 0; - const defaultImport = clause.name && keep(clause.name) ? clause.name : void 0; - const namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); - return defaultImport || namedBindings ? factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause(clause.isTypeOnly, defaultImport, namedBindings), - moduleSpecifier, - /*assertClause*/ - void 0 - ) : void 0; - } - case 270 /* ImportEqualsDeclaration */: - return keep(i.name) ? i : void 0; - case 259 /* VariableDeclaration */: { - const name = filterBindingName(i.name, keep); - return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : void 0; - } - default: - return Debug.assertNever(i, `Unexpected import kind ${i.kind}`); - } -} -function filterNamedBindings(namedBindings, keep) { - if (namedBindings.kind === 273 /* NamespaceImport */) { - return keep(namedBindings.name) ? namedBindings : void 0; - } else { - const newElements = namedBindings.elements.filter((e) => keep(e.name)); - return newElements.length ? factory.createNamedImports(newElements) : void 0; - } -} -function filterBindingName(name, keep) { - switch (name.kind) { - case 80 /* Identifier */: - return keep(name) ? name : void 0; - case 206 /* ArrayBindingPattern */: - return name; - case 205 /* ObjectBindingPattern */: { - const newElements = name.elements.filter((prop) => prop.propertyName || !isIdentifier(prop.name) || keep(prop.name)); - return newElements.length ? factory.createObjectBindingPattern(newElements) : void 0; - } - } -} -function forEachReference(node, checker, onReference) { - node.forEachChild(function cb(node2) { - if (isIdentifier(node2) && !isDeclarationName(node2)) { - const sym = checker.getSymbolAtLocation(node2); - if (sym) - onReference(sym); - } else { - node2.forEachChild(cb); - } - }); -} -var SymbolSet = class { - constructor() { - this.map = /* @__PURE__ */ new Map(); - } - add(symbol) { - this.map.set(String(getSymbolId(symbol)), symbol); - } - has(symbol) { - return this.map.has(String(getSymbolId(symbol))); - } - delete(symbol) { - this.map.delete(String(getSymbolId(symbol))); - } - forEach(cb) { - this.map.forEach(cb); - } - forEachEntry(cb) { - return forEachEntry(this.map, cb); - } - clone() { - const clone2 = new SymbolSet(); - copyEntries(this.map, clone2.map); - return clone2; - } - size() { - return this.map.size; - } -}; -function isTopLevelDeclaration(node) { - return isNonVariableTopLevelDeclaration(node) && isSourceFile(node.parent) || isVariableDeclaration(node) && isSourceFile(node.parent.parent.parent); -} -function sourceFileOfTopLevelDeclaration(node) { - return isVariableDeclaration(node) ? node.parent.parent.parent : node.parent; -} -function isTopLevelDeclarationStatement(node) { - Debug.assert(isSourceFile(node.parent), "Node parent should be a SourceFile"); - return isNonVariableTopLevelDeclaration(node) || isVariableStatement(node); -} -function isNonVariableTopLevelDeclaration(node) { - switch (node.kind) { - case 261 /* FunctionDeclaration */: - case 262 /* ClassDeclaration */: - case 266 /* ModuleDeclaration */: - case 265 /* EnumDeclaration */: - case 264 /* TypeAliasDeclaration */: - case 263 /* InterfaceDeclaration */: - case 270 /* ImportEqualsDeclaration */: - return true; - default: - return false; - } -} -function forEachTopLevelDeclaration(statement, cb) { - switch (statement.kind) { - case 261 /* FunctionDeclaration */: - case 262 /* ClassDeclaration */: - case 266 /* ModuleDeclaration */: - case 265 /* EnumDeclaration */: - case 264 /* TypeAliasDeclaration */: - case 263 /* InterfaceDeclaration */: - case 270 /* ImportEqualsDeclaration */: - return cb(statement); - case 242 /* VariableStatement */: - return firstDefined(statement.declarationList.declarations, (decl) => forEachTopLevelDeclarationInBindingName(decl.name, cb)); - case 243 /* ExpressionStatement */: { - const { expression } = statement; - return isBinaryExpression(expression) && getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : void 0; - } - } -} -function forEachTopLevelDeclarationInBindingName(name, cb) { - switch (name.kind) { - case 80 /* Identifier */: - return cb(cast(name.parent, (x) => isVariableDeclaration(x) || isBindingElement(x))); - case 206 /* ArrayBindingPattern */: - case 205 /* ObjectBindingPattern */: - return firstDefined(name.elements, (em) => isOmittedExpression(em) ? void 0 : forEachTopLevelDeclarationInBindingName(em.name, cb)); - default: - return Debug.assertNever(name, `Unexpected name kind ${name.kind}`); - } -} -function nameOfTopLevelDeclaration(d) { - return isExpressionStatement(d) ? tryCast(d.expression.left.name, isIdentifier) : tryCast(d.name, isIdentifier); -} -function getTopLevelDeclarationStatement(d) { - switch (d.kind) { - case 259 /* VariableDeclaration */: - return d.parent.parent; - case 207 /* BindingElement */: - return getTopLevelDeclarationStatement( - cast(d.parent.parent, (p) => isVariableDeclaration(p) || isBindingElement(p)) - ); - default: - return d; - } -} -function addExportToChanges(sourceFile, decl, name, changes, useEs6Exports) { - if (isExported(sourceFile, decl, useEs6Exports, name)) - return; - if (useEs6Exports) { - if (!isExpressionStatement(decl)) - changes.insertExportModifier(sourceFile, decl); - } else { - const names = getNamesToExportInCommonJS(decl); - if (names.length !== 0) - changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); - } -} -function isExported(sourceFile, decl, useEs6Exports, name) { - var _a; - if (useEs6Exports) { - return !isExpressionStatement(decl) && hasSyntacticModifier(decl, 1 /* Export */) || !!(name && ((_a = sourceFile.symbol.exports) == null ? void 0 : _a.has(name.escapedText))); - } - return !!sourceFile.symbol && !!sourceFile.symbol.exports && getNamesToExportInCommonJS(decl).some((name2) => sourceFile.symbol.exports.has(escapeLeadingUnderscores(name2))); -} -function addExport(decl, useEs6Exports) { - return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); -} -function addEs6Export(d) { - const modifiers = canHaveModifiers(d) ? concatenate([factory.createModifier(95 /* ExportKeyword */)], getModifiers(d)) : void 0; - switch (d.kind) { - case 261 /* FunctionDeclaration */: - return factory.updateFunctionDeclaration(d, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); - case 262 /* ClassDeclaration */: - const decorators = canHaveDecorators(d) ? getDecorators(d) : void 0; - return factory.updateClassDeclaration(d, concatenate(decorators, modifiers), d.name, d.typeParameters, d.heritageClauses, d.members); - case 242 /* VariableStatement */: - return factory.updateVariableStatement(d, modifiers, d.declarationList); - case 266 /* ModuleDeclaration */: - return factory.updateModuleDeclaration(d, modifiers, d.name, d.body); - case 265 /* EnumDeclaration */: - return factory.updateEnumDeclaration(d, modifiers, d.name, d.members); - case 264 /* TypeAliasDeclaration */: - return factory.updateTypeAliasDeclaration(d, modifiers, d.name, d.typeParameters, d.type); - case 263 /* InterfaceDeclaration */: - return factory.updateInterfaceDeclaration(d, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 270 /* ImportEqualsDeclaration */: - return factory.updateImportEqualsDeclaration(d, modifiers, d.isTypeOnly, d.name, d.moduleReference); - case 243 /* ExpressionStatement */: - return Debug.fail(); - default: - return Debug.assertNever(d, `Unexpected declaration kind ${d.kind}`); - } -} -function addCommonjsExport(decl) { - return [decl, ...getNamesToExportInCommonJS(decl).map(createExportAssignment)]; -} -function getNamesToExportInCommonJS(decl) { - switch (decl.kind) { - case 261 /* FunctionDeclaration */: - case 262 /* ClassDeclaration */: - return [decl.name.text]; - case 242 /* VariableStatement */: - return mapDefined(decl.declarationList.declarations, (d) => isIdentifier(d.name) ? d.name.text : void 0); - case 266 /* ModuleDeclaration */: - case 265 /* EnumDeclaration */: - case 264 /* TypeAliasDeclaration */: - case 263 /* InterfaceDeclaration */: - case 270 /* ImportEqualsDeclaration */: - return emptyArray; - case 243 /* ExpressionStatement */: - return Debug.fail("Can't export an ExpressionStatement"); - default: - return Debug.assertNever(decl, `Unexpected decl kind ${decl.kind}`); - } -} -function createExportAssignment(name) { - return factory.createExpressionStatement( - factory.createBinaryExpression( - factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(name)), - 64 /* EqualsToken */, - factory.createIdentifier(name) - ) - ); -} - -// src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts -var ts_refactor_addOrRemoveBracesToArrowFunction_exports = {}; - -// src/services/refactors/convertOverloadListToSingleSignature.ts -var refactorName5 = "Convert overload list to single signature"; -var refactorDescription = Diagnostics.Convert_overload_list_to_single_signature.message; -var functionOverloadAction = { - name: refactorName5, - description: refactorDescription, - kind: "refactor.rewrite.function.overloadList" -}; -registerRefactor(refactorName5, { - kinds: [functionOverloadAction.kind], - getEditsForAction: getRefactorEditsToConvertOverloadsToOneSignature, - getAvailableActions: getRefactorActionsToConvertOverloadsToOneSignature -}); -function getRefactorActionsToConvertOverloadsToOneSignature(context) { - const { file, startPosition, program } = context; - const info = getConvertableOverloadListAtPosition(file, startPosition, program); - if (!info) - return emptyArray; - return [{ - name: refactorName5, - description: refactorDescription, - actions: [functionOverloadAction] - }]; -} -function getRefactorEditsToConvertOverloadsToOneSignature(context) { - const { file, startPosition, program } = context; - const signatureDecls = getConvertableOverloadListAtPosition(file, startPosition, program); - if (!signatureDecls) - return void 0; - const checker = program.getTypeChecker(); - const lastDeclaration = signatureDecls[signatureDecls.length - 1]; - let updated = lastDeclaration; - switch (lastDeclaration.kind) { - case 172 /* MethodSignature */: { - updated = factory.updateMethodSignature( - lastDeclaration, - lastDeclaration.modifiers, - lastDeclaration.name, - lastDeclaration.questionToken, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type - ); - break; - } - case 173 /* MethodDeclaration */: { - updated = factory.updateMethodDeclaration( - lastDeclaration, - lastDeclaration.modifiers, - lastDeclaration.asteriskToken, - lastDeclaration.name, - lastDeclaration.questionToken, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type, - lastDeclaration.body - ); - break; - } - case 178 /* CallSignature */: { - updated = factory.updateCallSignature( - lastDeclaration, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type - ); - break; - } - case 175 /* Constructor */: { - updated = factory.updateConstructorDeclaration( - lastDeclaration, - lastDeclaration.modifiers, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.body - ); - break; - } - case 179 /* ConstructSignature */: { - updated = factory.updateConstructSignature( - lastDeclaration, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type - ); - break; - } - case 261 /* FunctionDeclaration */: { - updated = factory.updateFunctionDeclaration( - lastDeclaration, - lastDeclaration.modifiers, - lastDeclaration.asteriskToken, - lastDeclaration.name, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type, - lastDeclaration.body - ); - break; - } - default: - return Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring"); - } - if (updated === lastDeclaration) { - return; - } - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => { - t.replaceNodeRange(file, signatureDecls[0], signatureDecls[signatureDecls.length - 1], updated); - }); - return { renameFilename: void 0, renameLocation: void 0, edits }; - function getNewParametersForCombinedSignature(signatureDeclarations) { - const lastSig = signatureDeclarations[signatureDeclarations.length - 1]; - if (isFunctionLikeDeclaration(lastSig) && lastSig.body) { - signatureDeclarations = signatureDeclarations.slice(0, signatureDeclarations.length - 1); - } - return factory.createNodeArray([ - factory.createParameterDeclaration( - /*modifiers*/ - void 0, - factory.createToken(26 /* DotDotDotToken */), - "args", - /*questionToken*/ - void 0, - factory.createUnionTypeNode(map(signatureDeclarations, convertSignatureParametersToTuple)) - ) - ]); - } - function convertSignatureParametersToTuple(decl) { - const members = map(decl.parameters, convertParameterToNamedTupleMember); - return setEmitFlags(factory.createTupleTypeNode(members), some(members, (m) => !!length(getSyntheticLeadingComments(m))) ? 0 /* None */ : 1 /* SingleLine */); - } - function convertParameterToNamedTupleMember(p) { - Debug.assert(isIdentifier(p.name)); - const result = setTextRange(factory.createNamedTupleMember( - p.dotDotDotToken, - p.name, - p.questionToken, - p.type || factory.createKeywordTypeNode(133 /* AnyKeyword */) - ), p); - const parameterDocComment = p.symbol && p.symbol.getDocumentationComment(checker); - if (parameterDocComment) { - const newComment = displayPartsToString(parameterDocComment); - if (newComment.length) { - setSyntheticLeadingComments(result, [{ - text: `* -${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} - `, - kind: 3 /* MultiLineCommentTrivia */, - pos: -1, - end: -1, - hasTrailingNewLine: true, - hasLeadingNewline: true - }]); - } - } - return result; - } -} -function isConvertableSignatureDeclaration(d) { - switch (d.kind) { - case 172 /* MethodSignature */: - case 173 /* MethodDeclaration */: - case 178 /* CallSignature */: - case 175 /* Constructor */: - case 179 /* ConstructSignature */: - case 261 /* FunctionDeclaration */: - return true; - } - return false; -} -function getConvertableOverloadListAtPosition(file, startPosition, program) { - const node = getTokenAtPosition(file, startPosition); - const containingDecl = findAncestor(node, isConvertableSignatureDeclaration); - if (!containingDecl) { - return; - } - if (isFunctionLikeDeclaration(containingDecl) && containingDecl.body && rangeContainsPosition(containingDecl.body, startPosition)) { - return; - } - const checker = program.getTypeChecker(); - const signatureSymbol = containingDecl.symbol; - if (!signatureSymbol) { - return; - } - const decls = signatureSymbol.declarations; - if (length(decls) <= 1) { - return; - } - if (!every(decls, (d) => getSourceFileOfNode(d) === file)) { - return; - } - if (!isConvertableSignatureDeclaration(decls[0])) { - return; - } - const kindOne = decls[0].kind; - if (!every(decls, (d) => d.kind === kindOne)) { - return; - } - const signatureDecls = decls; - if (some(signatureDecls, (d) => !!d.typeParameters || some(d.parameters, (p) => !!p.modifiers || !isIdentifier(p.name)))) { - return; - } - const signatures = mapDefined(signatureDecls, (d) => checker.getSignatureFromDeclaration(d)); - if (length(signatures) !== length(decls)) { - return; - } - const returnOne = checker.getReturnTypeOfSignature(signatures[0]); - if (!every(signatures, (s) => checker.getReturnTypeOfSignature(s) === returnOne)) { - return; - } - return signatureDecls; -} - -// src/services/refactors/addOrRemoveBracesToArrowFunction.ts -var refactorName6 = "Add or remove braces in an arrow function"; -var refactorDescription2 = Diagnostics.Add_or_remove_braces_in_an_arrow_function.message; -var addBracesAction = { - name: "Add braces to arrow function", - description: Diagnostics.Add_braces_to_arrow_function.message, - kind: "refactor.rewrite.arrow.braces.add" -}; -var removeBracesAction = { - name: "Remove braces from arrow function", - description: Diagnostics.Remove_braces_from_arrow_function.message, - kind: "refactor.rewrite.arrow.braces.remove" -}; -registerRefactor(refactorName6, { - kinds: [removeBracesAction.kind], - getEditsForAction: getRefactorEditsToRemoveFunctionBraces, - getAvailableActions: getRefactorActionsToRemoveFunctionBraces -}); -function getRefactorActionsToRemoveFunctionBraces(context) { - const { file, startPosition, triggerReason } = context; - const info = getConvertibleArrowFunctionAtPosition(file, startPosition, triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - return [{ - name: refactorName6, - description: refactorDescription2, - actions: [ - info.addBraces ? addBracesAction : removeBracesAction - ] - }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorName6, - description: refactorDescription2, - actions: [ - { ...addBracesAction, notApplicableReason: info.error }, - { ...removeBracesAction, notApplicableReason: info.error } - ] - }]; - } - return emptyArray; -} -function getRefactorEditsToRemoveFunctionBraces(context, actionName2) { - const { file, startPosition } = context; - const info = getConvertibleArrowFunctionAtPosition(file, startPosition); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const { expression, returnStatement, func } = info; - let body; - if (actionName2 === addBracesAction.name) { - const returnStatement2 = factory.createReturnStatement(expression); - body = factory.createBlock( - [returnStatement2], - /*multiLine*/ - true - ); - copyLeadingComments( - expression, - returnStatement2, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - true - ); - } else if (actionName2 === removeBracesAction.name && returnStatement) { - const actualExpression = expression || factory.createVoidZero(); - body = needsParentheses(actualExpression) ? factory.createParenthesizedExpression(actualExpression) : actualExpression; - copyTrailingAsLeadingComments( - returnStatement, - body, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - copyLeadingComments( - returnStatement, - body, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - copyTrailingComments( - returnStatement, - body, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - } else { - Debug.fail("invalid action"); - } - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => { - t.replaceNode(file, func.body, body); - }); - return { renameFilename: void 0, renameLocation: void 0, edits }; -} -function getConvertibleArrowFunctionAtPosition(file, startPosition, considerFunctionBodies = true, kind) { - const node = getTokenAtPosition(file, startPosition); - const func = getContainingFunction(node); - if (!func) { - return { - error: getLocaleSpecificMessage(Diagnostics.Could_not_find_a_containing_arrow_function) - }; - } - if (!isArrowFunction(func)) { - return { - error: getLocaleSpecificMessage(Diagnostics.Containing_function_is_not_an_arrow_function) - }; - } - if (!rangeContainsRange(func, node) || rangeContainsRange(func.body, node) && !considerFunctionBodies) { - return void 0; - } - if (refactorKindBeginsWith(addBracesAction.kind, kind) && isExpression(func.body)) { - return { func, addBraces: true, expression: func.body }; - } else if (refactorKindBeginsWith(removeBracesAction.kind, kind) && isBlock(func.body) && func.body.statements.length === 1) { - const firstStatement = first(func.body.statements); - if (isReturnStatement(firstStatement)) { - return { func, addBraces: false, expression: firstStatement.expression, returnStatement: firstStatement }; - } - } - return void 0; -} - -// src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts -var ts_refactor_convertArrowFunctionOrFunctionExpression_exports = {}; - -// src/services/refactors/convertArrowFunctionOrFunctionExpression.ts -var refactorName7 = "Convert arrow function or function expression"; -var refactorDescription3 = getLocaleSpecificMessage(Diagnostics.Convert_arrow_function_or_function_expression); -var toAnonymousFunctionAction = { - name: "Convert to anonymous function", - description: getLocaleSpecificMessage(Diagnostics.Convert_to_anonymous_function), - kind: "refactor.rewrite.function.anonymous" -}; -var toNamedFunctionAction = { - name: "Convert to named function", - description: getLocaleSpecificMessage(Diagnostics.Convert_to_named_function), - kind: "refactor.rewrite.function.named" -}; -var toArrowFunctionAction = { - name: "Convert to arrow function", - description: getLocaleSpecificMessage(Diagnostics.Convert_to_arrow_function), - kind: "refactor.rewrite.function.arrow" -}; -registerRefactor(refactorName7, { - kinds: [ - toAnonymousFunctionAction.kind, - toNamedFunctionAction.kind, - toArrowFunctionAction.kind - ], - getEditsForAction: getRefactorEditsToConvertFunctionExpressions, - getAvailableActions: getRefactorActionsToConvertFunctionExpressions -}); -function getRefactorActionsToConvertFunctionExpressions(context) { - const { file, startPosition, program, kind } = context; - const info = getFunctionInfo(file, startPosition, program); - if (!info) - return emptyArray; - const { selectedVariableDeclaration, func } = info; - const possibleActions = []; - const errors = []; - if (refactorKindBeginsWith(toNamedFunctionAction.kind, kind)) { - const error = selectedVariableDeclaration || isArrowFunction(func) && isVariableDeclaration(func.parent) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_named_function); - if (error) { - errors.push({ ...toNamedFunctionAction, notApplicableReason: error }); - } else { - possibleActions.push(toNamedFunctionAction); - } - } - if (refactorKindBeginsWith(toAnonymousFunctionAction.kind, kind)) { - const error = !selectedVariableDeclaration && isArrowFunction(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_anonymous_function); - if (error) { - errors.push({ ...toAnonymousFunctionAction, notApplicableReason: error }); - } else { - possibleActions.push(toAnonymousFunctionAction); - } - } - if (refactorKindBeginsWith(toArrowFunctionAction.kind, kind)) { - const error = isFunctionExpression(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_arrow_function); - if (error) { - errors.push({ ...toArrowFunctionAction, notApplicableReason: error }); - } else { - possibleActions.push(toArrowFunctionAction); - } - } - return [{ - name: refactorName7, - description: refactorDescription3, - actions: possibleActions.length === 0 && context.preferences.provideRefactorNotApplicableReason ? errors : possibleActions - }]; -} -function getRefactorEditsToConvertFunctionExpressions(context, actionName2) { - const { file, startPosition, program } = context; - const info = getFunctionInfo(file, startPosition, program); - if (!info) - return void 0; - const { func } = info; - const edits = []; - switch (actionName2) { - case toAnonymousFunctionAction.name: - edits.push(...getEditInfoForConvertToAnonymousFunction(context, func)); - break; - case toNamedFunctionAction.name: - const variableInfo = getVariableInfo(func); - if (!variableInfo) - return void 0; - edits.push(...getEditInfoForConvertToNamedFunction(context, func, variableInfo)); - break; - case toArrowFunctionAction.name: - if (!isFunctionExpression(func)) - return void 0; - edits.push(...getEditInfoForConvertToArrowFunction(context, func)); - break; - default: - return Debug.fail("invalid action"); - } - return { renameFilename: void 0, renameLocation: void 0, edits }; -} -function containingThis(node) { - let containsThis = false; - node.forEachChild(function checkThis(child) { - if (isThis(child)) { - containsThis = true; - return; - } - if (!isClassLike(child) && !isFunctionDeclaration(child) && !isFunctionExpression(child)) { - forEachChild(child, checkThis); - } - }); - return containsThis; -} -function getFunctionInfo(file, startPosition, program) { - const token = getTokenAtPosition(file, startPosition); - const typeChecker = program.getTypeChecker(); - const func = tryGetFunctionFromVariableDeclaration(file, typeChecker, token.parent); - if (func && !containingThis(func.body) && !typeChecker.containsArgumentsReference(func)) { - return { selectedVariableDeclaration: true, func }; - } - const maybeFunc = getContainingFunction(token); - if (maybeFunc && (isFunctionExpression(maybeFunc) || isArrowFunction(maybeFunc)) && !rangeContainsRange(maybeFunc.body, token) && !containingThis(maybeFunc.body) && !typeChecker.containsArgumentsReference(maybeFunc)) { - if (isFunctionExpression(maybeFunc) && isFunctionReferencedInFile(file, typeChecker, maybeFunc)) - return void 0; - return { selectedVariableDeclaration: false, func: maybeFunc }; - } - return void 0; -} -function isSingleVariableDeclaration(parent2) { - return isVariableDeclaration(parent2) || isVariableDeclarationList(parent2) && parent2.declarations.length === 1; -} -function tryGetFunctionFromVariableDeclaration(sourceFile, typeChecker, parent2) { - if (!isSingleVariableDeclaration(parent2)) { - return void 0; - } - const variableDeclaration = isVariableDeclaration(parent2) ? parent2 : first(parent2.declarations); - const initializer = variableDeclaration.initializer; - if (initializer && (isArrowFunction(initializer) || isFunctionExpression(initializer) && !isFunctionReferencedInFile(sourceFile, typeChecker, initializer))) { - return initializer; - } - return void 0; -} -function convertToBlock(body) { - if (isExpression(body)) { - const returnStatement = factory.createReturnStatement(body); - const file = body.getSourceFile(); - setTextRange(returnStatement, body); - suppressLeadingAndTrailingTrivia(returnStatement); - copyTrailingAsLeadingComments( - body, - returnStatement, - file, - /*commentKind*/ - void 0, - /*hasTrailingNewLine*/ - true - ); - return factory.createBlock( - [returnStatement], - /*multiLine*/ - true - ); - } else { - return body; - } -} -function getVariableInfo(func) { - const variableDeclaration = func.parent; - if (!isVariableDeclaration(variableDeclaration) || !isVariableDeclarationInVariableStatement(variableDeclaration)) - return void 0; - const variableDeclarationList = variableDeclaration.parent; - const statement = variableDeclarationList.parent; - if (!isVariableDeclarationList(variableDeclarationList) || !isVariableStatement(statement) || !isIdentifier(variableDeclaration.name)) - return void 0; - return { variableDeclaration, variableDeclarationList, statement, name: variableDeclaration.name }; -} -function getEditInfoForConvertToAnonymousFunction(context, func) { - const { file } = context; - const body = convertToBlock(func.body); - const newNode = factory.createFunctionExpression( - func.modifiers, - func.asteriskToken, - /*name*/ - void 0, - func.typeParameters, - func.parameters, - func.type, - body - ); - return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode)); -} -function getEditInfoForConvertToNamedFunction(context, func, variableInfo) { - const { file } = context; - const body = convertToBlock(func.body); - const { variableDeclaration, variableDeclarationList, statement, name } = variableInfo; - suppressLeadingTrivia(statement); - const modifiersFlags = getCombinedModifierFlags(variableDeclaration) & 1 /* Export */ | getEffectiveModifierFlags(func); - const modifiers = factory.createModifiersFromModifierFlags(modifiersFlags); - const newNode = factory.createFunctionDeclaration(length(modifiers) ? modifiers : void 0, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); - if (variableDeclarationList.declarations.length === 1) { - return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, statement, newNode)); - } else { - return ts_textChanges_exports.ChangeTracker.with(context, (t) => { - t.delete(file, variableDeclaration); - t.insertNodeAfter(file, statement, newNode); - }); - } -} -function getEditInfoForConvertToArrowFunction(context, func) { - const { file } = context; - const statements = func.body.statements; - const head = statements[0]; - let body; - if (canBeConvertedToExpression(func.body, head)) { - body = head.expression; - suppressLeadingAndTrailingTrivia(body); - copyComments(head, body); - } else { - body = func.body; - } - const newNode = factory.createArrowFunction(func.modifiers, func.typeParameters, func.parameters, func.type, factory.createToken(39 /* EqualsGreaterThanToken */), body); - return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode)); -} -function canBeConvertedToExpression(body, head) { - return body.statements.length === 1 && (isReturnStatement(head) && !!head.expression); -} -function isFunctionReferencedInFile(sourceFile, typeChecker, node) { - return !!node.name && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(node.name, typeChecker, sourceFile); -} - -// src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts -var ts_refactor_convertParamsToDestructuredObject_exports = {}; - -// src/services/refactors/convertParamsToDestructuredObject.ts -var refactorName8 = "Convert parameters to destructured object"; -var minimumParameterLength = 1; -var refactorDescription4 = getLocaleSpecificMessage(Diagnostics.Convert_parameters_to_destructured_object); -var toDestructuredAction = { - name: refactorName8, - description: refactorDescription4, - kind: "refactor.rewrite.parameters.toDestructured" -}; -registerRefactor(refactorName8, { - kinds: [toDestructuredAction.kind], - getEditsForAction: getRefactorEditsToConvertParametersToDestructuredObject, - getAvailableActions: getRefactorActionsToConvertParametersToDestructuredObject -}); -function getRefactorActionsToConvertParametersToDestructuredObject(context) { - const { file, startPosition } = context; - const isJSFile = isSourceFileJS(file); - if (isJSFile) - return emptyArray; - const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker()); - if (!functionDeclaration) - return emptyArray; - return [{ - name: refactorName8, - description: refactorDescription4, - actions: [toDestructuredAction] - }]; -} -function getRefactorEditsToConvertParametersToDestructuredObject(context, actionName2) { - Debug.assert(actionName2 === refactorName8, "Unexpected action name"); - const { file, startPosition, program, cancellationToken, host } = context; - const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); - if (!functionDeclaration || !cancellationToken) - return void 0; - const groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken); - if (groupedReferences.valid) { - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange37(file, program, host, t, functionDeclaration, groupedReferences)); - return { renameFilename: void 0, renameLocation: void 0, edits }; - } - return { edits: [] }; -} -function doChange37(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { - const signature = groupedReferences.signature; - const newFunctionDeclarationParams = map(createNewParameters(functionDeclaration, program, host), (param) => getSynthesizedDeepClone(param)); - if (signature) { - const newSignatureParams = map(createNewParameters(signature, program, host), (param) => getSynthesizedDeepClone(param)); - replaceParameters(signature, newSignatureParams); - } - replaceParameters(functionDeclaration, newFunctionDeclarationParams); - const functionCalls = sortAndDeduplicate( - groupedReferences.functionCalls, - /*comparer*/ - (a, b) => compareValues(a.pos, b.pos) - ); - for (const call of functionCalls) { - if (call.arguments && call.arguments.length) { - const newArgument = getSynthesizedDeepClone( - createNewArgument(functionDeclaration, call.arguments), - /*includeTrivia*/ - true - ); - changes.replaceNodeRange( - getSourceFileOfNode(call), - first(call.arguments), - last(call.arguments), - newArgument, - { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include } - ); - } - } - function replaceParameters(declarationOrSignature, parameterDeclarations) { - changes.replaceNodeRangeWithNodes( - sourceFile, - first(declarationOrSignature.parameters), - last(declarationOrSignature.parameters), - parameterDeclarations, - { - joiner: ", ", - // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter - indentation: 0, - leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include - } - ); - } -} -function getGroupedReferences(functionDeclaration, program, cancellationToken) { - const functionNames = getFunctionNames(functionDeclaration); - const classNames = isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : []; - const names = deduplicate([...functionNames, ...classNames], equateValues); - const checker = program.getTypeChecker(); - const references = flatMap( - names, - /*mapfn*/ - (name) => ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken) - ); - const groupedReferences = groupReferences(references); - if (!every( - groupedReferences.declarations, - /*callback*/ - (decl) => contains(names, decl) - )) { - groupedReferences.valid = false; - } - return groupedReferences; - function groupReferences(referenceEntries) { - const classReferences = { accessExpressions: [], typeUsages: [] }; - const groupedReferences2 = { functionCalls: [], declarations: [], classReferences, valid: true }; - const functionSymbols = map(functionNames, getSymbolTargetAtLocation); - const classSymbols = map(classNames, getSymbolTargetAtLocation); - const isConstructor = isConstructorDeclaration(functionDeclaration); - const contextualSymbols = map(functionNames, (name) => getSymbolForContextualType(name, checker)); - for (const entry of referenceEntries) { - if (entry.kind === ts_FindAllReferences_exports.EntryKind.Span) { - groupedReferences2.valid = false; - continue; - } - if (contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) { - if (isValidMethodSignature(entry.node.parent)) { - groupedReferences2.signature = entry.node.parent; - continue; - } - const call = entryToFunctionCall(entry); - if (call) { - groupedReferences2.functionCalls.push(call); - continue; - } - } - const contextualSymbol = getSymbolForContextualType(entry.node, checker); - if (contextualSymbol && contains(contextualSymbols, contextualSymbol)) { - const decl = entryToDeclaration(entry); - if (decl) { - groupedReferences2.declarations.push(decl); - continue; - } - } - if (contains(functionSymbols, getSymbolTargetAtLocation(entry.node)) || isNewExpressionTarget(entry.node)) { - const importOrExportReference = entryToImportOrExport(entry); - if (importOrExportReference) { - continue; - } - const decl = entryToDeclaration(entry); - if (decl) { - groupedReferences2.declarations.push(decl); - continue; - } - const call = entryToFunctionCall(entry); - if (call) { - groupedReferences2.functionCalls.push(call); - continue; - } - } - if (isConstructor && contains(classSymbols, getSymbolTargetAtLocation(entry.node))) { - const importOrExportReference = entryToImportOrExport(entry); - if (importOrExportReference) { - continue; - } - const decl = entryToDeclaration(entry); - if (decl) { - groupedReferences2.declarations.push(decl); - continue; - } - const accessExpression = entryToAccessExpression(entry); - if (accessExpression) { - classReferences.accessExpressions.push(accessExpression); - continue; - } - if (isClassDeclaration(functionDeclaration.parent)) { - const type = entryToType(entry); - if (type) { - classReferences.typeUsages.push(type); - continue; - } - } - } - groupedReferences2.valid = false; - } - return groupedReferences2; - } - function getSymbolTargetAtLocation(node) { - const symbol = checker.getSymbolAtLocation(node); - return symbol && getSymbolTarget(symbol, checker); - } -} -function getSymbolForContextualType(node, checker) { - const element = getContainingObjectLiteralElement(node); - if (element) { - const contextualType = checker.getContextualTypeForObjectLiteralElement(element); - const symbol = contextualType == null ? void 0 : contextualType.getSymbol(); - if (symbol && !(getCheckFlags(symbol) & 6 /* Synthetic */)) { - return symbol; - } - } -} -function entryToImportOrExport(entry) { - const node = entry.node; - if (isImportSpecifier(node.parent) || isImportClause(node.parent) || isImportEqualsDeclaration(node.parent) || isNamespaceImport(node.parent)) { - return node; - } - if (isExportSpecifier(node.parent) || isExportAssignment(node.parent)) { - return node; - } - return void 0; -} -function entryToDeclaration(entry) { - if (isDeclaration(entry.node.parent)) { - return entry.node; - } - return void 0; -} -function entryToFunctionCall(entry) { - if (entry.node.parent) { - const functionReference = entry.node; - const parent2 = functionReference.parent; - switch (parent2.kind) { - case 212 /* CallExpression */: - case 213 /* NewExpression */: - const callOrNewExpression = tryCast(parent2, isCallOrNewExpression); - if (callOrNewExpression && callOrNewExpression.expression === functionReference) { - return callOrNewExpression; - } - break; - case 210 /* PropertyAccessExpression */: - const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); - if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { - const callOrNewExpression2 = tryCast(propertyAccessExpression.parent, isCallOrNewExpression); - if (callOrNewExpression2 && callOrNewExpression2.expression === propertyAccessExpression) { - return callOrNewExpression2; - } - } - break; - case 211 /* ElementAccessExpression */: - const elementAccessExpression = tryCast(parent2, isElementAccessExpression); - if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { - const callOrNewExpression2 = tryCast(elementAccessExpression.parent, isCallOrNewExpression); - if (callOrNewExpression2 && callOrNewExpression2.expression === elementAccessExpression) { - return callOrNewExpression2; - } - } - break; - } - } - return void 0; -} -function entryToAccessExpression(entry) { - if (entry.node.parent) { - const reference = entry.node; - const parent2 = reference.parent; - switch (parent2.kind) { - case 210 /* PropertyAccessExpression */: - const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); - if (propertyAccessExpression && propertyAccessExpression.expression === reference) { - return propertyAccessExpression; - } - break; - case 211 /* ElementAccessExpression */: - const elementAccessExpression = tryCast(parent2, isElementAccessExpression); - if (elementAccessExpression && elementAccessExpression.expression === reference) { - return elementAccessExpression; - } - break; - } - } - return void 0; -} -function entryToType(entry) { - const reference = entry.node; - if (getMeaningFromLocation(reference) === 2 /* Type */ || isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) { - return reference; - } - return void 0; -} -function getFunctionDeclarationAtPosition(file, startPosition, checker) { - const node = getTouchingToken(file, startPosition); - const functionDeclaration = getContainingFunctionDeclaration(node); - if (isTopLevelJSDoc(node)) - return void 0; - if (functionDeclaration && isValidFunctionDeclaration(functionDeclaration, checker) && rangeContainsRange(functionDeclaration, node) && !(functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node))) - return functionDeclaration; - return void 0; -} -function isTopLevelJSDoc(node) { - const containingJSDoc = findAncestor(node, isJSDocNode); - if (containingJSDoc) { - const containingNonJSDoc = findAncestor(containingJSDoc, (n) => !isJSDocNode(n)); - return !!containingNonJSDoc && isFunctionLikeDeclaration(containingNonJSDoc); - } - return false; -} -function isValidMethodSignature(node) { - return isMethodSignature(node) && (isInterfaceDeclaration(node.parent) || isTypeLiteralNode(node.parent)); -} -function isValidFunctionDeclaration(functionDeclaration, checker) { - var _a; - if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) - return false; - switch (functionDeclaration.kind) { - case 261 /* FunctionDeclaration */: - return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); - case 173 /* MethodDeclaration */: - if (isObjectLiteralExpression(functionDeclaration.parent)) { - const contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); - return ((_a = contextualSymbol == null ? void 0 : contextualSymbol.declarations) == null ? void 0 : _a.length) === 1 && isSingleImplementation(functionDeclaration, checker); - } - return isSingleImplementation(functionDeclaration, checker); - case 175 /* Constructor */: - if (isClassDeclaration(functionDeclaration.parent)) { - return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker); - } else { - return isValidVariableDeclaration(functionDeclaration.parent.parent) && isSingleImplementation(functionDeclaration, checker); - } - case 217 /* FunctionExpression */: - case 218 /* ArrowFunction */: - return isValidVariableDeclaration(functionDeclaration.parent); - } - return false; -} -function isSingleImplementation(functionDeclaration, checker) { - return !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); -} -function hasNameOrDefault(functionOrClassDeclaration) { - if (!functionOrClassDeclaration.name) { - const defaultKeyword = findModifier(functionOrClassDeclaration, 90 /* DefaultKeyword */); - return !!defaultKeyword; - } - return true; -} -function isValidParameterNodeArray(parameters, checker) { - return getRefactorableParametersLength(parameters) >= minimumParameterLength && every( - parameters, - /*callback*/ - (paramDecl) => isValidParameterDeclaration(paramDecl, checker) - ); -} -function isValidParameterDeclaration(parameterDeclaration, checker) { - if (isRestParameter(parameterDeclaration)) { - const type = checker.getTypeAtLocation(parameterDeclaration); - if (!checker.isArrayType(type) && !checker.isTupleType(type)) - return false; - } - return !parameterDeclaration.modifiers && isIdentifier(parameterDeclaration.name); -} -function isValidVariableDeclaration(node) { - return isVariableDeclaration(node) && isVarConst(node) && isIdentifier(node.name) && !node.type; -} -function hasThisParameter(parameters) { - return parameters.length > 0 && isThis(parameters[0].name); -} -function getRefactorableParametersLength(parameters) { - if (hasThisParameter(parameters)) { - return parameters.length - 1; - } - return parameters.length; -} -function getRefactorableParameters(parameters) { - if (hasThisParameter(parameters)) { - parameters = factory.createNodeArray(parameters.slice(1), parameters.hasTrailingComma); - } - return parameters; -} -function createPropertyOrShorthandAssignment(name, initializer) { - if (isIdentifier(initializer) && getTextOfIdentifierOrLiteral(initializer) === name) { - return factory.createShorthandPropertyAssignment(name); - } - return factory.createPropertyAssignment(name, initializer); -} -function createNewArgument(functionDeclaration, functionArguments) { - const parameters = getRefactorableParameters(functionDeclaration.parameters); - const hasRestParameter2 = isRestParameter(last(parameters)); - const nonRestArguments = hasRestParameter2 ? functionArguments.slice(0, parameters.length - 1) : functionArguments; - const properties = map(nonRestArguments, (arg, i) => { - const parameterName = getParameterName(parameters[i]); - const property = createPropertyOrShorthandAssignment(parameterName, arg); - suppressLeadingAndTrailingTrivia(property.name); - if (isPropertyAssignment(property)) - suppressLeadingAndTrailingTrivia(property.initializer); - copyComments(arg, property); - return property; - }); - if (hasRestParameter2 && functionArguments.length >= parameters.length) { - const restArguments = functionArguments.slice(parameters.length - 1); - const restProperty = factory.createPropertyAssignment(getParameterName(last(parameters)), factory.createArrayLiteralExpression(restArguments)); - properties.push(restProperty); - } - const objectLiteral = factory.createObjectLiteralExpression( - properties, - /*multiLine*/ - false - ); - return objectLiteral; -} -function createNewParameters(functionDeclaration, program, host) { - const checker = program.getTypeChecker(); - const refactorableParameters = getRefactorableParameters(functionDeclaration.parameters); - const bindingElements = map(refactorableParameters, createBindingElementFromParameterDeclaration); - const objectParameterName = factory.createObjectBindingPattern(bindingElements); - const objectParameterType = createParameterTypeNode(refactorableParameters); - let objectInitializer; - if (every(refactorableParameters, isOptionalParameter)) { - objectInitializer = factory.createObjectLiteralExpression(); - } - const objectParameter = factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - objectParameterName, - /*questionToken*/ - void 0, - objectParameterType, - objectInitializer - ); - if (hasThisParameter(functionDeclaration.parameters)) { - const thisParameter = functionDeclaration.parameters[0]; - const newThisParameter = factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - thisParameter.name, - /*questionToken*/ - void 0, - thisParameter.type - ); - suppressLeadingAndTrailingTrivia(newThisParameter.name); - copyComments(thisParameter.name, newThisParameter.name); - if (thisParameter.type) { - suppressLeadingAndTrailingTrivia(newThisParameter.type); - copyComments(thisParameter.type, newThisParameter.type); - } - return factory.createNodeArray([newThisParameter, objectParameter]); - } - return factory.createNodeArray([objectParameter]); - function createBindingElementFromParameterDeclaration(parameterDeclaration) { - const element = factory.createBindingElement( - /*dotDotDotToken*/ - void 0, - /*propertyName*/ - void 0, - getParameterName(parameterDeclaration), - isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? factory.createArrayLiteralExpression() : parameterDeclaration.initializer - ); - suppressLeadingAndTrailingTrivia(element); - if (parameterDeclaration.initializer && element.initializer) { - copyComments(parameterDeclaration.initializer, element.initializer); - } - return element; - } - function createParameterTypeNode(parameters) { - const members = map(parameters, createPropertySignatureFromParameterDeclaration); - const typeNode = addEmitFlags(factory.createTypeLiteralNode(members), 1 /* SingleLine */); - return typeNode; - } - function createPropertySignatureFromParameterDeclaration(parameterDeclaration) { - let parameterType = parameterDeclaration.type; - if (!parameterType && (parameterDeclaration.initializer || isRestParameter(parameterDeclaration))) { - parameterType = getTypeNode3(parameterDeclaration); - } - const propertySignature = factory.createPropertySignature( - /*modifiers*/ - void 0, - getParameterName(parameterDeclaration), - isOptionalParameter(parameterDeclaration) ? factory.createToken(58 /* QuestionToken */) : parameterDeclaration.questionToken, - parameterType - ); - suppressLeadingAndTrailingTrivia(propertySignature); - copyComments(parameterDeclaration.name, propertySignature.name); - if (parameterDeclaration.type && propertySignature.type) { - copyComments(parameterDeclaration.type, propertySignature.type); - } - return propertySignature; - } - function getTypeNode3(node) { - const type = checker.getTypeAtLocation(node); - return getTypeNodeIfAccessible(type, node, program, host); - } - function isOptionalParameter(parameterDeclaration) { - if (isRestParameter(parameterDeclaration)) { - const type = checker.getTypeAtLocation(parameterDeclaration); - return !checker.isTupleType(type); - } - return checker.isOptionalParameter(parameterDeclaration); - } -} -function getParameterName(paramDeclaration) { - return getTextOfIdentifierOrLiteral(paramDeclaration.name); -} -function getClassNames(constructorDeclaration) { - switch (constructorDeclaration.parent.kind) { - case 262 /* ClassDeclaration */: - const classDeclaration = constructorDeclaration.parent; - if (classDeclaration.name) - return [classDeclaration.name]; - const defaultModifier = Debug.checkDefined( - findModifier(classDeclaration, 90 /* DefaultKeyword */), - "Nameless class declaration should be a default export" - ); - return [defaultModifier]; - case 230 /* ClassExpression */: - const classExpression = constructorDeclaration.parent; - const variableDeclaration = constructorDeclaration.parent.parent; - const className = classExpression.name; - if (className) - return [className, variableDeclaration.name]; - return [variableDeclaration.name]; - } -} -function getFunctionNames(functionDeclaration) { - switch (functionDeclaration.kind) { - case 261 /* FunctionDeclaration */: - if (functionDeclaration.name) - return [functionDeclaration.name]; - const defaultModifier = Debug.checkDefined( - findModifier(functionDeclaration, 90 /* DefaultKeyword */), - "Nameless function declaration should be a default export" - ); - return [defaultModifier]; - case 173 /* MethodDeclaration */: - return [functionDeclaration.name]; - case 175 /* Constructor */: - const ctrKeyword = Debug.checkDefined( - findChildOfKind(functionDeclaration, 137 /* ConstructorKeyword */, functionDeclaration.getSourceFile()), - "Constructor declaration should have constructor keyword" - ); - if (functionDeclaration.parent.kind === 230 /* ClassExpression */) { - const variableDeclaration = functionDeclaration.parent.parent; - return [variableDeclaration.name, ctrKeyword]; - } - return [ctrKeyword]; - case 218 /* ArrowFunction */: - return [functionDeclaration.parent.name]; - case 217 /* FunctionExpression */: - if (functionDeclaration.name) - return [functionDeclaration.name, functionDeclaration.parent.name]; - return [functionDeclaration.parent.name]; - default: - return Debug.assertNever(functionDeclaration, `Unexpected function declaration kind ${functionDeclaration.kind}`); - } -} - -// src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts -var ts_refactor_convertStringOrTemplateLiteral_exports = {}; - -// src/services/refactors/convertStringOrTemplateLiteral.ts -var refactorName9 = "Convert to template string"; -var refactorDescription5 = getLocaleSpecificMessage(Diagnostics.Convert_to_template_string); -var convertStringAction = { - name: refactorName9, - description: refactorDescription5, - kind: "refactor.rewrite.string" -}; -registerRefactor(refactorName9, { - kinds: [convertStringAction.kind], - getEditsForAction: getRefactorEditsToConvertToTemplateString, - getAvailableActions: getRefactorActionsToConvertToTemplateString -}); -function getRefactorActionsToConvertToTemplateString(context) { - const { file, startPosition } = context; - const node = getNodeOrParentOfParentheses(file, startPosition); - const maybeBinary = getParentBinaryExpression(node); - const refactorInfo = { name: refactorName9, description: refactorDescription5, actions: [] }; - if (isBinaryExpression(maybeBinary) && treeToArray(maybeBinary).isValidConcatenation) { - refactorInfo.actions.push(convertStringAction); - return [refactorInfo]; - } else if (context.preferences.provideRefactorNotApplicableReason) { - refactorInfo.actions.push({ - ...convertStringAction, - notApplicableReason: getLocaleSpecificMessage(Diagnostics.Can_only_convert_string_concatenation) - }); - return [refactorInfo]; - } - return emptyArray; -} -function getNodeOrParentOfParentheses(file, startPosition) { - const node = getTokenAtPosition(file, startPosition); - const nestedBinary = getParentBinaryExpression(node); - const isNonStringBinary = !treeToArray(nestedBinary).isValidConcatenation; - if (isNonStringBinary && isParenthesizedExpression(nestedBinary.parent) && isBinaryExpression(nestedBinary.parent.parent)) { - return nestedBinary.parent.parent; - } - return node; -} -function getRefactorEditsToConvertToTemplateString(context, actionName2) { - const { file, startPosition } = context; - const node = getNodeOrParentOfParentheses(file, startPosition); - switch (actionName2) { - case refactorDescription5: - return { edits: getEditsForToTemplateLiteral(context, node) }; - default: - return Debug.fail("invalid action"); - } -} -function getEditsForToTemplateLiteral(context, node) { - const maybeBinary = getParentBinaryExpression(node); - const file = context.file; - const templateLiteral = nodesToTemplate(treeToArray(maybeBinary), file); - const trailingCommentRanges = getTrailingCommentRanges(file.text, maybeBinary.end); - if (trailingCommentRanges) { - const lastComment = trailingCommentRanges[trailingCommentRanges.length - 1]; - const trailingRange = { pos: trailingCommentRanges[0].pos, end: lastComment.end }; - return ts_textChanges_exports.ChangeTracker.with(context, (t) => { - t.deleteRange(file, trailingRange); - t.replaceNode(file, maybeBinary, templateLiteral); - }); - } else { - return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, maybeBinary, templateLiteral)); - } -} -function isNotEqualsOperator(node) { - return node.operatorToken.kind !== 64 /* EqualsToken */; -} -function getParentBinaryExpression(expr) { - const container = findAncestor(expr.parent, (n) => { - switch (n.kind) { - case 210 /* PropertyAccessExpression */: - case 211 /* ElementAccessExpression */: - return false; - case 227 /* TemplateExpression */: - case 225 /* BinaryExpression */: - return !(isBinaryExpression(n.parent) && isNotEqualsOperator(n.parent)); - default: - return "quit"; - } - }); - return container || expr; -} -function treeToArray(current) { - const loop = (current2) => { - if (!isBinaryExpression(current2)) { - return { - nodes: [current2], - operators: [], - validOperators: true, - hasString: isStringLiteral(current2) || isNoSubstitutionTemplateLiteral(current2) - }; - } - const { nodes: nodes2, operators: operators2, hasString: leftHasString, validOperators: leftOperatorValid } = loop(current2.left); - if (!(leftHasString || isStringLiteral(current2.right) || isTemplateExpression(current2.right))) { - return { nodes: [current2], operators: [], hasString: false, validOperators: true }; - } - const currentOperatorValid = current2.operatorToken.kind === 40 /* PlusToken */; - const validOperators2 = leftOperatorValid && currentOperatorValid; - nodes2.push(current2.right); - operators2.push(current2.operatorToken); - return { nodes: nodes2, operators: operators2, hasString: true, validOperators: validOperators2 }; - }; - const { nodes, operators, validOperators, hasString } = loop(current); - return { nodes, operators, isValidConcatenation: validOperators && hasString }; -} -var copyTrailingOperatorComments = (operators, file) => (index, targetNode) => { - if (index < operators.length) { - copyTrailingComments( - operators[index], - targetNode, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - } -}; -var copyCommentFromMultiNode = (nodes, file, copyOperatorComments) => (indexes, targetNode) => { - while (indexes.length > 0) { - const index = indexes.shift(); - copyTrailingComments( - nodes[index], - targetNode, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - copyOperatorComments(index, targetNode); - } -}; -function escapeRawStringForTemplate(s) { - return s.replace(/\\.|[$`]/g, (m) => m[0] === "\\" ? m : "\\" + m); -} -function getRawTextOfTemplate(node) { - const rightShaving = isTemplateHead(node) || isTemplateMiddle(node) ? -2 : -1; - return getTextOfNode(node).slice(1, rightShaving); -} -function concatConsecutiveString(index, nodes) { - const indexes = []; - let text = "", rawText = ""; - while (index < nodes.length) { - const node = nodes[index]; - if (isStringLiteralLike(node)) { - text += node.text; - rawText += escapeRawStringForTemplate(getTextOfNode(node).slice(1, -1)); - indexes.push(index); - index++; - } else if (isTemplateExpression(node)) { - text += node.head.text; - rawText += getRawTextOfTemplate(node.head); - break; - } else { - break; - } - } - return [index, text, rawText, indexes]; -} -function nodesToTemplate({ nodes, operators }, file) { - const copyOperatorComments = copyTrailingOperatorComments(operators, file); - const copyCommentFromStringLiterals = copyCommentFromMultiNode(nodes, file, copyOperatorComments); - const [begin, headText, rawHeadText, headIndexes] = concatConsecutiveString(0, nodes); - if (begin === nodes.length) { - const noSubstitutionTemplateLiteral = factory.createNoSubstitutionTemplateLiteral(headText, rawHeadText); - copyCommentFromStringLiterals(headIndexes, noSubstitutionTemplateLiteral); - return noSubstitutionTemplateLiteral; - } - const templateSpans = []; - const templateHead = factory.createTemplateHead(headText, rawHeadText); - copyCommentFromStringLiterals(headIndexes, templateHead); - for (let i = begin; i < nodes.length; i++) { - const currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); - copyOperatorComments(i, currentNode); - const [newIndex, subsequentText, rawSubsequentText, stringIndexes] = concatConsecutiveString(i + 1, nodes); - i = newIndex - 1; - const isLast = i === nodes.length - 1; - if (isTemplateExpression(currentNode)) { - const spans = map(currentNode.templateSpans, (span, index) => { - copyExpressionComments(span); - 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)); - }); - templateSpans.push(...spans); - } else { - const templatePart = isLast ? factory.createTemplateTail(subsequentText, rawSubsequentText) : factory.createTemplateMiddle(subsequentText, rawSubsequentText); - copyCommentFromStringLiterals(stringIndexes, templatePart); - templateSpans.push(factory.createTemplateSpan(currentNode, templatePart)); - } - } - return factory.createTemplateExpression(templateHead, templateSpans); -} -function copyExpressionComments(node) { - const file = node.getSourceFile(); - copyTrailingComments( - node, - node.expression, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - copyTrailingAsLeadingComments( - node.expression, - node.expression, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); -} -function getExpressionFromParenthesesOrExpression(node) { - if (isParenthesizedExpression(node)) { - copyExpressionComments(node); - node = node.expression; - } - return node; -} - -// src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts -var ts_refactor_convertToOptionalChainExpression_exports = {}; - -// src/services/refactors/convertToOptionalChainExpression.ts -var refactorName10 = "Convert to optional chain expression"; -var convertToOptionalChainExpressionMessage = getLocaleSpecificMessage(Diagnostics.Convert_to_optional_chain_expression); -var toOptionalChainAction = { - name: refactorName10, - description: convertToOptionalChainExpressionMessage, - kind: "refactor.rewrite.expression.optionalChain" -}; -registerRefactor(refactorName10, { - kinds: [toOptionalChainAction.kind], - getEditsForAction: getRefactorEditsToConvertToOptionalChain, - getAvailableActions: getRefactorActionsToConvertToOptionalChain -}); -function getRefactorActionsToConvertToOptionalChain(context) { - const info = getInfo20(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - return [{ - name: refactorName10, - description: convertToOptionalChainExpressionMessage, - actions: [toOptionalChainAction] - }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorName10, - description: convertToOptionalChainExpressionMessage, - actions: [{ ...toOptionalChainAction, notApplicableReason: info.error }] - }]; - } - return emptyArray; -} -function getRefactorEditsToConvertToOptionalChain(context, actionName2) { - const info = getInfo20(context); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_textChanges_exports.ChangeTracker.with( - context, - (t) => doChange38(context.file, context.program.getTypeChecker(), t, info, actionName2) - ); - return { edits, renameFilename: void 0, renameLocation: void 0 }; -} -function isValidExpression(node) { - return isBinaryExpression(node) || isConditionalExpression(node); -} -function isValidStatement(node) { - return isExpressionStatement(node) || isReturnStatement(node) || isVariableStatement(node); -} -function isValidExpressionOrStatement(node) { - return isValidExpression(node) || isValidStatement(node); -} -function getInfo20(context, considerEmptySpans = true) { - const { file, program } = context; - const span = getRefactorContextSpan(context); - const forEmptySpan = span.length === 0; - if (forEmptySpan && !considerEmptySpans) - return void 0; - const startToken = getTokenAtPosition(file, span.start); - const endToken = findTokenOnLeftOfPosition(file, span.start + span.length); - const adjustedSpan = createTextSpanFromBounds(startToken.pos, endToken && endToken.end >= startToken.pos ? endToken.getEnd() : startToken.getEnd()); - const parent2 = forEmptySpan ? getValidParentNodeOfEmptySpan(startToken) : getValidParentNodeContainingSpan(startToken, adjustedSpan); - const expression = parent2 && isValidExpressionOrStatement(parent2) ? getExpression(parent2) : void 0; - if (!expression) - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; - const checker = program.getTypeChecker(); - return isConditionalExpression(expression) ? getConditionalInfo(expression, checker) : getBinaryInfo(expression); -} -function getConditionalInfo(expression, checker) { - const condition = expression.condition; - const finalExpression = getFinalExpressionInChain(expression.whenTrue); - if (!finalExpression || checker.isNullableType(checker.getTypeAtLocation(finalExpression))) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; - } - if ((isPropertyAccessExpression(condition) || isIdentifier(condition)) && getMatchingStart(condition, finalExpression.expression)) { - return { finalExpression, occurrences: [condition], expression }; - } else if (isBinaryExpression(condition)) { - const occurrences = getOccurrencesInExpression(finalExpression.expression, condition); - return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) }; - } -} -function getBinaryInfo(expression) { - if (expression.operatorToken.kind !== 56 /* AmpersandAmpersandToken */) { - return { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_logical_AND_access_chains) }; - } - const finalExpression = getFinalExpressionInChain(expression.right); - if (!finalExpression) - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; - const occurrences = getOccurrencesInExpression(finalExpression.expression, expression.left); - return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) }; -} -function getOccurrencesInExpression(matchTo, expression) { - const occurrences = []; - while (isBinaryExpression(expression) && expression.operatorToken.kind === 56 /* AmpersandAmpersandToken */) { - const match = getMatchingStart(skipParentheses(matchTo), skipParentheses(expression.right)); - if (!match) { - break; - } - occurrences.push(match); - matchTo = match; - expression = expression.left; - } - const finalMatch = getMatchingStart(matchTo, expression); - if (finalMatch) { - occurrences.push(finalMatch); - } - return occurrences.length > 0 ? occurrences : void 0; -} -function getMatchingStart(chain, subchain) { - if (!isIdentifier(subchain) && !isPropertyAccessExpression(subchain) && !isElementAccessExpression(subchain)) { - return void 0; - } - return chainStartsWith(chain, subchain) ? subchain : void 0; -} -function chainStartsWith(chain, subchain) { - while (isCallExpression(chain) || isPropertyAccessExpression(chain) || isElementAccessExpression(chain)) { - if (getTextOfChainNode(chain) === getTextOfChainNode(subchain)) - break; - chain = chain.expression; - } - while (isPropertyAccessExpression(chain) && isPropertyAccessExpression(subchain) || isElementAccessExpression(chain) && isElementAccessExpression(subchain)) { - if (getTextOfChainNode(chain) !== getTextOfChainNode(subchain)) - return false; - chain = chain.expression; - subchain = subchain.expression; - } - return isIdentifier(chain) && isIdentifier(subchain) && chain.getText() === subchain.getText(); -} -function getTextOfChainNode(node) { - if (isIdentifier(node) || isStringOrNumericLiteralLike(node)) { - return node.getText(); - } - if (isPropertyAccessExpression(node)) { - return getTextOfChainNode(node.name); - } - if (isElementAccessExpression(node)) { - return getTextOfChainNode(node.argumentExpression); - } - return void 0; -} -function getValidParentNodeContainingSpan(node, span) { - while (node.parent) { - if (isValidExpressionOrStatement(node) && span.length !== 0 && node.end >= span.start + span.length) { - return node; - } - node = node.parent; - } - return void 0; -} -function getValidParentNodeOfEmptySpan(node) { - while (node.parent) { - if (isValidExpressionOrStatement(node) && !isValidExpressionOrStatement(node.parent)) { - return node; - } - node = node.parent; - } - return void 0; -} -function getExpression(node) { - if (isValidExpression(node)) { - return node; - } - if (isVariableStatement(node)) { - const variable = getSingleVariableOfVariableStatement(node); - const initializer = variable == null ? void 0 : variable.initializer; - return initializer && isValidExpression(initializer) ? initializer : void 0; - } - return node.expression && isValidExpression(node.expression) ? node.expression : void 0; -} -function getFinalExpressionInChain(node) { - node = skipParentheses(node); - if (isBinaryExpression(node)) { - return getFinalExpressionInChain(node.left); - } else if ((isPropertyAccessExpression(node) || isElementAccessExpression(node) || isCallExpression(node)) && !isOptionalChain(node)) { - return node; - } - return void 0; -} -function convertOccurrences(checker, toConvert, occurrences) { - if (isPropertyAccessExpression(toConvert) || isElementAccessExpression(toConvert) || isCallExpression(toConvert)) { - const chain = convertOccurrences(checker, toConvert.expression, occurrences); - const lastOccurrence = occurrences.length > 0 ? occurrences[occurrences.length - 1] : void 0; - const isOccurrence = (lastOccurrence == null ? void 0 : lastOccurrence.getText()) === toConvert.expression.getText(); - if (isOccurrence) - occurrences.pop(); - if (isCallExpression(toConvert)) { - return isOccurrence ? factory.createCallChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.typeArguments, toConvert.arguments) : factory.createCallChain(chain, toConvert.questionDotToken, toConvert.typeArguments, toConvert.arguments); - } else if (isPropertyAccessExpression(toConvert)) { - return isOccurrence ? factory.createPropertyAccessChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.name) : factory.createPropertyAccessChain(chain, toConvert.questionDotToken, toConvert.name); - } else if (isElementAccessExpression(toConvert)) { - return isOccurrence ? factory.createElementAccessChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.argumentExpression) : factory.createElementAccessChain(chain, toConvert.questionDotToken, toConvert.argumentExpression); - } - } - return toConvert; -} -function doChange38(sourceFile, checker, changes, info, _actionName) { - const { finalExpression, occurrences, expression } = info; - const firstOccurrence = occurrences[occurrences.length - 1]; - const convertedChain = convertOccurrences(checker, finalExpression, occurrences); - if (convertedChain && (isPropertyAccessExpression(convertedChain) || isElementAccessExpression(convertedChain) || isCallExpression(convertedChain))) { - if (isBinaryExpression(expression)) { - changes.replaceNodeRange(sourceFile, firstOccurrence, finalExpression, convertedChain); - } else if (isConditionalExpression(expression)) { - changes.replaceNode( - sourceFile, - expression, - factory.createBinaryExpression(convertedChain, factory.createToken(61 /* QuestionQuestionToken */), expression.whenFalse) - ); - } - } -} - -// src/services/_namespaces/ts.refactor.extractSymbol.ts -var ts_refactor_extractSymbol_exports = {}; -__export(ts_refactor_extractSymbol_exports, { - Messages: () => Messages, - RangeFacts: () => RangeFacts, - getRangeToExtract: () => getRangeToExtract2, - getRefactorActionsToExtractSymbol: () => getRefactorActionsToExtractSymbol, - getRefactorEditsToExtractSymbol: () => getRefactorEditsToExtractSymbol -}); - -// src/services/refactors/extractSymbol.ts -var refactorName11 = "Extract Symbol"; -var extractConstantAction = { - name: "Extract Constant", - description: getLocaleSpecificMessage(Diagnostics.Extract_constant), - kind: "refactor.extract.constant" -}; -var extractFunctionAction = { - name: "Extract Function", - description: getLocaleSpecificMessage(Diagnostics.Extract_function), - kind: "refactor.extract.function" -}; -registerRefactor(refactorName11, { - kinds: [ - extractConstantAction.kind, - extractFunctionAction.kind - ], - getEditsForAction: getRefactorEditsToExtractSymbol, - getAvailableActions: getRefactorActionsToExtractSymbol -}); -function getRefactorActionsToExtractSymbol(context) { - const requestedRefactor = context.kind; - const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context), context.triggerReason === "invoked"); - const targetRange = rangeToExtract.targetRange; - if (targetRange === void 0) { - if (!rangeToExtract.errors || rangeToExtract.errors.length === 0 || !context.preferences.provideRefactorNotApplicableReason) { - return emptyArray; - } - const errors = []; - if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { - errors.push({ - name: refactorName11, - description: extractFunctionAction.description, - actions: [{ ...extractFunctionAction, notApplicableReason: getStringError(rangeToExtract.errors) }] - }); - } - if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { - errors.push({ - name: refactorName11, - description: extractConstantAction.description, - actions: [{ ...extractConstantAction, notApplicableReason: getStringError(rangeToExtract.errors) }] - }); - } - return errors; - } - const extractions = getPossibleExtractions(targetRange, context); - if (extractions === void 0) { - return emptyArray; - } - const functionActions = []; - const usedFunctionNames = /* @__PURE__ */ new Map(); - let innermostErrorFunctionAction; - const constantActions = []; - const usedConstantNames = /* @__PURE__ */ new Map(); - let innermostErrorConstantAction; - let i = 0; - for (const { functionExtraction, constantExtraction } of extractions) { - if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { - const description2 = functionExtraction.description; - if (functionExtraction.errors.length === 0) { - if (!usedFunctionNames.has(description2)) { - usedFunctionNames.set(description2, true); - functionActions.push({ - description: description2, - name: `function_scope_${i}`, - kind: extractFunctionAction.kind - }); - } - } else if (!innermostErrorFunctionAction) { - innermostErrorFunctionAction = { - description: description2, - name: `function_scope_${i}`, - notApplicableReason: getStringError(functionExtraction.errors), - kind: extractFunctionAction.kind - }; - } - } - if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { - const description2 = constantExtraction.description; - if (constantExtraction.errors.length === 0) { - if (!usedConstantNames.has(description2)) { - usedConstantNames.set(description2, true); - constantActions.push({ - description: description2, - name: `constant_scope_${i}`, - kind: extractConstantAction.kind - }); - } - } else if (!innermostErrorConstantAction) { - innermostErrorConstantAction = { - description: description2, - name: `constant_scope_${i}`, - notApplicableReason: getStringError(constantExtraction.errors), - kind: extractConstantAction.kind - }; - } - } - i++; - } - const infos = []; - if (functionActions.length) { - infos.push({ - name: refactorName11, - description: getLocaleSpecificMessage(Diagnostics.Extract_function), - actions: functionActions - }); - } else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorFunctionAction) { - infos.push({ - name: refactorName11, - description: getLocaleSpecificMessage(Diagnostics.Extract_function), - actions: [innermostErrorFunctionAction] - }); - } - if (constantActions.length) { - infos.push({ - name: refactorName11, - description: getLocaleSpecificMessage(Diagnostics.Extract_constant), - actions: constantActions - }); - } else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorConstantAction) { - infos.push({ - name: refactorName11, - description: getLocaleSpecificMessage(Diagnostics.Extract_constant), - actions: [innermostErrorConstantAction] - }); - } - return infos.length ? infos : emptyArray; - function getStringError(errors) { - let error = errors[0].messageText; - if (typeof error !== "string") { - error = error.messageText; - } - return error; - } -} -function getRefactorEditsToExtractSymbol(context, actionName2) { - const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context)); - const targetRange = rangeToExtract.targetRange; - const parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName2); - if (parsedFunctionIndexMatch) { - const index = +parsedFunctionIndexMatch[1]; - Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index"); - return getFunctionExtractionAtIndex(targetRange, context, index); - } - const parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName2); - if (parsedConstantIndexMatch) { - const index = +parsedConstantIndexMatch[1]; - Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index"); - return getConstantExtractionAtIndex(targetRange, context, index); - } - Debug.fail("Unrecognized action name"); -} -var Messages; -((Messages2) => { - function createMessage(message) { - return { message, code: 0, category: 3 /* Message */, key: message }; - } - Messages2.cannotExtractRange = createMessage("Cannot extract range."); - Messages2.cannotExtractImport = createMessage("Cannot extract import statement."); - Messages2.cannotExtractSuper = createMessage("Cannot extract super call."); - Messages2.cannotExtractJSDoc = createMessage("Cannot extract JSDoc."); - Messages2.cannotExtractEmpty = createMessage("Cannot extract empty range."); - Messages2.expressionExpected = createMessage("expression expected."); - Messages2.uselessConstantType = createMessage("No reason to extract constant of type."); - Messages2.statementOrExpressionExpected = createMessage("Statement or expression expected."); - Messages2.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); - Messages2.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); - Messages2.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); - Messages2.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); - Messages2.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); - Messages2.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); - Messages2.cannotExtractIdentifier = createMessage("Select more than a single identifier."); - Messages2.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); - Messages2.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); - Messages2.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); - Messages2.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); - Messages2.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); - Messages2.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); - Messages2.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); - Messages2.cannotExtractFunctionsContainingThisToMethod = createMessage("Cannot extract functions containing this to method"); -})(Messages || (Messages = {})); -var RangeFacts = /* @__PURE__ */ ((RangeFacts2) => { - RangeFacts2[RangeFacts2["None"] = 0] = "None"; - RangeFacts2[RangeFacts2["HasReturn"] = 1] = "HasReturn"; - RangeFacts2[RangeFacts2["IsGenerator"] = 2] = "IsGenerator"; - RangeFacts2[RangeFacts2["IsAsyncFunction"] = 4] = "IsAsyncFunction"; - RangeFacts2[RangeFacts2["UsesThis"] = 8] = "UsesThis"; - RangeFacts2[RangeFacts2["UsesThisInFunction"] = 16] = "UsesThisInFunction"; - RangeFacts2[RangeFacts2["InStaticRegion"] = 32] = "InStaticRegion"; - return RangeFacts2; -})(RangeFacts || {}); -function getRangeToExtract2(sourceFile, span, invoked = true) { - const { length: length2 } = span; - if (length2 === 0 && !invoked) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractEmpty)] }; - } - const cursorRequest = length2 === 0 && invoked; - const startToken = findFirstNonJsxWhitespaceToken(sourceFile, span.start); - const endToken = findTokenOnLeftOfPosition(sourceFile, textSpanEnd(span)); - const adjustedSpan = startToken && endToken && invoked ? getAdjustedSpanFromNodes(startToken, endToken, sourceFile) : span; - const start2 = cursorRequest ? getExtractableParent(startToken) : getParentNodeInSpan(startToken, sourceFile, adjustedSpan); - const end = cursorRequest ? start2 : getParentNodeInSpan(endToken, sourceFile, adjustedSpan); - let rangeFacts = 0 /* None */; - let thisNode; - if (!start2 || !end) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; - } - if (start2.flags & 8388608 /* JSDoc */) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractJSDoc)] }; - } - if (start2.parent !== end.parent) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; - } - if (start2 !== end) { - if (!isBlockLike(start2.parent)) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; - } - const statements = []; - for (const statement of start2.parent.statements) { - if (statement === start2 || statements.length) { - const errors2 = checkNode(statement); - if (errors2) { - return { errors: errors2 }; - } - statements.push(statement); - } - if (statement === end) { - break; - } - } - if (!statements.length) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; - } - return { targetRange: { range: statements, facts: rangeFacts, thisNode } }; - } - if (isReturnStatement(start2) && !start2.expression) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; - } - const node = refineNode(start2); - const errors = checkRootNode(node) || checkNode(node); - if (errors) { - return { errors }; - } - return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, thisNode } }; - function refineNode(node2) { - if (isReturnStatement(node2)) { - if (node2.expression) { - return node2.expression; - } - } else if (isVariableStatement(node2) || isVariableDeclarationList(node2)) { - const declarations = isVariableStatement(node2) ? node2.declarationList.declarations : node2.declarations; - let numInitializers = 0; - let lastInitializer; - for (const declaration of declarations) { - if (declaration.initializer) { - numInitializers++; - lastInitializer = declaration.initializer; - } - } - if (numInitializers === 1) { - return lastInitializer; - } - } else if (isVariableDeclaration(node2)) { - if (node2.initializer) { - return node2.initializer; - } - } - return node2; - } - function checkRootNode(node2) { - if (isIdentifier(isExpressionStatement(node2) ? node2.expression : node2)) { - return [createDiagnosticForNode(node2, Messages.cannotExtractIdentifier)]; - } - return void 0; - } - function checkForStaticContext(nodeToCheck, containingClass) { - let current = nodeToCheck; - while (current !== containingClass) { - if (current.kind === 171 /* PropertyDeclaration */) { - if (isStatic(current)) { - rangeFacts |= 32 /* InStaticRegion */; - } - break; - } else if (current.kind === 168 /* Parameter */) { - const ctorOrMethod = getContainingFunction(current); - if (ctorOrMethod.kind === 175 /* Constructor */) { - rangeFacts |= 32 /* InStaticRegion */; - } - break; - } else if (current.kind === 173 /* MethodDeclaration */) { - if (isStatic(current)) { - rangeFacts |= 32 /* InStaticRegion */; - } - } - current = current.parent; - } - } - function checkNode(nodeToCheck) { - let PermittedJumps; - ((PermittedJumps2) => { - PermittedJumps2[PermittedJumps2["None"] = 0] = "None"; - PermittedJumps2[PermittedJumps2["Break"] = 1] = "Break"; - PermittedJumps2[PermittedJumps2["Continue"] = 2] = "Continue"; - PermittedJumps2[PermittedJumps2["Return"] = 4] = "Return"; - })(PermittedJumps || (PermittedJumps = {})); - Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (1)"); - Debug.assert(!positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (2)"); - if (!isStatement(nodeToCheck) && !(isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck)) && !isStringLiteralJsxAttribute(nodeToCheck)) { - return [createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)]; - } - if (nodeToCheck.flags & 16777216 /* Ambient */) { - return [createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)]; - } - const containingClass = getContainingClass(nodeToCheck); - if (containingClass) { - checkForStaticContext(nodeToCheck, containingClass); - } - let errors2; - let permittedJumps = 4 /* Return */; - let seenLabels; - visit(nodeToCheck); - if (rangeFacts & 8 /* UsesThis */) { - const container = getThisContainer( - nodeToCheck, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); - if (container.kind === 261 /* FunctionDeclaration */ || container.kind === 173 /* MethodDeclaration */ && container.parent.kind === 209 /* ObjectLiteralExpression */ || container.kind === 217 /* FunctionExpression */) { - rangeFacts |= 16 /* UsesThisInFunction */; - } - } - return errors2; - function visit(node2) { - if (errors2) { - return true; - } - if (isDeclaration(node2)) { - const declaringNode = node2.kind === 259 /* VariableDeclaration */ ? node2.parent.parent : node2; - if (hasSyntacticModifier(declaringNode, 1 /* Export */)) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity)); - return true; - } - } - switch (node2.kind) { - case 271 /* ImportDeclaration */: - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractImport)); - return true; - case 276 /* ExportAssignment */: - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity)); - return true; - case 108 /* SuperKeyword */: - if (node2.parent.kind === 212 /* CallExpression */) { - const containingClass2 = getContainingClass(node2); - if (containingClass2 === void 0 || containingClass2.pos < span.start || containingClass2.end >= span.start + span.length) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractSuper)); - return true; - } - } else { - rangeFacts |= 8 /* UsesThis */; - thisNode = node2; - } - break; - case 218 /* ArrowFunction */: - forEachChild(node2, function check(n) { - if (isThis(n)) { - rangeFacts |= 8 /* UsesThis */; - thisNode = node2; - } else if (isClassLike(n) || isFunctionLike(n) && !isArrowFunction(n)) { - return false; - } else { - forEachChild(n, check); - } - }); - case 262 /* ClassDeclaration */: - case 261 /* FunctionDeclaration */: - if (isSourceFile(node2.parent) && node2.parent.externalModuleIndicator === void 0) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.functionWillNotBeVisibleInTheNewScope)); - } - case 230 /* ClassExpression */: - case 217 /* FunctionExpression */: - case 173 /* MethodDeclaration */: - case 175 /* Constructor */: - case 176 /* GetAccessor */: - case 177 /* SetAccessor */: - return false; - } - const savedPermittedJumps = permittedJumps; - switch (node2.kind) { - case 244 /* IfStatement */: - permittedJumps &= ~4 /* Return */; - break; - case 257 /* TryStatement */: - permittedJumps = 0 /* None */; - break; - case 240 /* Block */: - if (node2.parent && node2.parent.kind === 257 /* TryStatement */ && node2.parent.finallyBlock === node2) { - permittedJumps = 4 /* Return */; - } - break; - case 296 /* DefaultClause */: - case 295 /* CaseClause */: - permittedJumps |= 1 /* Break */; - break; - default: - if (isIterationStatement( - node2, - /*lookInLabeledStatements*/ - false - )) { - permittedJumps |= 1 /* Break */ | 2 /* Continue */; - } - break; - } - switch (node2.kind) { - case 196 /* ThisType */: - case 110 /* ThisKeyword */: - rangeFacts |= 8 /* UsesThis */; - thisNode = node2; - break; - case 255 /* LabeledStatement */: { - const label = node2.label; - (seenLabels || (seenLabels = [])).push(label.escapedText); - forEachChild(node2, visit); - seenLabels.pop(); - break; - } - case 251 /* BreakStatement */: - case 250 /* ContinueStatement */: { - const label = node2.label; - if (label) { - if (!contains(seenLabels, label.escapedText)) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); - } - } else { - if (!(permittedJumps & (node2.kind === 251 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); - } - } - break; - } - case 222 /* AwaitExpression */: - rangeFacts |= 4 /* IsAsyncFunction */; - break; - case 228 /* YieldExpression */: - rangeFacts |= 2 /* IsGenerator */; - break; - case 252 /* ReturnStatement */: - if (permittedJumps & 4 /* Return */) { - rangeFacts |= 1 /* HasReturn */; - } else { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalReturnStatement)); - } - break; - default: - forEachChild(node2, visit); - break; - } - permittedJumps = savedPermittedJumps; - } - } -} -function getAdjustedSpanFromNodes(startNode2, endNode2, sourceFile) { - const start2 = startNode2.getStart(sourceFile); - let end = endNode2.getEnd(); - if (sourceFile.text.charCodeAt(end) === 59 /* semicolon */) { - end++; - } - return { start: start2, length: end - start2 }; -} -function getStatementOrExpressionRange(node) { - if (isStatement(node)) { - return [node]; - } - if (isExpressionNode(node)) { - return isExpressionStatement(node.parent) ? [node.parent] : node; - } - if (isStringLiteralJsxAttribute(node)) { - return node; - } - return void 0; -} -function isScope(node) { - return isArrowFunction(node) ? isFunctionBody(node.body) : isFunctionLikeDeclaration(node) || isSourceFile(node) || isModuleBlock(node) || isClassLike(node); -} -function collectEnclosingScopes(range) { - let current = isReadonlyArray(range.range) ? first(range.range) : range.range; - if (range.facts & 8 /* UsesThis */ && !(range.facts & 16 /* UsesThisInFunction */)) { - const containingClass = getContainingClass(current); - if (containingClass) { - const containingFunction = findAncestor(current, isFunctionLikeDeclaration); - return containingFunction ? [containingFunction, containingClass] : [containingClass]; - } - } - const scopes = []; - while (true) { - current = current.parent; - if (current.kind === 168 /* Parameter */) { - current = findAncestor(current, (parent2) => isFunctionLikeDeclaration(parent2)).parent; - } - if (isScope(current)) { - scopes.push(current); - if (current.kind === 311 /* SourceFile */) { - return scopes; - } - } - } -} -function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { - const { scopes, readsAndWrites: { target, usagesPerScope, functionErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); - Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); - context.cancellationToken.throwIfCancellationRequested(); - return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); -} -function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { - const { scopes, readsAndWrites: { target, usagesPerScope, constantErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); - Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); - Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); - context.cancellationToken.throwIfCancellationRequested(); - const expression = isExpression(target) ? target : target.statements[0].expression; - return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context); -} -function getPossibleExtractions(targetRange, context) { - const { scopes, readsAndWrites: { functionErrorsPerScope, constantErrorsPerScope } } = getPossibleExtractionsWorker(targetRange, context); - const extractions = scopes.map((scope, i) => { - const functionDescriptionPart = getDescriptionForFunctionInScope(scope); - const constantDescriptionPart = getDescriptionForConstantInScope(scope); - const scopeDescription = isFunctionLikeDeclaration(scope) ? getDescriptionForFunctionLikeDeclaration(scope) : isClassLike(scope) ? getDescriptionForClassLikeDeclaration(scope) : getDescriptionForModuleLikeDeclaration(scope); - let functionDescription; - let constantDescription; - if (scopeDescription === 1 /* Global */) { - functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]); - constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]); - } else if (scopeDescription === 0 /* Module */) { - functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]); - constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]); - } else { - functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]); - constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]); - } - if (i === 0 && !isClassLike(scope)) { - constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]); - } - return { - functionExtraction: { - description: functionDescription, - errors: functionErrorsPerScope[i] - }, - constantExtraction: { - description: constantDescription, - errors: constantErrorsPerScope[i] - } - }; - }); - return extractions; -} -function getPossibleExtractionsWorker(targetRange, context) { - const { file: sourceFile } = context; - const scopes = collectEnclosingScopes(targetRange); - const enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); - const readsAndWrites = collectReadsAndWrites( - targetRange, - scopes, - enclosingTextRange, - sourceFile, - context.program.getTypeChecker(), - context.cancellationToken - ); - return { scopes, readsAndWrites }; -} -function getDescriptionForFunctionInScope(scope) { - return isFunctionLikeDeclaration(scope) ? "inner function" : isClassLike(scope) ? "method" : "function"; -} -function getDescriptionForConstantInScope(scope) { - return isClassLike(scope) ? "readonly field" : "constant"; -} -function getDescriptionForFunctionLikeDeclaration(scope) { - switch (scope.kind) { - case 175 /* Constructor */: - return "constructor"; - case 217 /* FunctionExpression */: - case 261 /* FunctionDeclaration */: - return scope.name ? `function '${scope.name.text}'` : ANONYMOUS; - case 218 /* ArrowFunction */: - return "arrow function"; - case 173 /* MethodDeclaration */: - return `method '${scope.name.getText()}'`; - case 176 /* GetAccessor */: - return `'get ${scope.name.getText()}'`; - case 177 /* SetAccessor */: - return `'set ${scope.name.getText()}'`; - default: - Debug.assertNever(scope, `Unexpected scope kind ${scope.kind}`); - } -} -function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 262 /* ClassDeclaration */ ? scope.name ? `class '${scope.name.text}'` : "anonymous class declaration" : scope.name ? `class expression '${scope.name.text}'` : "anonymous class expression"; -} -function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 267 /* ModuleBlock */ ? `namespace '${scope.parent.name.getText()}'` : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; -} -function extractFunctionInScope(node, scope, { usages: usagesInScope, typeParameterUsages, substitutions }, exposedVariableDeclarations, range, context) { - const checker = context.program.getTypeChecker(); - const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); - const importAdder = ts_codefix_exports.createImportAdder(context.file, context.program, context.preferences, context.host); - const file = scope.getSourceFile(); - const functionNameText = getUniqueName(isClassLike(scope) ? "newMethod" : "newFunction", file); - const isJS = isInJSFile(scope); - const functionName = factory.createIdentifier(functionNameText); - let returnType; - const parameters = []; - const callArguments = []; - let writes; - usagesInScope.forEach((usage, name) => { - let typeNode; - if (!isJS) { - let type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); - type = checker.getBaseTypeOfLiteralType(type); - typeNode = ts_codefix_exports.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */); - } - const paramDecl = factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - /*name*/ - name, - /*questionToken*/ - void 0, - typeNode - ); - parameters.push(paramDecl); - if (usage.usage === 2 /* Write */) { - (writes || (writes = [])).push(usage); - } - callArguments.push(factory.createIdentifier(name)); - }); - const typeParametersAndDeclarations = arrayFrom(typeParameterUsages.values(), (type) => ({ type, declaration: getFirstDeclarationBeforePosition(type, context.startPosition) })); - const sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); - const typeParameters = sortedTypeParametersAndDeclarations.length === 0 ? void 0 : mapDefined(sortedTypeParametersAndDeclarations, ({ declaration }) => declaration); - const callTypeArguments = typeParameters !== void 0 ? typeParameters.map((decl) => factory.createTypeReferenceNode( - decl.name, - /*typeArguments*/ - void 0 - )) : void 0; - if (isExpression(node) && !isJS) { - const contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); - } - const { body, returnValueProperty } = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & 1 /* HasReturn */)); - suppressLeadingAndTrailingTrivia(body); - let newFunction; - const callThis = !!(range.facts & 16 /* UsesThisInFunction */); - if (isClassLike(scope)) { - const modifiers = isJS ? [] : [factory.createModifier(123 /* PrivateKeyword */)]; - if (range.facts & 32 /* InStaticRegion */) { - modifiers.push(factory.createModifier(126 /* StaticKeyword */)); - } - if (range.facts & 4 /* IsAsyncFunction */) { - modifiers.push(factory.createModifier(134 /* AsyncKeyword */)); - } - newFunction = factory.createMethodDeclaration( - modifiers.length ? modifiers : void 0, - range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0, - functionName, - /*questionToken*/ - void 0, - typeParameters, - parameters, - returnType, - body - ); - } else { - if (callThis) { - parameters.unshift( - factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - /*name*/ - "this", - /*questionToken*/ - void 0, - checker.typeToTypeNode( - checker.getTypeAtLocation(range.thisNode), - scope, - 1 /* NoTruncation */ - ), - /*initializer*/ - void 0 - ) - ); - } - newFunction = factory.createFunctionDeclaration( - range.facts & 4 /* IsAsyncFunction */ ? [factory.createToken(134 /* AsyncKeyword */)] : void 0, - range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0, - functionName, - typeParameters, - parameters, - returnType, - body - ); - } - const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); - const minInsertionPos = (isReadonlyArray(range.range) ? last(range.range) : range.range).end; - const nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); - if (nodeToInsertBefore) { - changeTracker.insertNodeBefore( - context.file, - nodeToInsertBefore, - newFunction, - /*blankLineBetween*/ - true - ); - } else { - changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); - } - importAdder.writeFixes(changeTracker); - const newNodes = []; - const called = getCalledExpression(scope, range, functionNameText); - if (callThis) { - callArguments.unshift(factory.createIdentifier("this")); - } - let call = factory.createCallExpression( - callThis ? factory.createPropertyAccessExpression( - called, - "call" - ) : called, - callTypeArguments, - // Note that no attempt is made to take advantage of type argument inference - callArguments - ); - if (range.facts & 2 /* IsGenerator */) { - call = factory.createYieldExpression(factory.createToken(42 /* AsteriskToken */), call); - } - if (range.facts & 4 /* IsAsyncFunction */) { - call = factory.createAwaitExpression(call); - } - if (isInJSXContent(node)) { - call = factory.createJsxExpression( - /*dotDotDotToken*/ - void 0, - call - ); - } - if (exposedVariableDeclarations.length && !writes) { - Debug.assert(!returnValueProperty, "Expected no returnValueProperty"); - Debug.assert(!(range.facts & 1 /* HasReturn */), "Expected RangeFacts.HasReturn flag to be unset"); - if (exposedVariableDeclarations.length === 1) { - const variableDeclaration = exposedVariableDeclarations[0]; - newNodes.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - getSynthesizedDeepClone(variableDeclaration.name), - /*exclamationToken*/ - void 0, - /*type*/ - getSynthesizedDeepClone(variableDeclaration.type), - /*initializer*/ - call - )], - variableDeclaration.parent.flags - ) - )); - } else { - const bindingElements = []; - const typeElements = []; - let commonNodeFlags = exposedVariableDeclarations[0].parent.flags; - let sawExplicitType = false; - for (const variableDeclaration of exposedVariableDeclarations) { - bindingElements.push(factory.createBindingElement( - /*dotDotDotToken*/ - void 0, - /*propertyName*/ - void 0, - /*name*/ - getSynthesizedDeepClone(variableDeclaration.name) - )); - const variableType = checker.typeToTypeNode( - checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), - scope, - 1 /* NoTruncation */ - ); - typeElements.push(factory.createPropertySignature( - /*modifiers*/ - void 0, - /*name*/ - variableDeclaration.symbol.name, - /*questionToken*/ - void 0, - /*type*/ - variableType - )); - sawExplicitType = sawExplicitType || variableDeclaration.type !== void 0; - commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; - } - const typeLiteral = sawExplicitType ? factory.createTypeLiteralNode(typeElements) : void 0; - if (typeLiteral) { - setEmitFlags(typeLiteral, 1 /* SingleLine */); - } - newNodes.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - factory.createObjectBindingPattern(bindingElements), - /*exclamationToken*/ - void 0, - /*type*/ - typeLiteral, - /*initializer*/ - call - )], - commonNodeFlags - ) - )); - } - } else if (exposedVariableDeclarations.length || writes) { - if (exposedVariableDeclarations.length) { - for (const variableDeclaration of exposedVariableDeclarations) { - let flags = variableDeclaration.parent.flags; - if (flags & 2 /* Const */) { - flags = flags & ~2 /* Const */ | 1 /* Let */; - } - newNodes.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - variableDeclaration.symbol.name, - /*exclamationToken*/ - void 0, - getTypeDeepCloneUnionUndefined(variableDeclaration.type) - )], - flags - ) - )); - } - } - if (returnValueProperty) { - newNodes.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - returnValueProperty, - /*exclamationToken*/ - void 0, - getTypeDeepCloneUnionUndefined(returnType) - )], - 1 /* Let */ - ) - )); - } - const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); - if (returnValueProperty) { - assignments.unshift(factory.createShorthandPropertyAssignment(returnValueProperty)); - } - if (assignments.length === 1) { - Debug.assert(!returnValueProperty, "Shouldn't have returnValueProperty here"); - newNodes.push(factory.createExpressionStatement(factory.createAssignment(assignments[0].name, call))); - if (range.facts & 1 /* HasReturn */) { - newNodes.push(factory.createReturnStatement()); - } - } else { - newNodes.push(factory.createExpressionStatement(factory.createAssignment(factory.createObjectLiteralExpression(assignments), call))); - if (returnValueProperty) { - newNodes.push(factory.createReturnStatement(factory.createIdentifier(returnValueProperty))); - } - } - } else { - if (range.facts & 1 /* HasReturn */) { - newNodes.push(factory.createReturnStatement(call)); - } else if (isReadonlyArray(range.range)) { - newNodes.push(factory.createExpressionStatement(call)); - } else { - newNodes.push(call); - } - } - if (isReadonlyArray(range.range)) { - changeTracker.replaceNodeRangeWithNodes(context.file, first(range.range), last(range.range), newNodes); - } else { - changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes); - } - const edits = changeTracker.getChanges(); - const renameRange = isReadonlyArray(range.range) ? first(range.range) : range.range; - const renameFilename = renameRange.getSourceFile().fileName; - const renameLocation = getRenameLocation( - edits, - renameFilename, - functionNameText, - /*preferLastLocation*/ - false - ); - return { renameFilename, renameLocation, edits }; - function getTypeDeepCloneUnionUndefined(typeNode) { - if (typeNode === void 0) { - return void 0; - } - const clone2 = getSynthesizedDeepClone(typeNode); - let withoutParens = clone2; - while (isParenthesizedTypeNode(withoutParens)) { - withoutParens = withoutParens.type; - } - return isUnionTypeNode(withoutParens) && find(withoutParens.types, (t) => t.kind === 157 /* UndefinedKeyword */) ? clone2 : factory.createUnionTypeNode([clone2, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); - } -} -function extractConstantInScope(node, scope, { substitutions }, rangeFacts, context) { - const checker = context.program.getTypeChecker(); - const file = scope.getSourceFile(); - const localNameText = isPropertyAccessExpression(node) && !isClassLike(scope) && !checker.resolveName( - node.name.text, - node, - 111551 /* Value */, - /*excludeGlobals*/ - false - ) && !isPrivateIdentifier(node.name) && !identifierToKeywordKind(node.name) ? node.name.text : getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file); - const isJS = isInJSFile(scope); - let variableType = isJS || !checker.isContextSensitive(node) ? void 0 : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); - let initializer = transformConstantInitializer(skipParentheses(node), substitutions); - ({ variableType, initializer } = transformFunctionInitializerAndType(variableType, initializer)); - suppressLeadingAndTrailingTrivia(initializer); - const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); - if (isClassLike(scope)) { - Debug.assert(!isJS, "Cannot extract to a JS class"); - const modifiers = []; - modifiers.push(factory.createModifier(123 /* PrivateKeyword */)); - if (rangeFacts & 32 /* InStaticRegion */) { - modifiers.push(factory.createModifier(126 /* StaticKeyword */)); - } - modifiers.push(factory.createModifier(148 /* ReadonlyKeyword */)); - const newVariable = factory.createPropertyDeclaration( - modifiers, - localNameText, - /*questionOrExclamationToken*/ - void 0, - variableType, - initializer - ); - let localReference = factory.createPropertyAccessExpression( - rangeFacts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.getText()) : factory.createThis(), - factory.createIdentifier(localNameText) - ); - if (isInJSXContent(node)) { - localReference = factory.createJsxExpression( - /*dotDotDotToken*/ - void 0, - localReference - ); - } - const maxInsertionPos = node.pos; - const nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); - changeTracker.insertNodeBefore( - context.file, - nodeToInsertBefore, - newVariable, - /*blankLineBetween*/ - true - ); - changeTracker.replaceNode(context.file, node, localReference); - } else { - const newVariableDeclaration = factory.createVariableDeclaration( - localNameText, - /*exclamationToken*/ - void 0, - variableType, - initializer - ); - const oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); - if (oldVariableDeclaration) { - changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); - const localReference = factory.createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference); - } else if (node.parent.kind === 243 /* ExpressionStatement */ && scope === findAncestor(node, isScope)) { - const newVariableStatement = factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */) - ); - changeTracker.replaceNode(context.file, node.parent, newVariableStatement); - } else { - const newVariableStatement = factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */) - ); - const nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); - if (nodeToInsertBefore.pos === 0) { - changeTracker.insertNodeAtTopOfFile( - context.file, - newVariableStatement, - /*blankLineBetween*/ - false - ); - } else { - changeTracker.insertNodeBefore( - context.file, - nodeToInsertBefore, - newVariableStatement, - /*blankLineBetween*/ - false - ); - } - if (node.parent.kind === 243 /* ExpressionStatement */) { - changeTracker.delete(context.file, node.parent); - } else { - let localReference = factory.createIdentifier(localNameText); - if (isInJSXContent(node)) { - localReference = factory.createJsxExpression( - /*dotDotDotToken*/ - void 0, - localReference - ); - } - changeTracker.replaceNode(context.file, node, localReference); - } - } - } - const edits = changeTracker.getChanges(); - const renameFilename = node.getSourceFile().fileName; - const renameLocation = getRenameLocation( - edits, - renameFilename, - localNameText, - /*preferLastLocation*/ - true - ); - return { renameFilename, renameLocation, edits }; - function transformFunctionInitializerAndType(variableType2, initializer2) { - if (variableType2 === void 0) - return { variableType: variableType2, initializer: initializer2 }; - if (!isFunctionExpression(initializer2) && !isArrowFunction(initializer2) || !!initializer2.typeParameters) - return { variableType: variableType2, initializer: initializer2 }; - const functionType = checker.getTypeAtLocation(node); - const functionSignature = singleOrUndefined(checker.getSignaturesOfType(functionType, 0 /* Call */)); - if (!functionSignature) - return { variableType: variableType2, initializer: initializer2 }; - if (!!functionSignature.getTypeParameters()) - return { variableType: variableType2, initializer: initializer2 }; - const parameters = []; - let hasAny = false; - for (const p of initializer2.parameters) { - if (p.type) { - parameters.push(p); - } else { - 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, 1 /* NoTruncation */), - p.initializer - )); - } - } - if (hasAny) - return { variableType: variableType2, initializer: initializer2 }; - variableType2 = void 0; - if (isArrowFunction(initializer2)) { - initializer2 = factory.updateArrowFunction( - initializer2, - canHaveModifiers(node) ? getModifiers(node) : void 0, - initializer2.typeParameters, - parameters, - initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), - initializer2.equalsGreaterThanToken, - initializer2.body - ); - } else { - if (functionSignature && !!functionSignature.thisParameter) { - const firstParameter = firstOrUndefined(parameters); - if (!firstParameter || isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this") { - const thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node); - parameters.splice(0, 0, factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "this", - /*questionToken*/ - void 0, - checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */) - )); - } - } - initializer2 = factory.updateFunctionExpression( - initializer2, - canHaveModifiers(node) ? getModifiers(node) : void 0, - initializer2.asteriskToken, - initializer2.name, - initializer2.typeParameters, - parameters, - initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), - initializer2.body - ); - } - return { variableType: variableType2, initializer: initializer2 }; - } -} -function getContainingVariableDeclarationIfInList(node, scope) { - let prevNode; - while (node !== void 0 && node !== scope) { - if (isVariableDeclaration(node) && node.initializer === prevNode && isVariableDeclarationList(node.parent) && node.parent.declarations.length > 1) { - return node; - } - prevNode = node; - node = node.parent; - } -} -function getFirstDeclarationBeforePosition(type, position) { - let firstDeclaration; - const symbol = type.symbol; - if (symbol && symbol.declarations) { - for (const declaration of symbol.declarations) { - if ((firstDeclaration === void 0 || declaration.pos < firstDeclaration.pos) && declaration.pos < position) { - firstDeclaration = declaration; - } - } - } - return firstDeclaration; -} -function compareTypesByDeclarationOrder({ type: type1, declaration: declaration1 }, { type: type2, declaration: declaration2 }) { - return compareProperties(declaration1, declaration2, "pos", compareValues) || compareStringsCaseSensitive( - type1.symbol ? type1.symbol.getName() : "", - type2.symbol ? type2.symbol.getName() : "" - ) || compareValues(type1.id, type2.id); -} -function getCalledExpression(scope, range, functionNameText) { - const functionReference = factory.createIdentifier(functionNameText); - if (isClassLike(scope)) { - const lhs = range.facts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.text) : factory.createThis(); - return factory.createPropertyAccessExpression(lhs, functionReference); - } else { - return functionReference; - } -} -function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn2) { - const hasWritesOrVariableDeclarations = writes !== void 0 || exposedVariableDeclarations.length > 0; - if (isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { - return { body: factory.createBlock( - body.statements, - /*multiLine*/ - true - ), returnValueProperty: void 0 }; - } - let returnValueProperty; - let ignoreReturns = false; - const statements = factory.createNodeArray(isBlock(body) ? body.statements.slice(0) : [isStatement(body) ? body : factory.createReturnStatement(skipParentheses(body))]); - if (hasWritesOrVariableDeclarations || substitutions.size) { - const rewrittenStatements = visitNodes2(statements, visitor, isStatement).slice(); - if (hasWritesOrVariableDeclarations && !hasReturn2 && isStatement(body)) { - const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); - if (assignments.length === 1) { - rewrittenStatements.push(factory.createReturnStatement(assignments[0].name)); - } else { - rewrittenStatements.push(factory.createReturnStatement(factory.createObjectLiteralExpression(assignments))); - } - } - return { body: factory.createBlock( - rewrittenStatements, - /*multiLine*/ - true - ), returnValueProperty }; - } else { - return { body: factory.createBlock( - statements, - /*multiLine*/ - true - ), returnValueProperty: void 0 }; - } - function visitor(node) { - if (!ignoreReturns && isReturnStatement(node) && hasWritesOrVariableDeclarations) { - const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); - if (node.expression) { - if (!returnValueProperty) { - returnValueProperty = "__return"; - } - assignments.unshift(factory.createPropertyAssignment(returnValueProperty, visitNode(node.expression, visitor, isExpression))); - } - if (assignments.length === 1) { - return factory.createReturnStatement(assignments[0].name); - } else { - return factory.createReturnStatement(factory.createObjectLiteralExpression(assignments)); - } - } else { - const oldIgnoreReturns = ignoreReturns; - ignoreReturns = ignoreReturns || isFunctionLikeDeclaration(node) || isClassLike(node); - const substitution = substitutions.get(getNodeId(node).toString()); - const result = substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext); - ignoreReturns = oldIgnoreReturns; - return result; - } - } -} -function transformConstantInitializer(initializer, substitutions) { - return substitutions.size ? visitor(initializer) : initializer; - function visitor(node) { - const substitution = substitutions.get(getNodeId(node).toString()); - return substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext); - } -} -function getStatementsOrClassElements(scope) { - if (isFunctionLikeDeclaration(scope)) { - const body = scope.body; - if (isBlock(body)) { - return body.statements; - } - } else if (isModuleBlock(scope) || isSourceFile(scope)) { - return scope.statements; - } else if (isClassLike(scope)) { - return scope.members; - } else { - assertType(scope); - } - return emptyArray; -} -function getNodeToInsertFunctionBefore(minPos, scope) { - return find(getStatementsOrClassElements(scope), (child) => child.pos >= minPos && isFunctionLikeDeclaration(child) && !isConstructorDeclaration(child)); -} -function getNodeToInsertPropertyBefore(maxPos, scope) { - const members = scope.members; - Debug.assert(members.length > 0, "Found no members"); - let prevMember; - let allProperties = true; - for (const member of members) { - if (member.pos > maxPos) { - return prevMember || members[0]; - } - if (allProperties && !isPropertyDeclaration(member)) { - if (prevMember !== void 0) { - return member; - } - allProperties = false; - } - prevMember = member; - } - if (prevMember === void 0) - return Debug.fail(); - return prevMember; -} -function getNodeToInsertConstantBefore(node, scope) { - Debug.assert(!isClassLike(scope)); - let prevScope; - for (let curr = node; curr !== scope; curr = curr.parent) { - if (isScope(curr)) { - prevScope = curr; - } - } - for (let curr = (prevScope || node).parent; ; curr = curr.parent) { - if (isBlockLike(curr)) { - let prevStatement; - for (const statement of curr.statements) { - if (statement.pos > node.pos) { - break; - } - prevStatement = statement; - } - if (!prevStatement && isCaseClause(curr)) { - Debug.assert(isSwitchStatement(curr.parent.parent), "Grandparent isn't a switch statement"); - return curr.parent.parent; - } - return Debug.checkDefined(prevStatement, "prevStatement failed to get set"); - } - Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); - } -} -function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { - const variableAssignments = map(exposedVariableDeclarations, (v) => factory.createShorthandPropertyAssignment(v.symbol.name)); - const writeAssignments = map(writes, (w) => factory.createShorthandPropertyAssignment(w.symbol.name)); - return variableAssignments === void 0 ? writeAssignments : writeAssignments === void 0 ? variableAssignments : variableAssignments.concat(writeAssignments); -} -function isReadonlyArray(v) { - return isArray(v); -} -function getEnclosingTextRange(targetRange, sourceFile) { - return isReadonlyArray(targetRange.range) ? { pos: first(targetRange.range).getStart(sourceFile), end: last(targetRange.range).getEnd() } : targetRange.range; -} -function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { - const allTypeParameterUsages = /* @__PURE__ */ new Map(); - const usagesPerScope = []; - const substitutionsPerScope = []; - const functionErrorsPerScope = []; - const constantErrorsPerScope = []; - const visibleDeclarationsInExtractedRange = []; - const exposedVariableSymbolSet = /* @__PURE__ */ new Map(); - const exposedVariableDeclarations = []; - let firstExposedNonVariableDeclaration; - const expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && isExpressionStatement(targetRange.range[0]) ? targetRange.range[0].expression : void 0; - let expressionDiagnostic; - if (expression === void 0) { - const statements = targetRange.range; - const start2 = first(statements).getStart(); - const end = last(statements).end; - expressionDiagnostic = createFileDiagnostic(sourceFile, start2, end - start2, Messages.expressionExpected); - } else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) { - expressionDiagnostic = createDiagnosticForNode(expression, Messages.uselessConstantType); - } - for (const scope of scopes) { - usagesPerScope.push({ usages: /* @__PURE__ */ new Map(), typeParameterUsages: /* @__PURE__ */ new Map(), substitutions: /* @__PURE__ */ new Map() }); - substitutionsPerScope.push(/* @__PURE__ */ new Map()); - functionErrorsPerScope.push([]); - const constantErrors = []; - if (expressionDiagnostic) { - constantErrors.push(expressionDiagnostic); - } - if (isClassLike(scope) && isInJSFile(scope)) { - constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); - } - if (isArrowFunction(scope) && !isBlock(scope.body)) { - constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction)); - } - constantErrorsPerScope.push(constantErrors); - } - const seenUsages = /* @__PURE__ */ new Map(); - const target = isReadonlyArray(targetRange.range) ? factory.createBlock(targetRange.range) : targetRange.range; - const unmodifiedNode = isReadonlyArray(targetRange.range) ? first(targetRange.range) : targetRange.range; - const inGenericContext = isInGenericContext(unmodifiedNode); - collectUsages(target); - if (inGenericContext && !isReadonlyArray(targetRange.range) && !isJsxAttribute(targetRange.range)) { - const contextualType = checker.getContextualType(targetRange.range); - recordTypeParameterUsages(contextualType); - } - if (allTypeParameterUsages.size > 0) { - const seenTypeParameterUsages = /* @__PURE__ */ new Map(); - let i = 0; - for (let curr = unmodifiedNode; curr !== void 0 && i < scopes.length; curr = curr.parent) { - if (curr === scopes[i]) { - seenTypeParameterUsages.forEach((typeParameter, id) => { - usagesPerScope[i].typeParameterUsages.set(id, typeParameter); - }); - i++; - } - if (isDeclarationWithTypeParameters(curr)) { - for (const typeParameterDecl of getEffectiveTypeParameterDeclarations(curr)) { - const typeParameter = checker.getTypeAtLocation(typeParameterDecl); - if (allTypeParameterUsages.has(typeParameter.id.toString())) { - seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter); - } - } - } - } - Debug.assert(i === scopes.length, "Should have iterated all scopes"); - } - if (visibleDeclarationsInExtractedRange.length) { - const containingLexicalScopeOfExtraction = isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : getEnclosingBlockScopeContainer(scopes[0]); - forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); - } - for (let i = 0; i < scopes.length; i++) { - const scopeUsages = usagesPerScope[i]; - if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { - const errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; - constantErrorsPerScope[i].push(createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); - } - if (targetRange.facts & 16 /* UsesThisInFunction */ && isClassLike(scopes[i])) { - functionErrorsPerScope[i].push(createDiagnosticForNode(targetRange.thisNode, Messages.cannotExtractFunctionsContainingThisToMethod)); - } - let hasWrite = false; - let readonlyClassPropertyWrite; - usagesPerScope[i].usages.forEach((value) => { - if (value.usage === 2 /* Write */) { - hasWrite = true; - if (value.symbol.flags & 106500 /* ClassMember */ && value.symbol.valueDeclaration && hasEffectiveModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) { - readonlyClassPropertyWrite = value.symbol.valueDeclaration; - } - } - }); - Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0, "No variable declarations expected if something was extracted"); - if (hasWrite && !isReadonlyArray(targetRange.range)) { - const diag2 = createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression); - functionErrorsPerScope[i].push(diag2); - constantErrorsPerScope[i].push(diag2); - } else if (readonlyClassPropertyWrite && i > 0) { - const diag2 = createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor); - functionErrorsPerScope[i].push(diag2); - constantErrorsPerScope[i].push(diag2); - } else if (firstExposedNonVariableDeclaration) { - const diag2 = createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity); - functionErrorsPerScope[i].push(diag2); - constantErrorsPerScope[i].push(diag2); - } - } - return { target, usagesPerScope, functionErrorsPerScope, constantErrorsPerScope, exposedVariableDeclarations }; - function isInGenericContext(node) { - return !!findAncestor(node, (n) => isDeclarationWithTypeParameters(n) && getEffectiveTypeParameterDeclarations(n).length !== 0); - } - function recordTypeParameterUsages(type) { - const symbolWalker = checker.getSymbolWalker(() => (cancellationToken.throwIfCancellationRequested(), true)); - const { visitedTypes } = symbolWalker.walkType(type); - for (const visitedType of visitedTypes) { - if (visitedType.isTypeParameter()) { - allTypeParameterUsages.set(visitedType.id.toString(), visitedType); - } - } - } - function collectUsages(node, valueUsage = 1 /* Read */) { - if (inGenericContext) { - const type = checker.getTypeAtLocation(node); - recordTypeParameterUsages(type); - } - if (isDeclaration(node) && node.symbol) { - visibleDeclarationsInExtractedRange.push(node); - } - if (isAssignmentExpression(node)) { - collectUsages(node.left, 2 /* Write */); - collectUsages(node.right); - } else if (isUnaryExpressionWithWrite(node)) { - collectUsages(node.operand, 2 /* Write */); - } else if (isPropertyAccessExpression(node) || isElementAccessExpression(node)) { - forEachChild(node, collectUsages); - } else if (isIdentifier(node)) { - if (!node.parent) { - return; - } - if (isQualifiedName(node.parent) && node !== node.parent.left) { - return; - } - if (isPropertyAccessExpression(node.parent) && node !== node.parent.expression) { - return; - } - recordUsage( - node, - valueUsage, - /*isTypeNode*/ - isPartOfTypeNode(node) - ); - } else { - forEachChild(node, collectUsages); - } - } - function recordUsage(n, usage, isTypeNode2) { - const symbolId = recordUsagebySymbol(n, usage, isTypeNode2); - if (symbolId) { - for (let i = 0; i < scopes.length; i++) { - const substitution = substitutionsPerScope[i].get(symbolId); - if (substitution) { - usagesPerScope[i].substitutions.set(getNodeId(n).toString(), substitution); - } - } - } - } - function recordUsagebySymbol(identifier, usage, isTypeName) { - const symbol = getSymbolReferencedByIdentifier(identifier); - if (!symbol) { - return void 0; - } - const symbolId = getSymbolId(symbol).toString(); - const lastUsage = seenUsages.get(symbolId); - if (lastUsage && lastUsage >= usage) { - return symbolId; - } - seenUsages.set(symbolId, usage); - if (lastUsage) { - for (const perScope of usagesPerScope) { - const prevEntry = perScope.usages.get(identifier.text); - if (prevEntry) { - perScope.usages.set(identifier.text, { usage, symbol, node: identifier }); - } - } - return symbolId; - } - const decls = symbol.getDeclarations(); - const declInFile = decls && find(decls, (d) => d.getSourceFile() === sourceFile); - if (!declInFile) { - return void 0; - } - if (rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) { - return void 0; - } - if (targetRange.facts & 2 /* IsGenerator */ && usage === 2 /* Write */) { - const diag2 = createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators); - for (const errors of functionErrorsPerScope) { - errors.push(diag2); - } - for (const errors of constantErrorsPerScope) { - errors.push(diag2); - } - } - for (let i = 0; i < scopes.length; i++) { - const scope = scopes[i]; - const resolvedSymbol = checker.resolveName( - symbol.name, - scope, - symbol.flags, - /*excludeGlobals*/ - false - ); - if (resolvedSymbol === symbol) { - continue; - } - if (!substitutionsPerScope[i].has(symbolId)) { - const substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName); - if (substitution) { - substitutionsPerScope[i].set(symbolId, substitution); - } else if (isTypeName) { - if (!(symbol.flags & 262144 /* TypeParameter */)) { - const diag2 = createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope); - functionErrorsPerScope[i].push(diag2); - constantErrorsPerScope[i].push(diag2); - } - } else { - usagesPerScope[i].usages.set(identifier.text, { usage, symbol, node: identifier }); - } - } - } - return symbolId; - } - function checkForUsedDeclarations(node) { - if (node === targetRange.range || isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0) { - return; - } - const sym = isIdentifier(node) ? getSymbolReferencedByIdentifier(node) : checker.getSymbolAtLocation(node); - if (sym) { - const decl = find(visibleDeclarationsInExtractedRange, (d) => d.symbol === sym); - if (decl) { - if (isVariableDeclaration(decl)) { - const idString = decl.symbol.id.toString(); - if (!exposedVariableSymbolSet.has(idString)) { - exposedVariableDeclarations.push(decl); - exposedVariableSymbolSet.set(idString, true); - } - } else { - firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; - } - } - } - forEachChild(node, checkForUsedDeclarations); - } - function getSymbolReferencedByIdentifier(identifier) { - return identifier.parent && isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier ? checker.getShorthandAssignmentValueSymbol(identifier.parent) : checker.getSymbolAtLocation(identifier); - } - function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode2) { - if (!symbol) { - return void 0; - } - const decls = symbol.getDeclarations(); - if (decls && decls.some((d) => d.parent === scopeDecl)) { - return factory.createIdentifier(symbol.name); - } - const prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode2); - if (prefix === void 0) { - return void 0; - } - return isTypeNode2 ? factory.createQualifiedName(prefix, factory.createIdentifier(symbol.name)) : factory.createPropertyAccessExpression(prefix, symbol.name); - } -} -function getExtractableParent(node) { - return findAncestor(node, (node2) => node2.parent && isExtractableExpression(node2) && !isBinaryExpression(node2.parent)); -} -function isExtractableExpression(node) { - const { parent: parent2 } = node; - switch (parent2.kind) { - case 305 /* EnumMember */: - return false; - } - switch (node.kind) { - case 11 /* StringLiteral */: - return parent2.kind !== 271 /* ImportDeclaration */ && parent2.kind !== 275 /* ImportSpecifier */; - case 229 /* SpreadElement */: - case 205 /* ObjectBindingPattern */: - case 207 /* BindingElement */: - return false; - case 80 /* Identifier */: - return parent2.kind !== 207 /* BindingElement */ && parent2.kind !== 275 /* ImportSpecifier */ && parent2.kind !== 280 /* ExportSpecifier */; - } - return true; -} -function isBlockLike(node) { - switch (node.kind) { - case 240 /* Block */: - case 311 /* SourceFile */: - case 267 /* ModuleBlock */: - case 295 /* CaseClause */: - return true; - default: - return false; - } -} -function isInJSXContent(node) { - return isStringLiteralJsxAttribute(node) || (isJsxElement(node) || isJsxSelfClosingElement(node) || isJsxFragment(node)) && (isJsxElement(node.parent) || isJsxFragment(node.parent)); -} -function isStringLiteralJsxAttribute(node) { - return isStringLiteral(node) && node.parent && isJsxAttribute(node.parent); -} - -// src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts -var ts_refactor_generateGetAccessorAndSetAccessor_exports = {}; - -// src/services/refactors/generateGetAccessorAndSetAccessor.ts -var actionName = "Generate 'get' and 'set' accessors"; -var actionDescription = Diagnostics.Generate_get_and_set_accessors.message; -var generateGetSetAction = { - name: actionName, - description: actionDescription, - kind: "refactor.rewrite.property.generateAccessors" -}; -registerRefactor(actionName, { - kinds: [generateGetSetAction.kind], - getEditsForAction: function getRefactorActionsToGenerateGetAndSetAccessors(context, actionName2) { - if (!context.endPosition) - return void 0; - const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_codefix_exports.generateAccessorFromProperty(context.file, context.program, context.startPosition, context.endPosition, context, actionName2); - if (!edits) - return void 0; - const renameFilename = context.file.fileName; - const nameNeedRename = info.renameAccessor ? info.accessorName : info.fieldName; - const renameLocationOffset = isIdentifier(nameNeedRename) ? 0 : -1; - const renameLocation = renameLocationOffset + getRenameLocation( - edits, - renameFilename, - nameNeedRename.text, - /*preferLastLocation*/ - isParameter(info.declaration) - ); - return { renameFilename, renameLocation, edits }; - }, - getAvailableActions(context) { - if (!context.endPosition) - return emptyArray; - const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition, context.triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - return [{ - name: actionName, - description: actionDescription, - actions: [generateGetSetAction] - }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: actionName, - description: actionDescription, - actions: [{ ...generateGetSetAction, notApplicableReason: info.error }] - }]; - } - return emptyArray; - } -}); - -// src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts -var ts_refactor_inferFunctionReturnType_exports = {}; - -// src/services/refactors/inferFunctionReturnType.ts -var refactorName12 = "Infer function return type"; -var refactorDescription6 = Diagnostics.Infer_function_return_type.message; -var inferReturnTypeAction = { - name: refactorName12, - description: refactorDescription6, - kind: "refactor.rewrite.function.returnType" -}; -registerRefactor(refactorName12, { - kinds: [inferReturnTypeAction.kind], - getEditsForAction: getRefactorEditsToInferReturnType, - getAvailableActions: getRefactorActionsToInferReturnType -}); -function getRefactorEditsToInferReturnType(context) { - const info = getInfo21(context); - if (info && !isRefactorErrorInfo(info)) { - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange39(context.file, t, info.declaration, info.returnTypeNode)); - return { renameFilename: void 0, renameLocation: void 0, edits }; - } - return void 0; -} -function getRefactorActionsToInferReturnType(context) { - const info = getInfo21(context); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - return [{ - name: refactorName12, - description: refactorDescription6, - actions: [inferReturnTypeAction] - }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorName12, - description: refactorDescription6, - actions: [{ ...inferReturnTypeAction, notApplicableReason: info.error }] - }]; - } - return emptyArray; -} -function doChange39(sourceFile, changes, declaration, typeNode) { - const closeParen = findChildOfKind(declaration, 22 /* CloseParenToken */, sourceFile); - const needParens = isArrowFunction(declaration) && closeParen === void 0; - const endNode2 = needParens ? first(declaration.parameters) : closeParen; - if (endNode2) { - if (needParens) { - changes.insertNodeBefore(sourceFile, endNode2, factory.createToken(21 /* OpenParenToken */)); - changes.insertNodeAfter(sourceFile, endNode2, factory.createToken(22 /* CloseParenToken */)); - } - changes.insertNodeAt(sourceFile, endNode2.end, typeNode, { prefix: ": " }); - } -} -function getInfo21(context) { - if (isInJSFile(context.file) || !refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind)) - return; - const token = getTokenAtPosition(context.file, context.startPosition); - const declaration = findAncestor(token, (n) => isBlock(n) || n.parent && isArrowFunction(n.parent) && (n.kind === 39 /* EqualsGreaterThanToken */ || n.parent.body === n) ? "quit" : isConvertibleDeclaration(n)); - if (!declaration || !declaration.body || declaration.type) { - return { error: getLocaleSpecificMessage(Diagnostics.Return_type_must_be_inferred_from_a_function) }; - } - const typeChecker = context.program.getTypeChecker(); - const returnType = tryGetReturnType(typeChecker, declaration); - if (!returnType) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_determine_function_return_type) }; - } - const returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */); - if (returnTypeNode) { - return { declaration, returnTypeNode }; - } -} -function isConvertibleDeclaration(node) { - switch (node.kind) { - case 261 /* FunctionDeclaration */: - case 217 /* FunctionExpression */: - case 218 /* ArrowFunction */: - case 173 /* MethodDeclaration */: - return true; - default: - return false; - } -} -function tryGetReturnType(typeChecker, node) { - if (typeChecker.isImplementationOfOverload(node)) { - const signatures = typeChecker.getTypeAtLocation(node).getCallSignatures(); - if (signatures.length > 1) { - return typeChecker.getUnionType(mapDefined(signatures, (s) => s.getReturnType())); - } - } - const signature = typeChecker.getSignatureFromDeclaration(node); - if (signature) { - return typeChecker.getReturnTypeOfSignature(signature); - } -} - // src/services/_namespaces/ts.Rename.ts var ts_Rename_exports = {}; __export(ts_Rename_exports, { @@ -164393,7 +165190,7 @@ function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, so displayParts.push(spacePart()); displayParts.push(operatorPart(64 /* EqualsToken */)); displayParts.push(spacePart()); - addRange(displayParts, typeToDisplayParts(typeChecker, isConstTypeReference(location.parent) ? typeChecker.getTypeAtLocation(location.parent) : typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); + addRange(displayParts, typeToDisplayParts(typeChecker, location.parent && isConstTypeReference(location.parent) ? typeChecker.getTypeAtLocation(location.parent) : typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { prefixNextMeaning(); @@ -164469,12 +165266,12 @@ function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, so } if (symbol.flags & 2097152 /* Alias */) { prefixNextMeaning(); - if (!hasAddedSymbolInfo) { + if (!hasAddedSymbolInfo || documentation.length === 0 && tags.length === 0) { const resolvedSymbol = typeChecker.getAliasedSymbol(symbol); if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { const resolvedNode = resolvedSymbol.declarations[0]; const declarationName = getNameOfDeclaration(resolvedNode); - if (declarationName) { + if (declarationName && !hasAddedSymbolInfo) { const isExternalModuleDeclaration = isModuleWithStringLiteralName(resolvedNode) && hasSyntacticModifier(resolvedNode, 2 /* Ambient */); const shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind( @@ -164765,7 +165562,6 @@ __export(ts_textChanges_exports, { assignPositionsToNode: () => assignPositionsToNode, createWriter: () => createWriter, deleteNode: () => deleteNode, - getNewFileText: () => getNewFileText, isThisTypeAnnotatable: () => isThisTypeAnnotatable, isValidLocationToAddComment: () => isValidLocationToAddComment }); @@ -164942,7 +165738,6 @@ var ChangeTracker = class { this.newLineCharacter = newLineCharacter; this.formatContext = formatContext; this.changes = []; - this.newFiles = []; this.classesWithNodesInsertedAtStart = /* @__PURE__ */ new Map(); // Set implemented as Map this.deletedNodes = []; @@ -165058,6 +165853,12 @@ var ChangeTracker = class { this.insertNodeAt(sourceFile, pos, insert, options); } } + insertStatementsInNewFile(fileName, statements, oldFile) { + if (!this.newFileChanges) { + this.newFileChanges = createMultiMap(); + } + this.newFileChanges.add(fileName, { oldFile, statements }); + } insertFirstParameter(sourceFile, parameters, newParam) { const p0 = firstOrUndefined(parameters); if (p0) { @@ -165453,13 +166254,15 @@ ${options.prefix}` : "\n" : options.prefix this.finishDeleteDeclarations(); this.finishClassesWithNodesInsertedAtStart(); const changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); - for (const { oldFile, fileName, statements } of this.newFiles) { - changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); + if (this.newFileChanges) { + this.newFileChanges.forEach((insertions, fileName) => { + changes.push(changesToText.newFileChanges(fileName, insertions, this.newLineCharacter, this.formatContext)); + }); } return changes; } createNewFile(oldFile, fileName, statements) { - this.newFiles.push({ oldFile, fileName, statements }); + this.insertStatementsInNewFile(fileName, statements, oldFile); } }; function updateJSDocHost(parent2) { @@ -165550,16 +166353,6 @@ function getClassOrObjectBraceEnds(cls, sourceFile) { function getMembersOrProperties(node) { return isObjectLiteralExpression(node) ? node.properties : node.members; } -function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { - return changesToText.newFileChangesWorker( - /*oldFile*/ - void 0, - scriptKind, - statements, - newLineCharacter, - formatContext - ); -} var changesToText; ((changesToText2) => { function getTextChangesFromChanges(changes, newLineCharacter, formatContext, validate) { @@ -165571,8 +166364,9 @@ var changesToText; } const textChanges2 = mapDefined(normalized, (c) => { const span = createTextSpanFromRange(c.range); - const newText = computeNewText(c, sourceFile, newLineCharacter, formatContext, validate); - if (span.length === newText.length && stringContainsAt(sourceFile.text, newText, span.start)) { + const targetSourceFile = c.kind === 1 /* ReplaceWithSingleNode */ ? getSourceFileOfNode(getOriginalNode(c.node)) ?? c.sourceFile : c.kind === 2 /* ReplaceWithMultipleNodes */ ? getSourceFileOfNode(getOriginalNode(c.nodes[0])) ?? c.sourceFile : c.sourceFile; + const newText = computeNewText(c, targetSourceFile, sourceFile, newLineCharacter, formatContext, validate); + if (span.length === newText.length && stringContainsAt(targetSourceFile.text, newText, span.start)) { return void 0; } return createTextChange(span, newText); @@ -165581,13 +166375,13 @@ var changesToText; }); } changesToText2.getTextChangesFromChanges = getTextChangesFromChanges; - function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { - const text = newFileChangesWorker(oldFile, getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); + function newFileChanges(fileName, insertions, newLineCharacter, formatContext) { + const text = newFileChangesWorker(getScriptKindFromFileName(fileName), insertions, newLineCharacter, formatContext); return { fileName, textChanges: [createTextChange(createTextSpan(0, 0), text)], isNewFile: true }; } changesToText2.newFileChanges = newFileChanges; - function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { - const nonFormattedText = statements.map((s) => s === 4 /* NewLineTrivia */ ? "" : getNonformattedText(s, oldFile, newLineCharacter).text).join(newLineCharacter); + function newFileChangesWorker(scriptKind, insertions, newLineCharacter, formatContext) { + const nonFormattedText = flatMap(insertions, (insertion) => insertion.statements.map((s) => s === 4 /* NewLineTrivia */ ? "" : getNonformattedText(s, insertion.oldFile, newLineCharacter).text)).join(newLineCharacter); const sourceFile = createSourceFile( "any file name", nonFormattedText, @@ -165600,7 +166394,7 @@ var changesToText; return applyChanges(nonFormattedText, changes) + newLineCharacter; } changesToText2.newFileChangesWorker = newFileChangesWorker; - function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { + function computeNewText(change, targetSourceFile, sourceFile, newLineCharacter, formatContext, validate) { var _a; if (change.kind === 0 /* Remove */) { return ""; @@ -165609,17 +166403,17 @@ var changesToText; return change.text; } const { options = {}, range: { pos } } = change; - const format = (n) => getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); + const format = (n) => getFormattedTextOfNode(n, targetSourceFile, sourceFile, pos, options, newLineCharacter, formatContext, validate); const text = change.kind === 2 /* ReplaceWithMultipleNodes */ ? change.nodes.map((n) => removeSuffix(format(n), newLineCharacter)).join(((_a = change.options) == null ? void 0 : _a.joiner) || newLineCharacter) : format(change.node); - const noIndent = options.indentation !== void 0 || getLineStartPositionForPosition(pos, sourceFile) === pos ? text : text.replace(/^\s+/, ""); + const noIndent = options.indentation !== void 0 || getLineStartPositionForPosition(pos, targetSourceFile) === pos ? text : text.replace(/^\s+/, ""); return (options.prefix || "") + noIndent + (!options.suffix || endsWith(noIndent, options.suffix) ? "" : options.suffix); } - function getFormattedTextOfNode(nodeIn, sourceFile, pos, { indentation, prefix, delta }, newLineCharacter, formatContext, validate) { - const { node, text } = getNonformattedText(nodeIn, sourceFile, newLineCharacter); + function getFormattedTextOfNode(nodeIn, targetSourceFile, sourceFile, pos, { indentation, prefix, delta }, newLineCharacter, formatContext, validate) { + const { node, text } = getNonformattedText(nodeIn, targetSourceFile, newLineCharacter); if (validate) validate(node, text); - const formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile); - const initialIndentation = indentation !== void 0 ? indentation : ts_formatting_exports.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || getLineStartPositionForPosition(pos, sourceFile) === pos); + const formatOptions = getFormatCodeSettingsForWriting(formatContext, targetSourceFile); + const initialIndentation = indentation !== void 0 ? indentation : ts_formatting_exports.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || getLineStartPositionForPosition(pos, targetSourceFile) === pos); if (delta === void 0) { delta = ts_formatting_exports.SmartIndenter.shouldIndentChildNode(formatOptions, nodeIn) ? formatOptions.indentSize || 0 : 0; } @@ -165629,7 +166423,7 @@ var changesToText; return getLineAndCharacterOfPosition(this, pos2); } }; - const changes = ts_formatting_exports.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, { ...formatContext, options: formatOptions }); + const changes = ts_formatting_exports.formatNodeGivenIndentation(node, file, targetSourceFile.languageVariant, initialIndentation, delta, { ...formatContext, options: formatOptions }); return applyChanges(text, changes); } function getNonformattedText(node, sourceFile, newLineCharacter) { @@ -169175,6 +169969,7 @@ __export(ts_exports2, { createMemberAccessForPropertyName: () => createMemberAccessForPropertyName, createModeAwareCache: () => createModeAwareCache, createModeAwareCacheKey: () => createModeAwareCacheKey, + createModuleNotFoundChain: () => createModuleNotFoundChain, createModuleResolutionCache: () => createModuleResolutionCache, createModuleResolutionLoader: () => createModuleResolutionLoader, createModuleSpecifierResolutionHost: () => createModuleSpecifierResolutionHost, @@ -169309,6 +170104,7 @@ __export(ts_exports2, { fileExtensionIs: () => fileExtensionIs, fileExtensionIsOneOf: () => fileExtensionIsOneOf, fileIncludeReasonToDiagnostics: () => fileIncludeReasonToDiagnostics, + fileShouldUseJavaScriptRequire: () => fileShouldUseJavaScriptRequire, filter: () => filter, filterMutate: () => filterMutate, filterSemanticDiagnostics: () => filterSemanticDiagnostics, @@ -169544,6 +170340,7 @@ __export(ts_exports2, { getImportNeedsImportStarHelper: () => getImportNeedsImportStarHelper, getIndentSize: () => getIndentSize, getIndentString: () => getIndentString, + getInferredLibraryNameResolveFrom: () => getInferredLibraryNameResolveFrom, getInitializedVariables: () => getInitializedVariables, getInitializerOfBinaryExpression: () => getInitializerOfBinaryExpression, getInitializerOfBindingOrAssignmentElement: () => getInitializerOfBindingOrAssignmentElement, @@ -169664,6 +170461,7 @@ __export(ts_exports2, { getOperatorAssociativity: () => getOperatorAssociativity, getOperatorPrecedence: () => getOperatorPrecedence, getOptionFromName: () => getOptionFromName, + getOptionsForLibraryResolution: () => getOptionsForLibraryResolution, getOptionsNameMap: () => getOptionsNameMap, getOrCreateEmitNode: () => getOrCreateEmitNode, getOrCreateExternalHelpersModuleNameIfNeeded: () => getOrCreateExternalHelpersModuleNameIfNeeded, @@ -170054,7 +170852,6 @@ __export(ts_exports2, { isEmptyObjectLiteral: () => isEmptyObjectLiteral, isEmptyStatement: () => isEmptyStatement, isEmptyStringLiteral: () => isEmptyStringLiteral, - isEndOfDeclarationMarker: () => isEndOfDeclarationMarker, isEntityName: () => isEntityName, isEntityNameExpression: () => isEntityNameExpression, isEnumConst: () => isEnumConst, @@ -170285,7 +171082,6 @@ __export(ts_exports2, { isLogicalOrCoalescingBinaryOperator: () => isLogicalOrCoalescingBinaryOperator, isMappedTypeNode: () => isMappedTypeNode, isMemberName: () => isMemberName, - isMergeDeclarationMarker: () => isMergeDeclarationMarker, isMetaProperty: () => isMetaProperty, isMethodDeclaration: () => isMethodDeclaration, isMethodOrAccessor: () => isMethodOrAccessor, @@ -170775,6 +171571,7 @@ __export(ts_exports2, { resolutionExtensionIsTSOrJson: () => resolutionExtensionIsTSOrJson, resolveConfigFileProjectName: () => resolveConfigFileProjectName, resolveJSModule: () => resolveJSModule, + resolveLibrary: () => resolveLibrary, resolveModuleName: () => resolveModuleName, resolveModuleNameFromCache: () => resolveModuleNameFromCache, resolvePackageNameToPackageJson: () => resolvePackageNameToPackageJson, @@ -171165,9 +171962,9 @@ function buildOverload(name) { // src/deprecatedCompat/5.0/identifierProperties.ts addObjectAllocatorPatcher((objectAllocator2) => { - const Identifier73 = objectAllocator2.getIdentifierConstructor(); - if (!hasProperty(Identifier73.prototype, "originalKeywordKind")) { - Object.defineProperty(Identifier73.prototype, "originalKeywordKind", { + const Identifier74 = objectAllocator2.getIdentifierConstructor(); + if (!hasProperty(Identifier74.prototype, "originalKeywordKind")) { + Object.defineProperty(Identifier74.prototype, "originalKeywordKind", { get: deprecate(function() { return identifierToKeywordKind(this); }, { @@ -171179,8 +171976,8 @@ addObjectAllocatorPatcher((objectAllocator2) => { }) }); } - if (!hasProperty(Identifier73.prototype, "isInJSDocNamespace")) { - Object.defineProperty(Identifier73.prototype, "isInJSDocNamespace", { + if (!hasProperty(Identifier74.prototype, "isInJSDocNamespace")) { + Object.defineProperty(Identifier74.prototype, "isInJSDocNamespace", { get: deprecate(function() { return this.flags & 2048 /* IdentifierIsInJSDocNamespace */ ? true : void 0; }, { @@ -171200,6 +171997,7 @@ __export(ts_server_exports3, { ActionInvalidate: () => ActionInvalidate, ActionPackageInstalled: () => ActionPackageInstalled, ActionSet: () => ActionSet, + ActionWatchTypingLocations: () => ActionWatchTypingLocations, Arguments: () => Arguments, AutoImportProviderProject: () => AutoImportProviderProject, CharRangeSection: () => CharRangeSection, @@ -171333,19 +172131,6 @@ function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remainin } return { command, remaining: remaining - toSlice }; } -function endsWith2(str, suffix, caseSensitive) { - const expectedPos = str.length - suffix.length; - return expectedPos >= 0 && (str.indexOf(suffix, expectedPos) === expectedPos || !caseSensitive && compareStringsCaseInsensitive(str.substr(expectedPos), suffix) === 0 /* EqualTo */); -} -function isPackageOrBowerJson(fileName, caseSensitive) { - return endsWith2(fileName, "/package.json", caseSensitive) || endsWith2(fileName, "/bower.json", caseSensitive); -} -function sameFiles(a, b, caseSensitive) { - return a === b || !caseSensitive && compareStringsCaseInsensitive(a, b) === 0 /* EqualTo */; -} -function getDetailWatchInfo(projectName, watchers) { - return `Project: ${projectName} watcher already invoked: ${watchers == null ? void 0 : watchers.isInvoked}`; -} var TypingsInstaller = class { constructor(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log = nullLog) { this.installTypingHost = installTypingHost; @@ -171363,13 +172148,10 @@ var TypingsInstaller = class { this.installRunCount = 1; this.inFlightRequestCount = 0; this.latestDistTag = "latest"; - this.toCanonicalFileName = createGetCanonicalFileName(installTypingHost.useCaseSensitiveFileNames); - this.globalCachePackageJsonPath = combinePaths(globalCachePath, "package.json"); const isLoggingEnabled = this.log.isEnabled(); if (isLoggingEnabled) { this.log.writeLine(`Global cache location '${globalCachePath}', safe file path '${safeListPath}', types map path ${typesMapLocation}`); } - this.watchFactory = getWatchFactory(this.installTypingHost, isLoggingEnabled ? 2 /* Verbose */ : 0 /* None */, (s) => this.log.writeLine(s), getDetailWatchInfo); this.processCacheLocation(this.globalCachePath); } closeProject(req) { @@ -171386,8 +172168,8 @@ var TypingsInstaller = class { } return; } - clearMap(watchers, closeFileWatcher); this.projectWatchers.delete(projectName); + this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files: [] }); if (this.log.isEnabled()) { this.log.writeLine(`Closing file watchers for project '${projectName}' - done.`); } @@ -171420,7 +172202,7 @@ var TypingsInstaller = class { if (this.log.isEnabled()) { this.log.writeLine(`Finished typings discovery: ${JSON.stringify(discoverTypingsResult)}`); } - this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch, req.projectRootPath, req.watchOptions); + this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch); if (discoverTypingsResult.newTypingNames.length) { this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames); } else { @@ -171621,75 +172403,19 @@ var TypingsInstaller = class { host.createDirectory(directory); } } - watchFiles(projectName, files, projectRootPath, options) { + watchFiles(projectName, files) { if (!files.length) { this.closeWatchers(projectName); return; } - let watchers = this.projectWatchers.get(projectName); - const toRemove = /* @__PURE__ */ new Map(); - if (!watchers) { - watchers = /* @__PURE__ */ new Map(); - this.projectWatchers.set(projectName, watchers); + const existing = this.projectWatchers.get(projectName); + const newSet = new Set(files); + if (!existing || forEachKey(newSet, (s) => !existing.has(s)) || forEachKey(existing, (s) => !newSet.has(s))) { + this.projectWatchers.set(projectName, newSet); + this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files }); } else { - copyEntries(watchers, toRemove); + this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files: void 0 }); } - watchers.isInvoked = false; - const isLoggingEnabled = this.log.isEnabled(); - const createProjectWatcher = (path, projectWatcherType) => { - const canonicalPath = this.toCanonicalFileName(path); - toRemove.delete(canonicalPath); - if (watchers.has(canonicalPath)) { - return; - } - if (isLoggingEnabled) { - this.log.writeLine(`${projectWatcherType}:: Added:: WatchInfo: ${path}`); - } - const watcher = projectWatcherType === "FileWatcher" /* FileWatcher */ ? this.watchFactory.watchFile(path, () => { - if (!watchers.isInvoked) { - watchers.isInvoked = true; - this.sendResponse({ projectName, kind: ActionInvalidate }); - } - }, 2e3 /* High */, options, projectName, watchers) : this.watchFactory.watchDirectory(path, (f) => { - if (watchers.isInvoked || !fileExtensionIs(f, ".json" /* Json */)) { - return; - } - if (isPackageOrBowerJson(f, this.installTypingHost.useCaseSensitiveFileNames) && !sameFiles(f, this.globalCachePackageJsonPath, this.installTypingHost.useCaseSensitiveFileNames)) { - watchers.isInvoked = true; - this.sendResponse({ projectName, kind: ActionInvalidate }); - } - }, 1 /* Recursive */, options, projectName, watchers); - watchers.set(canonicalPath, isLoggingEnabled ? { - close: () => { - this.log.writeLine(`${projectWatcherType}:: Closed:: WatchInfo: ${path}`); - watcher.close(); - } - } : watcher); - }; - for (const file of files) { - if (file.endsWith("/package.json") || file.endsWith("/bower.json")) { - createProjectWatcher(file, "FileWatcher" /* FileWatcher */); - continue; - } - if (containsPath(projectRootPath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) { - const subDirectory = file.indexOf(directorySeparator, projectRootPath.length + 1); - if (subDirectory !== -1) { - createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */); - } else { - createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); - } - continue; - } - if (containsPath(this.globalCachePath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) { - createProjectWatcher(this.globalCachePath, "DirectoryWatcher" /* DirectoryWatcher */); - continue; - } - createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); - } - toRemove.forEach((watch, path) => { - watch.close(); - watchers.delete(path); - }); } createSetTypings(request, typings) { return { @@ -171746,7 +172472,6 @@ function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports true ).concat(project.getExcludedFiles()), compilerOptions: project.getCompilationSettings(), - watchOptions: project.projectService.getWatchOptions(project), typeAcquisition, unresolvedImports, projectRootPath: project.getCurrentDirectory(), @@ -172013,6 +172738,7 @@ var CommandTypes = /* @__PURE__ */ ((CommandTypes2) => { CommandTypes2["GetSupportedCodeFixes"] = "getSupportedCodeFixes"; CommandTypes2["GetApplicableRefactors"] = "getApplicableRefactors"; CommandTypes2["GetEditsForRefactor"] = "getEditsForRefactor"; + CommandTypes2["GetMoveToRefactoringFileSuggestions"] = "getMoveToRefactoringFileSuggestions"; CommandTypes2["GetEditsForRefactorFull"] = "getEditsForRefactor-full"; CommandTypes2["OrganizeImports"] = "organizeImports"; CommandTypes2["OrganizeImportsFull"] = "organizeImports-full"; @@ -172929,34 +173655,49 @@ var Project3 = class { updateProjectIfDirty(this); return hasOneOrMoreJsAndNoTsFiles(this); } - static resolveModule(moduleName, initialDir, host, log, logErrors) { - const resolvedPath = normalizeSlashes(host.resolvePath(combinePaths(initialDir, "node_modules"))); - log(`Loading ${moduleName} from ${initialDir} (resolved to ${resolvedPath})`); - const result = host.require(resolvedPath, moduleName); - if (result.error) { - const err = result.error.stack || result.error.message || JSON.stringify(result.error); - (logErrors || log)(`Failed to load module '${moduleName}' from ${resolvedPath}: ${err}`); - return void 0; - } - return result.module; + static resolveModule(moduleName, initialDir, host, log) { + return Project3.importServicePluginSync({ name: moduleName }, [initialDir], host, log).resolvedModule; } /** @internal */ - static async importServicePluginAsync(moduleName, initialDir, host, log, logErrors) { - Debug.assertIsDefined(host.importPlugin); - const resolvedPath = combinePaths(initialDir, "node_modules"); - log(`Dynamically importing ${moduleName} from ${initialDir} (resolved to ${resolvedPath})`); - let result; - try { - result = await host.importPlugin(resolvedPath, moduleName); - } catch (e) { - result = { module: void 0, error: e }; - } - if (result.error) { + static importServicePluginSync(pluginConfigEntry, searchPaths, host, log) { + Debug.assertIsDefined(host.require); + let errorLogs; + let resolvedModule; + for (const initialDir of searchPaths) { + const resolvedPath = normalizeSlashes(host.resolvePath(combinePaths(initialDir, "node_modules"))); + log(`Loading ${pluginConfigEntry.name} from ${initialDir} (resolved to ${resolvedPath})`); + const result = host.require(resolvedPath, pluginConfigEntry.name); + if (!result.error) { + resolvedModule = result.module; + break; + } const err = result.error.stack || result.error.message || JSON.stringify(result.error); - (logErrors || log)(`Failed to dynamically import module '${moduleName}' from ${resolvedPath}: ${err}`); - return void 0; + (errorLogs ?? (errorLogs = [])).push(`Failed to load module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`); } - return result.module; + return { pluginConfigEntry, resolvedModule, errorLogs }; + } + /** @internal */ + static async importServicePluginAsync(pluginConfigEntry, searchPaths, host, log) { + Debug.assertIsDefined(host.importPlugin); + let errorLogs; + let resolvedModule; + for (const initialDir of searchPaths) { + const resolvedPath = combinePaths(initialDir, "node_modules"); + log(`Dynamically importing ${pluginConfigEntry.name} from ${initialDir} (resolved to ${resolvedPath})`); + let result; + try { + result = await host.importPlugin(resolvedPath, pluginConfigEntry.name); + } catch (e) { + result = { module: void 0, error: e }; + } + if (!result.error) { + resolvedModule = result.module; + break; + } + const err = result.error.stack || result.error.message || JSON.stringify(result.error); + (errorLogs ?? (errorLogs = [])).push(`Failed to dynamically import module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`); + } + return { pluginConfigEntry, resolvedModule, errorLogs }; } isKnownTypesPackageName(name) { return this.typingsCache.isKnownTypesPackageName(name); @@ -173083,6 +173824,10 @@ var Project3 = class { reusedNames ); } + /** @internal */ + resolveLibrary(libraryName, resolveFrom, options, libFileName) { + return this.resolutionCache.resolveLibrary(libraryName, resolveFrom, options, libFileName); + } directoryExists(path) { return this.directoryStructureHost.directoryExists(path); } @@ -173344,6 +174089,8 @@ var Project3 = class { return path === options.configFilePath ? options.configFile : this.getSourceFile(path); } close() { + this.projectService.typingsCache.onProjectClosed(this); + this.closeWatchingTypingLocations(); if (this.program) { for (const f of this.program.getSourceFiles()) { this.detachScriptInfoIfNotRoot(f.fileName); @@ -173634,6 +174381,89 @@ var Project3 = class { } } /** @internal */ + closeWatchingTypingLocations() { + if (this.typingWatchers) + clearMap(this.typingWatchers, closeFileWatcher); + this.typingWatchers = void 0; + } + /** @internal */ + onTypingInstallerWatchInvoke() { + this.typingWatchers.isInvoked = true; + this.projectService.updateTypingsForProject({ projectName: this.getProjectName(), kind: ActionInvalidate }); + } + /** @internal */ + watchTypingLocations(files) { + if (!files) { + this.typingWatchers.isInvoked = false; + return; + } + if (!files.length) { + this.closeWatchingTypingLocations(); + return; + } + const toRemove = new Map(this.typingWatchers); + if (!this.typingWatchers) + this.typingWatchers = /* @__PURE__ */ new Map(); + this.typingWatchers.isInvoked = false; + const createProjectWatcher = (path, typingsWatcherType) => { + const canonicalPath = this.toPath(path); + toRemove.delete(canonicalPath); + if (!this.typingWatchers.has(canonicalPath)) { + this.typingWatchers.set( + canonicalPath, + typingsWatcherType === "FileWatcher" /* FileWatcher */ ? this.projectService.watchFactory.watchFile( + path, + () => !this.typingWatchers.isInvoked ? this.onTypingInstallerWatchInvoke() : this.writeLog(`TypingWatchers already invoked`), + 2e3 /* 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, ".json" /* 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(); + }, + 1 /* Recursive */, + this.projectService.getWatchOptions(this), + WatchType.TypingInstallerLocationDirectory, + this + ) + ); + } + }; + for (const file of files) { + const basename = getBaseFileName(file); + if (basename === "package.json" || basename === "bower.json") { + createProjectWatcher(file, "FileWatcher" /* FileWatcher */); + continue; + } + if (containsPath(this.currentDirectory, file, this.currentDirectory, !this.useCaseSensitiveFileNames())) { + const subDirectory = file.indexOf(directorySeparator, this.currentDirectory.length + 1); + if (subDirectory !== -1) { + createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */); + } else { + createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); + } + continue; + } + if (containsPath(this.projectService.typingsInstaller.globalTypingsCacheLocation, file, this.currentDirectory, !this.useCaseSensitiveFileNames())) { + createProjectWatcher(this.projectService.typingsInstaller.globalTypingsCacheLocation, "DirectoryWatcher" /* DirectoryWatcher */); + continue; + } + createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); + } + toRemove.forEach((watch, path) => { + watch.close(); + this.typingWatchers.delete(path); + }); + } + /** @internal */ getCurrentProgram() { return this.program; } @@ -173647,7 +174477,9 @@ var Project3 = class { Debug.assert(!this.isClosed(), "Called update graph worker of closed project"); this.writeLog(`Starting updateGraphWorker: Project: ${this.getProjectName()}`); const start2 = timestamp(); - this.hasInvalidatedResolutions = this.resolutionCache.createHasInvalidatedResolutions(returnFalse); + const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = this.resolutionCache.createHasInvalidatedResolutions(returnFalse, returnFalse); + this.hasInvalidatedResolutions = hasInvalidatedResolutions; + this.hasInvalidatedLibResolutions = hasInvalidatedLibResolutions; this.resolutionCache.startCachingPerDirectoryResolution(); this.program = this.languageService.getProgram(); this.dirty = false; @@ -173938,7 +174770,7 @@ var Project3 = class { if (changesAffectModuleResolution(oldOptions, compilerOptions)) { this.cachedUnresolvedImportsPerFile.clear(); this.lastCachedUnresolvedImportsList = void 0; - this.resolutionCache.clear(); + this.resolutionCache.onChangesAffectModuleResolution(); this.moduleSpecifierCache.clear(); } this.markAsDirty(); @@ -174064,7 +174896,7 @@ var Project3 = class { combinePaths(this.projectService.getExecutingFilePath(), "../../..") ]; } - enableGlobalPlugins(options, pluginConfigOverrides) { + enableGlobalPlugins(options) { if (!this.projectService.globalPlugins.length) return; const host = this.projectService.host; @@ -174079,67 +174911,13 @@ var Project3 = class { if (options.plugins && options.plugins.some((p) => p.name === globalPluginName)) continue; this.projectService.logger.info(`Loading global plugin ${globalPluginName}`); - this.enablePlugin({ name: globalPluginName, global: true }, searchPaths, pluginConfigOverrides); + this.enablePlugin({ name: globalPluginName, global: true }, searchPaths); } } - /** - * Performs the initial steps of enabling a plugin by finding and instantiating the module for a plugin synchronously using 'require'. - * - * @internal - */ - beginEnablePluginSync(pluginConfigEntry, searchPaths, pluginConfigOverrides) { - Debug.assertIsDefined(this.projectService.host.require); - let errorLogs; - const log = (message) => this.projectService.logger.info(message); - const logError = (message) => { - (errorLogs ?? (errorLogs = [])).push(message); - }; - const resolvedModule = firstDefined(searchPaths, (searchPath) => Project3.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log, logError)); - return { pluginConfigEntry, pluginConfigOverrides, resolvedModule, errorLogs }; - } - /** - * Performs the initial steps of enabling a plugin by finding and instantiating the module for a plugin asynchronously using dynamic `import`. - * - * @internal - */ - async beginEnablePluginAsync(pluginConfigEntry, searchPaths, pluginConfigOverrides) { - Debug.assertIsDefined(this.projectService.host.importPlugin); - let errorLogs; - const log = (message) => this.projectService.logger.info(message); - const logError = (message) => { - (errorLogs ?? (errorLogs = [])).push(message); - }; - let resolvedModule; - for (const searchPath of searchPaths) { - resolvedModule = await Project3.importServicePluginAsync(pluginConfigEntry.name, searchPath, this.projectService.host, log, logError); - if (resolvedModule !== void 0) { - break; - } - } - return { pluginConfigEntry, pluginConfigOverrides, resolvedModule, errorLogs }; - } - /** - * Performs the remaining steps of enabling a plugin after its module has been instantiated. - * - * @internal - */ - endEnablePlugin({ pluginConfigEntry, pluginConfigOverrides, resolvedModule, errorLogs }) { - if (resolvedModule) { - const configurationOverride = pluginConfigOverrides && pluginConfigOverrides.get(pluginConfigEntry.name); - if (configurationOverride) { - const pluginName = pluginConfigEntry.name; - pluginConfigEntry = configurationOverride; - pluginConfigEntry.name = pluginName; - } - this.enableProxy(resolvedModule, pluginConfigEntry); - } else { - forEach(errorLogs, (message) => this.projectService.logger.info(message)); - this.projectService.logger.info(`Couldn't find ${pluginConfigEntry.name}`); - } - } - enablePlugin(pluginConfigEntry, searchPaths, pluginConfigOverrides) { - this.projectService.requestEnablePlugin(this, pluginConfigEntry, searchPaths, pluginConfigOverrides); + enablePlugin(pluginConfigEntry, searchPaths) { + this.projectService.requestEnablePlugin(this, pluginConfigEntry, searchPaths); } + /** @internal */ enableProxy(pluginModuleFactory, configEntry) { try { if (typeof pluginModuleFactory !== "function") { @@ -174355,7 +175133,7 @@ function extractUnresolvedImportsFromSourceFile(file, ambientModules, cachedUnre } var InferredProject2 = class extends Project3 { /** @internal */ - constructor(projectService, documentRegistry, compilerOptions, watchOptions, projectRootPath, currentDirectory, pluginConfigOverrides, typeAcquisition) { + constructor(projectService, documentRegistry, compilerOptions, watchOptions, projectRootPath, currentDirectory, typeAcquisition) { super( projectService.newInferredProjectName(), 0 /* Inferred */, @@ -174379,7 +175157,7 @@ var InferredProject2 = class extends Project3 { if (!projectRootPath && !projectService.useSingleInferredProject) { this.canonicalCurrentDirectory = projectService.toCanonicalFileName(this.currentDirectory); } - this.enableGlobalPlugins(this.getCompilerOptions(), pluginConfigOverrides); + this.enableGlobalPlugins(this.getCompilerOptions()); } toggleJsInferredProject(isJsInferredProject) { if (isJsInferredProject !== this._isJsInferredProject) { @@ -174408,13 +175186,18 @@ var InferredProject2 = class extends Project3 { /*isJsInferredProject*/ true ); + } else if (this.isOrphan() && this._isJsInferredProject && !info.isJavaScript()) { + this.toggleJsInferredProject( + /*isJsInferredProject*/ + false + ); } super.addRoot(info); } removeRoot(info) { this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info); super.removeRoot(info); - if (this._isJsInferredProject && info.isJavaScript()) { + if (!this.isOrphan() && this._isJsInferredProject && info.isJavaScript()) { if (every(this.getRootScriptInfos(), (rootInfo) => !rootInfo.isJavaScript())) { this.toggleJsInferredProject( /*isJsInferredProject*/ @@ -174840,7 +175623,7 @@ var ConfiguredProject2 = class extends Project3 { return (_a = this.getCurrentProgram()) == null ? void 0 : _a.forEachResolvedProjectReference(cb); } /** @internal */ - enablePluginsWithOptions(options, pluginConfigOverrides) { + enablePluginsWithOptions(options) { var _a; this.plugins.length = 0; if (!((_a = options.plugins) == null ? void 0 : _a.length) && !this.projectService.globalPlugins.length) @@ -174858,10 +175641,10 @@ var ConfiguredProject2 = class extends Project3 { } if (options.plugins) { for (const pluginConfigEntry of options.plugins) { - this.enablePlugin(pluginConfigEntry, searchPaths, pluginConfigOverrides); + this.enablePlugin(pluginConfigEntry, searchPaths); } } - return this.enableGlobalPlugins(options, pluginConfigOverrides); + return this.enableGlobalPlugins(options); } /** * Get the errors that dont have any file name associated @@ -174954,7 +175737,7 @@ var ConfiguredProject2 = class extends Project3 { }; var ExternalProject2 = class extends Project3 { /** @internal */ - constructor(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath, pluginConfigOverrides, watchOptions) { + constructor(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath, watchOptions) { super( externalProjectName, 2 /* External */, @@ -174972,7 +175755,7 @@ var ExternalProject2 = class extends Project3 { this.externalProjectName = externalProjectName; this.compileOnSaveEnabled = compileOnSaveEnabled; this.excludedFiles = []; - this.enableGlobalPlugins(this.getCompilerOptions(), pluginConfigOverrides); + this.enableGlobalPlugins(this.getCompilerOptions()); } updateGraph() { const result = super.updateGraph(); @@ -175245,7 +176028,7 @@ function forEachReferencedProject(project, cb) { (potentialProjectRef) => callbackRefProject(project, cb, potentialProjectRef) ); } -function getDetailWatchInfo2(watchType, project) { +function getDetailWatchInfo(watchType, project) { return `${isString(project) ? `Config: ${project} ` : project ? `Project: ${project.getProjectName()} ` : ""}WatchType: ${watchType}`; } function isScriptInfoWatchedFromNodeModules(info) { @@ -175391,7 +176174,7 @@ var _ProjectService = class { this.watchFactory = this.serverMode !== 0 /* Semantic */ ? { watchFile: returnNoopFileWatcher, watchDirectory: returnNoopFileWatcher - } : getWatchFactory(this.host, watchLogLevel, log, getDetailWatchInfo2); + } : getWatchFactory(this.host, watchLogLevel, log, getDetailWatchInfo); } toPath(fileName) { return toPath(fileName, this.currentDirectory, this.toCanonicalFileName); @@ -175477,6 +176260,11 @@ var _ProjectService = class { } } /** @internal */ + watchTypingLocations(response) { + var _a; + (_a = this.findProject(response.projectName)) == null ? void 0 : _a.watchTypingLocations(response.files); + } + /** @internal */ delayEnsureProjectForOpenFiles() { if (!this.openFiles.size) return; @@ -176308,7 +177096,6 @@ var _ProjectService = class { options.compileOnSave === void 0 ? true : options.compileOnSave, /*projectFilePath*/ void 0, - this.currentPluginConfigOverrides, watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions ); project.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors); @@ -176457,7 +177244,7 @@ var _ProjectService = class { project.enableLanguageService(); this.watchWildcards(configFilename, configFileExistenceInfo, project); } - project.enablePluginsWithOptions(compilerOptions, this.currentPluginConfigOverrides); + project.enablePluginsWithOptions(compilerOptions); const filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave, parsedCommandLine.watchOptions); (_b = tracing) == null ? void 0 : _b.pop(); @@ -176798,7 +177585,7 @@ var _ProjectService = class { typeAcquisition = this.typeAcquisitionForInferredProjects; } watchOptionsAndErrors = watchOptionsAndErrors || void 0; - const project = new InferredProject2(this, this.documentRegistry, compilerOptions, watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions, projectRootPath, currentDirectory, this.currentPluginConfigOverrides, typeAcquisition); + const project = new InferredProject2(this, this.documentRegistry, compilerOptions, watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions, projectRootPath, currentDirectory, typeAcquisition); project.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors); if (isSingleInferredProject) { this.inferredProjects.unshift(project); @@ -178025,8 +178812,11 @@ Dynamic files must always be opened with service's current directory or service } return false; } - /** @internal */ - requestEnablePlugin(project, pluginConfigEntry, searchPaths, pluginConfigOverrides) { + /** + * Performs the initial steps of enabling a plugin by finding and instantiating the module for a plugin either asynchronously or synchronously + * @internal + */ + requestEnablePlugin(project, pluginConfigEntry, searchPaths) { if (!this.host.importPlugin && !this.host.require) { this.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -178037,7 +178827,12 @@ Dynamic files must always be opened with service's current directory or service return; } if (this.host.importPlugin) { - const importPromise = project.beginEnablePluginAsync(pluginConfigEntry, searchPaths, pluginConfigOverrides); + const importPromise = Project3.importServicePluginAsync( + pluginConfigEntry, + searchPaths, + this.host, + (s) => this.logger.info(s) + ); this.pendingPluginEnablements ?? (this.pendingPluginEnablements = /* @__PURE__ */ new Map()); let promises = this.pendingPluginEnablements.get(project); if (!promises) @@ -178045,7 +178840,31 @@ Dynamic files must always be opened with service's current directory or service promises.push(importPromise); return; } - project.endEnablePlugin(project.beginEnablePluginSync(pluginConfigEntry, searchPaths, pluginConfigOverrides)); + this.endEnablePlugin(project, Project3.importServicePluginSync( + pluginConfigEntry, + searchPaths, + this.host, + (s) => this.logger.info(s) + )); + } + /** + * Performs the remaining steps of enabling a plugin after its module has been instantiated. + * @internal + */ + endEnablePlugin(project, { pluginConfigEntry, resolvedModule, errorLogs }) { + var _a; + if (resolvedModule) { + const configurationOverride = (_a = this.currentPluginConfigOverrides) == null ? void 0 : _a.get(pluginConfigEntry.name); + if (configurationOverride) { + const pluginName = pluginConfigEntry.name; + pluginConfigEntry = configurationOverride; + pluginConfigEntry.name = pluginName; + } + project.enableProxy(resolvedModule, pluginConfigEntry); + } else { + forEach(errorLogs, (message) => this.logger.info(message)); + this.logger.info(`Couldn't find ${pluginConfigEntry.name}`); + } } /** @internal */ hasNewPluginEnablementRequests() { @@ -178099,7 +178918,7 @@ Dynamic files must always be opened with service's current directory or service return; } for (const result of results) { - project.endEnablePlugin(result); + this.endEnablePlugin(project, result); } this.delayUpdateProjectGraph(project); } @@ -178458,7 +179277,7 @@ function formatMessage2(msg, logger, byteLength, newLine) { const verboseLogging = logger.hasLevel(3 /* verbose */); const json = JSON.stringify(msg); if (verboseLogging) { - logger.info(`${msg.type}:${indent2(json)}`); + logger.info(`${msg.type}:${indent2(JSON.stringify(msg, void 0, " "))}`); } const len = byteLength(json, "utf8"); return `Content-Length: ${1 + len}\r @@ -178561,14 +179380,14 @@ function combineProjectOutput(defaultValue, getValue, projects, action) { function createDocumentSpanSet() { return createSet(({ textSpan }) => textSpan.start + 100003 * textSpan.length, documentSpansEqual); } -function getRenameLocationsWorker(projects, defaultProject, initialLocation, findInStrings, findInComments, { providePrefixAndSuffixTextForRename }) { +function getRenameLocationsWorker(projects, defaultProject, initialLocation, findInStrings, findInComments, preferences) { const perProjectResults = getPerProjectReferences( projects, defaultProject, initialLocation, /*isForRename*/ true, - (project, position) => project.getLanguageService().findRenameLocations(position.fileName, position.pos, findInStrings, findInComments, providePrefixAndSuffixTextForRename), + (project, position) => project.getLanguageService().findRenameLocations(position.fileName, position.pos, findInStrings, findInComments, preferences), (renameLocation, cb) => cb(documentSpanLocation(renameLocation)) ); if (isArray(perProjectResults)) { @@ -178839,6 +179658,7 @@ var invalidPartialSemanticModeCommands = [ "applyCodeActionCommand" /* ApplyCodeActionCommand */, "getSupportedCodeFixes" /* GetSupportedCodeFixes */, "getApplicableRefactors" /* GetApplicableRefactors */, + "getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */, "getEditsForRefactor" /* GetEditsForRefactor */, "getEditsForRefactor-full" /* GetEditsForRefactorFull */, "organizeImports" /* OrganizeImports */, @@ -179384,6 +180204,9 @@ var Session3 = class { true )); }, + ["getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */]: (request) => { + return this.requiredResponse(this.getMoveToRefactoringFileSuggestions(request.arguments)); + }, ["getEditsForRefactor-full" /* GetEditsForRefactorFull */]: (request) => { return this.requiredResponse(this.getEditsForRefactor( request.arguments, @@ -179516,7 +180339,7 @@ var Session3 = class { })); this.host = opts.host; this.cancellationToken = opts.cancellationToken; - this.typingsInstaller = opts.typingsInstaller; + this.typingsInstaller = opts.typingsInstaller || nullTypingsInstaller; this.byteLength = opts.byteLength; this.hrtime = opts.hrtime; this.logger = opts.logger; @@ -181112,7 +181935,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter getApplicableRefactors(args) { const { file, project } = this.getFileAndProject(args); const scriptInfo = project.getScriptInfoForNormalizedPath(file); - return project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file), args.triggerReason, args.kind); + return project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file), args.triggerReason, args.kind, args.includeInteractiveActions); } getEditsForRefactor(args, simplifiedResult) { const { file, project } = this.getFileAndProject(args); @@ -181123,7 +181946,8 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter this.extractPositionOrRange(args, scriptInfo), args.refactor, args.action, - this.getPreferences(file) + this.getPreferences(file), + args.interactiveRefactorArguments ); if (result === void 0) { return { @@ -181137,10 +181961,18 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const renameScriptInfo = project.getScriptInfoForNormalizedPath(toNormalizedPath(renameFilename)); mappedRenameLocation = getLocationInNewDocument(getSnapshotText(renameScriptInfo.getSnapshot()), renameFilename, renameLocation, edits); } - return { renameLocation: mappedRenameLocation, renameFilename, edits: this.mapTextChangesToCodeEdits(edits) }; - } else { - return result; + return { + renameLocation: mappedRenameLocation, + renameFilename, + edits: this.mapTextChangesToCodeEdits(edits) + }; } + return result; + } + getMoveToRefactoringFileSuggestions(args) { + const { file, project } = this.getFileAndProject(args); + const scriptInfo = project.getScriptInfoForNormalizedPath(file); + return project.getLanguageService().getMoveToRefactoringFileSuggestions(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file)); } organizeImports(args, simplifiedResult) { Debug.assert(args.scope.type === "file"); @@ -181245,11 +182077,11 @@ ${e.message}`; } return { startPosition, endPosition }; } - mapCodeAction({ description: description2, changes, commands }) { - return { description: description2, changes: this.mapTextChangesToCodeEdits(changes), commands }; + mapCodeAction({ description: description3, changes, commands }) { + return { description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands }; } - mapCodeFixAction({ fixName: fixName8, description: description2, changes, commands, fixId: fixId52, fixAllDescription }) { - return { fixName: fixName8, description: description2, changes: this.mapTextChangesToCodeEdits(changes), commands, fixId: fixId52, fixAllDescription }; + mapCodeFixAction({ fixName: fixName8, description: description3, changes, commands, fixId: fixId52, fixAllDescription }) { + return { fixName: fixName8, description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands, fixId: fixId52, fixAllDescription }; } mapTextChangesToCodeEdits(textChanges2) { return textChanges2.map((change) => this.mapTextChangeToCodeEdit(change)); @@ -182392,6 +183224,7 @@ __export(ts_server_exports4, { ActionInvalidate: () => ActionInvalidate, ActionPackageInstalled: () => ActionPackageInstalled, ActionSet: () => ActionSet, + ActionWatchTypingLocations: () => ActionWatchTypingLocations, Arguments: () => Arguments, AutoImportProviderProject: () => AutoImportProviderProject, CharRangeSection: () => CharRangeSection, @@ -182715,13 +183548,6 @@ function initializeNodeSystem() { return (_a = global.gc) == null ? void 0 : _a.call(global); }; } - sys2.require = (initialDir, moduleName) => { - try { - return { module: require(resolveJSModule(moduleName, initialDir, sys2)), error: void 0 }; - } catch (error) { - return { module: void 0, error }; - } - }; let cancellationToken; try { const factory2 = require("./cancellationToken"); @@ -183010,6 +183836,9 @@ function startNodeSession(options, logger, cancellationToken) { this.event(response, "setTypings"); break; } + case ActionWatchTypingLocations: + this.projectService.watchTypingLocations(response); + break; default: assertType(response); } @@ -183610,6 +184439,7 @@ start(initializeNodeSystem(), require("os").platform()); createMemberAccessForPropertyName, createModeAwareCache, createModeAwareCacheKey, + createModuleNotFoundChain, createModuleResolutionCache, createModuleResolutionLoader, createModuleSpecifierResolutionHost, @@ -183744,6 +184574,7 @@ start(initializeNodeSystem(), require("os").platform()); fileExtensionIs, fileExtensionIsOneOf, fileIncludeReasonToDiagnostics, + fileShouldUseJavaScriptRequire, filter, filterMutate, filterSemanticDiagnostics, @@ -183979,6 +184810,7 @@ start(initializeNodeSystem(), require("os").platform()); getImportNeedsImportStarHelper, getIndentSize, getIndentString, + getInferredLibraryNameResolveFrom, getInitializedVariables, getInitializerOfBinaryExpression, getInitializerOfBindingOrAssignmentElement, @@ -184099,6 +184931,7 @@ start(initializeNodeSystem(), require("os").platform()); getOperatorAssociativity, getOperatorPrecedence, getOptionFromName, + getOptionsForLibraryResolution, getOptionsNameMap, getOrCreateEmitNode, getOrCreateExternalHelpersModuleNameIfNeeded, @@ -184489,7 +185322,6 @@ start(initializeNodeSystem(), require("os").platform()); isEmptyObjectLiteral, isEmptyStatement, isEmptyStringLiteral, - isEndOfDeclarationMarker, isEntityName, isEntityNameExpression, isEnumConst, @@ -184720,7 +185552,6 @@ start(initializeNodeSystem(), require("os").platform()); isLogicalOrCoalescingBinaryOperator, isMappedTypeNode, isMemberName, - isMergeDeclarationMarker, isMetaProperty, isMethodDeclaration, isMethodOrAccessor, @@ -185210,6 +186041,7 @@ start(initializeNodeSystem(), require("os").platform()); resolutionExtensionIsTSOrJson, resolveConfigFileProjectName, resolveJSModule, + resolveLibrary, resolveModuleName, resolveModuleNameFromCache, resolvePackageNameToPackageJson, diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 7a7adbc8a07..870d8816449 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -22,8 +22,9 @@ declare namespace ts { 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; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed | ActionWatchTypingLocations; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -32,7 +33,6 @@ declare namespace ts { readonly fileNames: string[]; readonly projectRootPath: Path; readonly compilerOptions: CompilerOptions; - readonly watchOptions?: WatchOptions; readonly typeAcquisition: TypeAcquisition; readonly unresolvedImports: SortedReadonlyArray; readonly cachePath?: string; @@ -84,8 +84,6 @@ declare namespace ts { writeFile(path: string, content: string): void; createDirectory(path: string): void; getCurrentDirectory?(): string; - watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: WatchOptions): FileWatcher; - watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: WatchOptions): FileWatcher; } interface SetTypings extends ProjectResponse { readonly typeAcquisition: TypeAcquisition; @@ -94,6 +92,11 @@ declare namespace ts { 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", @@ -155,6 +158,7 @@ declare namespace ts { GetSupportedCodeFixes = "getSupportedCodeFixes", GetApplicableRefactors = "getApplicableRefactors", GetEditsForRefactor = "getEditsForRefactor", + GetMoveToRefactoringFileSuggestions = "getMoveToRefactoringFileSuggestions", OrganizeImports = "organizeImports", GetEditsForFileRename = "getEditsForFileRename", ConfigurePlugin = "configurePlugin", @@ -501,6 +505,14 @@ declare namespace ts { 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"; /** @@ -510,6 +522,26 @@ declare namespace ts { 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. */ @@ -557,6 +589,11 @@ declare namespace ts { * 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; @@ -569,6 +606,7 @@ declare namespace ts { type GetEditsForRefactorRequestArgs = FileLocationOrRangeRequestArgs & { refactor: string; action: string; + interactiveRefactorArguments?: InteractiveRefactorArguments; }; interface GetEditsForRefactorResponse extends Response { body?: RefactorEditInfo; @@ -3009,8 +3047,6 @@ declare namespace ts { private readonly knownCachesSet; private readonly projectWatchers; private safeList; - private readonly toCanonicalFileName; - private readonly globalCachePackageJsonPath; private installRunCount; private inFlightRequestCount; abstract readonly typesRegistry: Map>; @@ -3029,7 +3065,7 @@ declare namespace ts { private installTypingsAsync; private executeWithThrottling; protected abstract installWorker(requestId: number, packageNames: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void; - protected abstract sendResponse(response: SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes): void; + protected abstract sendResponse(response: SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes | WatchTypingLocations): void; protected readonly latestDistTag = "latest"; } } @@ -3241,7 +3277,7 @@ declare namespace ts { private readonly cancellationToken; isNonTsProject(): boolean; isJsOnlyProject(): boolean; - static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void, logErrors?: (message: string) => void): {} | undefined; + static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {} | undefined; isKnownTypesPackageName(name: string): boolean; installPackage(options: InstallPackageOptions): Promise; private get typingsCache(); @@ -3328,9 +3364,8 @@ declare namespace ts { setTypeAcquisition(newTypeAcquisition: TypeAcquisition | undefined): void; getTypeAcquisition(): ts.TypeAcquisition; protected removeRoot(info: ScriptInfo): void; - protected enableGlobalPlugins(options: CompilerOptions, pluginConfigOverrides: Map | undefined): void; - protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[], pluginConfigOverrides: Map | undefined): void; - private enableProxy; + 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; } @@ -3554,7 +3589,7 @@ declare namespace ts { cancellationToken: HostCancellationToken; useSingleInferredProject: boolean; useInferredProjectPerProjectRoot: boolean; - typingsInstaller: ITypingsInstaller; + typingsInstaller?: ITypingsInstaller; eventHandler?: ProjectServiceEventHandler; suppressDiagnosticEvents?: boolean; throttleWaitMilliseconds?: number; @@ -3631,7 +3666,6 @@ declare namespace ts { readonly globalPlugins: readonly string[]; readonly pluginProbeLocations: readonly string[]; readonly allowLocalPluginLoads: boolean; - private currentPluginConfigOverrides; readonly typesMapLocation: string | undefined; readonly serverMode: LanguageServiceMode; /** Tracks projects that we have already sent telemetry for. */ @@ -3826,7 +3860,7 @@ declare namespace ts { cancellationToken: ServerCancellationToken; useSingleInferredProject: boolean; useInferredProjectPerProjectRoot: boolean; - typingsInstaller: ITypingsInstaller; + typingsInstaller?: ITypingsInstaller; byteLength: (buf: string, encoding?: BufferEncoding) => number; hrtime: (start?: [ number, @@ -3976,6 +4010,7 @@ declare namespace ts { private getRange; private getApplicableRefactors; private getEditsForRefactor; + private getMoveToRefactoringFileSuggestions; private organizeImports; private getEditsForFileRename; private getCodeFixes; @@ -4419,10 +4454,8 @@ declare namespace ts { NotEmittedStatement = 358, PartiallyEmittedExpression = 359, CommaListExpression = 360, - MergeDeclarationMarker = 361, - EndOfDeclarationMarker = 362, - SyntheticReferenceExpression = 363, - Count = 364, + SyntheticReferenceExpression = 361, + Count = 362, FirstAssignment = 64, LastAssignment = 79, FirstCompoundAssignment = 65, @@ -4564,7 +4597,7 @@ declare namespace ts { 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 | ShorthandPropertyAssignment | SpreadAssignment | SwitchStatement | ThrowStatement | TryStatement | TypeAliasDeclaration | TypeParameterDeclaration | VariableDeclaration | VariableStatement | WhileStatement | WithStatement; + 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; @@ -4658,7 +4691,7 @@ declare namespace ts { type EntityName = Identifier | QualifiedName; type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | PrivateIdentifier; type MemberName = Identifier | PrivateIdentifier; - type DeclarationName = Identifier | PrivateIdentifier | StringLiteralLike | NumericLiteral | ComputedPropertyName | ElementAccessExpression | BindingPattern | EntityNameExpression; + type DeclarationName = PropertyName | JsxAttributeName | StringLiteralLike | ElementAccessExpression | BindingPattern | EntityNameExpression; interface Declaration extends Node { _declarationBrand: any; } @@ -4843,7 +4876,7 @@ declare namespace ts { readonly body?: FunctionBody | undefined; } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ - interface SemicolonClassElement extends ClassElement { + interface SemicolonClassElement extends ClassElement, JSDocContainer { readonly kind: SyntaxKind.SemicolonClassElement; readonly parent: ClassLikeDeclaration; } @@ -5005,7 +5038,7 @@ declare namespace ts { readonly kind: SyntaxKind.StringLiteral; } type StringLiteralLike = StringLiteral | NoSubstitutionTemplateLiteral; - type PropertyNameLiteral = Identifier | StringLiteralLike | NumericLiteral; + type PropertyNameLiteral = Identifier | StringLiteralLike | NumericLiteral | JsxNamespacedName; interface TemplateLiteralTypeNode extends TypeNode { kind: SyntaxKind.TemplateLiteralType; readonly head: TemplateHead; @@ -5364,14 +5397,14 @@ declare namespace ts { type JsxAttributeName = Identifier | JsxNamespacedName; type JsxTagNameExpression = Identifier | ThisExpression | JsxTagNamePropertyAccess | JsxNamespacedName; interface JsxTagNamePropertyAccess extends PropertyAccessExpression { - readonly expression: JsxTagNameExpression; + readonly expression: Identifier | ThisExpression | JsxTagNamePropertyAccess; } interface JsxAttributes extends PrimaryExpression, Declaration { readonly properties: NodeArray; readonly kind: SyntaxKind.JsxAttributes; readonly parent: JsxOpeningLikeElement; } - interface JsxNamespacedName extends PrimaryExpression { + interface JsxNamespacedName extends Node { readonly kind: SyntaxKind.JsxNamespacedName; readonly name: Identifier; readonly namespace: Identifier; @@ -7513,9 +7546,8 @@ declare namespace ts { ReuseTempVariableScope = 1048576, CustomPrologue = 2097152, NoHoisting = 4194304, - HasEndOfDeclarationMarker = 8388608, - Iterator = 16777216, - NoAsciiEscaping = 33554432 + Iterator = 8388608, + NoAsciiEscaping = 16777216 } interface EmitHelperBase { readonly name: string; @@ -8786,6 +8818,26 @@ declare namespace ts { 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 */ @@ -9234,7 +9286,7 @@ declare namespace ts { * 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): ModuleResolutionCache; + 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; @@ -10084,6 +10136,8 @@ declare namespace ts { 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; @@ -10129,8 +10183,18 @@ declare namespace ts { applyCodeActionCommand(fileName: string, action: CodeActionCommand[]): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; - getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined, triggerReason?: RefactorTriggerReason, kind?: string): ApplicableRefactorInfo[]; - getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; + /** + * @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, includeInteractiveActions?: 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; @@ -10401,6 +10465,11 @@ declare namespace ts { * 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 @@ -10633,6 +10702,9 @@ declare namespace ts { interface DocCommentTemplateOptions { readonly generateReturnInDocTemplate?: boolean; } + interface InteractiveRefactorArguments { + targetFile: string; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 0d1d2fcd02e..632e24ea6d1 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -35,7 +35,7 @@ var ts = (() => { "src/compiler/corePublic.ts"() { "use strict"; versionMajorMinor = "5.1"; - version = "5.1.0-beta"; + version = "5.1.1-rc"; Comparison = /* @__PURE__ */ ((Comparison3) => { Comparison3[Comparison3["LessThan"] = -1] = "LessThan"; Comparison3[Comparison3["EqualTo"] = 0] = "EqualTo"; @@ -3886,10 +3886,8 @@ ${lanes.join("\n")} SyntaxKind5[SyntaxKind5["NotEmittedStatement"] = 358] = "NotEmittedStatement"; SyntaxKind5[SyntaxKind5["PartiallyEmittedExpression"] = 359] = "PartiallyEmittedExpression"; SyntaxKind5[SyntaxKind5["CommaListExpression"] = 360] = "CommaListExpression"; - SyntaxKind5[SyntaxKind5["MergeDeclarationMarker"] = 361] = "MergeDeclarationMarker"; - SyntaxKind5[SyntaxKind5["EndOfDeclarationMarker"] = 362] = "EndOfDeclarationMarker"; - SyntaxKind5[SyntaxKind5["SyntheticReferenceExpression"] = 363] = "SyntheticReferenceExpression"; - SyntaxKind5[SyntaxKind5["Count"] = 364] = "Count"; + SyntaxKind5[SyntaxKind5["SyntheticReferenceExpression"] = 361] = "SyntheticReferenceExpression"; + SyntaxKind5[SyntaxKind5["Count"] = 362] = "Count"; SyntaxKind5[SyntaxKind5["FirstAssignment"] = 64 /* EqualsToken */] = "FirstAssignment"; SyntaxKind5[SyntaxKind5["LastAssignment"] = 79 /* CaretEqualsToken */] = "LastAssignment"; SyntaxKind5[SyntaxKind5["FirstCompoundAssignment"] = 65 /* PlusEqualsToken */] = "FirstCompoundAssignment"; @@ -4739,10 +4737,10 @@ ${lanes.join("\n")} LanguageVariant4[LanguageVariant4["JSX"] = 1] = "JSX"; return LanguageVariant4; })(LanguageVariant || {}); - WatchDirectoryFlags = /* @__PURE__ */ ((WatchDirectoryFlags4) => { - WatchDirectoryFlags4[WatchDirectoryFlags4["None"] = 0] = "None"; - WatchDirectoryFlags4[WatchDirectoryFlags4["Recursive"] = 1] = "Recursive"; - return WatchDirectoryFlags4; + WatchDirectoryFlags = /* @__PURE__ */ ((WatchDirectoryFlags3) => { + WatchDirectoryFlags3[WatchDirectoryFlags3["None"] = 0] = "None"; + WatchDirectoryFlags3[WatchDirectoryFlags3["Recursive"] = 1] = "Recursive"; + return WatchDirectoryFlags3; })(WatchDirectoryFlags || {}); CharacterCodes = /* @__PURE__ */ ((CharacterCodes2) => { CharacterCodes2[CharacterCodes2["nullCharacter"] = 0] = "nullCharacter"; @@ -4990,9 +4988,8 @@ ${lanes.join("\n")} EmitFlags3[EmitFlags3["ReuseTempVariableScope"] = 1048576] = "ReuseTempVariableScope"; EmitFlags3[EmitFlags3["CustomPrologue"] = 2097152] = "CustomPrologue"; EmitFlags3[EmitFlags3["NoHoisting"] = 4194304] = "NoHoisting"; - EmitFlags3[EmitFlags3["HasEndOfDeclarationMarker"] = 8388608] = "HasEndOfDeclarationMarker"; - EmitFlags3[EmitFlags3["Iterator"] = 16777216] = "Iterator"; - EmitFlags3[EmitFlags3["NoAsciiEscaping"] = 33554432] = "NoAsciiEscaping"; + EmitFlags3[EmitFlags3["Iterator"] = 8388608] = "Iterator"; + EmitFlags3[EmitFlags3["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; return EmitFlags3; })(EmitFlags || {}); InternalEmitFlags = /* @__PURE__ */ ((InternalEmitFlags3) => { @@ -8288,6 +8285,7 @@ ${lanes.join("\n")} List_of_folders_to_include_type_definitions_from: diag(6161, 3 /* Message */, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), Disable_size_limitations_on_JavaScript_projects: diag(6162, 3 /* Message */, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), The_character_set_of_the_input_files: diag(6163, 3 /* Message */, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1: diag(6164, 3 /* Message */, "Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1_6164", "Skipping module '{0}' that looks like an absolute URI, target file types: {1}."), Do_not_truncate_error_messages: diag(6165, 3 /* Message */, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), Output_directory_for_generated_declaration_files: diag(6166, 3 /* Message */, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, 3 /* Message */, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), @@ -8767,6 +8765,7 @@ ${lanes.join("\n")} You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder: diag(8036, 1 /* Error */, "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036", "You cannot rename elements that are defined in another 'node_modules' folder."), Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files: diag(8037, 1 /* Error */, "Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files_8037", "Type satisfaction expressions can only be used in TypeScript files."), Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export: diag(8038, 1 /* Error */, "Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export_8038", "Decorators may not appear after 'export' or 'export default' if they also appear before 'export'."), + A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag: diag(8039, 1 /* Error */, "A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag_8039", "A JSDoc '@template' tag may not follow a '@typedef', '@callback', or '@overload' tag"), Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, 1 /* Error */, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."), Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, 1 /* Error */, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."), JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17e3, 1 /* Error */, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), @@ -9018,6 +9017,7 @@ ${lanes.join("\n")} Use_Number_isNaN_in_all_conditions: diag(95175, 3 /* Message */, "Use_Number_isNaN_in_all_conditions_95175", "Use `Number.isNaN` in all conditions."), Convert_typedef_to_TypeScript_type: diag(95176, 3 /* Message */, "Convert_typedef_to_TypeScript_type_95176", "Convert typedef to TypeScript type."), Convert_all_typedef_to_TypeScript_types: diag(95177, 3 /* Message */, "Convert_all_typedef_to_TypeScript_types_95177", "Convert all typedef to TypeScript types."), + Move_to_file: diag(95178, 3 /* Message */, "Move_to_file_95178", "Move to file"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, 1 /* Error */, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, 1 /* Error */, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, 1 /* Error */, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -12388,7 +12388,6 @@ ${lanes.join("\n")} case 283 /* JsxElement */: case 284 /* JsxSelfClosingElement */: case 287 /* JsxFragment */: - case 294 /* JsxNamespacedName */: case 214 /* TaggedTemplateExpression */: case 208 /* ArrayLiteralExpression */: case 216 /* ParenthesizedExpression */: @@ -12654,7 +12653,7 @@ ${lanes.join("\n")} return kind === 261 /* FunctionDeclaration */ || kind === 281 /* MissingDeclaration */ || kind === 262 /* ClassDeclaration */ || kind === 263 /* InterfaceDeclaration */ || kind === 264 /* TypeAliasDeclaration */ || kind === 265 /* EnumDeclaration */ || kind === 266 /* ModuleDeclaration */ || kind === 271 /* ImportDeclaration */ || kind === 270 /* ImportEqualsDeclaration */ || kind === 277 /* ExportDeclaration */ || kind === 276 /* ExportAssignment */ || kind === 269 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 251 /* BreakStatement */ || kind === 250 /* ContinueStatement */ || kind === 258 /* DebuggerStatement */ || kind === 245 /* DoStatement */ || kind === 243 /* ExpressionStatement */ || kind === 241 /* EmptyStatement */ || kind === 248 /* ForInStatement */ || kind === 249 /* ForOfStatement */ || kind === 247 /* ForStatement */ || kind === 244 /* IfStatement */ || kind === 255 /* LabeledStatement */ || kind === 252 /* ReturnStatement */ || kind === 254 /* SwitchStatement */ || kind === 256 /* ThrowStatement */ || kind === 257 /* TryStatement */ || kind === 242 /* VariableStatement */ || kind === 246 /* WhileStatement */ || kind === 253 /* WithStatement */ || kind === 358 /* NotEmittedStatement */ || kind === 362 /* EndOfDeclarationMarker */ || kind === 361 /* MergeDeclarationMarker */; + return kind === 251 /* BreakStatement */ || kind === 250 /* ContinueStatement */ || kind === 258 /* DebuggerStatement */ || kind === 245 /* DoStatement */ || kind === 243 /* ExpressionStatement */ || kind === 241 /* EmptyStatement */ || kind === 248 /* ForInStatement */ || kind === 249 /* ForOfStatement */ || kind === 247 /* ForStatement */ || kind === 244 /* IfStatement */ || kind === 255 /* LabeledStatement */ || kind === 252 /* ReturnStatement */ || kind === 254 /* SwitchStatement */ || kind === 256 /* ThrowStatement */ || kind === 257 /* TryStatement */ || kind === 242 /* VariableStatement */ || kind === 246 /* WhileStatement */ || kind === 253 /* WithStatement */ || kind === 358 /* NotEmittedStatement */; } function isDeclaration(node) { if (node.kind === 167 /* TypeParameter */) { @@ -12952,7 +12951,39 @@ ${lanes.join("\n")} return oldRef.path === newRef.path && !oldRef.prepend === !newRef.prepend && !oldRef.circular === !newRef.circular; } function moduleResolutionIsEqualTo(oldResolution, newResolution) { - 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); + 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; + } + function createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageName) { + var _a, _b; + const node10Result = (_b = (_a = sourceFile.resolvedModules) == null ? void 0 : _a.get(moduleReference, mode)) == null ? void 0 : _b.node10Result; + const result = node10Result ? chainDiagnosticMessages( + /*details*/ + void 0, + 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 + ) : host.typesPackageExists(packageName) ? chainDiagnosticMessages( + /*details*/ + void 0, + 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*/ + void 0, + 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*/ + void 0, + 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 ? void 0 : packageName }); + return result; } function packageIdIsEqual(a, b) { return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; @@ -13629,7 +13660,7 @@ ${lanes.join("\n")} } switch (node.kind) { case 11 /* StringLiteral */: { - const escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString : flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + const escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString : flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; if (node.singleQuote) { return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; } else { @@ -13640,7 +13671,7 @@ ${lanes.join("\n")} case 16 /* TemplateHead */: case 17 /* TemplateMiddle */: case 18 /* TemplateTail */: { - const escapeText = flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + const escapeText = flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; const rawText = node.rawText ?? escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */)); switch (node.kind) { case 15 /* NoSubstitutionTemplateLiteral */: @@ -13736,7 +13767,7 @@ ${lanes.join("\n")} return kind === 1 /* CommonJS */ || kind === 100 /* Node16 */ || kind === 199 /* NodeNext */; } function isEffectiveExternalModule(node, compilerOptions) { - return isExternalModule(node) || getIsolatedModules(compilerOptions) || isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator; + return isExternalModule(node) || isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator; } function isEffectiveStrictModeSourceFile(node, compilerOptions) { switch (node.scriptKind) { @@ -13899,6 +13930,8 @@ ${lanes.join("\n")} if (isStringOrNumericLiteralLike(name.expression)) return escapeLeadingUnderscores(name.expression.text); return void 0; + case 294 /* JsxNamespacedName */: + return getEscapedTextOfJsxNamespacedName(name); default: return Debug.assertNever(name); } @@ -15390,6 +15423,7 @@ ${lanes.join("\n")} case 171 /* PropertyDeclaration */: case 170 /* PropertySignature */: case 252 /* ReturnStatement */: + case 239 /* SemicolonClassElement */: case 177 /* SetAccessor */: case 303 /* ShorthandPropertyAssignment */: case 304 /* SpreadAssignment */: @@ -15863,6 +15897,8 @@ ${lanes.join("\n")} return nameExpression.operand.text; } return void 0; + case 294 /* JsxNamespacedName */: + return getEscapedTextOfJsxNamespacedName(name); default: return Debug.assertNever(name); } @@ -15879,16 +15915,16 @@ ${lanes.join("\n")} } } function getTextOfIdentifierOrLiteral(node) { - return isMemberName(node) ? idText(node) : node.text; + return isMemberName(node) ? idText(node) : isJsxNamespacedName(node) ? getTextOfJsxNamespacedName(node) : node.text; } function getEscapedTextOfIdentifierOrLiteral(node) { - return isMemberName(node) ? node.escapedText : escapeLeadingUnderscores(node.text); + return isMemberName(node) ? node.escapedText : isJsxNamespacedName(node) ? getEscapedTextOfJsxNamespacedName(node) : escapeLeadingUnderscores(node.text); } function getPropertyNameForUniqueESSymbol(symbol) { return `__@${getSymbolId(symbol)}@${symbol.escapedName}`; } - function getSymbolNameForPrivateIdentifier(containingClassSymbol, description2) { - return `__#${getSymbolId(containingClassSymbol)}@${description2}`; + function getSymbolNameForPrivateIdentifier(containingClassSymbol, description3) { + return `__#${getSymbolId(containingClassSymbol)}@${description3}`; } function isKnownSymbol(symbol) { return startsWith(symbol.escapedName, "__@"); @@ -17112,6 +17148,8 @@ ${lanes.join("\n")} } } else if (isIdentifier(expr)) { return unescapeLeadingUnderscores(expr.escapedText); + } else if (isJsxNamespacedName(expr)) { + return getTextOfJsxNamespacedName(expr); } return void 0; } @@ -19288,7 +19326,7 @@ ${lanes.join("\n")} supportedTSExtensions = [[".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */], [".cts" /* Cts */, ".d.cts" /* Dcts */], [".mts" /* Mts */, ".d.mts" /* Dmts */]]; supportedTSExtensionsFlat = flatten(supportedTSExtensions); supportedTSExtensionsWithJson = [...supportedTSExtensions, [".json" /* Json */]]; - supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */, ".cts" /* Cts */, ".mts" /* Mts */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".cts" /* Cts */, ".mts" /* Mts */]; + supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */, ".cts" /* Cts */, ".mts" /* Mts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; supportedJSExtensions = [[".js" /* Js */, ".jsx" /* Jsx */], [".mjs" /* Mjs */], [".cjs" /* Cjs */]]; supportedJSExtensionsFlat = flatten(supportedJSExtensions); allSupportedExtensions = [[".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".js" /* Js */, ".jsx" /* Jsx */], [".cts" /* Cts */, ".d.cts" /* Dcts */, ".cjs" /* Cjs */], [".mts" /* Mts */, ".d.mts" /* Dmts */, ".mjs" /* Mjs */]]; @@ -20416,8 +20454,6 @@ ${lanes.join("\n")} updatePartiallyEmittedExpression, createCommaListExpression, updateCommaListExpression, - createEndOfDeclarationMarker, - createMergeDeclarationMarker, createSyntheticReferenceExpression, updateSyntheticReferenceExpression, cloneNode, @@ -23485,20 +23521,8 @@ ${lanes.join("\n")} function updateCommaListExpression(node, elements) { return node.elements !== elements ? update(createCommaListExpression(elements), node) : node; } - function createEndOfDeclarationMarker(original) { - const node = createBaseNode(362 /* EndOfDeclarationMarker */); - node.emitNode = {}; - node.original = original; - return node; - } - function createMergeDeclarationMarker(original) { - const node = createBaseNode(361 /* MergeDeclarationMarker */); - node.emitNode = {}; - node.original = original; - return node; - } function createSyntheticReferenceExpression(expression, thisArg) { - const node = createBaseNode(363 /* SyntheticReferenceExpression */); + const node = createBaseNode(361 /* SyntheticReferenceExpression */); node.expression = expression; node.thisArg = thisArg; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.thisArg); @@ -23890,8 +23914,8 @@ ${lanes.join("\n")} function inlineExpressions(expressions) { return expressions.length > 10 ? createCommaListExpression(expressions) : reduceLeft(expressions, factory2.createComma); } - function getName(node, allowComments, allowSourceMaps, emitFlags = 0) { - const nodeName = getNameOfDeclaration(node); + function getName(node, allowComments, allowSourceMaps, emitFlags = 0, ignoreAssignedName) { + const nodeName = ignoreAssignedName ? node && getNonAssignedNameOfDeclaration(node) : getNameOfDeclaration(node); if (nodeName && isIdentifier(nodeName) && !isGeneratedIdentifier(nodeName)) { const name = setParent(setTextRange(cloneNode(nodeName), nodeName), nodeName.parent); emitFlags |= getEmitFlags(nodeName); @@ -23908,8 +23932,8 @@ ${lanes.join("\n")} function getInternalName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */ | 65536 /* InternalName */); } - function getLocalName(node, allowComments, allowSourceMaps) { - return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */); + function getLocalName(node, allowComments, allowSourceMaps, ignoreAssignedName) { + return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */, ignoreAssignedName); } function getExportName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps, 16384 /* ExportName */); @@ -26348,13 +26372,7 @@ ${lanes.join("\n")} return node.kind === 358 /* NotEmittedStatement */; } function isSyntheticReference(node) { - return node.kind === 363 /* SyntheticReferenceExpression */; - } - function isMergeDeclarationMarker(node) { - return node.kind === 361 /* MergeDeclarationMarker */; - } - function isEndOfDeclarationMarker(node) { - return node.kind === 362 /* EndOfDeclarationMarker */; + return node.kind === 361 /* SyntheticReferenceExpression */; } function isExternalModuleReference(node) { return node.kind === 282 /* ExternalModuleReference */; @@ -29670,8 +29688,13 @@ ${lanes.join("\n")} return tokenIsIdentifierOrKeyword(token()) || token() === 19 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; + case 25 /* JSDocComment */: + return true; + case 26 /* Count */: + return Debug.fail("ParsingContext.Count used as a context"); + default: + Debug.assertNever(parsingContext2, "Non-exhaustive case in 'isListElement'."); } - return Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { Debug.assert(token() === 19 /* OpenBraceToken */); @@ -29765,7 +29788,8 @@ ${lanes.join("\n")} return false; } function isInSomeParsingContext() { - for (let kind = 0; kind < 25 /* Count */; kind++) { + Debug.assert(parsingContext, "Missing parsing context"); + for (let kind = 0; kind < 26 /* Count */; kind++) { if (parsingContext & 1 << kind) { if (isListElement2( kind, @@ -30024,7 +30048,9 @@ ${lanes.join("\n")} return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); case 24 /* AssertEntries */: return parseErrorAtCurrentToken(Diagnostics.Identifier_or_string_literal_expected); - case 25 /* Count */: + case 25 /* JSDocComment */: + return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); + case 26 /* Count */: return Debug.fail("ParsingContext.Count used as a context"); default: Debug.assertNever(context); @@ -32075,7 +32101,11 @@ ${lanes.join("\n")} } function parseJsxElementName() { const pos = getNodePos(); - let expression = parseJsxTagName(); + const initialExpression = parseJsxTagName(); + if (isJsxNamespacedName(initialExpression)) { + return initialExpression; + } + let expression = initialExpression; while (parseOptional(25 /* DotToken */)) { expression = finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot( /*allowIdentifierNames*/ @@ -33605,11 +33635,11 @@ ${lanes.join("\n")} } function parseClassElement() { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); if (token() === 27 /* SemicolonToken */) { nextToken(); - return finishNode(factory2.createSemicolonClassElement(), pos); + return withJSDoc(finishNode(factory2.createSemicolonClassElement(), pos), hasJSDoc); } - const hasJSDoc = hasPrecedingJSDocComment(); const modifiers = parseModifiers( /*allowDecorators*/ true, @@ -34156,7 +34186,8 @@ ${lanes.join("\n")} ParsingContext2[ParsingContext2["HeritageClauses"] = 22] = "HeritageClauses"; ParsingContext2[ParsingContext2["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; ParsingContext2[ParsingContext2["AssertEntries"] = 24] = "AssertEntries"; - ParsingContext2[ParsingContext2["Count"] = 25] = "Count"; + ParsingContext2[ParsingContext2["JSDocComment"] = 25] = "JSDocComment"; + ParsingContext2[ParsingContext2["Count"] = 26] = "Count"; })(ParsingContext || (ParsingContext = {})); let Tristate; ((Tristate2) => { @@ -34278,6 +34309,8 @@ ${lanes.join("\n")} PropertyLikeParse2[PropertyLikeParse2["CallbackParameter"] = 4] = "CallbackParameter"; })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start = 0, length2) { + const saveParsingContext = parsingContext; + parsingContext |= 1 << 25 /* JSDocComment */; const content = sourceText; const end = length2 === void 0 ? content.length : start + length2; length2 = end - start; @@ -34294,7 +34327,10 @@ ${lanes.join("\n")} let commentsPos; let comments = []; const parts = []; - return scanner2.scanRange(start + 3, length2 - 5, () => { + const result = scanner2.scanRange(start + 3, length2 - 5, doJSDocScan); + parsingContext = saveParsingContext; + return result; + function doJSDocScan() { let state = 1 /* SawAsterisk */; let margin; let indent3 = start - (content.lastIndexOf("\n", start) + 1) + 4; @@ -34390,7 +34426,7 @@ ${lanes.join("\n")} Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); const tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); return finishNode(factory2.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : trimmedComments.length ? trimmedComments : void 0, tagsArray), start, end); - }); + } function removeLeadingNewlines(comments2) { while (comments2.length && (comments2[0] === "\n" || comments2[0] === "\r")) { comments2.shift(); @@ -34749,8 +34785,8 @@ ${lanes.join("\n")} typeExpression = nestedTypeLiteral; isNameFirst = true; } - const result = target === 1 /* Property */ ? factory2.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) : factory2.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment); - return finishNode(result, start2); + const result2 = target === 1 /* Property */ ? factory2.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) : factory2.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment); + return finishNode(result2, start2); } function parseNestedTypeLiteral(typeExpression, name, target, indent3) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { @@ -34760,6 +34796,8 @@ ${lanes.join("\n")} while (child = tryParse(() => parseChildParameterOrPropertyTag(target, indent3, name))) { if (child.kind === 347 /* JSDocParameterTag */ || child.kind === 354 /* JSDocPropertyTag */) { children = append(children, child); + } else if (child.kind === 351 /* JSDocTemplateTag */) { + parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag); } } if (children) { @@ -34847,7 +34885,9 @@ ${lanes.join("\n")} const usedBrace = parseOptional(19 /* OpenBraceToken */); const pos = getNodePos(); const expression = parsePropertyAccessEntityNameExpression(); + scanner2.setInJSDocType(true); const typeArguments = tryParseTypeArguments(); + scanner2.setInJSDocType(false); const node = factory2.createExpressionWithTypeArguments(expression, typeArguments); const res = finishNode(node, pos); if (usedBrace) { @@ -34896,6 +34936,9 @@ ${lanes.join("\n")} let jsDocPropertyTags; let hasChildren = false; while (child = tryParse(() => parseChildPropertyTag(indent3))) { + if (child.kind === 351 /* JSDocTemplateTag */) { + break; + } hasChildren = true; if (child.kind === 350 /* JSDocTypeTag */) { if (childTypeTag) { @@ -34955,6 +34998,10 @@ ${lanes.join("\n")} let child; let parameters; while (child = tryParse(() => parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent3))) { + if (child.kind === 351 /* JSDocTemplateTag */) { + parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag); + break; + } parameters = append(parameters, child); } return createNodeArray(parameters || [], pos); @@ -35049,7 +35096,7 @@ ${lanes.join("\n")} const start2 = scanner2.getTokenFullStart(); nextTokenJSDoc(); const tagName = parseJSDocIdentifierName(); - skipWhitespace(); + const indentText = skipWhitespaceOrAsterisk(); let t; switch (tagName.escapedText) { case "type": @@ -35063,6 +35110,8 @@ ${lanes.join("\n")} case "param": t = 2 /* Parameter */ | 4 /* CallbackParameter */; break; + case "template": + return parseTemplateTag(start2, tagName, indent3, indentText); default: return false; } @@ -35150,9 +35199,9 @@ ${lanes.join("\n")} const end2 = scanner2.getTokenEnd(); const originalKeywordKind = token(); const text = internIdentifier(scanner2.getTokenValue()); - const result = finishNode(factoryCreateIdentifier(text, originalKeywordKind), start2, end2); + const result2 = finishNode(factoryCreateIdentifier(text, originalKeywordKind), start2, end2); nextTokenJSDoc(); - return result; + return result2; } } })(JSDocParser = Parser2.JSDocParser || (Parser2.JSDocParser = {})); @@ -36274,8 +36323,8 @@ ${lanes.join("\n")} result.push(`${tab}${tab}/* ${getLocaleSpecificMessage(Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file)} */`); result.push(""); for (const entry of entries) { - const { value, description: description2 = "" } = entry; - result.push(value && `${tab}${tab}${value}${description2 && makePadding(marginLength - value.length + 2) + description2}`); + const { value, description: description3 = "" } = entry; + result.push(value && `${tab}${tab}${value}${description3 && makePadding(marginLength - value.length + 2) + description3}`); } if (fileNames.length) { result.push(`${tab}},`); @@ -39501,13 +39550,12 @@ ${lanes.join("\n")} nonRelativeNameResolutionCache.update(options2); } } - function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) { + function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache) { const result = createModuleOrTypeReferenceResolutionCache( currentDirectory, getCanonicalFileName, options, - /*packageJsonInfoCache*/ - void 0, + packageJsonInfoCache, getOriginalOrResolvedModuleFileName ); result.getOrCreateCacheForModuleName = (nonRelativeName, mode, redirectedReference) => result.getOrCreateCacheForNonRelativeName(nonRelativeName, mode, redirectedReference); @@ -39522,6 +39570,12 @@ ${lanes.join("\n")} getOriginalOrResolvedTypeReferenceFileName ); } + function getOptionsForLibraryResolution(options) { + return { moduleResolution: 2 /* Node10 */, traceResolution: options.traceResolution }; + } + function resolveLibrary(libraryName, resolveFrom, compilerOptions, host, cache) { + return resolveModuleName(libraryName, resolveFrom, getOptionsForLibraryResolution(compilerOptions), host, cache); + } function resolveModuleNameFromCache(moduleName, containingFile, cache, mode) { const containingDirectory = getDirectoryPath(containingFile); return cache.getFromDirectoryCache( @@ -39877,8 +39931,6 @@ ${lanes.join("\n")} const diagnosticState = { ...state, features: state.features & ~8 /* Exports */, - failedLookupLocations: [], - affectingLocations: [], reportDiagnostic: noop }; const diagnosticResult = tryResolve(extensions & (1 /* TypeScript */ | 4 /* Declaration */), diagnosticState); @@ -39918,6 +39970,12 @@ ${lanes.join("\n")} resolved2 = loadModuleFromSelfNameReference(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); } if (!resolved2) { + if (moduleName.indexOf(":") > -1) { + if (traceEnabled) { + trace(host, Diagnostics.Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); + } + return void 0; + } if (traceEnabled) { trace(host, Diagnostics.Loading_module_0_from_node_modules_folder_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); } @@ -40003,22 +40061,22 @@ ${lanes.join("\n")} function pathContainsNodeModules(path) { return stringContains(path, nodeModulesPathPart); } - function parseNodeModuleFromPath(resolved) { + function parseNodeModuleFromPath(resolved, isFolder) { const path = normalizePath(resolved); const idx = path.lastIndexOf(nodeModulesPathPart); if (idx === -1) { return void 0; } const indexAfterNodeModules = idx + nodeModulesPathPart.length; - let indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + let indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules, isFolder); if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { - indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName, isFolder); } return path.slice(0, indexAfterPackageName); } - function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex, isFolder) { const nextSeparatorIndex = path.indexOf(directorySeparator, prevSeparatorIndex + 1); - return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + return nextSeparatorIndex === -1 ? isFolder ? path.length : prevSeparatorIndex : nextSeparatorIndex; } function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); @@ -40950,7 +41008,7 @@ ${lanes.join("\n")} return withPackageId(packageInfo, fromDirectory); } const loader = (extensions2, candidate2, onlyRecordFailures, state2) => { - let pathAndExtension = loadModuleFromFile(extensions2, candidate2, onlyRecordFailures, state2) || loadNodeModuleFromDirectoryWorker( + let pathAndExtension = (rest || !(state2.features & 32 /* EsmMode */)) && loadModuleFromFile(extensions2, candidate2, onlyRecordFailures, state2) || loadNodeModuleFromDirectoryWorker( extensions2, candidate2, onlyRecordFailures, @@ -41402,7 +41460,7 @@ ${lanes.join("\n")} var inStrictMode; var inAssignmentPattern = false; var symbolCount = 0; - var Symbol46; + var Symbol47; var classifiableNames; var unreachableFlow = { flags: 1 /* Unreachable */ }; var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; @@ -41419,7 +41477,7 @@ ${lanes.join("\n")} inStrictMode = bindInStrictMode(file, opts); classifiableNames = /* @__PURE__ */ new Set(); symbolCount = 0; - Symbol46 = objectAllocator.getSymbolConstructor(); + Symbol47 = objectAllocator.getSymbolConstructor(); Debug.attachFlowNodeDebugInfo(unreachableFlow); Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { @@ -41467,7 +41525,7 @@ ${lanes.join("\n")} } function createSymbol(flags, name) { symbolCount++; - return new Symbol46(flags, name); + return new Symbol47(flags, name); } function addDeclarationToSymbol(symbol, node, symbolFlags) { symbol.flags |= symbolFlags; @@ -41516,7 +41574,7 @@ ${lanes.join("\n")} return getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText); } if (isJsxNamespacedName(name)) { - return getEscapedTextOfJsxAttributeName(name); + return getEscapedTextOfJsxNamespacedName(name); } return isPropertyNameLiteral(name) ? getEscapedTextOfIdentifierOrLiteral(name) : void 0; } @@ -44304,15 +44362,16 @@ ${lanes.join("\n")} if (getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */) { return preferredEnding === 2 /* JsExtension */ ? [2 /* JsExtension */, 1 /* Index */] : [1 /* Index */, 2 /* JsExtension */]; } + const allowImportingTsExtension = shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName); switch (preferredEnding) { case 2 /* JsExtension */: - return [2 /* JsExtension */, 0 /* Minimal */, 1 /* Index */]; + return allowImportingTsExtension ? [2 /* JsExtension */, 3 /* TsExtension */, 0 /* Minimal */, 1 /* Index */] : [2 /* JsExtension */, 0 /* Minimal */, 1 /* Index */]; case 3 /* TsExtension */: return [3 /* TsExtension */, 0 /* Minimal */, 2 /* JsExtension */, 1 /* Index */]; case 1 /* Index */: - return [1 /* Index */, 0 /* Minimal */, 2 /* JsExtension */]; + return allowImportingTsExtension ? [1 /* Index */, 0 /* Minimal */, 3 /* TsExtension */, 2 /* JsExtension */] : [1 /* Index */, 0 /* Minimal */, 2 /* JsExtension */]; case 0 /* Minimal */: - return [0 /* Minimal */, 1 /* Index */, 2 /* JsExtension */]; + return allowImportingTsExtension ? [0 /* Minimal */, 1 /* Index */, 3 /* TsExtension */, 2 /* JsExtension */] : [0 /* Minimal */, 1 /* Index */, 2 /* JsExtension */]; default: Debug.assertNever(preferredEnding); } @@ -44508,7 +44567,7 @@ ${lanes.join("\n")} return pathsOnly ? void 0 : relativePath; } const baseDirectory = getNormalizedAbsolutePath(getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); - const relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); + const relativeToBaseUrl = getRelativePathIfInSameVolume(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) { return pathsOnly ? void 0 : relativePath; } @@ -44716,7 +44775,7 @@ ${lanes.join("\n")} for (const { ending, value } of candidates) { if (value.length >= prefix.length + suffix.length && startsWith(value, prefix) && endsWith(value, suffix) && validateEnding({ ending, value })) { const matchedStar = value.substring(prefix.length, value.length - suffix.length); - return key.replace("*", matchedStar); + return pathIsRelative(matchedStar) ? void 0 : key.replace("*", matchedStar); } } } else if (some(candidates, (c) => c.ending !== 0 /* Minimal */ && pattern === c.value) || some(candidates, (c) => c.ending === 0 /* Minimal */ && pattern === c.value && validateEnding(c))) { @@ -44905,7 +44964,10 @@ ${lanes.join("\n")} const mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main || "index.js"; if (isString(mainFileRelative) && !(maybeBlockedByTypesVersions && matchPatternOrExact(tryParsePatterns(versionPaths.paths), mainFileRelative))) { const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (removeFileExtension(mainExportFile) === removeFileExtension(getCanonicalFileName(moduleFileToTry))) { + const canonicalModuleFileToTry = getCanonicalFileName(moduleFileToTry); + if (removeFileExtension(mainExportFile) === removeFileExtension(canonicalModuleFileToTry)) { + return { packageRootPath, moduleFileToTry }; + } else if (packageJsonContent.type !== "module" && !fileExtensionIsOneOf(canonicalModuleFileToTry, extensionsNotSupportingExtensionlessResolution) && startsWith(canonicalModuleFileToTry, mainExportFile) && getDirectoryPath(canonicalModuleFileToTry) === removeTrailingDirectorySeparator(mainExportFile) && removeFileExtension(getBaseFileName(canonicalModuleFileToTry)) === "index") { return { packageRootPath, moduleFileToTry }; } } @@ -44931,7 +44993,7 @@ ${lanes.join("\n")} } function getPathsRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { return mapDefined(rootDirs, (rootDir) => { - const relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + const relativePath = getRelativePathIfInSameVolume(path, rootDir, getCanonicalFileName); return relativePath !== void 0 && isPathRelativeToParent(relativePath) ? void 0 : relativePath; }); } @@ -44943,7 +45005,11 @@ ${lanes.join("\n")} if (fileName === noExtension) { return fileName; } - if (fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".d.cts" /* Dcts */, ".cts" /* Cts */])) { + const jsPriority = allowedEndings.indexOf(2 /* JsExtension */); + const tsPriority = allowedEndings.indexOf(3 /* TsExtension */); + if (fileExtensionIsOneOf(fileName, [".mts" /* Mts */, ".cts" /* Cts */]) && tsPriority !== -1 && tsPriority < jsPriority) { + return fileName; + } else if (fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".d.cts" /* Dcts */, ".cts" /* Cts */])) { return noExtension + getJSExtensionForFile(fileName, options); } else if (!fileExtensionIsOneOf(fileName, [".d.ts" /* Dts */]) && fileExtensionIsOneOf(fileName, [".ts" /* Ts */]) && stringContains(fileName, ".d.")) { return tryGetRealFileNameForNonJsDeclarationFileName(fileName); @@ -44962,7 +45028,6 @@ ${lanes.join("\n")} case 3 /* TsExtension */: if (isDeclarationFileName(fileName)) { const extensionlessPriority = allowedEndings.findIndex((e) => e === 0 /* Minimal */ || e === 1 /* Index */); - const jsPriority = allowedEndings.indexOf(2 /* JsExtension */); return extensionlessPriority !== -1 && extensionlessPriority < jsPriority ? noExtension : noExtension + getJSExtensionForFile(fileName, options); } return fileName; @@ -45005,7 +45070,7 @@ ${lanes.join("\n")} return void 0; } } - function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + function getRelativePathIfInSameVolume(path, directoryPath, getCanonicalFileName) { const relativePath = getRelativePathToDirectoryOrUrl( directoryPath, path, @@ -45070,18 +45135,6 @@ ${lanes.join("\n")} return moduleState === 1 /* Instantiated */ || preserveConstEnums && moduleState === 2 /* ConstEnumOnly */; } function createTypeChecker(host) { - var getPackagesMap = memoize(() => { - var map2 = /* @__PURE__ */ new Map(); - host.getSourceFiles().forEach((sf) => { - if (!sf.resolvedModules) - return; - sf.resolvedModules.forEach(({ resolvedModule }) => { - if (resolvedModule == null ? void 0 : resolvedModule.packageId) - map2.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!map2.get(resolvedModule.packageId.name)); - }); - }); - return map2; - }); var deferredDiagnosticsCallbacks = []; var addLazyDiagnostic = (arg) => { deferredDiagnosticsCallbacks.push(arg); @@ -45090,7 +45143,7 @@ ${lanes.join("\n")} var requestedExternalEmitHelperNames = /* @__PURE__ */ new Set(); var requestedExternalEmitHelpers; var externalHelpersModule; - var Symbol46 = objectAllocator.getSymbolConstructor(); + var Symbol47 = objectAllocator.getSymbolConstructor(); var Type27 = objectAllocator.getTypeConstructor(); var Signature15 = objectAllocator.getSignatureConstructor(); var typeCount = 0; @@ -45812,7 +45865,7 @@ ${lanes.join("\n")} getGlobalIterableType: getGlobalAsyncIterableType, getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType, getGlobalGeneratorType: getGlobalAsyncGeneratorType, - resolveIterationType: getAwaitedType, + resolveIterationType: (type, errorNode) => getAwaitedType(type, errorNode, Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member), mustHaveANextMethodDiagnostic: Diagnostics.An_async_iterator_must_have_a_next_method, mustBeAMethodDiagnostic: Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method, mustHaveAValueDiagnostic: Diagnostics.The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property @@ -46094,13 +46147,14 @@ ${lanes.join("\n")} return diagnostic; } function isDeprecatedSymbol(symbol) { - if (length(symbol.declarations) > 1) { - const parentSymbol = getParentOfSymbol(symbol); - if (parentSymbol && parentSymbol.flags & 64 /* Interface */) { - return some(symbol.declarations, (d) => !!(getCombinedNodeFlags(d) & 268435456 /* Deprecated */)); - } + const parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol && length(symbol.declarations) > 1) { + return parentSymbol.flags & 64 /* Interface */ ? some(symbol.declarations, isDeprecatedDeclaration2) : every(symbol.declarations, isDeprecatedDeclaration2); } - return !!(getDeclarationNodeFlagsFromSymbol(symbol) & 268435456 /* Deprecated */); + return !!symbol.valueDeclaration && isDeprecatedDeclaration2(symbol.valueDeclaration) || length(symbol.declarations) && every(symbol.declarations, isDeprecatedDeclaration2); + } + function isDeprecatedDeclaration2(declaration) { + return !!(getCombinedNodeFlags(declaration) & 268435456 /* Deprecated */); } function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { const diagnostic = createDiagnosticForNode(location, Diagnostics._0_is_deprecated, deprecatedEntity); @@ -46112,7 +46166,7 @@ ${lanes.join("\n")} } function createSymbol(flags, name, checkFlags) { symbolCount++; - const symbol = new Symbol46(flags | 33554432 /* Transient */, name); + const symbol = new Symbol47(flags | 33554432 /* Transient */, name); symbol.links = new SymbolLinks(); symbol.links.checkFlags = checkFlags || 0 /* None */; return symbol; @@ -46454,7 +46508,7 @@ ${lanes.join("\n")} return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { + if (getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */ && useDefineForClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration( declaration, usage, @@ -46617,6 +46671,10 @@ ${lanes.join("\n")} if (name === "const" && isConstAssertion(location)) { return void 0; } + if (isModuleDeclaration(location) && lastLocation && location.name === lastLocation) { + lastLocation = location; + location = location.parent; + } if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) { if (result = lookup(location.locals, name, meaning)) { let useResult = true; @@ -46807,6 +46865,11 @@ ${lanes.join("\n")} } } break; + case 280 /* ExportSpecifier */: + if (lastLocation && lastLocation === location.propertyName && location.parent.parent.moduleSpecifier) { + location = location.parent.parent.parent; + } + break; } if (isSelfReferenceLocation(location)) { lastSelfReferenceLocation = location; @@ -46854,7 +46917,7 @@ ${lanes.join("\n")} if (!result) { if (nameNotFoundMessage) { addLazyDiagnostic(() => { - if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 + if (!errorLocation || errorLocation.parent.kind !== 330 /* 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)) { let suggestion; let suggestedLib; @@ -48407,35 +48470,9 @@ ${lanes.join("\n")} } } function errorOnImplicitAnyModule(isError, errorNode, sourceFile, mode, { packageId, resolvedFileName }, moduleReference) { - var _a, _b; let errorInfo; if (!isExternalModuleNameRelative(moduleReference) && packageId) { - const node10Result = (_b = (_a = sourceFile.resolvedModules) == null ? void 0 : _a.get(moduleReference, mode)) == null ? void 0 : _b.node10Result; - errorInfo = node10Result ? chainDiagnosticMessages( - /*details*/ - void 0, - 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(packageId.name)}` : packageId.name - ) : typesPackageExists(packageId.name) ? chainDiagnosticMessages( - /*details*/ - void 0, - 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, - packageId.name, - mangleScopedPackageName(packageId.name) - ) : packageBundlesTypes(packageId.name) ? chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1, - packageId.name, - moduleReference - ) : chainDiagnosticMessages( - /*details*/ - void 0, - 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(packageId.name) - ); + errorInfo = createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageId.name); } errorOrSuggestion(isError, errorNode, chainDiagnosticMessages( errorInfo, @@ -48444,12 +48481,6 @@ ${lanes.join("\n")} resolvedFileName )); } - function typesPackageExists(packageName) { - return getPackagesMap().has(getTypesPackageName(packageName)); - } - function packageBundlesTypes(packageName) { - return !!getPackagesMap().get(packageName); - } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { if (moduleSymbol == null ? void 0 : moduleSymbol.exports) { const exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias); @@ -49612,7 +49643,7 @@ ${lanes.join("\n")} } if (type.flags & 128 /* StringLiteral */) { context.approximateLength += type.value.length + 2; - return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 33554432 /* NoAsciiEscaping */)); + return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */)); } if (type.flags & 256 /* NumberLiteral */) { const value = type.value; @@ -50500,7 +50531,7 @@ ${lanes.join("\n")} const typePredicate = getTypePredicateOfSignature(signature); if (typePredicate) { const assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? factory.createToken(131 /* AssertsKeyword */) : void 0; - const parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? setEmitFlags(factory.createIdentifier(typePredicate.parameterName), 33554432 /* NoAsciiEscaping */) : factory.createThisTypeNode(); + const parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? setEmitFlags(factory.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : factory.createThisTypeNode(); const typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = factory.createTypePredicateNode(assertsModifier, parameterName, typeNode); } else { @@ -50627,7 +50658,7 @@ ${lanes.join("\n")} const modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && canHaveModifiers(parameterDeclaration) ? map(getModifiers(parameterDeclaration), factory.cloneNode) : void 0; const isRest = parameterDeclaration && isRestParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 32768 /* RestParameter */; const dotDotDotToken = isRest ? factory.createToken(26 /* DotDotDotToken */) : void 0; - const name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 80 /* Identifier */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), 33554432 /* NoAsciiEscaping */) : parameterDeclaration.name.kind === 165 /* QualifiedName */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), 33554432 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol); + const name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 80 /* Identifier */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : parameterDeclaration.name.kind === 165 /* QualifiedName */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol); const isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */; const questionToken = isOptional ? factory.createToken(58 /* QuestionToken */) : void 0; const parameterNode = factory.createParameterDeclaration( @@ -50668,7 +50699,7 @@ ${lanes.join("\n")} if (!nodeIsSynthesized(visited)) { visited = factory.cloneNode(visited); } - return setEmitFlags(visited, 1 /* SingleLine */ | 33554432 /* NoAsciiEscaping */); + return setEmitFlags(visited, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); } } } @@ -50993,7 +51024,7 @@ ${lanes.join("\n")} return factory.createIndexedAccessTypeNode(factory.createTypeReferenceNode(LHS, typeParameterNodes), factory.createLiteralTypeNode(factory.createStringLiteral(symbolName2))); } } - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; @@ -51079,7 +51110,7 @@ ${lanes.join("\n")} if (index === 0) { context.flags ^= 16777216 /* InInitialEntityName */; } - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; @@ -51104,7 +51135,7 @@ ${lanes.join("\n")} return factory.createStringLiteral(getSpecifierForModuleSymbol(symbol2, context)); } if (index === 0 || canUsePropertyAccess(symbolName2, languageVersion)) { - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; @@ -51121,7 +51152,7 @@ ${lanes.join("\n")} expression = factory.createNumericLiteral(+symbolName2); } if (!expression) { - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; @@ -51274,7 +51305,7 @@ ${lanes.join("\n")} const type = getDeclaredTypeOfSymbol(sym); const name = sym.flags & 262144 /* TypeParameter */ && !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration) ? typeParameterToName(type, context) : factory.cloneNode(node); name.symbol = sym; - return { introducesError, node: setEmitFlags(setOriginalNode(name, node), 33554432 /* NoAsciiEscaping */) }; + return { introducesError, node: setEmitFlags(setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */) }; } } return { introducesError, node }; @@ -51717,7 +51748,7 @@ ${lanes.join("\n")} if (symbol.flags & 524288 /* TypeAlias */) { serializeTypeAlias(symbol, symbolName2, modifierFlags); } - if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && symbol.escapedName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) && !(symbol.flags & 32 /* Class */) && !(symbol.flags & 8192 /* Method */) && !isConstMergedWithNSPrintableAsSignatureMerge) { + if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */ | 98304 /* Accessor */) && symbol.escapedName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) && !(symbol.flags & 32 /* Class */) && !(symbol.flags & 8192 /* Method */) && !isConstMergedWithNSPrintableAsSignatureMerge) { if (propertyAsAlias) { const createdExport = serializeMaybeAliasAssignment(symbol); if (createdExport) { @@ -52135,7 +52166,7 @@ ${lanes.join("\n")} context.enclosingDeclaration = originalDecl || oldEnclosing; const localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); const typeParamDecls = map(localParams, (p) => typeParameterToDeclaration(p, context)); - const classType = getDeclaredTypeOfClassOrInterface(symbol); + const classType = getTypeWithThisArgument(getDeclaredTypeOfClassOrInterface(symbol)); const baseTypes = getBaseTypes(classType); const originalImplements = originalDecl && getEffectiveImplementsTypeNodes(originalDecl); const implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements) || mapDefined(getImplementsTypes(classType), serializeImplementedType); @@ -53334,7 +53365,7 @@ ${lanes.join("\n")} const elementType = checkIteratedTypeOrElementType(65 /* Destructuring */ | (declaration.dotDotDotToken ? 0 : 128 /* PossiblyOutOfBounds */), parentType, undefinedType, pattern); const index = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - const baseConstraint = getBaseConstraintOrType(parentType); + const baseConstraint = mapType(parentType, (t) => t.flags & 58982400 /* InstantiableNonPrimitive */ ? getBaseConstraintOrType(t) : t); type = everyType(baseConstraint, isTupleType) ? mapType(baseConstraint, (t) => sliceTupleType(t, index)) : createArrayType(elementType); } else if (isArrayLikeType(parentType)) { const indexType = getNumberLiteralType(index); @@ -55062,6 +55093,9 @@ ${lanes.join("\n")} } return needApparentType ? getApparentType(type) : type; } + function getThisArgument(type) { + return getObjectFlags(type) & 4 /* Reference */ && length(getTypeArguments(type)) > getTypeReferenceArity(type) ? last(getTypeArguments(type)) : type; + } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { let mapper; let members; @@ -55192,7 +55226,7 @@ ${lanes.join("\n")} } return [sig.parameters]; function expandSignatureParametersWithTupleMembers(restType, restIndex) { - const elementTypes = getTypeArguments(restType); + const elementTypes = getElementTypes(restType); const associatedNames = getUniqAssociatedNamesFromTupleType(restType); const restParams = map(elementTypes, (t, i) => { const name = associatedNames && associatedNames[i] ? associatedNames[i] : getParameterNameAtPosition(sig, restIndex + i, restType); @@ -56008,7 +56042,7 @@ ${lanes.join("\n")} } function isConstTypeVariable(type) { var _a; - return !!(type && (type.flags & 262144 /* TypeParameter */ && some((_a = type.symbol) == null ? void 0 : _a.declarations, (d) => hasSyntacticModifier(d, 2048 /* Const */)) || type.flags & 1048576 /* Union */ && some(type.types, isConstTypeVariable) || type.flags & 8388608 /* IndexedAccess */ && isConstTypeVariable(type.objectType) || type.flags & 16777216 /* Conditional */ && isConstTypeVariable(getConstraintOfConditionalType(type)) || type.flags & 33554432 /* Substitution */ && isConstTypeVariable(type.baseType) || isGenericTupleType(type) && findIndex(getTypeArguments(type), (t, i) => !!(type.target.elementFlags[i] & 8 /* Variadic */) && isConstTypeVariable(t)) >= 0)); + return !!(type && (type.flags & 262144 /* TypeParameter */ && some((_a = type.symbol) == null ? void 0 : _a.declarations, (d) => hasSyntacticModifier(d, 2048 /* Const */)) || type.flags & 1048576 /* Union */ && some(type.types, isConstTypeVariable) || type.flags & 8388608 /* IndexedAccess */ && isConstTypeVariable(type.objectType) || type.flags & 16777216 /* Conditional */ && isConstTypeVariable(getConstraintOfConditionalType(type)) || type.flags & 33554432 /* Substitution */ && isConstTypeVariable(type.baseType) || isGenericTupleType(type) && findIndex(getElementTypes(type), (t, i) => !!(type.target.elementFlags[i] & 8 /* Variadic */) && isConstTypeVariable(t)) >= 0)); } function getConstraintOfIndexedAccess(type) { return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : void 0; @@ -56110,7 +56144,7 @@ ${lanes.join("\n")} return void 0; } function getBaseConstraintOfType(type) { - if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) { + if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) || isGenericTupleType(type)) { const constraint = getResolvedBaseConstraint(type); return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : void 0; } @@ -56127,7 +56161,7 @@ ${lanes.join("\n")} return type.resolvedBaseConstraint; } const stack = []; - return type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type); + return type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), getThisArgument(type)); function getImmediateBaseConstraint(t) { if (!t.immediateBaseConstraint) { if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { @@ -56217,6 +56251,13 @@ ${lanes.join("\n")} if (t.flags & 33554432 /* Substitution */) { return getBaseConstraint(getSubstitutionIntersection(t)); } + if (isGenericTupleType(t)) { + const newElements = map(getElementTypes(t), (v, i) => { + const constraint = t.target.elementFlags[i] & 8 /* Variadic */ && getBaseConstraint(v) || v; + return constraint && everyType(constraint, (c) => isArrayOrTupleType(c) && !isGenericTupleType(c)) ? constraint : v; + }); + return createTupleType(newElements, t.target.elementFlags, t.target.readonly, t.target.labeledElementDeclarations); + } return t; } } @@ -56757,7 +56798,8 @@ ${lanes.join("\n")} thisParameter = createSymbolWithType(createSymbol(1 /* FunctionScopedVariable */, "this" /* This */), getTypeFromTypeNode(thisTag.typeExpression)); } } - const classType = declaration.kind === 175 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : void 0; + const hostDeclaration = isJSDocSignature(declaration) ? getEffectiveJSDocHost(declaration) : declaration; + const classType = hostDeclaration && isConstructorDeclaration(hostDeclaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(hostDeclaration.parent.symbol)) : void 0; const typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); if (hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { flags |= 1 /* HasRestParameter */; @@ -56983,16 +57025,16 @@ ${lanes.join("\n")} if (declaration.kind === 175 /* Constructor */) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); } + const typeNode = getEffectiveReturnTypeNode(declaration); if (isJSDocSignature(declaration)) { const root = getJSDocRoot(declaration); - if (root && isConstructorDeclaration(root.parent)) { + if (root && isConstructorDeclaration(root.parent) && !typeNode) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(root.parent.parent.symbol)); } } if (isJSDocConstructSignature(declaration)) { return getTypeFromTypeNode(declaration.parameters[0].type); } - const typeNode = getEffectiveReturnTypeNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); } @@ -58270,7 +58312,7 @@ ${lanes.join("\n")} if (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type)) { addElement(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) == null ? void 0 : _a[i]); } else if (isTupleType(type)) { - const elements = getTypeArguments(type); + const elements = getElementTypes(type); if (elements.length + expandedTypes.length >= 1e4) { 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; @@ -58348,6 +58390,11 @@ ${lanes.join("\n")} function getEndElementCount(type, flags) { return type.elementFlags.length - findLastIndex(type.elementFlags, (f) => !(f & flags)) - 1; } + function getElementTypes(type) { + const typeArguments = getTypeArguments(type); + const arity = getTypeReferenceArity(type); + return typeArguments.length === arity ? typeArguments : typeArguments.slice(0, arity); + } function getTypeFromOptionalTypeNode(node) { return addOptionality( getTypeFromTypeNode(node.type), @@ -58944,7 +58991,20 @@ ${lanes.join("\n")} if (isPrivateIdentifier(name)) { return neverType; } - return isIdentifier(name) ? getStringLiteralType(unescapeLeadingUnderscores(name.escapedText)) : getRegularTypeOfLiteralType(isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + if (isNumericLiteral(name)) { + return getRegularTypeOfLiteralType(checkExpression(name)); + } + if (isComputedPropertyName(name)) { + return getRegularTypeOfLiteralType(checkComputedPropertyName(name)); + } + const propertyName = getPropertyNameForPropertyNameNode(name); + if (propertyName !== void 0) { + return getStringLiteralType(unescapeLeadingUnderscores(propertyName)); + } + if (isExpression(name)) { + return getRegularTypeOfLiteralType(checkExpression(name)); + } + return neverType; } function getLiteralTypeFromProperty(prop, include, includeNonPublic) { if (includeNonPublic || !(getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { @@ -59598,7 +59658,7 @@ ${lanes.join("\n")} return isTupleTypeNode(node) && length(node.elements) > 0 && !some(node.elements, (e) => isOptionalTypeNode(e) || isRestTypeNode(e) || isNamedTupleMember(e) && !!(e.questionToken || e.dotDotDotToken)); } function isDeferredType(type, checkTuples) { - return isGenericType(type) || checkTuples && isTupleType(type) && some(getTypeArguments(type), isGenericType); + return isGenericType(type) || checkTuples && isTupleType(type) && some(getElementTypes(type), isGenericType); } function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { let result; @@ -60533,7 +60593,7 @@ ${lanes.join("\n")} } function instantiateMappedGenericTupleType(tupleType, mappedType, typeVariable, mapper) { const elementFlags = tupleType.target.elementFlags; - const elementTypes = map(getTypeArguments(tupleType), (t, i) => { + const elementTypes = map(getElementTypes(tupleType), (t, i) => { const singleton = elementFlags[i] & 8 /* Variadic */ ? t : elementFlags[i] & 4 /* Rest */ ? createArrayType(t) : createTupleType([t], [elementFlags[i]]); return instantiateMappedType(mappedType, prependTypeMapping(typeVariable, singleton, mapper)); }); @@ -60552,7 +60612,7 @@ ${lanes.join("\n")} } function instantiateMappedTupleType(tupleType, mappedType, mapper) { const elementFlags = tupleType.target.elementFlags; - const elementTypes = map(getTypeArguments(tupleType), (_, i) => instantiateMappedTypeTemplate(mappedType, getStringLiteralType("" + i), !!(elementFlags[i] & 2 /* Optional */), mapper)); + const elementTypes = map(getElementTypes(tupleType), (_, i) => instantiateMappedTypeTemplate(mappedType, getStringLiteralType("" + i), !!(elementFlags[i] & 2 /* Optional */), mapper)); const modifiers = getMappedTypeModifiers(mappedType); const newTupleModifiers = modifiers & 4 /* IncludeOptional */ ? map(elementFlags, (f) => f & 1 /* Required */ ? 2 /* Optional */ : f) : modifiers & 8 /* ExcludeOptional */ ? map(elementFlags, (f) => f & 2 /* Optional */ ? 1 /* Required */ : f) : elementFlags; const newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers); @@ -61738,7 +61798,7 @@ ${lanes.join("\n")} return type; } function getNormalizedTupleType(type, writing) { - const elements = getTypeArguments(type); + const elements = getElementTypes(type); const normalizedElements = sameMap(elements, (t) => t.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(t, writing) : t); return elements !== normalizedElements ? createNormalizedTupleType(type.target, normalizedElements) : type; } @@ -62027,6 +62087,8 @@ ${lanes.join("\n")} return isRelatedTo(source2, target2, 3 /* Both */, reportErrors2); } function isRelatedTo(originalSource, originalTarget, recursionFlags = 3 /* Both */, reportErrors2 = false, headMessage2, intersectionState = 0 /* None */) { + if (originalSource === originalTarget) + return -1 /* True */; if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 402784252 /* Primitive */) { if (relation === comparableRelation && !(originalTarget.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(originalTarget, originalSource, relation) || isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors2 ? reportError : void 0)) { return -1 /* True */; @@ -63245,6 +63307,11 @@ ${lanes.join("\n")} } else { return 0 /* False */; } + } else if (isGenericTupleType(source2) && isTupleType(target2) && !isGenericTupleType(target2)) { + const constraint = getBaseConstraintOrType(source2); + if (constraint !== source2) { + return isRelatedTo(constraint, target2, 1 /* Source */, reportErrors2); + } } else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target2) && getObjectFlags(target2) & 8192 /* FreshLiteral */ && !isEmptyObjectType(source2)) { return 0 /* False */; } @@ -65160,7 +65227,7 @@ ${lanes.join("\n")} return type; } function isPartiallyInferableType(type) { - return !(getObjectFlags(type) & 262144 /* NonInferrableType */) || isObjectLiteralType2(type) && some(getPropertiesOfType(type), (prop) => isPartiallyInferableType(getTypeOfSymbol(prop))) || isTupleType(type) && some(getTypeArguments(type), isPartiallyInferableType); + return !(getObjectFlags(type) & 262144 /* NonInferrableType */) || isObjectLiteralType2(type) && some(getPropertiesOfType(type), (prop) => isPartiallyInferableType(getTypeOfSymbol(prop))) || isTupleType(type) && some(getElementTypes(type), isPartiallyInferableType); } function createReverseMappedType(source, target, constraint) { if (!(getIndexInfoOfType(source, stringType) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) { @@ -65170,7 +65237,7 @@ ${lanes.join("\n")} return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source)); } if (isTupleType(source)) { - const elementTypes = map(getTypeArguments(source), (t) => inferReverseMappedType(t, target, constraint)); + const elementTypes = map(getElementTypes(source), (t) => inferReverseMappedType(t, target, constraint)); const elementFlags = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? sameMap(source.target.elementFlags, (f) => f & 2 /* Optional */ ? 1 /* Required */ : f) : source.target.elementFlags; return createTupleType(elementTypes, elementFlags, source.target.readonly, source.target.labeledElementDeclarations); } @@ -66006,14 +66073,14 @@ ${lanes.join("\n")} const inference = context.inferences[index]; if (!inference.inferredType) { let inferredType; - const signature = context.signature; - if (signature) { - const inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : void 0; - if (inference.contraCandidates) { - const useCovariantType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* 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))); - inferredType = useCovariantType ? inferredCovariantType : getContravariantInference(inference); - } else if (inferredCovariantType) { - inferredType = inferredCovariantType; + let fallbackType; + if (context.signature) { + const inferredCovariantType = inference.candidates ? getCovariantInference(inference, context.signature) : void 0; + const inferredContravariantType = inference.contraCandidates ? getContravariantInference(inference) : void 0; + if (inferredCovariantType || inferredContravariantType) { + const preferCovariantType = inferredCovariantType && (!inferredContravariantType || !(inferredCovariantType.flags & 131072 /* 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)))); + inferredType = preferCovariantType ? inferredCovariantType : inferredContravariantType; + fallbackType = preferCovariantType ? inferredContravariantType : inferredCovariantType; } else if (context.flags & 1 /* NoDefault */) { inferredType = silentNeverType; } else { @@ -66030,7 +66097,7 @@ ${lanes.join("\n")} if (constraint) { const instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper); if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - inference.inferredType = inferredType = instantiatedConstraint; + inference.inferredType = fallbackType && context.compareTypes(fallbackType, getTypeWithThisArgument(instantiatedConstraint, fallbackType)) ? fallbackType : instantiatedConstraint; } } } @@ -68250,7 +68317,7 @@ ${lanes.join("\n")} markAliasReferenced(symbol, node); } const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - const targetSymbol = checkDeprecatedAliasedSymbol(localOrExportSymbol, node); + const targetSymbol = resolveAliasWithDeprecationCheck(localOrExportSymbol, node); if (isDeprecatedSymbol(targetSymbol) && isUncalledFunctionReference(node, targetSymbol) && targetSymbol.declarations) { addDeprecatedSuggestion(node, targetSymbol.declarations, node.escapedText); } @@ -69343,7 +69410,7 @@ ${lanes.join("\n")} return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType2(conditional, contextFlags) : void 0; } function getContextualTypeForChildJsxExpression(node, child, contextFlags) { - const attributesType = getApparentTypeOfContextualType(node.openingElement.tagName, contextFlags); + const attributesType = getApparentTypeOfContextualType(node.openingElement.attributes, contextFlags); const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { return void 0; @@ -69419,6 +69486,7 @@ ${lanes.join("\n")} ); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { + const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); return discriminateTypeByDiscriminableItems( contextualType, concatenate( @@ -69429,7 +69497,14 @@ ${lanes.join("\n")} map( filter(getPropertiesOfType(contextualType), (s) => { var _a; - return !!(s.flags & 16777216 /* Optional */) && !!((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); + if (!(s.flags & 16777216 /* Optional */) || !((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members)) { + return false; + } + const element = node.parent.parent; + if (s.escapedName === jsxChildrenPropertyName && isJsxElement(element) && getSemanticJsxChildren(element.children).length) { + return false; + } + return !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), (s) => [() => undefinedType, s.escapedName] ) @@ -69671,18 +69746,10 @@ ${lanes.join("\n")} function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { const managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { - const declaredManagedType = getDeclaredTypeOfSymbol(managedSym); const ctorType = getStaticTypeOfReferencedJsxConstructor(context); - if (managedSym.flags & 524288 /* TypeAlias */) { - const params = getSymbolLinks(managedSym).typeParameters; - if (length(params) >= 2) { - const args = fillMissingTypeArguments([ctorType, attributesType], params, 2, isInJSFile(context)); - return getTypeAliasInstantiation(managedSym, args); - } - } - if (length(declaredManagedType.typeParameters) >= 2) { - const args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, isInJSFile(context)); - return createTypeReference(declaredManagedType, args); + const result = instantiateAliasOrInterfaceWithDefaults(managedSym, isInJSFile(context), ctorType, attributesType); + if (result) { + return result; } } return attributesType; @@ -70040,7 +70107,7 @@ ${lanes.join("\n")} } return links.immediateTarget; } - function checkObjectLiteral(node, checkMode) { + function checkObjectLiteral(node, checkMode = 0 /* Normal */) { var _a; const inDestructuringPattern = isAssignmentTarget(node); checkGrammarObjectLiteralExpression(node, inDestructuringPattern); @@ -70123,7 +70190,7 @@ ${lanes.join("\n")} prop.links.target = member; member = prop; allPropertiesTable == null ? void 0 : allPropertiesTable.set(prop.escapedName, prop); - if (contextualType && checkMode && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && (memberDecl.kind === 302 /* PropertyAssignment */ || memberDecl.kind === 173 /* MethodDeclaration */) && isContextSensitive(memberDecl)) { + if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && (memberDecl.kind === 302 /* PropertyAssignment */ || memberDecl.kind === 173 /* MethodDeclaration */) && isContextSensitive(memberDecl)) { const inferenceContext = getInferenceContext(node); Debug.assert(inferenceContext); const inferenceNode = memberDecl.kind === 302 /* PropertyAssignment */ ? memberDecl.initializer : memberDecl; @@ -70141,7 +70208,7 @@ ${lanes.join("\n")} hasComputedNumberProperty = false; hasComputedSymbolProperty = false; } - const type = getReducedType(checkExpression(memberDecl.expression)); + const type = getReducedType(checkExpression(memberDecl.expression, checkMode & 2 /* Inferential */)); if (isValidSpreadType(type)) { const mergedType = tryMergeUnionOfObjectTypeAndEmptyObject(type, inConstContext); if (allPropertiesTable) { @@ -70282,7 +70349,7 @@ ${lanes.join("\n")} function checkJsxAttribute(node, checkMode) { return node.initializer ? checkExpressionForMutableLocation(node.initializer, checkMode) : trueType; } - function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode = 0 /* Normal */) { const attributes = openingLikeElement.attributes; const contextualType = getContextualType2(attributes, 0 /* None */); const allAttributesTable = strictNullChecks ? createSymbolTable() : void 0; @@ -70317,7 +70384,7 @@ ${lanes.join("\n")} addDeprecatedSuggestion(attributeDecl.name, prop.declarations, attributeDecl.name.escapedText); } } - if (contextualType && checkMode && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && isContextSensitive(attributeDecl)) { + if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && isContextSensitive(attributeDecl)) { const inferenceContext = getInferenceContext(attributes); Debug.assert(inferenceContext); const inferenceNode = attributeDecl.initializer.expression; @@ -70336,7 +70403,7 @@ ${lanes.join("\n")} ); attributesTable = createSymbolTable(); } - const exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode)); + const exprType = getReducedType(checkExpression(attributeDecl.expression, checkMode & 2 /* Inferential */)); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } @@ -70569,6 +70636,9 @@ ${lanes.join("\n")} function getJsxLibraryManagedAttributes(jsxNamespace) { return jsxNamespace && getSymbol2(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */); } + function getJsxElementTypeSymbol(jsxNamespace) { + return jsxNamespace && getSymbol2(jsxNamespace.exports, JsxNames.ElementType, 788968 /* Type */); + } function getJsxElementPropertiesName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); } @@ -70675,11 +70745,32 @@ ${lanes.join("\n")} } } function getJsxElementTypeTypeAt(location) { - const type = getJsxType(JsxNames.ElementType, location); - if (isErrorType(type)) + const ns = getJsxNamespaceAt(location); + if (!ns) + return void 0; + const sym = getJsxElementTypeSymbol(ns); + if (!sym) + return void 0; + const type = instantiateAliasOrInterfaceWithDefaults(sym, isInJSFile(location)); + if (!type || isErrorType(type)) return void 0; return type; } + function instantiateAliasOrInterfaceWithDefaults(managedSym, inJs, ...typeArguments) { + const declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + if (managedSym.flags & 524288 /* TypeAlias */) { + const params = getSymbolLinks(managedSym).typeParameters; + if (length(params) >= typeArguments.length) { + const args = fillMissingTypeArguments(typeArguments, params, typeArguments.length, inJs); + return length(args) === 0 ? declaredManagedType : getTypeAliasInstantiation(managedSym, args); + } + } + if (length(declaredManagedType.typeParameters) >= typeArguments.length) { + const args = fillMissingTypeArguments(typeArguments, declaredManagedType.typeParameters, typeArguments.length, inJs); + return createTypeReference(declaredManagedType, args); + } + return void 0; + } function getJsxIntrinsicTagNamesAt(location) { const intrinsics = getJsxType(JsxNames.IntrinsicElements, location); return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; @@ -71230,8 +71321,9 @@ ${lanes.join("\n")} addDeprecatedSuggestion(right, [indexInfo.declaration], right.escapedText); } } else { - if (isDeprecatedSymbol(prop) && isUncalledFunctionReference(node, prop) && prop.declarations) { - addDeprecatedSuggestion(right, prop.declarations, right.escapedText); + const targetPropSymbol = resolveAliasWithDeprecationCheck(prop, right); + if (isDeprecatedSymbol(targetPropSymbol) && isUncalledFunctionReference(node, targetPropSymbol) && targetPropSymbol.declarations) { + addDeprecatedSuggestion(right, targetPropSymbol.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, isSelfTypeAccess(left, parentSymbol)); @@ -71926,7 +72018,7 @@ ${lanes.join("\n")} } function getMutableArrayOrTupleType(type) { return type.flags & 1048576 /* Union */ ? mapType(type, getMutableArrayOrTupleType) : type.flags & 1 /* Any */ || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type : isTupleType(type) ? createTupleType( - getTypeArguments(type), + getElementTypes(type), type.target.elementFlags, /*readonly*/ false, @@ -72042,7 +72134,7 @@ ${lanes.join("\n")} if (getJsxNamespaceContainerForImplicitImport(node)) { return true; } - const tagType = isJsxOpeningElement(node) || isJsxSelfClosingElement(node) && !isJsxIntrinsicTagName(node.tagName) ? checkExpression(node.tagName) : void 0; + const tagType = (isJsxOpeningElement(node) || isJsxSelfClosingElement(node)) && !(isJsxIntrinsicTagName(node.tagName) || isJsxNamespacedName(node.tagName)) ? checkExpression(node.tagName) : void 0; if (!tagType) { return true; } @@ -72240,7 +72332,7 @@ ${lanes.join("\n")} const arg = args[i]; const spreadType = arg.kind === 229 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); if (spreadType && isTupleType(spreadType)) { - forEach(getTypeArguments(spreadType), (t, i2) => { + forEach(getElementTypes(spreadType), (t, i2) => { var _a; const flags = spreadType.target.elementFlags[i2]; const syntheticArg = createSyntheticExpression( @@ -73767,6 +73859,8 @@ ${lanes.join("\n")} } return getRegularTypeOfLiteralType(exprType); } + const links = getNodeLinks(node); + links.assertionExpressionType = exprType; checkSourceElement(type); checkNodeDeferred(node); return getTypeFromTypeNode(type); @@ -73788,9 +73882,11 @@ ${lanes.join("\n")} return { type, expression }; } function checkAssertionDeferred(node) { - const { type, expression } = getAssertionTypeAndExpression(node); + const { type } = getAssertionTypeAndExpression(node); const errNode = isParenthesizedExpression(node) ? type : node; - const exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression))); + const links = getNodeLinks(node); + Debug.assertIsDefined(links.assertionExpressionType); + const exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(links.assertionExpressionType)); const targetType = getTypeFromTypeNode(type); if (!isErrorType(targetType)) { addLazyDiagnostic(() => { @@ -74754,6 +74850,10 @@ ${lanes.join("\n")} forEachReturnStatement(func.body, (returnStatement) => { const expr = returnStatement.expression; if (expr) { + if (expr.kind === 212 /* CallExpression */ && expr.expression.kind === 80 /* Identifier */ && checkExpressionCached(expr.expression).symbol === func.symbol) { + hasReturnOfTypeNever = true; + return; + } let type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */); if (functionFlags & 2 /* Async */) { type = unwrapAwaitedType(checkAwaitedType( @@ -76234,7 +76334,7 @@ ${lanes.join("\n")} } function padTupleType(type, pattern) { const patternElements = pattern.elements; - const elementTypes = getTypeArguments(type).slice(); + const elementTypes = getElementTypes(type).slice(); const elementFlags = type.target.elementFlags.slice(); for (let i = getTypeReferenceArity(type); i < patternElements.length; i++) { const e = patternElements[i]; @@ -81507,19 +81607,17 @@ ${lanes.join("\n")} } } if (isImportSpecifier(node)) { - const targetSymbol = checkDeprecatedAliasedSymbol(symbol, node); - if (isDeprecatedAliasedSymbol(targetSymbol) && targetSymbol.declarations) { + const targetSymbol = resolveAliasWithDeprecationCheck(symbol, node); + if (isDeprecatedSymbol(targetSymbol) && targetSymbol.declarations) { addDeprecatedSuggestion(node, targetSymbol.declarations, targetSymbol.escapedName); } } } } - function isDeprecatedAliasedSymbol(symbol) { - return !!symbol.declarations && every(symbol.declarations, (d) => !!(getCombinedNodeFlags(d) & 268435456 /* Deprecated */)); - } - function checkDeprecatedAliasedSymbol(symbol, location) { - if (!(symbol.flags & 2097152 /* Alias */)) + function resolveAliasWithDeprecationCheck(symbol, location) { + if (!(symbol.flags & 2097152 /* Alias */) || isDeprecatedSymbol(symbol) || !getDeclarationOfAliasSymbol(symbol)) { return symbol; + } const targetSymbol = resolveAlias(symbol); if (targetSymbol === unknownSymbol) return targetSymbol; @@ -81529,7 +81627,7 @@ ${lanes.join("\n")} if (target === targetSymbol) break; if (target.declarations && length(target.declarations)) { - if (isDeprecatedAliasedSymbol(target)) { + if (isDeprecatedSymbol(target)) { addDeprecatedSuggestion(location, target.declarations, target.escapedName); break; } else { @@ -82622,7 +82720,7 @@ ${lanes.join("\n")} name, meaning, /*ignoreErrors*/ - false, + true, /*dontResolveAlias*/ true, getHostSignatureFromJSDoc(name) @@ -82633,7 +82731,7 @@ ${lanes.join("\n")} return resolveJSDocMemberName( name, /*ignoreErrors*/ - false, + true, getSymbolOfDeclaration(container) ); } @@ -83486,6 +83584,41 @@ ${lanes.join("\n")} } return void 0; } + function getReferencedValueDeclarations(referenceIn) { + if (!isGeneratedIdentifier(referenceIn)) { + const reference = getParseTreeNode(referenceIn, isIdentifier); + if (reference) { + const symbol = getReferencedValueSymbol(reference); + if (symbol) { + return filter(getExportSymbolOfValueSymbolIfExported(symbol).declarations, (declaration) => { + switch (declaration.kind) { + case 259 /* VariableDeclaration */: + case 168 /* Parameter */: + case 207 /* BindingElement */: + case 171 /* PropertyDeclaration */: + case 302 /* PropertyAssignment */: + case 303 /* ShorthandPropertyAssignment */: + case 305 /* EnumMember */: + case 209 /* ObjectLiteralExpression */: + case 261 /* FunctionDeclaration */: + case 217 /* FunctionExpression */: + case 218 /* ArrowFunction */: + case 262 /* ClassDeclaration */: + case 230 /* ClassExpression */: + case 265 /* EnumDeclaration */: + case 173 /* MethodDeclaration */: + case 176 /* GetAccessor */: + case 177 /* SetAccessor */: + case 266 /* ModuleDeclaration */: + return true; + } + return false; + }); + } + } + } + return void 0; + } function isLiteralConstDeclaration(node) { if (isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node)) { return isFreshLiteralType(getTypeOfSymbol(getSymbolOfDeclaration(node))); @@ -83584,6 +83717,7 @@ ${lanes.join("\n")} }, collectLinkedAliases, getReferencedValueDeclaration, + getReferencedValueDeclarations, getTypeReferenceSerializationKind, isOptionalParameter, moduleExportsSomeValue, @@ -87765,7 +87899,7 @@ ${lanes.join("\n")} case 242 /* VariableStatement */: if (hasSyntacticModifier(node, 1 /* Export */)) { for (const decl of node.declarationList.declarations) { - exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings); } } break; @@ -87827,11 +87961,11 @@ ${lanes.join("\n")} } } } - function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + function collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings) { if (isBindingPattern(decl.name)) { for (const element of decl.name.elements) { if (!isOmittedExpression(element)) { - exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames, exportedBindings); } } } else if (!isGeneratedIdentifier(decl.name)) { @@ -87839,6 +87973,9 @@ ${lanes.join("\n")} if (!uniqueExports.get(text)) { uniqueExports.set(text, true); exportedNames = append(exportedNames, decl.name); + if (isLocalName(decl.name)) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), decl.name); + } } } return exportedNames; @@ -88982,7 +89119,7 @@ ${lanes.join("\n")} if (promoteToIIFE) { context.startLexicalEnvironment(); } - const moveModifiers = promoteToIIFE || facts & 8 /* IsExportOfNamespace */ || facts & 2 /* HasClassOrConstructorParameterDecorators */ && legacyDecorators || facts & 1 /* HasStaticInitializedProperties */; + const moveModifiers = promoteToIIFE || facts & 8 /* IsExportOfNamespace */; let modifiers = moveModifiers ? visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike) : visitNodes2(node.modifiers, visitor, isModifierLike); if (facts & 2 /* HasClassOrConstructorParameterDecorators */) { modifiers = injectClassTypeMetadata(modifiers, node); @@ -89048,13 +89185,13 @@ ${lanes.join("\n")} } if (moveModifiers) { if (facts & 8 /* IsExportOfNamespace */) { - return demarcateMultiStatementExport( + return [ statement, createExportMemberAssignmentStatement(node) - ); + ]; } if (facts & 32 /* IsDefaultExternalExport */) { - return demarcateMultiStatementExport( + return [ statement, factory2.createExportDefault(factory2.getLocalName( node, @@ -89063,10 +89200,10 @@ ${lanes.join("\n")} /*allowSourceMaps*/ true )) - ); + ]; } if (facts & 16 /* IsNamedExternalExport */ && !promoteToIIFE) { - return demarcateMultiStatementExport( + return [ statement, factory2.createExternalModuleExport(factory2.getLocalName( node, @@ -89075,19 +89212,11 @@ ${lanes.join("\n")} /*allowSourceMaps*/ true )) - ); + ]; } } return statement; } - function demarcateMultiStatementExport(declarationStatement, exportStatement) { - addEmitFlags(declarationStatement, 8388608 /* HasEndOfDeclarationMarker */); - return [ - declarationStatement, - exportStatement, - factory2.createEndOfDeclarationMarker(declarationStatement) - ]; - } function visitClassExpression(node) { let modifiers = visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike); if (classOrConstructorParameterIsDecorated(legacyDecorators, node)) { @@ -89705,14 +89834,14 @@ ${lanes.join("\n")} } const parameterName = getNamespaceParameterName(node); const containerName = getNamespaceContainerName(node); - const exportName = hasSyntacticModifier(node, 1 /* Export */) ? factory2.getExternalModuleOrNamespaceExportName( + const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName( currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true - ) : factory2.getLocalName( + ) : factory2.getDeclarationName( node, /*allowComments*/ false, @@ -89726,7 +89855,7 @@ ${lanes.join("\n")} factory2.createObjectLiteralExpression() ) ); - if (hasNamespaceQualifiedExportName(node)) { + if (isExportOfNamespace(node)) { const localName = factory2.getLocalName( node, /*allowComments*/ @@ -89771,7 +89900,6 @@ ${lanes.join("\n")} setTextRange(enumStatement, node); addEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); - statements.push(factory2.createEndOfDeclarationMarker(node)); return statements; } function transformEnumBody(node, localName) { @@ -89844,9 +89972,6 @@ ${lanes.join("\n")} } return isInstantiatedModule(node, shouldPreserveConstEnums(compilerOptions)); } - function hasNamespaceQualifiedExportName(node) { - return isExportOfNamespace(node) || isExternalModuleExport(node) && moduleKind !== 5 /* ES2015 */ && moduleKind !== 6 /* ES2020 */ && moduleKind !== 7 /* ES2022 */ && moduleKind !== 99 /* ESNext */ && moduleKind !== 4 /* System */; - } function recordEmittedDeclarationInScope(node) { if (!currentScopeFirstDeclarationsOfName) { currentScopeFirstDeclarationsOfName = /* @__PURE__ */ new Map(); @@ -89868,20 +89993,21 @@ ${lanes.join("\n")} return node.name.escapedText; } function addVarForEnumOrModuleDeclaration(statements, node) { + const varDecl = factory2.createVariableDeclaration(factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + )); + const varFlags = currentLexicalScope.kind === 311 /* SourceFile */ ? 0 /* None */ : 1 /* Let */; const statement = factory2.createVariableStatement( visitNodes2(node.modifiers, modifierVisitor, isModifier), - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - factory2.getLocalName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ) - ) - ], currentLexicalScope.kind === 311 /* SourceFile */ ? 0 /* None */ : 1 /* Let */) + factory2.createVariableDeclarationList([varDecl], varFlags) ); + setOriginalNode(varDecl, node); + setSyntheticLeadingComments(varDecl, void 0); + setSyntheticTrailingComments(varDecl, void 0); setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -89891,15 +90017,11 @@ ${lanes.join("\n")} setSourceMapRange(statement, node); } setCommentRange(statement, node); - addEmitFlags(statement, 2048 /* NoTrailingComments */ | 8388608 /* HasEndOfDeclarationMarker */); + addEmitFlags(statement, 2048 /* NoTrailingComments */); statements.push(statement); return true; - } else { - const mergeMarker = factory2.createMergeDeclarationMarker(statement); - setEmitFlags(mergeMarker, 3072 /* NoComments */ | 8388608 /* HasEndOfDeclarationMarker */); - statements.push(mergeMarker); - return false; } + return false; } function visitModuleDeclaration(node) { if (!shouldEmitModuleDeclaration(node)) { @@ -89917,14 +90039,14 @@ ${lanes.join("\n")} } const parameterName = getNamespaceParameterName(node); const containerName = getNamespaceContainerName(node); - const exportName = hasSyntacticModifier(node, 1 /* Export */) ? factory2.getExternalModuleOrNamespaceExportName( + const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName( currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true - ) : factory2.getLocalName( + ) : factory2.getDeclarationName( node, /*allowComments*/ false, @@ -89938,7 +90060,7 @@ ${lanes.join("\n")} factory2.createObjectLiteralExpression() ) ); - if (hasNamespaceQualifiedExportName(node)) { + if (isExportOfNamespace(node)) { const localName = factory2.getLocalName( node, /*allowComments*/ @@ -89983,7 +90105,6 @@ ${lanes.join("\n")} setTextRange(moduleStatement, node); addEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); - statements.push(factory2.createEndOfDeclarationMarker(node)); return statements; } function transformModuleBody(node, namespaceLocalName) { @@ -91577,23 +91698,12 @@ ${lanes.join("\n")} getClassLexicalEnvironment().classThis = node.emitNode.classThis; } } - const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); + const isExport = hasSyntacticModifier(node, 1 /* Export */); + const isDefault = hasSyntacticModifier(node, 1024 /* Default */); + let modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); const heritageClauses = visitNodes2(node.heritageClauses, heritageClauseVisitor, isHeritageClause); const { members, prologue } = transformClassMembers(node); - const classDecl = factory2.updateClassDeclaration( - node, - modifiers, - node.name, - /*typeParameters*/ - void 0, - heritageClauses, - members - ); const statements = []; - if (prologue) { - statements.push(factory2.createExpressionStatement(prologue)); - } - statements.push(classDecl); if (pendingClassReferenceAssignment) { getPendingExpressions().unshift(pendingClassReferenceAssignment); } @@ -91606,6 +91716,35 @@ ${lanes.join("\n")} addPropertyOrClassStaticBlockStatements(statements, staticProperties, factory2.getInternalName(node)); } } + if (statements.length > 0 && isExport && isDefault) { + modifiers = visitNodes2(modifiers, (node2) => isExportOrDefaultModifier(node2) ? void 0 : node2, isModifier); + statements.push(factory2.createExportAssignment( + /*modifiers*/ + void 0, + /*isExportEquals*/ + false, + factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ) + )); + } + const classDecl = factory2.updateClassDeclaration( + node, + modifiers, + node.name, + /*typeParameters*/ + void 0, + heritageClauses, + members + ); + statements.unshift(classDecl); + if (prologue) { + statements.unshift(factory2.createExpressionStatement(prologue)); + } return statements; } function visitClassExpression(node, referencedName) { @@ -93055,10 +93194,6 @@ ${lanes.join("\n")} true, node ) ? transformClassDeclarationWithClassDecorators(node, node.name) : transformClassDeclarationWithoutClassDecorators(node, node.name); - if (statements.length > 1) { - statements.push(factory2.createEndOfDeclarationMarker(node)); - setEmitFlags(statements[0], getEmitFlags(statements[0]) | 8388608 /* HasEndOfDeclarationMarker */); - } return singleOrMany(statements); } function decoratorContainsPrivateIdentifierInExpression(decorator) { @@ -93131,9 +93266,12 @@ ${lanes.join("\n")} return addRange([updated], decorationStatements); } function transformClassDeclarationWithClassDecorators(node, name) { + const isExport = hasSyntacticModifier(node, 1 /* Export */); + const isDefault = hasSyntacticModifier(node, 1024 /* Default */); + const modifiers = visitNodes2(node.modifiers, (node2) => isExportOrDefaultModifier(node2) || isDecorator(node2) ? void 0 : node2, isModifierLike); const location = moveRangePastModifiers(node); const classAlias = getClassAliasIfNeeded(node); - const declName = languageVersion <= 2 /* ES2015 */ ? factory2.getInternalName( + const declName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName( node, /*allowComments*/ false, @@ -93150,9 +93288,21 @@ ${lanes.join("\n")} let members = visitNodes2(node.members, visitor, isClassElement); let decorationStatements = []; ({ members, decorationStatements } = transformDecoratorsOfClassElements(node, members)); + const assignClassAliasInStaticBlock = languageVersion >= 9 /* ES2022 */ && !!classAlias && some(members, (member) => isPropertyDeclaration(member) && hasSyntacticModifier(member, 32 /* Static */) || isClassStaticBlockDeclaration(member)); + if (assignClassAliasInStaticBlock) { + members = setTextRange(factory2.createNodeArray([ + factory2.createClassStaticBlockDeclaration( + factory2.createBlock([ + factory2.createExpressionStatement( + factory2.createAssignment(classAlias, factory2.createThis()) + ) + ]) + ), + ...members + ]), members); + } const classExpression = factory2.createClassExpression( - /*modifiers*/ - void 0, + modifiers, name && isGeneratedIdentifier(name) ? void 0 : name, /*typeParameters*/ void 0, @@ -93161,18 +93311,23 @@ ${lanes.join("\n")} ); setOriginalNode(classExpression, node); setTextRange(classExpression, location); - const statement = factory2.createVariableStatement( - /*modifiers*/ + const varDecl = factory2.createVariableDeclaration( + declName, + /*exclamationToken*/ void 0, + /*type*/ + void 0, + classAlias && !assignClassAliasInStaticBlock ? factory2.createAssignment(classAlias, classExpression) : classExpression + ); + setOriginalNode(varDecl, node); + let varModifiers; + if (isExport && !isDefault) { + varModifiers = factory2.createModifiersFromModifierFlags(1 /* Export */); + } + const statement = factory2.createVariableStatement( + varModifiers, factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - declName, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - classAlias ? factory2.createAssignment(classAlias, classExpression) : classExpression - ) + varDecl ], 1 /* Let */) ); setOriginalNode(statement, node); @@ -93181,6 +93336,15 @@ ${lanes.join("\n")} const statements = [statement]; addRange(statements, decorationStatements); addConstructorDecorationStatement(statements, node); + if (isExport && isDefault) { + statements.push(factory2.createExportAssignment( + /*modifiers*/ + void 0, + /*isExportEquals*/ + false, + declName + )); + } return statements; } function visitClassExpression(node) { @@ -93357,13 +93521,13 @@ ${lanes.join("\n")} return void 0; } const classAlias = classAliases && classAliases[getOriginalNodeId(node)]; - const localName = languageVersion <= 2 /* ES2015 */ ? factory2.getInternalName( + const localName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName( node, /*allowComments*/ false, /*allowSourceMaps*/ true - ) : factory2.getLocalName( + ) : factory2.getDeclarationName( node, /*allowComments*/ false, @@ -93858,7 +94022,15 @@ ${lanes.join("\n")} function transformClassLike(node, className) { var _a; startLexicalEnvironment(); - const classReference = node.name ?? factory2.getGeneratedNameForNode(node); + const classReference = factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + false, + /*ignoreAssignedName*/ + true + ); const classInfo2 = createClassInfo(node); const classDefinitionStatements = []; let leadingBlockStatements; @@ -94174,6 +94346,7 @@ ${lanes.join("\n")} void 0, iife ); + setOriginalNode(varDecl, node); const varDecls = factory2.createVariableDeclarationList([varDecl], 1 /* Let */); const statement = factory2.createVariableStatement(modifiers, varDecls); setOriginalNode(statement, node); @@ -96510,10 +96683,7 @@ ${lanes.join("\n")} const exitNonUserCodeExpression = factory2.createAssignment(nonUserCode, factory2.createFalse()); const exitNonUserCodeStatement = factory2.createExpressionStatement(exitNonUserCodeExpression); setSourceMapRange(exitNonUserCodeStatement, node.expression); - const enterNonUserCodeExpression = factory2.createAssignment(nonUserCode, factory2.createTrue()); - const enterNonUserCodeStatement = factory2.createExpressionStatement(enterNonUserCodeExpression); - setSourceMapRange(exitNonUserCodeStatement, node.expression); - const statements = []; + const statements = [iteratorValueStatement, exitNonUserCodeStatement]; const binding = createForOfBindingStatement(factory2, node.initializer, value); statements.push(visitNode(binding, visitor, isStatement)); let bodyLocation; @@ -96526,29 +96696,14 @@ ${lanes.join("\n")} } else { statements.push(statement); } - const body = setEmitFlags( - setTextRange( - factory2.createBlock( - setTextRange(factory2.createNodeArray(statements), statementsLocation), - /*multiLine*/ - true - ), - bodyLocation + return setTextRange( + factory2.createBlock( + setTextRange(factory2.createNodeArray(statements), statementsLocation), + /*multiLine*/ + true ), - 96 /* NoSourceMap */ | 768 /* NoTokenSourceMaps */ + bodyLocation ); - return factory2.createBlock([ - iteratorValueStatement, - exitNonUserCodeStatement, - factory2.createTryStatement( - body, - /*catchClause*/ - void 0, - factory2.createBlock([ - enterNonUserCodeStatement - ]) - ) - ]); } function createDownlevelAwait(expression) { return enclosingFunctionFlags & 1 /* Generator */ ? factory2.createYieldExpression( @@ -96627,7 +96782,7 @@ ${lanes.join("\n")} factory2.createLogicalNot(done) ]), /*incrementor*/ - void 0, + factory2.createAssignment(nonUserCode, factory2.createTrue()), /*statement*/ convertForOfStatementHead(node, getValue, nonUserCode) ), @@ -98921,11 +99076,6 @@ ${lanes.join("\n")} setOriginalNode(exportStatement, statement); statements.push(exportStatement); } - const emitFlags = getEmitFlags(node); - if ((emitFlags & 8388608 /* HasEndOfDeclarationMarker */) === 0) { - statements.push(factory2.createEndOfDeclarationMarker(node)); - setEmitFlags(statement, emitFlags | 8388608 /* HasEndOfDeclarationMarker */); - } return singleOrMany(statements); } function visitClassExpression(node) { @@ -100888,7 +101038,7 @@ ${lanes.join("\n")} ); const callResult = containsYield ? factory2.createYieldExpression( factory2.createToken(42 /* AsteriskToken */), - setEmitFlags(call, 16777216 /* Iterator */) + setEmitFlags(call, 8388608 /* Iterator */) ) : call; return factory2.createExpressionStatement(callResult); } @@ -100903,7 +101053,7 @@ ${lanes.join("\n")} ); const callResult = containsYield ? factory2.createYieldExpression( factory2.createToken(42 /* AsteriskToken */), - setEmitFlags(call, 16777216 /* Iterator */) + setEmitFlags(call, 8388608 /* Iterator */) ) : call; if (isSimpleLoop) { statements.push(factory2.createExpressionStatement(callResult)); @@ -102239,7 +102389,7 @@ ${lanes.join("\n")} const resumeLabel = defineLabel(); const expression = visitNode(node.expression, visitor, isExpression); if (node.asteriskToken) { - const iterator = (getEmitFlags(node.expression) & 16777216 /* Iterator */) === 0 ? setTextRange(emitHelpers().createValuesHelper(expression), node) : expression; + const iterator = (getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0 ? setTextRange(emitHelpers().createValuesHelper(expression), node) : expression; emitYieldStar( iterator, /*location*/ @@ -103793,7 +103943,6 @@ ${lanes.join("\n")} context.enableSubstitution(303 /* ShorthandPropertyAssignment */); context.enableEmitNotification(311 /* SourceFile */); const moduleInfoMap = []; - const deferredExports = []; let currentSourceFile; let currentModuleInfo; const noSubstitution = []; @@ -104212,16 +104361,56 @@ ${lanes.join("\n")} return visitExportDeclaration(node); case 276 /* ExportAssignment */: return visitExportAssignment(node); + case 261 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 262 /* ClassDeclaration */: + return visitClassDeclaration(node); + default: + return topLevelNestedVisitor(node); + } + } + function topLevelNestedVisitor(node) { + switch (node.kind) { case 242 /* VariableStatement */: return visitVariableStatement(node); case 261 /* FunctionDeclaration */: return visitFunctionDeclaration(node); case 262 /* ClassDeclaration */: return visitClassDeclaration(node); - case 361 /* MergeDeclarationMarker */: - return visitMergeDeclarationMarker(node); - case 362 /* EndOfDeclarationMarker */: - return visitEndOfDeclarationMarker(node); + case 247 /* ForStatement */: + return visitForStatement( + node, + /*isTopLevel*/ + true + ); + case 248 /* ForInStatement */: + return visitForInStatement(node); + case 249 /* ForOfStatement */: + return visitForOfStatement(node); + case 245 /* DoStatement */: + return visitDoStatement(node); + case 246 /* WhileStatement */: + return visitWhileStatement(node); + case 255 /* LabeledStatement */: + return visitLabeledStatement(node); + case 253 /* WithStatement */: + return visitWithStatement(node); + case 244 /* IfStatement */: + return visitIfStatement(node); + case 254 /* SwitchStatement */: + return visitSwitchStatement(node); + case 268 /* CaseBlock */: + return visitCaseBlock(node); + case 295 /* CaseClause */: + return visitCaseClause(node); + case 296 /* DefaultClause */: + return visitDefaultClause(node); + case 257 /* TryStatement */: + return visitTryStatement(node); + case 298 /* CatchClause */: + return visitCatchClause(node); + case 240 /* Block */: + return visitBlock(node); default: return visitor(node); } @@ -104232,7 +104421,11 @@ ${lanes.join("\n")} } switch (node.kind) { case 247 /* ForStatement */: - return visitForStatement(node); + return visitForStatement( + node, + /*isTopLevel*/ + false + ); case 243 /* ExpressionStatement */: return visitExpressionStatement(node); case 216 /* ParenthesizedExpression */: @@ -104317,15 +104510,177 @@ ${lanes.join("\n")} } return visitEachChild(node, visitor, context); } - function visitForStatement(node) { + function visitForStatement(node, isTopLevel) { + if (isTopLevel && node.initializer && isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 3 /* BlockScoped */)) { + const exportStatements = appendExportsOfVariableDeclarationList( + /*statements*/ + void 0, + node.initializer, + /*isForInOrOfInitializer*/ + false + ); + if (exportStatements) { + const statements = []; + const varDeclList = visitNode(node.initializer, discardedValueVisitor, isVariableDeclarationList); + const varStatement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + varDeclList + ); + statements.push(varStatement); + addRange(statements, exportStatements); + const condition = visitNode(node.condition, visitor, isExpression); + const incrementor = visitNode(node.incrementor, discardedValueVisitor, isExpression); + const body = visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context); + statements.push(factory2.updateForStatement( + node, + /*initializer*/ + void 0, + condition, + incrementor, + body + )); + return statements; + } + } return factory2.updateForStatement( node, visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, discardedValueVisitor, isExpression), - visitIterationBody(node.statement, visitor, context) + visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context) ); } + function visitForInStatement(node) { + if (isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 3 /* BlockScoped */)) { + const exportStatements = appendExportsOfVariableDeclarationList( + /*statements*/ + void 0, + node.initializer, + /*isForInOrOfInitializer*/ + true + ); + if (some(exportStatements)) { + const initializer = visitNode(node.initializer, discardedValueVisitor, isForInitializer); + const expression = visitNode(node.expression, visitor, isExpression); + const body = visitIterationBody(node.statement, topLevelNestedVisitor, context); + const mergedBody = isBlock(body) ? factory2.updateBlock(body, [...exportStatements, ...body.statements]) : factory2.createBlock( + [...exportStatements, body], + /*multiLine*/ + true + ); + return factory2.updateForInStatement(node, initializer, expression, mergedBody); + } + } + return factory2.updateForInStatement( + node, + visitNode(node.initializer, discardedValueVisitor, isForInitializer), + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + } + function visitForOfStatement(node) { + if (isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 3 /* BlockScoped */)) { + const exportStatements = appendExportsOfVariableDeclarationList( + /*statements*/ + void 0, + node.initializer, + /*isForInOrOfInitializer*/ + true + ); + const initializer = visitNode(node.initializer, discardedValueVisitor, isForInitializer); + const expression = visitNode(node.expression, visitor, isExpression); + let body = visitIterationBody(node.statement, topLevelNestedVisitor, context); + if (some(exportStatements)) { + body = isBlock(body) ? factory2.updateBlock(body, [...exportStatements, ...body.statements]) : factory2.createBlock( + [...exportStatements, body], + /*multiLine*/ + true + ); + } + return factory2.updateForOfStatement(node, node.awaitModifier, initializer, expression, body); + } + return factory2.updateForOfStatement( + node, + node.awaitModifier, + visitNode(node.initializer, discardedValueVisitor, isForInitializer), + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + } + function visitDoStatement(node) { + return factory2.updateDoStatement( + node, + visitIterationBody(node.statement, topLevelNestedVisitor, context), + visitNode(node.expression, visitor, isExpression) + ); + } + function visitWhileStatement(node) { + return factory2.updateWhileStatement( + node, + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + } + function visitLabeledStatement(node) { + return factory2.updateLabeledStatement( + node, + node.label, + Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) + ); + } + function visitWithStatement(node) { + return factory2.updateWithStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) + ); + } + function visitIfStatement(node) { + return factory2.updateIfStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)), + visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) + ); + } + function visitSwitchStatement(node) { + return factory2.updateSwitchStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock)) + ); + } + function visitCaseBlock(node) { + return factory2.updateCaseBlock( + node, + visitNodes2(node.clauses, topLevelNestedVisitor, isCaseOrDefaultClause) + ); + } + function visitCaseClause(node) { + return factory2.updateCaseClause( + node, + visitNode(node.expression, visitor, isExpression), + visitNodes2(node.statements, topLevelNestedVisitor, isStatement) + ); + } + function visitDefaultClause(node) { + return visitEachChild(node, topLevelNestedVisitor, context); + } + function visitTryStatement(node) { + return visitEachChild(node, topLevelNestedVisitor, context); + } + function visitCatchClause(node) { + return factory2.updateCatchClause( + node, + node.variableDeclaration, + Debug.checkDefined(visitNode(node.block, topLevelNestedVisitor, isBlock)) + ); + } + function visitBlock(node) { + node = visitEachChild(node, topLevelNestedVisitor, context); + return node; + } function visitExpressionStatement(node) { return factory2.updateExpressionStatement( node, @@ -104698,12 +105053,7 @@ ${lanes.join("\n")} ) ); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfImportDeclaration(statements, node); - } + statements = appendExportsOfImportDeclaration(statements, node); return singleOrMany(statements); } function createRequireCall2(importNode) { @@ -104784,12 +105134,7 @@ ${lanes.join("\n")} ); } } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfImportEqualsDeclaration(statements, node); - } + statements = appendExportsOfImportEqualsDeclaration(statements, node); return singleOrMany(statements); } function visitExportDeclaration(node) { @@ -104898,31 +105243,14 @@ ${lanes.join("\n")} if (node.isExportEquals) { return void 0; } - let statements; - const original = node.original; - if (original && hasAssociatedEndOfDeclarationMarker(original)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportStatement( - deferredExports[id], - factory2.createIdentifier("default"), - visitNode(node.expression, visitor, isExpression), - /*location*/ - node, - /*allowComments*/ - true - ); - } else { - statements = appendExportStatement( - statements, - factory2.createIdentifier("default"), - visitNode(node.expression, visitor, isExpression), - /*location*/ - node, - /*allowComments*/ - true - ); - } - return singleOrMany(statements); + return createExportStatement( + factory2.createIdentifier("default"), + visitNode(node.expression, visitor, isExpression), + /*location*/ + node, + /*allowComments*/ + true + ); } function visitFunctionDeclaration(node) { let statements; @@ -104958,12 +105286,7 @@ ${lanes.join("\n")} } else { statements = append(statements, visitEachChild(node, visitor, context)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfHoistedDeclaration(statements, node); - } + statements = appendExportsOfHoistedDeclaration(statements, node); return singleOrMany(statements); } function visitClassDeclaration(node) { @@ -104995,12 +105318,7 @@ ${lanes.join("\n")} } else { statements = append(statements, visitEachChild(node, visitor, context)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfHoistedDeclaration(statements, node); - } + statements = appendExportsOfHoistedDeclaration(statements, node); return singleOrMany(statements); } function visitVariableStatement(node) { @@ -105072,12 +105390,7 @@ ${lanes.join("\n")} } else { statements = append(statements, visitEachChild(node, visitor, context)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); - } else { - statements = appendExportsOfVariableStatement(statements, node); - } + statements = appendExportsOfVariableStatement(statements, node); return singleOrMany(statements); } function createAllExportExpressions(name, value, location) { @@ -105122,25 +105435,6 @@ ${lanes.join("\n")} ); } } - function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 242 /* VariableStatement */) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); - } - return node; - } - function hasAssociatedEndOfDeclarationMarker(node) { - return (getEmitFlags(node) & 8388608 /* HasEndOfDeclarationMarker */) !== 0; - } - function visitEndOfDeclarationMarker(node) { - const id = getOriginalNodeId(node); - const statements = deferredExports[id]; - if (statements) { - delete deferredExports[id]; - return append(statements, node); - } - return node; - } function appendExportsOfImportDeclaration(statements, decl) { if (currentModuleInfo.exportEquals) { return statements; @@ -105179,25 +105473,33 @@ ${lanes.join("\n")} return appendExportsOfDeclaration(statements, decl); } function appendExportsOfVariableStatement(statements, node) { + return appendExportsOfVariableDeclarationList( + statements, + node.declarationList, + /*isForInOrOfInitializer*/ + false + ); + } + function appendExportsOfVariableDeclarationList(statements, node, isForInOrOfInitializer) { if (currentModuleInfo.exportEquals) { return statements; } - for (const decl of node.declarationList.declarations) { - statements = appendExportsOfBindingElement(statements, decl); + for (const decl of node.declarations) { + statements = appendExportsOfBindingElement(statements, decl, isForInOrOfInitializer); } return statements; } - function appendExportsOfBindingElement(statements, decl) { + function appendExportsOfBindingElement(statements, decl, isForInOrOfInitializer) { if (currentModuleInfo.exportEquals) { return statements; } if (isBindingPattern(decl.name)) { for (const element of decl.name.elements) { if (!isOmittedExpression(element)) { - statements = appendExportsOfBindingElement(statements, element); + statements = appendExportsOfBindingElement(statements, element, isForInOrOfInitializer); } } - } else if (!isGeneratedIdentifier(decl.name)) { + } else if (!isGeneratedIdentifier(decl.name) && (!isVariableDeclaration(decl) || decl.initializer || isForInOrOfInitializer)) { statements = appendExportsOfDeclaration(statements, decl); } return statements; @@ -105468,7 +105770,7 @@ ${lanes.join("\n")} return node; } function substituteBinaryExpression(node) { - if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left) && !isDeclarationNameOfEnumOrNamespace(node.left)) { + if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left)) { const exportedNames = getExports(node.left); if (exportedNames) { let expression = node; @@ -105488,9 +105790,24 @@ ${lanes.join("\n")} } function getExports(name) { if (!isGeneratedIdentifier(name)) { - const valueDeclaration = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); - if (valueDeclaration) { - return currentModuleInfo && currentModuleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]; + const importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + return currentModuleInfo == null ? void 0 : currentModuleInfo.exportedBindings[getOriginalNodeId(importDeclaration)]; + } + const bindingsSet = /* @__PURE__ */ new Set(); + const declarations = resolver.getReferencedValueDeclarations(name); + if (declarations) { + for (const declaration of declarations) { + const bindings = currentModuleInfo == null ? void 0 : currentModuleInfo.exportedBindings[getOriginalNodeId(declaration)]; + if (bindings) { + for (const binding of bindings) { + bindingsSet.add(binding); + } + } + } + if (bindingsSet.size) { + return arrayFrom(bindingsSet); + } } } } @@ -105530,7 +105847,6 @@ ${lanes.join("\n")} context.enableSubstitution(235 /* MetaProperty */); context.enableEmitNotification(311 /* SourceFile */); const moduleInfoMap = []; - const deferredExports = []; const exportFunctionsMap = []; const noSubstitutionMap = []; const contextObjectMap = []; @@ -106003,13 +106319,7 @@ ${lanes.join("\n")} if (node.importClause) { hoistVariableDeclaration(getLocalNameForExternalImport(factory2, node, currentSourceFile)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfImportDeclaration(statements, node); - } - return singleOrMany(statements); + return singleOrMany(appendExportsOfImportDeclaration(statements, node)); } function visitExportDeclaration(node) { Debug.assertIsDefined(node); @@ -106019,37 +106329,19 @@ ${lanes.join("\n")} Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); let statements; hoistVariableDeclaration(getLocalNameForExternalImport(factory2, node, currentSourceFile)); - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfImportEqualsDeclaration(statements, node); - } - return singleOrMany(statements); + return singleOrMany(appendExportsOfImportEqualsDeclaration(statements, node)); } function visitExportAssignment(node) { if (node.isExportEquals) { return void 0; } const expression = visitNode(node.expression, visitor, isExpression); - const original = node.original; - if (original && hasAssociatedEndOfDeclarationMarker(original)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportStatement( - deferredExports[id], - factory2.createIdentifier("default"), - expression, - /*allowComments*/ - true - ); - } else { - return createExportStatement( - factory2.createIdentifier("default"), - expression, - /*allowComments*/ - true - ); - } + return createExportStatement( + factory2.createIdentifier("default"), + expression, + /*allowComments*/ + true + ); } function visitFunctionDeclaration(node) { if (hasSyntacticModifier(node, 1 /* Export */)) { @@ -106077,12 +106369,7 @@ ${lanes.join("\n")} } else { hoistedStatements = append(hoistedStatements, visitEachChild(node, visitor, context)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else { - hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); - } + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); return void 0; } function visitClassDeclaration(node) { @@ -106111,12 +106398,7 @@ ${lanes.join("\n")} node ) ); - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfHoistedDeclaration(statements, node); - } + statements = appendExportsOfHoistedDeclaration(statements, node); return singleOrMany(statements); } function visitVariableStatement(node) { @@ -106125,10 +106407,9 @@ ${lanes.join("\n")} } let expressions; const isExportedDeclaration = hasSyntacticModifier(node, 1 /* Export */); - const isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); for (const variable of node.declarationList.declarations) { if (variable.initializer) { - expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration)); + expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration)); } else { hoistBindingElement(variable); } @@ -106137,17 +106418,12 @@ ${lanes.join("\n")} if (expressions) { statements = append(statements, setTextRange(factory2.createExpressionStatement(factory2.inlineExpressions(expressions)), node)); } - if (isMarkedDeclaration) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); - } else { - statements = appendExportsOfVariableStatement( - statements, - node, - /*exportSelf*/ - false - ); - } + statements = appendExportsOfVariableStatement( + statements, + node, + /*exportSelf*/ + false + ); return singleOrMany(statements); } function hoistBindingElement(node) { @@ -106198,31 +106474,6 @@ ${lanes.join("\n")} hoistVariableDeclaration(factory2.cloneNode(name)); return isExportedDeclaration ? createExportExpression(name, preventSubstitution(setTextRange(factory2.createAssignment(name, value), location))) : preventSubstitution(setTextRange(factory2.createAssignment(name, value), location)); } - function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 242 /* VariableStatement */) { - const id = getOriginalNodeId(node); - const isExportedDeclaration = hasSyntacticModifier(node.original, 1 /* Export */); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); - } - return node; - } - function hasAssociatedEndOfDeclarationMarker(node) { - return (getEmitFlags(node) & 8388608 /* HasEndOfDeclarationMarker */) !== 0; - } - function visitEndOfDeclarationMarker(node) { - const id = getOriginalNodeId(node); - const statements = deferredExports[id]; - if (statements) { - delete deferredExports[id]; - return append(statements, node); - } else { - const original = getOriginalNode(node); - if (isModuleOrEnumDeclaration(original)) { - return append(appendExportsOfDeclaration(statements, original), node); - } - } - return node; - } function appendExportsOfImportDeclaration(statements, decl) { if (moduleInfo.exportEquals) { return statements; @@ -106364,6 +106615,8 @@ ${lanes.join("\n")} return visitLabeledStatement(node); case 253 /* WithStatement */: return visitWithStatement(node); + case 244 /* IfStatement */: + return visitIfStatement(node); case 254 /* SwitchStatement */: return visitSwitchStatement(node); case 268 /* CaseBlock */: @@ -106378,10 +106631,6 @@ ${lanes.join("\n")} return visitCatchClause(node); case 240 /* Block */: return visitBlock(node); - case 361 /* MergeDeclarationMarker */: - return visitMergeDeclarationMarker(node); - case 362 /* EndOfDeclarationMarker */: - return visitEndOfDeclarationMarker(node); default: return visitor(node); } @@ -106473,6 +106722,14 @@ ${lanes.join("\n")} Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) ); } + function visitIfStatement(node) { + return factory2.updateIfStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)), + visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) + ); + } function visitSwitchStatement(node) { return factory2.updateSwitchStatement( node, @@ -106787,7 +107044,7 @@ ${lanes.join("\n")} return node; } function substituteBinaryExpression(node) { - if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left) && !isDeclarationNameOfEnumOrNamespace(node.left)) { + if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left)) { const exportedNames = getExports(node.left); if (exportedNames) { let expression = node; @@ -106807,22 +107064,38 @@ ${lanes.join("\n")} } function getExports(name) { let exportedNames; - if (!isGeneratedIdentifier(name)) { - const valueDeclaration = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); - if (valueDeclaration) { - const exportContainer = resolver.getReferencedExportContainer( - name, - /*prefixLocals*/ - false - ); - if (exportContainer && exportContainer.kind === 311 /* SourceFile */) { - exportedNames = append(exportedNames, factory2.getDeclarationName(valueDeclaration)); - } - exportedNames = addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]); + const valueDeclaration = getReferencedDeclaration(name); + if (valueDeclaration) { + const exportContainer = resolver.getReferencedExportContainer( + name, + /*prefixLocals*/ + false + ); + if (exportContainer && exportContainer.kind === 311 /* SourceFile */) { + exportedNames = append(exportedNames, factory2.getDeclarationName(valueDeclaration)); } + exportedNames = addRange(exportedNames, moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]); } return exportedNames; } + function getReferencedDeclaration(name) { + if (!isGeneratedIdentifier(name)) { + const importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) + return importDeclaration; + const valueDeclaration = resolver.getReferencedValueDeclaration(name); + if (valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)])) + return valueDeclaration; + const declarations = resolver.getReferencedValueDeclarations(name); + if (declarations) { + for (const declaration of declarations) { + if (declaration !== valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(declaration)])) + return declaration; + } + } + return valueDeclaration; + } + } function preventSubstitution(node) { if (noSubstitution === void 0) noSubstitution = []; @@ -109266,7 +109539,7 @@ ${lanes.join("\n")} } function transformNodes(resolver, host, factory2, options, nodes, transformers, allowDtsFiles) { var _a, _b; - const enabledSyntaxKindFeatures = new Array(364 /* Count */); + const enabledSyntaxKindFeatures = new Array(362 /* Count */); let lexicalEnvironmentVariableDeclarations; let lexicalEnvironmentFunctionDeclarations; let lexicalEnvironmentStatements; @@ -111029,6 +111302,8 @@ ${lanes.join("\n")} return emitJsxSpreadAttribute(node); case 293 /* JsxExpression */: return emitJsxExpression(node); + case 294 /* JsxNamespacedName */: + return emitJsxNamespacedName(node); case 295 /* CaseClause */: return emitCaseClause(node); case 296 /* DefaultClause */: @@ -111124,8 +111399,6 @@ ${lanes.join("\n")} case 353 /* JSDocSeeTag */: return emitJSDocSeeTag(node); case 358 /* NotEmittedStatement */: - case 362 /* EndOfDeclarationMarker */: - case 361 /* MergeDeclarationMarker */: return; } if (isExpression(node)) { @@ -111226,8 +111499,6 @@ ${lanes.join("\n")} return emitJsxSelfClosingElement(node); case 287 /* JsxFragment */: return emitJsxFragment(node); - case 294 /* JsxNamespacedName */: - return emitJsxNamespacedName(node); case 357 /* SyntaxList */: return Debug.fail("SyntaxList should not be printed"); case 358 /* NotEmittedStatement */: @@ -111236,10 +111507,7 @@ ${lanes.join("\n")} return emitPartiallyEmittedExpression(node); case 360 /* CommaListExpression */: return emitCommaList(node); - case 361 /* MergeDeclarationMarker */: - case 362 /* EndOfDeclarationMarker */: - return; - case 363 /* SyntheticReferenceExpression */: + case 361 /* SyntheticReferenceExpression */: return Debug.fail("SyntheticReferenceExpression should not be printed"); } } @@ -113561,7 +113829,7 @@ ${lanes.join("\n")} } } function emitEmbeddedStatement(parent2, node) { - if (isBlock(node) || getEmitFlags(parent2) & 1 /* SingleLine */) { + if (isBlock(node) || getEmitFlags(parent2) & 1 /* SingleLine */ || preserveSourceNewlines && !getLeadingLineTerminatorCount(parent2, node, 0 /* None */)) { writeSpace(); emit(node); } else { @@ -114062,6 +114330,10 @@ ${lanes.join("\n")} if (!canUseSourceFile || getSourceFileOfNode(node) !== getOriginalNode(sourceFile)) { return idText(node); } + } else if (isJsxNamespacedName(node)) { + if (!canUseSourceFile || getSourceFileOfNode(node) !== getOriginalNode(sourceFile)) { + return getTextOfJsxNamespacedName(node); + } } else { Debug.assertNode(node, isLiteralExpression); if (!canUseSourceFile) { @@ -114073,9 +114345,9 @@ ${lanes.join("\n")} function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) { if (node.kind === 11 /* StringLiteral */ && node.textSourceNode) { const textSourceNode = node.textSourceNode; - if (isIdentifier(textSourceNode) || isPrivateIdentifier(textSourceNode) || isNumericLiteral(textSourceNode)) { + if (isIdentifier(textSourceNode) || isPrivateIdentifier(textSourceNode) || isNumericLiteral(textSourceNode) || isJsxNamespacedName(textSourceNode)) { const text = isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode2(textSourceNode); - return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` : neverAsciiEscape || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? `"${escapeString(text)}"` : `"${escapeNonAsciiString(text)}"`; + return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` : neverAsciiEscape || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? `"${escapeString(text)}"` : `"${escapeNonAsciiString(text)}"`; } else { return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape); } @@ -115057,6 +115329,7 @@ ${lanes.join("\n")} // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant getConstantValue: notImplemented, getReferencedValueDeclaration: notImplemented, + getReferencedValueDeclarations: notImplemented, getTypeReferenceSerializationKind: notImplemented, isOptionalParameter: notImplemented, moduleExportsSomeValue: notImplemented, @@ -115456,7 +115729,7 @@ ${lanes.join("\n")} } return program.isEmittedFile(file); } - function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo3) { + function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo2) { setSysLog(watchLogLevel === 2 /* Verbose */ ? log : noop); const plainInvokeFactory = { watchFile: (file, callback, pollingInterval, options) => host.watchFile(file, callback, pollingInterval, options), @@ -115494,23 +115767,23 @@ ${lanes.join("\n")} return typeof host.useCaseSensitiveFileNames === "boolean" ? host.useCaseSensitiveFileNames : host.useCaseSensitiveFileNames(); } function createExcludeWatcherWithLogging(file, flags, options, detailInfo1, detailInfo2) { - log(`ExcludeWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3)}`); + log(`ExcludeWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`); return { - close: () => log(`ExcludeWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3)}`) + close: () => log(`ExcludeWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`) }; } function createFileWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) { - log(`FileWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3)}`); + log(`FileWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`); const watcher = triggerInvokingFactory.watchFile(file, cb, flags, options, detailInfo1, detailInfo2); return { close: () => { - log(`FileWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3)}`); + log(`FileWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`); watcher.close(); } }; } function createDirectoryWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) { - const watchInfo = `DirectoryWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3)}`; + const watchInfo = `DirectoryWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`; log(watchInfo); const start = timestamp(); const watcher = triggerInvokingFactory.watchDirectory(file, cb, flags, options, detailInfo1, detailInfo2); @@ -115518,7 +115791,7 @@ ${lanes.join("\n")} log(`Elapsed:: ${elapsed}ms ${watchInfo}`); return { close: () => { - const watchInfo2 = `DirectoryWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3)}`; + const watchInfo2 = `DirectoryWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`; log(watchInfo2); const start2 = timestamp(); watcher.close(); @@ -115533,7 +115806,7 @@ ${lanes.join("\n")} void 0, file, (...args) => { - const triggerredInfo = `${key === "watchFile" ? "FileWatcher" : "DirectoryWatcher"}:: Triggered with ${args[0]} ${args[1] !== void 0 ? args[1] : ""}:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3)}`; + const triggerredInfo = `${key === "watchFile" ? "FileWatcher" : "DirectoryWatcher"}:: Triggered with ${args[0]} ${args[1] !== void 0 ? args[1] : ""}:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`; log(triggerredInfo); const start = timestamp(); cb.call( @@ -115550,8 +115823,8 @@ ${lanes.join("\n")} detailInfo2 ); } - function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo4) { - return `WatchInfo: ${file} ${flags} ${JSON.stringify(options)} ${getDetailWatchInfo4 ? getDetailWatchInfo4(detailInfo1, detailInfo2) : detailInfo2 === void 0 ? detailInfo1 : `${detailInfo1} ${detailInfo2}`}`; + function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3) { + return `WatchInfo: ${file} ${flags} ${JSON.stringify(options)} ${getDetailWatchInfo3 ? getDetailWatchInfo3(detailInfo1, detailInfo2) : detailInfo2 === void 0 ? detailInfo1 : `${detailInfo1} ${detailInfo2}`}`; } } function getFallbackOptions(options) { @@ -116109,6 +116382,25 @@ ${lanes.join("\n")} }); } } + function getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName) { + const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : currentDirectory; + return combinePaths(containingDirectory, `__lib_node_modules_lookup_${libFileName}__.ts`); + } + function getLibraryNameFromLibFileName(libFileName) { + const components = libFileName.split("."); + let path = components[1]; + let i = 2; + while (components[i] && components[i] !== "d") { + path += (i === 2 ? "/" : "-") + components[i]; + i++; + } + return "@typescript/lib-" + path; + } + function getLibFileNameFromLibReference(libReference) { + const libName = toFileNameLowerCase(libReference.fileName); + const libFileName = libMap.get(libName); + return { libName, libFileName }; + } function isReferencedFile(reason) { switch (reason == null ? void 0 : reason.kind) { case 3 /* Import */: @@ -116152,7 +116444,7 @@ ${lanes.join("\n")} } return { file, pos, end, packageId }; } - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) { if (!program || (hasChangedAutomaticTypeDirectiveNames == null ? void 0 : hasChangedAutomaticTypeDirectiveNames())) return false; if (!arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) @@ -116167,6 +116459,8 @@ ${lanes.join("\n")} const currentOptions = program.getCompilerOptions(); if (!compareDataObjects(currentOptions, newOptions)) return false; + if (program.resolvedLibReferences && forEachEntry(program.resolvedLibReferences, (_value, libFileName) => hasInvalidatedLibResolutions(libFileName))) + return false; if (currentOptions.configFile && newOptions.configFile) return currentOptions.configFile.text === newOptions.configFile.text; return true; @@ -116259,6 +116553,9 @@ ${lanes.join("\n")} let fileProcessingDiagnostics; let automaticTypeDirectiveNames; let automaticTypeDirectiveResolutions; + let resolvedLibReferences; + let resolvedLibProcessing; + let packageMap; const maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; let currentNodeModulesDepth = 0; const modulesWithElidedImports = /* @__PURE__ */ new Map(); @@ -116346,6 +116643,14 @@ ${lanes.join("\n")} createTypeReferenceResolutionLoader ); } + const hasInvalidatedLibResolutions = host.hasInvalidatedLibResolutions || returnFalse; + let actualResolveLibrary; + if (host.resolveLibrary) { + actualResolveLibrary = host.resolveLibrary.bind(host); + } else { + const libraryResolutionCache = createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + actualResolveLibrary = (libraryName, resolveFrom, options2) => resolveLibrary(libraryName, resolveFrom, options2, host, libraryResolutionCache); + } const packageIdToSourceFile = /* @__PURE__ */ new Map(); let sourceFileToPackageName = /* @__PURE__ */ new Map(); let redirectTargetsMap = createMultiMap(); @@ -116422,7 +116727,7 @@ ${lanes.join("\n")} automaticTypeDirectiveResolutions = createModeAwareCache(); if (automaticTypeDirectiveNames.length) { (_k = tracing) == null ? void 0 : _k.push(tracing.Phase.Program, "processTypeReferences", { count: automaticTypeDirectiveNames.length }); - const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : currentDirectory; const containingFilename = combinePaths(containingDirectory, inferredTypesContainingFile); const resolutions = resolveTypeReferenceDirectiveNamesReusingOldState(automaticTypeDirectiveNames, containingFilename); for (let i = 0; i < automaticTypeDirectiveNames.length; i++) { @@ -116512,6 +116817,7 @@ ${lanes.join("\n")} ); } oldProgram = void 0; + resolvedLibProcessing = void 0; const program = { getRootFileNames: () => rootNames, getSourceFile, @@ -116553,6 +116859,10 @@ ${lanes.join("\n")} sourceFileToPackageName, redirectTargetsMap, usesUriStyleNodeCoreModules, + resolvedLibReferences, + getCurrentPackagesMap: () => packageMap, + typesPackageExists, + packageBundlesTypes, isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics2, getProjectReferences, @@ -116593,6 +116903,26 @@ ${lanes.join("\n")} measure("Program", "beforeProgram", "afterProgram"); (_p = tracing) == null ? void 0 : _p.pop(); return program; + function getPackagesMap() { + if (packageMap) + return packageMap; + packageMap = /* @__PURE__ */ new Map(); + files.forEach((sf) => { + if (!sf.resolvedModules) + return; + sf.resolvedModules.forEach(({ resolvedModule }) => { + if (resolvedModule == null ? void 0 : resolvedModule.packageId) + packageMap.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!packageMap.get(resolvedModule.packageId.name)); + }); + }); + return packageMap; + } + function typesPackageExists(packageName) { + return getPackagesMap().has(getTypesPackageName(packageName)); + } + function packageBundlesTypes(packageName) { + return !!getPackagesMap().get(packageName); + } function addResolutionDiagnostics(resolution) { var _a2; if (!((_a2 = resolution.resolutionDiagnostics) == null ? void 0 : _a2.length)) @@ -117041,6 +117371,9 @@ ${lanes.join("\n")} if (changesAffectingProgramStructure(oldOptions, options)) { return 1 /* SafeModules */; } + if (oldProgram.resolvedLibReferences && forEachEntry(oldProgram.resolvedLibReferences, (resolution, libFileName) => pathForLibFileWorker(libFileName).actual !== resolution.actual)) { + return 1 /* SafeModules */; + } if (host.hasChangedAutomaticTypeDirectiveNames) { if (host.hasChangedAutomaticTypeDirectiveNames()) return 1 /* SafeModules */; @@ -117077,6 +117410,8 @@ ${lanes.join("\n")} sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; usesUriStyleNodeCoreModules = oldProgram.usesUriStyleNodeCoreModules; + resolvedLibReferences = oldProgram.resolvedLibReferences; + packageMap = oldProgram.getCurrentPackagesMap(); return 2 /* Completely */; } function getEmitHost(writeFileCallback) { @@ -117186,7 +117521,7 @@ ${lanes.join("\n")} if (!options.lib) { return equalityComparer(file.fileName, getDefaultLibraryFileName()); } else { - return some(options.lib, (libFileName) => equalityComparer(file.fileName, pathForLibFile(libFileName))); + return some(options.lib, (libFileName) => equalityComparer(file.fileName, resolvedLibReferences.get(libFileName).actual)); } } function getTypeChecker() { @@ -117777,11 +118112,10 @@ ${lanes.join("\n")} } } function getLibFileFromReference(ref) { - const libName = toFileNameLowerCase(ref.fileName); - const libFileName = libMap.get(libName); - if (libFileName) { - return getSourceFile(pathForLibFile(libFileName)); - } + var _a2; + const { libFileName } = getLibFileNameFromLibReference(ref); + const actualFileName = libFileName && ((_a2 = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName)) == null ? void 0 : _a2.actual); + return actualFileName !== void 0 ? getSourceFile(actualFileName) : void 0; } function getSourceFileFromReference(referencingFile, ref) { return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), getSourceFile); @@ -118206,24 +118540,55 @@ ${lanes.join("\n")} } } function pathForLibFile(libFileName) { - const components = libFileName.split("."); - let path = components[1]; - let i = 2; - while (components[i] && components[i] !== "d") { - path += (i === 2 ? "/" : "-") + components[i]; - i++; + const existing = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName); + if (existing) + return existing.actual; + const result = pathForLibFileWorker(libFileName); + (resolvedLibReferences ?? (resolvedLibReferences = /* @__PURE__ */ new Map())).set(libFileName, result); + return result.actual; + } + function pathForLibFileWorker(libFileName) { + var _a2, _b2, _c2, _d2, _e2; + const existing = resolvedLibProcessing == null ? void 0 : resolvedLibProcessing.get(libFileName); + if (existing) + return existing; + if (structureIsReused !== 0 /* Not */ && oldProgram && !hasInvalidatedLibResolutions(libFileName)) { + const oldResolution = (_a2 = oldProgram.resolvedLibReferences) == null ? void 0 : _a2.get(libFileName); + if (oldResolution) { + if (oldResolution.resolution && isTraceEnabled(options, host)) { + const libraryName2 = getLibraryNameFromLibFileName(libFileName); + const resolveFrom2 = getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName); + trace( + host, + oldResolution.resolution.resolvedModule ? 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, + libraryName2, + getNormalizedAbsolutePath(resolveFrom2, currentDirectory), + (_b2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _b2.resolvedFileName, + ((_c2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _c2.packageId) && packageIdToString(oldResolution.resolution.resolvedModule.packageId) + ); + } + (resolvedLibProcessing ?? (resolvedLibProcessing = /* @__PURE__ */ new Map())).set(libFileName, oldResolution); + return oldResolution; + } } - const resolveFrom = combinePaths(currentDirectory, `__lib_node_modules_lookup_${libFileName}__.ts`); - const localOverrideModuleResult = resolveModuleName("@typescript/lib-" + path, resolveFrom, { moduleResolution: 2 /* Node10 */ }, host, moduleResolutionCache); - if (localOverrideModuleResult == null ? void 0 : localOverrideModuleResult.resolvedModule) { - return localOverrideModuleResult.resolvedModule.resolvedFileName; - } - return combinePaths(defaultLibraryPath, libFileName); + const libraryName = getLibraryNameFromLibFileName(libFileName); + const resolveFrom = getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName); + (_d2 = tracing) == null ? void 0 : _d2.push(tracing.Phase.Program, "resolveLibrary", { resolveFrom }); + mark("beforeResolveLibrary"); + const resolution = actualResolveLibrary(libraryName, resolveFrom, options, libFileName); + mark("afterResolveLibrary"); + measure("ResolveLibrary", "beforeResolveLibrary", "afterResolveLibrary"); + (_e2 = tracing) == null ? void 0 : _e2.pop(); + const result = { + resolution, + actual: resolution.resolvedModule ? resolution.resolvedModule.resolvedFileName : combinePaths(defaultLibraryPath, libFileName) + }; + (resolvedLibProcessing ?? (resolvedLibProcessing = /* @__PURE__ */ new Map())).set(libFileName, result); + return result; } function processLibReferenceDirectives(file) { forEach(file.libReferenceDirectives, (libReference, index) => { - const libName = toFileNameLowerCase(libReference.fileName); - const libFileName = libMap.get(libName); + const { libName, libFileName } = getLibFileNameFromLibReference(libReference); if (libFileName) { processRootFile( pathForLibFile(libFileName), @@ -118349,7 +118714,7 @@ ${lanes.join("\n")} void 0 ); } else { - const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), host.getCurrentDirectory()); + const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), currentDirectory); sourceFile = host.getSourceFile(refPath, 100 /* JSON */); addFileToFilesByName( sourceFile, @@ -120052,7 +120417,10 @@ ${lanes.join("\n")} return; const diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { - state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics); + state.semanticDiagnosticsPerFile.set( + sourceFilePath, + oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : repopulateDiagnostics(diagnostics, newProgram) + ); if (!state.semanticDiagnosticsFromOldState) { state.semanticDiagnosticsFromOldState = /* @__PURE__ */ new Set(); } @@ -120123,6 +120491,33 @@ ${lanes.join("\n")} isString(oldEmitSignature) ? [oldEmitSignature] : oldEmitSignature[0] ); } + function repopulateDiagnostics(diagnostics, newProgram) { + if (!diagnostics.length) + return diagnostics; + return sameMap(diagnostics, (diag2) => { + if (isString(diag2.messageText)) + return diag2; + const repopulatedChain = convertOrRepopulateDiagnosticMessageChain(diag2.messageText, diag2.file, newProgram, (chain) => { + var _a; + return (_a = chain.repopulateInfo) == null ? void 0 : _a.call(chain); + }); + return repopulatedChain === diag2.messageText ? diag2 : { ...diag2, messageText: repopulatedChain }; + }); + } + function convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo) { + const info = repopulateInfo(chain); + if (info) { + return { + ...createModuleNotFoundChain(sourceFile, newProgram, info.moduleReference, info.mode, info.packageName || info.moduleReference), + next: convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo) + }; + } + const next = convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo); + return next === chain.next ? chain : { ...chain, next }; + } + function convertOrRepopulateDiagnosticMessageChainArray(array, sourceFile, newProgram, repopulateInfo) { + return sameMap(array, (chain) => convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo)); + } function convertToDiagnostics(diagnostics, newProgram) { if (!diagnostics.length) return emptyArray; @@ -120144,9 +120539,11 @@ ${lanes.join("\n")} } function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath3) { const { file } = diagnostic; + const sourceFile = file ? newProgram.getSourceFileByPath(toPath3(file)) : void 0; return { ...diagnostic, - file: file ? newProgram.getSourceFileByPath(toPath3(file)) : void 0 + file: sourceFile, + messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertOrRepopulateDiagnosticMessageChain(diagnostic.messageText, sourceFile, newProgram, (chain) => chain.info) }; } function releaseCache(state) { @@ -120688,9 +121085,35 @@ ${lanes.join("\n")} const { file } = diagnostic; return { ...diagnostic, - file: file ? relativeToBuildInfo(file.resolvedPath) : void 0 + file: file ? relativeToBuildInfo(file.resolvedPath) : void 0, + messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertToReusableDiagnosticMessageChain(diagnostic.messageText) }; } + function convertToReusableDiagnosticMessageChain(chain) { + if (chain.repopulateInfo) { + return { + info: chain.repopulateInfo(), + next: convertToReusableDiagnosticMessageChainArray(chain.next) + }; + } + const next = convertToReusableDiagnosticMessageChainArray(chain.next); + return next === chain.next ? chain : { ...chain, next }; + } + function convertToReusableDiagnosticMessageChainArray(array) { + if (!array) + return array; + return forEach(array, (chain, index) => { + const reusable = convertToReusableDiagnosticMessageChain(chain); + if (chain === reusable) + return void 0; + const result = index > 0 ? array.slice(0, index - 1) : []; + result.push(reusable); + for (let i = index + 1; i < array.length; i++) { + result.push(convertToReusableDiagnosticMessageChain(array[i])); + } + return result; + }) || array; + } function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { let host; let newProgram; @@ -121380,6 +121803,7 @@ ${lanes.join("\n")} let failedLookupChecks; let startsWithPathChecks; let isInDirectoryChecks; + let allModuleAndTypeResolutionsAreInvalidated = false; const getCurrentDirectory = memoize(() => resolutionHost.getCurrentDirectory()); const cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); const resolvedModuleNames = /* @__PURE__ */ new Map(); @@ -121395,6 +121819,13 @@ ${lanes.join("\n")} resolutionHost.getCompilationSettings(), moduleResolutionCache.getPackageJsonInfoCache() ); + const resolvedLibraries = /* @__PURE__ */ new Map(); + const libraryResolutionCache = createModuleResolutionCache( + getCurrentDirectory(), + resolutionHost.getCanonicalFileName, + getOptionsForLibraryResolution(resolutionHost.getCompilationSettings()), + moduleResolutionCache.getPackageJsonInfoCache() + ); const directoryWatchesOfFailedLookups = /* @__PURE__ */ new Map(); const fileWatchesOfAffectingLocations = /* @__PURE__ */ new Map(); const rootDir = getRootDirectoryOfResolutionCache(rootDirForResolution, getCurrentDirectory); @@ -121411,6 +121842,7 @@ ${lanes.join("\n")} finishCachingPerDirectoryResolution, resolveModuleNameLiterals, resolveTypeReferenceDirectiveReferences, + resolveLibrary: resolveLibrary2, resolveSingleModuleNameWithoutWatching, removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile, @@ -121422,7 +121854,8 @@ ${lanes.join("\n")} isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch, closeTypeRootsWatch, - clear: clear2 + clear: clear2, + onChangesAffectModuleResolution }; function getResolvedModule2(resolution) { return resolution.resolvedModule; @@ -121445,13 +121878,23 @@ ${lanes.join("\n")} isInDirectoryChecks = void 0; affectingPathChecks = void 0; affectingPathChecksForFile = void 0; + allModuleAndTypeResolutionsAreInvalidated = false; moduleResolutionCache.clear(); typeReferenceDirectiveResolutionCache.clear(); moduleResolutionCache.update(resolutionHost.getCompilationSettings()); typeReferenceDirectiveResolutionCache.update(resolutionHost.getCompilationSettings()); + libraryResolutionCache.clear(); impliedFormatPackageJsons.clear(); + resolvedLibraries.clear(); hasChangedAutomaticTypeDirectiveNames = false; } + function onChangesAffectModuleResolution() { + allModuleAndTypeResolutionsAreInvalidated = true; + moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); + typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + moduleResolutionCache.update(resolutionHost.getCompilationSettings()); + typeReferenceDirectiveResolutionCache.update(resolutionHost.getCompilationSettings()); + } function startRecordingFilesWithChangedResolutions() { filesWithChangedSetOfUnresolvedImports = []; } @@ -121467,23 +121910,45 @@ ${lanes.join("\n")} const value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); return !!value && !!value.length; } - function createHasInvalidatedResolutions(customHasInvalidatedResolutions) { + function createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidatedLibResolutions) { invalidateResolutionsOfFailedLookupLocations(); const collected = filesWithInvalidatedResolutions; filesWithInvalidatedResolutions = void 0; - return (path) => customHasInvalidatedResolutions(path) || !!(collected == null ? void 0 : collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); + return { + hasInvalidatedResolutions: (path) => customHasInvalidatedResolutions(path) || allModuleAndTypeResolutionsAreInvalidated || !!(collected == null ? void 0 : collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path), + hasInvalidatedLibResolutions: (libFileName) => { + var _a; + return customHasInvalidatedLibResolutions(libFileName) || !!((_a = resolvedLibraries == null ? void 0 : resolvedLibraries.get(libFileName)) == null ? void 0 : _a.isInvalidated); + } + }; } function startCachingPerDirectoryResolution() { moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + libraryResolutionCache.clearAllExceptPackageJsonInfoCache(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } + function cleanupLibResolutionWatching(newProgram) { + resolvedLibraries.forEach((resolution, libFileName) => { + var _a; + if (!((_a = newProgram == null ? void 0 : newProgram.resolvedLibReferences) == null ? void 0 : _a.has(libFileName))) { + stopWatchFailedLookupLocationOfResolution( + resolution, + resolutionHost.toPath(getInferredLibraryNameResolveFrom(newProgram.getCompilerOptions(), getCurrentDirectory(), libFileName)), + getResolvedModule2 + ); + resolvedLibraries.delete(libFileName); + } + }); + } function finishCachingPerDirectoryResolution(newProgram, oldProgram) { filesWithInvalidatedNonRelativeUnresolvedImports = void 0; + allModuleAndTypeResolutionsAreInvalidated = false; nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); if (newProgram !== oldProgram) { + cleanupLibResolutionWatching(newProgram); newProgram == null ? void 0 : newProgram.getSourceFiles().forEach((newFile) => { var _a; const expected = isExternalOrCommonJsModule(newFile) ? ((_a = newFile.packageJsonLocations) == null ? void 0 : _a.length) ?? 0 : 0; @@ -121575,6 +122040,7 @@ ${lanes.join("\n")} reusedNames, loader, getResolutionWithResolvedFileName, + deferWatchingNonRelativeResolution, shouldRetryResolution, logChanges }) { @@ -121591,15 +122057,15 @@ ${lanes.join("\n")} const name = loader.nameAndMode.getName(entry); const mode = loader.nameAndMode.getMode(entry, containingSourceFile); let resolution = resolutionsInFile.get(name, mode); - if (!seenNamesInFile.has(name, mode) && unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate - hasInvalidatedNonRelativeUnresolvedImport && !isExternalModuleNameRelative(name) && shouldRetryResolution(resolution)) { + 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))) { const existingResolution = resolution; resolution = loader.resolve(name, mode); if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) { resolutionHost.onDiscoveredSymlink(); } resolutionsInFile.set(name, mode, resolution); - watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution); if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName); } @@ -121675,7 +122141,8 @@ ${lanes.join("\n")} typeReferenceDirectiveResolutionCache ), getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective2, - shouldRetryResolution: (resolution) => resolution.resolvedTypeReferenceDirective === void 0 + shouldRetryResolution: (resolution) => resolution.resolvedTypeReferenceDirective === void 0, + deferWatchingNonRelativeResolution: false }); } function resolveModuleNameLiterals(moduleLiterals, containingFile, redirectedReference, options, containingSourceFile, reusedNames) { @@ -121694,9 +122161,46 @@ ${lanes.join("\n")} ), getResolutionWithResolvedFileName: getResolvedModule2, shouldRetryResolution: (resolution) => !resolution.resolvedModule || !resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension), - logChanges: logChangesWhenResolvingModule + logChanges: logChangesWhenResolvingModule, + deferWatchingNonRelativeResolution: true + // Defer non relative resolution watch because we could be using ambient modules }); } + function resolveLibrary2(libraryName, resolveFrom, options, libFileName) { + var _a; + const host = ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost; + let resolution = resolvedLibraries == null ? void 0 : resolvedLibraries.get(libFileName); + if (!resolution || resolution.isInvalidated) { + const existingResolution = resolution; + resolution = resolveLibrary(libraryName, resolveFrom, options, host, libraryResolutionCache); + const path = resolutionHost.toPath(resolveFrom); + watchFailedLookupLocationsOfExternalModuleResolutions( + libraryName, + resolution, + path, + getResolvedModule2, + /*deferWatchingNonRelativeResolution*/ + false + ); + resolvedLibraries.set(libFileName, resolution); + if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolvedModule2); + } + } else { + if (isTraceEnabled(options, host)) { + const resolved = getResolvedModule2(resolution); + trace( + host, + (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.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, + resolveFrom, + resolved == null ? void 0 : resolved.resolvedFileName, + (resolved == null ? void 0 : resolved.packageId) && packageIdToString(resolved.packageId) + ); + } + } + return resolution; + } function resolveSingleModuleNameWithoutWatching(moduleName, containingFile) { const path = resolutionHost.toPath(containingFile); const resolutionsInFile = resolvedModuleNames.get(path); @@ -121712,7 +122216,7 @@ ${lanes.join("\n")} function isNodeModulesAtTypesDirectory(dirPath) { return endsWith(dirPath, "/node_modules/@types"); } - function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) { + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution) { var _a; if (resolution.refCount) { resolution.refCount++; @@ -121720,7 +122224,7 @@ ${lanes.join("\n")} } else { resolution.refCount = 1; Debug.assert(!((_a = resolution.files) == null ? void 0 : _a.size)); - if (isExternalModuleNameRelative(name)) { + if (!deferWatchingNonRelativeResolution || isExternalModuleNameRelative(name)) { watchFailedLookupLocationOfResolution(resolution); } else { nonRelativeExternalModuleResolutions.add(name, resolution); @@ -121736,45 +122240,51 @@ ${lanes.join("\n")} } (resolution.files ?? (resolution.files = /* @__PURE__ */ new Set())).add(filePath); } + function watchFailedLookupLocation(failedLookupLocation, setAtRoot) { + const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + const toWatch = getDirectoryToWatchFailedLookupLocation( + failedLookupLocation, + failedLookupLocationPath, + rootDir, + rootPath, + rootPathComponents, + getCurrentDirectory + ); + if (toWatch) { + const { dir, dirPath, nonRecursive } = toWatch; + if (dirPath === rootPath) { + Debug.assert(nonRecursive); + setAtRoot = true; + } else { + setDirectoryWatcher(dir, dirPath, nonRecursive); + } + } + return setAtRoot; + } function watchFailedLookupLocationOfResolution(resolution) { Debug.assert(!!resolution.refCount); - const { failedLookupLocations, affectingLocations } = resolution; - if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length)) + const { failedLookupLocations, affectingLocations, node10Result } = resolution; + if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length) && !node10Result) return; - if (failedLookupLocations == null ? void 0 : failedLookupLocations.length) + if ((failedLookupLocations == null ? void 0 : failedLookupLocations.length) || node10Result) resolutionsWithFailedLookups.add(resolution); let setAtRoot = false; if (failedLookupLocations) { for (const failedLookupLocation of failedLookupLocations) { - const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - const toWatch = getDirectoryToWatchFailedLookupLocation( - failedLookupLocation, - failedLookupLocationPath, - rootDir, - rootPath, - rootPathComponents, - getCurrentDirectory - ); - if (toWatch) { - const { dir, dirPath, nonRecursive } = toWatch; - if (dirPath === rootPath) { - Debug.assert(nonRecursive); - setAtRoot = true; - } else { - setDirectoryWatcher(dir, dirPath, nonRecursive); - } - } - } - if (setAtRoot) { - setDirectoryWatcher( - rootDir, - rootPath, - /*nonRecursive*/ - true - ); + setAtRoot = watchFailedLookupLocation(failedLookupLocation, setAtRoot); } } - watchAffectingLocationsOfResolution(resolution, !(failedLookupLocations == null ? void 0 : failedLookupLocations.length)); + if (node10Result) + setAtRoot = watchFailedLookupLocation(node10Result, setAtRoot); + if (setAtRoot) { + setDirectoryWatcher( + rootDir, + rootPath, + /*nonRecursive*/ + true + ); + } + watchAffectingLocationsOfResolution(resolution, !(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !node10Result); } function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) { Debug.assert(!!resolution.refCount); @@ -121868,6 +122378,26 @@ ${lanes.join("\n")} directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive }); } } + function stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot) { + const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + const toWatch = getDirectoryToWatchFailedLookupLocation( + failedLookupLocation, + failedLookupLocationPath, + rootDir, + rootPath, + rootPathComponents, + getCurrentDirectory + ); + if (toWatch) { + const { dirPath } = toWatch; + if (dirPath === rootPath) { + removeAtRoot = true; + } else { + removeDirectoryWatcher(dirPath); + } + } + return removeAtRoot; + } function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) { Debug.checkDefined(resolution.files).delete(filePath); resolution.refCount--; @@ -121881,31 +122411,18 @@ ${lanes.join("\n")} if ((resolutions == null ? void 0 : resolutions.delete(resolution)) && !resolutions.size) resolvedFileToResolution.delete(key); } - const { failedLookupLocations, affectingLocations } = resolution; + const { failedLookupLocations, affectingLocations, node10Result } = resolution; if (resolutionsWithFailedLookups.delete(resolution)) { let removeAtRoot = false; - for (const failedLookupLocation of failedLookupLocations) { - const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - const toWatch = getDirectoryToWatchFailedLookupLocation( - failedLookupLocation, - failedLookupLocationPath, - rootDir, - rootPath, - rootPathComponents, - getCurrentDirectory - ); - if (toWatch) { - const { dirPath } = toWatch; - if (dirPath === rootPath) { - removeAtRoot = true; - } else { - removeDirectoryWatcher(dirPath); - } + if (failedLookupLocations) { + for (const failedLookupLocation of failedLookupLocations) { + removeAtRoot = stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot); } } - if (removeAtRoot) { + if (node10Result) + removeAtRoot = stopWatchFailedLookupLocation(node10Result, removeAtRoot); + if (removeAtRoot) removeDirectoryWatcher(rootPath); - } } else if (affectingLocations == null ? void 0 : affectingLocations.length) { resolutionsWithOnlyAffectingLocations.delete(resolution); } @@ -122000,15 +122517,37 @@ ${lanes.join("\n")} return false; } (failedLookupChecks || (failedLookupChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); - const packagePath = parseNodeModuleFromPath(fileOrDirectoryPath); + const packagePath = parseNodeModuleFromPath( + fileOrDirectoryPath, + /*isFolder*/ + true + ); if (packagePath) (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } + function invalidatePackageJsonMap() { + const packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) { + packageJsonMap.forEach((_value, path) => isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : void 0); + } + } function invalidateResolutionsOfFailedLookupLocations() { var _a; + if (allModuleAndTypeResolutionsAreInvalidated) { + affectingPathChecksForFile = void 0; + invalidatePackageJsonMap(); + if (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks || affectingPathChecks) { + invalidateResolutions(resolvedLibraries, canInvalidateFailedLookupResolution); + } + failedLookupChecks = void 0; + startsWithPathChecks = void 0; + isInDirectoryChecks = void 0; + affectingPathChecks = void 0; + return true; + } let invalidated = false; if (affectingPathChecksForFile) { (_a = resolutionHost.getCurrentProgram()) == null ? void 0 : _a.getSourceFiles().forEach((f) => { @@ -122023,10 +122562,7 @@ ${lanes.join("\n")} return invalidated; } invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution) || invalidated; - const packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); - if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) { - packageJsonMap.forEach((_value, path) => isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : void 0); - } + invalidatePackageJsonMap(); failedLookupChecks = void 0; startsWithPathChecks = void 0; isInDirectoryChecks = void 0; @@ -122040,7 +122576,7 @@ ${lanes.join("\n")} return true; if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) return false; - return (_a = resolution.failedLookupLocations) == null ? void 0 : _a.some((location) => isInvalidatedFailedLookup(resolutionHost.toPath(location))); + return ((_a = resolution.failedLookupLocations) == null ? void 0 : _a.some((location) => isInvalidatedFailedLookup(resolutionHost.toPath(location)))) || !!resolution.node10Result && isInvalidatedFailedLookup(resolutionHost.toPath(resolution.node10Result)); } function isInvalidatedFailedLookup(locationPath) { return (failedLookupChecks == null ? void 0 : failedLookupChecks.has(locationPath)) || firstDefinedIterator((startsWithPathChecks == null ? void 0 : startsWithPathChecks.keys()) || [], (fileOrDirectoryPath) => startsWith(locationPath, fileOrDirectoryPath) ? true : void 0) || firstDefinedIterator((isInDirectoryChecks == null ? void 0 : isInDirectoryChecks.keys()) || [], (dirPath) => locationPath.length > dirPath.length && startsWith(locationPath, dirPath) && (isDiskPathRoot(dirPath) || locationPath[dirPath.length] === directorySeparator) ? true : void 0); @@ -122761,7 +123297,9 @@ ${lanes.join("\n")} 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" + NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation", + TypingInstallerLocationFile: "File location for typing installer", + TypingInstallerLocationDirectory: "Directory location for typing installer" }; } }); @@ -122920,9 +123458,11 @@ ${lanes.join("\n")} if (!compilerHost.resolveTypeReferenceDirectiveReferences && !compilerHost.resolveTypeReferenceDirectives) { compilerHost.resolveTypeReferenceDirectiveReferences = resolutionCache.resolveTypeReferenceDirectiveReferences.bind(resolutionCache); } + compilerHost.resolveLibrary = !host.resolveLibrary ? resolutionCache.resolveLibrary.bind(resolutionCache) : host.resolveLibrary.bind(host); compilerHost.getModuleResolutionCache = host.resolveModuleNameLiterals || host.resolveModuleNames ? maybeBind(host, host.getModuleResolutionCache) : () => resolutionCache.getModuleResolutionCache(); const userProvidedResolution = !!host.resolveModuleNameLiterals || !!host.resolveTypeReferenceDirectiveReferences || !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; const customHasInvalidatedResolutions = userProvidedResolution ? maybeBind(host, host.hasInvalidatedResolutions) || returnTrue : returnFalse; + const customHasInvalidLibResolutions = host.resolveLibrary ? maybeBind(host, host.hasInvalidatedLibResolutions) || returnTrue : returnFalse; builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); watchConfigFileWildCardDirectories(); @@ -122983,10 +123523,11 @@ ${lanes.join("\n")} if (hasChangedCompilerOptions) { newLine = updateNewLine(); if (program && changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { - resolutionCache.clear(); + debugger; + resolutionCache.onChangesAffectModuleResolution(); } } - const hasInvalidatedResolutions = resolutionCache.createHasInvalidatedResolutions(customHasInvalidatedResolutions); + const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = resolutionCache.createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidLibResolutions); const { originalReadFile, originalFileExists, @@ -122995,7 +123536,7 @@ ${lanes.join("\n")} originalWriteFile, readFileWithCache } = changeCompilerHostLikeToUseCache(compilerHost, toPath3); - if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, (path) => getSourceVersion(path, readFileWithCache), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, (path) => getSourceVersion(path, readFileWithCache), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { if (reportFileChangeDetectedOnCreateProgram) { reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation); @@ -123016,7 +123557,7 @@ ${lanes.join("\n")} if (reportFileChangeDetectedOnCreateProgram) { reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation); } - createNewProgram(hasInvalidatedResolutions); + createNewProgram(hasInvalidatedResolutions, hasInvalidatedLibResolutions); } reportFileChangeDetectedOnCreateProgram = false; if (host.afterProgramCreate && program !== builderProgram) { @@ -123029,7 +123570,7 @@ ${lanes.join("\n")} compilerHost.writeFile = originalWriteFile; return builderProgram; } - function createNewProgram(hasInvalidatedResolutions) { + function createNewProgram(hasInvalidatedResolutions, hasInvalidatedLibResolutions) { writeLog("CreatingProgramWith::"); writeLog(` roots: ${JSON.stringify(rootFileNames)}`); writeLog(` options: ${JSON.stringify(compilerOptions)}`); @@ -123040,6 +123581,7 @@ ${lanes.join("\n")} hasChangedConfigFileParsingErrors = false; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolutions = hasInvalidatedResolutions; + compilerHost.hasInvalidatedLibResolutions = hasInvalidatedLibResolutions; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; const oldProgram = getCurrentProgram(); builderProgram = createProgram2(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); @@ -123624,6 +124166,7 @@ ${lanes.join("\n")} compilerHost.getParsedCommandLine = (fileName) => parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); compilerHost.resolveModuleNameLiterals = maybeBind(host, host.resolveModuleNameLiterals); compilerHost.resolveTypeReferenceDirectiveReferences = maybeBind(host, host.resolveTypeReferenceDirectiveReferences); + compilerHost.resolveLibrary = maybeBind(host, host.resolveLibrary); compilerHost.resolveModuleNames = maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = maybeBind(host, host.resolveTypeReferenceDirectives); compilerHost.getModuleResolutionCache = maybeBind(host, host.getModuleResolutionCache); @@ -123661,6 +124204,23 @@ ${lanes.join("\n")} createTypeReferenceResolutionLoader ); } + let libraryResolutionCache; + if (!compilerHost.resolveLibrary) { + libraryResolutionCache = createModuleResolutionCache( + compilerHost.getCurrentDirectory(), + compilerHost.getCanonicalFileName, + /*options*/ + void 0, + moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache() + ); + compilerHost.resolveLibrary = (libraryName, resolveFrom, options2) => resolveLibrary( + libraryName, + resolveFrom, + options2, + host, + libraryResolutionCache + ); + } compilerHost.getBuildInfo = (fileName, configFilePath) => getBuildInfo3( state, fileName, @@ -123692,6 +124252,7 @@ ${lanes.join("\n")} compilerHost, moduleResolutionCache, typeReferenceDirectiveResolutionCache, + libraryResolutionCache, // Mutable state buildOrder: void 0, readFileWithCache: (f) => host.readFile(f), @@ -123909,7 +124470,7 @@ ${lanes.join("\n")} function disableCache(state) { if (!state.cache) return; - const { cache, host, compilerHost, extendedConfigCache, moduleResolutionCache, typeReferenceDirectiveResolutionCache } = state; + const { cache, host, compilerHost, extendedConfigCache, moduleResolutionCache, typeReferenceDirectiveResolutionCache, libraryResolutionCache } = state; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -123920,6 +124481,7 @@ ${lanes.join("\n")} extendedConfigCache.clear(); moduleResolutionCache == null ? void 0 : moduleResolutionCache.clear(); typeReferenceDirectiveResolutionCache == null ? void 0 : typeReferenceDirectiveResolutionCache.clear(); + libraryResolutionCache == null ? void 0 : libraryResolutionCache.clear(); state.cache = void 0; } function clearProjectStatus(state, resolved) { @@ -125954,7 +126516,7 @@ ${lanes.join("\n")} const d = /* @__PURE__ */ new Date(); return `${padLeft(d.getHours().toString(), 2, "0")}:${padLeft(d.getMinutes().toString(), 2, "0")}:${padLeft(d.getSeconds().toString(), 2, "0")}.${padLeft(d.getMilliseconds().toString(), 3, "0")}`; } - var ActionSet, ActionInvalidate, ActionPackageInstalled, EventTypesRegistry, EventBeginInstallTypes, EventEndInstallTypes, EventInitializationFailed, Arguments; + var ActionSet, ActionInvalidate, ActionPackageInstalled, EventTypesRegistry, EventBeginInstallTypes, EventEndInstallTypes, EventInitializationFailed, ActionWatchTypingLocations, Arguments; var init_shared = __esm({ "src/jsTyping/shared.ts"() { "use strict"; @@ -125966,6 +126528,7 @@ ${lanes.join("\n")} EventBeginInstallTypes = "event::beginInstallTypes"; EventEndInstallTypes = "event::endInstallTypes"; EventInitializationFailed = "event::initializationFailed"; + ActionWatchTypingLocations = "action::watchTypingLocations"; ((Arguments2) => { Arguments2.GlobalCacheLocation = "--globalTypingsCacheLocation"; Arguments2.LogFile = "--logFile"; @@ -128303,7 +128866,12 @@ ${lanes.join("\n")} return visited; } function getSynthesizedDeepClones(nodes, includeTrivia = true) { - return nodes && factory.createNodeArray(nodes.map((n) => getSynthesizedDeepClone(n, includeTrivia)), nodes.hasTrailingComma); + if (nodes) { + const cloned = factory.createNodeArray(nodes.map((n) => getSynthesizedDeepClone(n, includeTrivia)), nodes.hasTrailingComma); + setTextRange(cloned, nodes); + return cloned; + } + return nodes; } function getSynthesizedDeepClonesWithReplacements(nodes, includeTrivia, replaceNode) { return factory.createNodeArray(nodes.map((n) => getSynthesizedDeepCloneWithReplacements(n, includeTrivia, replaceNode)), nodes.hasTrailingComma); @@ -129022,6 +129590,37 @@ ${lanes.join("\n")} } } } + function fileShouldUseJavaScriptRequire(file, program, host, preferRequire) { + var _a; + const fileName = typeof file === "string" ? file : file.fileName; + if (!hasJSFileExtension(fileName)) { + return false; + } + const compilerOptions = program.getCompilerOptions(); + const moduleKind = getEmitModuleKind(compilerOptions); + const impliedNodeFormat = typeof file === "string" ? getImpliedNodeFormatForFile(toPath(file, host.getCurrentDirectory(), hostGetCanonicalFileName(host)), (_a = program.getPackageJsonInfoCache) == null ? void 0 : _a.call(program), host, compilerOptions) : file.impliedNodeFormat; + if (impliedNodeFormat === 99 /* ESNext */) { + return false; + } + if (impliedNodeFormat === 1 /* CommonJS */) { + return true; + } + if (compilerOptions.verbatimModuleSyntax && moduleKind === 1 /* CommonJS */) { + return true; + } + if (compilerOptions.verbatimModuleSyntax && emitModuleKindIsNonNodeESM(moduleKind)) { + return false; + } + if (typeof file === "object") { + if (file.commonJsModuleIndicator) { + return true; + } + if (file.externalModuleIndicator) { + return false; + } + } + return preferRequire; + } var scanner, SemanticMeaning, tripleSlashDirectivePrefixRegex, typeKeywords, QuotePreference, displayPartWriter, lineFeed2, ANONYMOUS, syntaxMayBeASICandidate; var init_utilities4 = __esm({ "src/services/utilities.ts"() { @@ -129063,10 +129662,10 @@ ${lanes.join("\n")} 158 /* UniqueKeyword */, 159 /* UnknownKeyword */ ]; - QuotePreference = /* @__PURE__ */ ((QuotePreference5) => { - QuotePreference5[QuotePreference5["Single"] = 0] = "Single"; - QuotePreference5[QuotePreference5["Double"] = 1] = "Double"; - return QuotePreference5; + QuotePreference = /* @__PURE__ */ ((QuotePreference7) => { + QuotePreference7[QuotePreference7["Single"] = 0] = "Single"; + QuotePreference7[QuotePreference7["Double"] = 1] = "Double"; + return QuotePreference7; })(QuotePreference || {}); displayPartWriter = getDisplayPartWriter(); lineFeed2 = "\n"; @@ -133306,6 +133905,5293 @@ ${lanes.join("\n")} } }); + // src/services/refactorProvider.ts + function registerRefactor(name, refactor) { + refactors.set(name, refactor); + } + function getApplicableRefactors(context, includeInteractiveActions) { + return arrayFrom(flatMapIterator(refactors.values(), (refactor) => { + var _a; + return context.cancellationToken && context.cancellationToken.isCancellationRequested() || !((_a = refactor.kinds) == null ? void 0 : _a.some((kind) => refactorKindBeginsWith(kind, context.kind))) ? void 0 : refactor.getAvailableActions(context, includeInteractiveActions); + })); + } + function getEditsForRefactor(context, refactorName13, actionName2, interactiveRefactorArguments) { + const refactor = refactors.get(refactorName13); + return refactor && refactor.getEditsForAction(context, actionName2, interactiveRefactorArguments); + } + var refactors; + var init_refactorProvider = __esm({ + "src/services/refactorProvider.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactors = /* @__PURE__ */ new Map(); + } + }); + + // src/services/refactors/convertExport.ts + function getInfo2(context, considerPartialSpans = true) { + const { file, program } = context; + const span = getRefactorContextSpan(context); + const token = getTokenAtPosition(file, span.start); + const exportNode = !!(token.parent && getSyntacticModifierFlags(token.parent) & 1 /* Export */) && considerPartialSpans ? token.parent : getParentNodeInSpan(token, file, span); + if (!exportNode || !isSourceFile(exportNode.parent) && !(isModuleBlock(exportNode.parent) && isAmbientModule(exportNode.parent.parent))) { + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_export_statement) }; + } + const checker = program.getTypeChecker(); + const exportingModuleSymbol = getExportingModuleSymbol(exportNode.parent, checker); + const flags = getSyntacticModifierFlags(exportNode) || (isExportAssignment(exportNode) && !exportNode.isExportEquals ? 1025 /* ExportDefault */ : 0 /* None */); + const wasDefault = !!(flags & 1024 /* Default */); + if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { + return { error: getLocaleSpecificMessage(Diagnostics.This_file_already_has_a_default_export) }; + } + const noSymbolError = (id) => isIdentifier(id) && checker.getSymbolAtLocation(id) ? void 0 : { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_named_export) }; + switch (exportNode.kind) { + case 261 /* FunctionDeclaration */: + case 262 /* ClassDeclaration */: + case 263 /* InterfaceDeclaration */: + case 265 /* EnumDeclaration */: + case 264 /* TypeAliasDeclaration */: + case 266 /* ModuleDeclaration */: { + const node = exportNode; + if (!node.name) + return void 0; + return noSymbolError(node.name) || { exportNode: node, exportName: node.name, wasDefault, exportingModuleSymbol }; + } + case 242 /* VariableStatement */: { + const vs = exportNode; + if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { + return void 0; + } + const decl = first(vs.declarationList.declarations); + if (!decl.initializer) + return void 0; + Debug.assert(!wasDefault, "Can't have a default flag here"); + return noSymbolError(decl.name) || { exportNode: vs, exportName: decl.name, wasDefault, exportingModuleSymbol }; + } + case 276 /* ExportAssignment */: { + const node = exportNode; + if (node.isExportEquals) + return void 0; + return noSymbolError(node.expression) || { exportNode: node, exportName: node.expression, wasDefault, exportingModuleSymbol }; + } + default: + return void 0; + } + } + function doChange(exportingSourceFile, program, info, changes, cancellationToken) { + changeExport(exportingSourceFile, info, changes, program.getTypeChecker()); + changeImports(program, info, changes, cancellationToken); + } + function changeExport(exportingSourceFile, { wasDefault, exportNode, exportName }, changes, checker) { + if (wasDefault) { + if (isExportAssignment(exportNode) && !exportNode.isExportEquals) { + const exp = exportNode.expression; + const spec = makeExportSpecifier(exp.text, exp.text); + changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createNamedExports([spec]) + )); + } else { + changes.delete(exportingSourceFile, Debug.checkDefined(findModifier(exportNode, 90 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + } + } else { + const exportKeyword = Debug.checkDefined(findModifier(exportNode, 95 /* ExportKeyword */), "Should find an export keyword in modifier list"); + switch (exportNode.kind) { + case 261 /* FunctionDeclaration */: + case 262 /* ClassDeclaration */: + case 263 /* InterfaceDeclaration */: + changes.insertNodeAfter(exportingSourceFile, exportKeyword, factory.createToken(90 /* DefaultKeyword */)); + break; + case 242 /* VariableStatement */: + const decl = first(exportNode.declarationList.declarations); + if (!ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile) && !decl.type) { + changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDefault(Debug.checkDefined(decl.initializer, "Initializer was previously known to be present"))); + break; + } + case 265 /* EnumDeclaration */: + case 264 /* TypeAliasDeclaration */: + case 266 /* ModuleDeclaration */: + changes.deleteModifier(exportingSourceFile, exportKeyword); + changes.insertNodeAfter(exportingSourceFile, exportNode, factory.createExportDefault(factory.createIdentifier(exportName.text))); + break; + default: + Debug.fail(`Unexpected exportNode kind ${exportNode.kind}`); + } + } + } + function changeImports(program, { wasDefault, exportName, exportingModuleSymbol }, changes, cancellationToken) { + const checker = program.getTypeChecker(); + const exportSymbol = Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol"); + ts_FindAllReferences_exports.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, (ref) => { + if (exportName === ref) + return; + const importingSourceFile = ref.getSourceFile(); + if (wasDefault) { + changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); + } else { + changeNamedToDefaultImport(importingSourceFile, ref, changes); + } + }); + } + function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { + const { parent: parent2 } = ref; + switch (parent2.kind) { + case 210 /* PropertyAccessExpression */: + changes.replaceNode(importingSourceFile, ref, factory.createIdentifier(exportName)); + break; + case 275 /* ImportSpecifier */: + case 280 /* ExportSpecifier */: { + const spec = parent2; + changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); + break; + } + case 272 /* ImportClause */: { + const clause = parent2; + Debug.assert(clause.name === ref, "Import clause name should match provided ref"); + const spec = makeImportSpecifier(exportName, ref.text); + const { namedBindings } = clause; + if (!namedBindings) { + changes.replaceNode(importingSourceFile, ref, factory.createNamedImports([spec])); + } else if (namedBindings.kind === 273 /* NamespaceImport */) { + changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); + const quotePreference = isStringLiteral(clause.parent.moduleSpecifier) ? quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; + const newImport = makeImport( + /*defaultImport*/ + void 0, + [makeImportSpecifier(exportName, ref.text)], + clause.parent.moduleSpecifier, + quotePreference + ); + changes.insertNodeAfter(importingSourceFile, clause.parent, newImport); + } else { + changes.delete(importingSourceFile, ref); + changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec); + } + break; + } + case 204 /* ImportType */: + const importTypeNode = parent2; + changes.replaceNode(importingSourceFile, parent2, factory.createImportTypeNode(importTypeNode.argument, importTypeNode.assertions, factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); + break; + default: + Debug.failBadSyntaxKind(parent2); + } + } + function changeNamedToDefaultImport(importingSourceFile, ref, changes) { + const parent2 = ref.parent; + switch (parent2.kind) { + case 210 /* PropertyAccessExpression */: + changes.replaceNode(importingSourceFile, ref, factory.createIdentifier("default")); + break; + case 275 /* ImportSpecifier */: { + const defaultImport = factory.createIdentifier(parent2.name.text); + if (parent2.parent.elements.length === 1) { + changes.replaceNode(importingSourceFile, parent2.parent, defaultImport); + } else { + changes.delete(importingSourceFile, parent2); + changes.insertNodeBefore(importingSourceFile, parent2.parent, defaultImport); + } + break; + } + case 280 /* ExportSpecifier */: { + changes.replaceNode(importingSourceFile, parent2, makeExportSpecifier("default", parent2.name.text)); + break; + } + default: + Debug.assertNever(parent2, `Unexpected parent kind ${parent2.kind}`); + } + } + function makeImportSpecifier(propertyName, name) { + return factory.createImportSpecifier( + /*isTypeOnly*/ + false, + propertyName === name ? void 0 : factory.createIdentifier(propertyName), + factory.createIdentifier(name) + ); + } + function makeExportSpecifier(propertyName, name) { + return factory.createExportSpecifier( + /*isTypeOnly*/ + false, + propertyName === name ? void 0 : factory.createIdentifier(propertyName), + factory.createIdentifier(name) + ); + } + function getExportingModuleSymbol(parent2, checker) { + if (isSourceFile(parent2)) { + return parent2.symbol; + } + const symbol = parent2.parent.symbol; + if (symbol.valueDeclaration && isExternalModuleAugmentation(symbol.valueDeclaration)) { + return checker.getMergedSymbol(symbol); + } + return symbol; + } + var refactorName, defaultToNamedAction, namedToDefaultAction; + var init_convertExport = __esm({ + "src/services/refactors/convertExport.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName = "Convert export"; + defaultToNamedAction = { + name: "Convert default export to named export", + description: Diagnostics.Convert_default_export_to_named_export.message, + kind: "refactor.rewrite.export.named" + }; + namedToDefaultAction = { + name: "Convert named export to default export", + description: Diagnostics.Convert_named_export_to_default_export.message, + kind: "refactor.rewrite.export.default" + }; + registerRefactor(refactorName, { + kinds: [ + defaultToNamedAction.kind, + namedToDefaultAction.kind + ], + getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndDefaultExports(context) { + const info = getInfo2(context, context.triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + const action = info.wasDefault ? defaultToNamedAction : namedToDefaultAction; + return [{ name: refactorName, description: action.description, actions: [action] }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [ + { name: refactorName, description: Diagnostics.Convert_default_export_to_named_export.message, actions: [ + { ...defaultToNamedAction, notApplicableReason: info.error }, + { ...namedToDefaultAction, notApplicableReason: info.error } + ] } + ]; + } + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndDefaultExports(context, actionName2) { + Debug.assert(actionName2 === defaultToNamedAction.name || actionName2 === namedToDefaultAction.name, "Unexpected action name"); + const info = getInfo2(context); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange(context.file, context.program, info, t, context.cancellationToken)); + return { edits, renameFilename: void 0, renameLocation: void 0 }; + } + }); + } + }); + + // src/services/refactors/convertImport.ts + function getImportConversionInfo(context, considerPartialSpans = true) { + const { file } = context; + const span = getRefactorContextSpan(context); + const token = getTokenAtPosition(file, span.start); + const importDecl = considerPartialSpans ? findAncestor(token, isImportDeclaration) : getParentNodeInSpan(token, file, span); + if (!importDecl || !isImportDeclaration(importDecl)) + return { error: "Selection is not an import declaration." }; + const end = span.start + span.length; + const nextToken = findNextToken(importDecl, importDecl.parent, file); + if (nextToken && end > nextToken.getStart()) + return void 0; + const { importClause } = importDecl; + if (!importClause) { + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_import_clause) }; + } + if (!importClause.namedBindings) { + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_namespace_import_or_named_imports) }; + } + if (importClause.namedBindings.kind === 273 /* NamespaceImport */) { + return { convertTo: 0 /* Named */, import: importClause.namedBindings }; + } + const shouldUseDefault = getShouldUseDefault(context.program, importClause); + return shouldUseDefault ? { convertTo: 1 /* Default */, import: importClause.namedBindings } : { convertTo: 2 /* Namespace */, import: importClause.namedBindings }; + } + function getShouldUseDefault(program, importClause) { + return getAllowSyntheticDefaultImports(program.getCompilerOptions()) && isExportEqualsModule(importClause.parent.moduleSpecifier, program.getTypeChecker()); + } + function doChange2(sourceFile, program, changes, info) { + const checker = program.getTypeChecker(); + if (info.convertTo === 0 /* Named */) { + doChangeNamespaceToNamed(sourceFile, checker, changes, info.import, getAllowSyntheticDefaultImports(program.getCompilerOptions())); + } else { + doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, info.import, info.convertTo === 1 /* Default */); + } + } + function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { + let usedAsNamespaceOrDefault = false; + const nodesToReplace = []; + const conflictingNames = /* @__PURE__ */ new Map(); + ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, (id) => { + if (!isPropertyAccessOrQualifiedName(id.parent)) { + usedAsNamespaceOrDefault = true; + } else { + const exportName = getRightOfPropertyAccessOrQualifiedName(id.parent).text; + if (checker.resolveName( + exportName, + id, + 67108863 /* All */, + /*excludeGlobals*/ + true + )) { + conflictingNames.set(exportName, true); + } + Debug.assert(getLeftOfPropertyAccessOrQualifiedName(id.parent) === id, "Parent expression should match id"); + nodesToReplace.push(id.parent); + } + }); + const exportNameToImportName = /* @__PURE__ */ new Map(); + for (const propertyAccessOrQualifiedName of nodesToReplace) { + const exportName = getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName).text; + let importName = exportNameToImportName.get(exportName); + if (importName === void 0) { + exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? getUniqueName(exportName, sourceFile) : exportName); + } + changes.replaceNode(sourceFile, propertyAccessOrQualifiedName, factory.createIdentifier(importName)); + } + const importSpecifiers = []; + exportNameToImportName.forEach((name, propertyName) => { + importSpecifiers.push(factory.createImportSpecifier( + /*isTypeOnly*/ + false, + name === propertyName ? void 0 : factory.createIdentifier(propertyName), + factory.createIdentifier(name) + )); + }); + const importDecl = toConvert.parent.parent; + if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) { + changes.insertNodeAfter(sourceFile, importDecl, updateImport( + importDecl, + /*defaultImportName*/ + void 0, + importSpecifiers + )); + } else { + changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? factory.createIdentifier(toConvert.name.text) : void 0, importSpecifiers)); + } + } + function getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { + return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.name : propertyAccessOrQualifiedName.right; + } + function getLeftOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { + return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.expression : propertyAccessOrQualifiedName.left; + } + function doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, toConvert, shouldUseDefault = getShouldUseDefault(program, toConvert.parent)) { + const checker = program.getTypeChecker(); + const importDecl = toConvert.parent.parent; + const { moduleSpecifier } = importDecl; + const toConvertSymbols = /* @__PURE__ */ new Set(); + toConvert.elements.forEach((namedImport) => { + const symbol = checker.getSymbolAtLocation(namedImport.name); + if (symbol) { + toConvertSymbols.add(symbol); + } + }); + const preferredName = moduleSpecifier && isStringLiteral(moduleSpecifier) ? ts_codefix_exports.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 99 /* ESNext */) : "module"; + function hasNamespaceNameConflict(namedImport) { + return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(namedImport.name, checker, sourceFile, (id) => { + const symbol = checker.resolveName( + preferredName, + id, + 67108863 /* All */, + /*excludeGlobals*/ + true + ); + if (symbol) { + if (toConvertSymbols.has(symbol)) { + return isExportSpecifier(id.parent); + } + return true; + } + return false; + }); + } + const namespaceNameConflicts = toConvert.elements.some(hasNamespaceNameConflict); + const namespaceImportName = namespaceNameConflicts ? getUniqueName(preferredName, sourceFile) : preferredName; + const neededNamedImports = /* @__PURE__ */ new Set(); + for (const element of toConvert.elements) { + const propertyName = (element.propertyName || element.name).text; + ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, (id) => { + const access = factory.createPropertyAccessExpression(factory.createIdentifier(namespaceImportName), propertyName); + if (isShorthandPropertyAssignment(id.parent)) { + changes.replaceNode(sourceFile, id.parent, factory.createPropertyAssignment(id.text, access)); + } else if (isExportSpecifier(id.parent)) { + neededNamedImports.add(element); + } else { + changes.replaceNode(sourceFile, id, access); + } + }); + } + changes.replaceNode(sourceFile, toConvert, shouldUseDefault ? factory.createIdentifier(namespaceImportName) : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName))); + if (neededNamedImports.size) { + const newNamedImports = 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*/ + void 0, + newNamedImports + )); + } + } + function isExportEqualsModule(moduleSpecifier, checker) { + const externalModule = checker.resolveExternalModuleName(moduleSpecifier); + if (!externalModule) + return false; + const exportEquals = checker.resolveExternalModuleSymbol(externalModule); + return externalModule !== exportEquals; + } + function updateImport(old, defaultImportName, elements) { + return factory.createImportDeclaration( + /*modifiers*/ + void 0, + factory.createImportClause( + /*isTypeOnly*/ + false, + defaultImportName, + elements && elements.length ? factory.createNamedImports(elements) : void 0 + ), + old.moduleSpecifier, + /*assertClause*/ + void 0 + ); + } + var refactorName2, actions; + var init_convertImport = __esm({ + "src/services/refactors/convertImport.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName2 = "Convert import"; + actions = { + [0 /* Named */]: { + name: "Convert namespace import to named imports", + description: Diagnostics.Convert_namespace_import_to_named_imports.message, + kind: "refactor.rewrite.import.named" + }, + [2 /* Namespace */]: { + name: "Convert named imports to namespace import", + description: Diagnostics.Convert_named_imports_to_namespace_import.message, + kind: "refactor.rewrite.import.namespace" + }, + [1 /* Default */]: { + name: "Convert named imports to default import", + description: Diagnostics.Convert_named_imports_to_default_import.message, + kind: "refactor.rewrite.import.default" + } + }; + registerRefactor(refactorName2, { + kinds: getOwnValues(actions).map((a) => a.kind), + getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndNamespacedImports(context) { + const info = getImportConversionInfo(context, context.triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + const action = actions[info.convertTo]; + return [{ name: refactorName2, description: action.description, actions: [action] }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return getOwnValues(actions).map((action) => ({ + name: refactorName2, + description: action.description, + actions: [{ ...action, notApplicableReason: info.error }] + })); + } + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndNamespacedImports(context, actionName2) { + Debug.assert(some(getOwnValues(actions), (action) => action.name === actionName2), "Unexpected action name"); + const info = getImportConversionInfo(context); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange2(context.file, context.program, t, info)); + return { edits, renameFilename: void 0, renameLocation: void 0 }; + } + }); + } + }); + + // src/services/refactors/extractType.ts + function getRangeToExtract(context, considerEmptySpans = true) { + const { file, startPosition } = context; + const isJS = isSourceFileJS(file); + const current = getTokenAtPosition(file, startPosition); + 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))); + if (!selection || !isTypeNode(selection)) + return { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) }; + const checker = context.program.getTypeChecker(); + const enclosingNode = getEnclosingNode(selection, isJS); + if (enclosingNode === void 0) + return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }; + const typeParameters = collectTypeParameters(checker, selection, enclosingNode, file); + if (!typeParameters) + return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }; + const typeElements = flattenTypeLiteralNodeReference(checker, selection); + return { isJS, selection, enclosingNode, typeParameters, typeElements }; + } + function flattenTypeLiteralNodeReference(checker, node) { + if (!node) + return void 0; + if (isIntersectionTypeNode(node)) { + const result = []; + const seen = /* @__PURE__ */ new Map(); + for (const type of node.types) { + const flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type); + if (!flattenedTypeMembers || !flattenedTypeMembers.every((type2) => type2.name && addToSeen(seen, getNameFromPropertyName(type2.name)))) { + return void 0; + } + addRange(result, flattenedTypeMembers); + } + return result; + } else if (isParenthesizedTypeNode(node)) { + return flattenTypeLiteralNodeReference(checker, node.type); + } else if (isTypeLiteralNode(node)) { + return node.members; + } + return void 0; + } + function rangeContainsSkipTrivia(r1, node, file) { + return rangeContainsStartEnd(r1, skipTrivia(file.text, node.pos), node.end); + } + function collectTypeParameters(checker, selection, enclosingNode, file) { + const result = []; + return visitor(selection) ? void 0 : result; + function visitor(node) { + if (isTypeReferenceNode(node)) { + if (isIdentifier(node.typeName)) { + const typeName = node.typeName; + const symbol = checker.resolveName( + typeName.text, + typeName, + 262144 /* TypeParameter */, + /*excludeGlobals*/ + true + ); + for (const decl of (symbol == null ? void 0 : symbol.declarations) || emptyArray) { + if (isTypeParameterDeclaration(decl) && decl.getSourceFile() === file) { + if (decl.name.escapedText === typeName.escapedText && rangeContainsSkipTrivia(decl, selection, file)) { + return true; + } + if (rangeContainsSkipTrivia(enclosingNode, decl, file) && !rangeContainsSkipTrivia(selection, decl, file)) { + pushIfUnique(result, decl); + break; + } + } + } + } + } else if (isInferTypeNode(node)) { + const conditionalTypeNode = findAncestor(node, (n) => isConditionalTypeNode(n) && rangeContainsSkipTrivia(n.extendsType, node, file)); + if (!conditionalTypeNode || !rangeContainsSkipTrivia(selection, conditionalTypeNode, file)) { + return true; + } + } else if (isTypePredicateNode(node) || isThisTypeNode(node)) { + const functionLikeNode = findAncestor(node.parent, isFunctionLike); + if (functionLikeNode && functionLikeNode.type && rangeContainsSkipTrivia(functionLikeNode.type, node, file) && !rangeContainsSkipTrivia(selection, functionLikeNode, file)) { + return true; + } + } else if (isTypeQueryNode(node)) { + if (isIdentifier(node.exprName)) { + const symbol = checker.resolveName( + node.exprName.text, + node.exprName, + 111551 /* Value */, + /*excludeGlobals*/ + false + ); + if ((symbol == null ? void 0 : symbol.valueDeclaration) && rangeContainsSkipTrivia(enclosingNode, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) { + return true; + } + } else { + if (isThisIdentifier(node.exprName.left) && !rangeContainsSkipTrivia(selection, node.parent, file)) { + return true; + } + } + } + if (file && isTupleTypeNode(node) && getLineAndCharacterOfPosition(file, node.pos).line === getLineAndCharacterOfPosition(file, node.end).line) { + setEmitFlags(node, 1 /* SingleLine */); + } + return forEachChild(node, visitor); + } + } + function doTypeAliasChange(changes, file, name, info) { + const { enclosingNode, selection, typeParameters } = info; + const newTypeNode = factory.createTypeAliasDeclaration( + /*modifiers*/ + void 0, + name, + typeParameters.map((id) => factory.updateTypeParameterDeclaration( + id, + id.modifiers, + id.name, + id.constraint, + /*defaultType*/ + void 0 + )), + selection + ); + changes.insertNodeBefore( + file, + enclosingNode, + ignoreSourceNewlines(newTypeNode), + /*blankLineBetween*/ + true + ); + changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( + id.name, + /*typeArguments*/ + void 0 + ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace }); + } + function doInterfaceChange(changes, file, name, info) { + var _a; + const { enclosingNode, selection, typeParameters, typeElements } = info; + const newTypeNode = factory.createInterfaceDeclaration( + /*modifiers*/ + void 0, + name, + typeParameters, + /*heritageClauses*/ + void 0, + typeElements + ); + setTextRange(newTypeNode, (_a = typeElements[0]) == null ? void 0 : _a.parent); + changes.insertNodeBefore( + file, + enclosingNode, + ignoreSourceNewlines(newTypeNode), + /*blankLineBetween*/ + true + ); + changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( + id.name, + /*typeArguments*/ + void 0 + ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace }); + } + function doTypedefChange(changes, context, file, name, info) { + var _a; + const { enclosingNode, selection, typeParameters } = info; + setEmitFlags(selection, 3072 /* NoComments */ | 4096 /* NoNestedComments */); + const node = factory.createJSDocTypedefTag( + factory.createIdentifier("typedef"), + factory.createJSDocTypeExpression(selection), + factory.createIdentifier(name) + ); + const templates = []; + forEach(typeParameters, (typeParameter) => { + const constraint = getEffectiveConstraintOfTypeParameter(typeParameter); + const parameter = factory.createTypeParameterDeclaration( + /*modifiers*/ + void 0, + typeParameter.name + ); + const template = factory.createJSDocTemplateTag( + factory.createIdentifier("template"), + constraint && cast(constraint, isJSDocTypeExpression), + [parameter] + ); + templates.push(template); + }); + const jsDoc = factory.createJSDocComment( + /*comment*/ + void 0, + factory.createNodeArray(concatenate(templates, [node])) + ); + if (isJSDoc(enclosingNode)) { + const pos = enclosingNode.getStart(file); + const newLineCharacter = getNewLineOrDefaultFromHost(context.host, (_a = context.formatContext) == null ? void 0 : _a.options); + changes.insertNodeAt(file, enclosingNode.getStart(file), jsDoc, { + suffix: newLineCharacter + newLineCharacter + file.text.slice(getPrecedingNonSpaceCharacterPosition(file.text, pos - 1), pos) + }); + } else { + changes.insertNodeBefore( + file, + enclosingNode, + jsDoc, + /*blankLineBetween*/ + true + ); + } + changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( + id.name, + /*typeArguments*/ + void 0 + )))); + } + function getEnclosingNode(node, isJS) { + return findAncestor(node, isStatement) || (isJS ? findAncestor(node, isJSDoc) : void 0); + } + var refactorName3, extractToTypeAliasAction, extractToInterfaceAction, extractToTypeDefAction; + var init_extractType = __esm({ + "src/services/refactors/extractType.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName3 = "Extract type"; + extractToTypeAliasAction = { + name: "Extract to type alias", + description: getLocaleSpecificMessage(Diagnostics.Extract_to_type_alias), + kind: "refactor.extract.type" + }; + extractToInterfaceAction = { + name: "Extract to interface", + description: getLocaleSpecificMessage(Diagnostics.Extract_to_interface), + kind: "refactor.extract.interface" + }; + extractToTypeDefAction = { + name: "Extract to typedef", + description: getLocaleSpecificMessage(Diagnostics.Extract_to_typedef), + kind: "refactor.extract.typedef" + }; + registerRefactor(refactorName3, { + kinds: [ + extractToTypeAliasAction.kind, + extractToInterfaceAction.kind, + extractToTypeDefAction.kind + ], + getAvailableActions: function getRefactorActionsToExtractType(context) { + const info = getRangeToExtract(context, context.triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + return [{ + name: refactorName3, + description: getLocaleSpecificMessage(Diagnostics.Extract_type), + actions: info.isJS ? [extractToTypeDefAction] : append([extractToTypeAliasAction], info.typeElements && extractToInterfaceAction) + }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorName3, + description: getLocaleSpecificMessage(Diagnostics.Extract_type), + actions: [ + { ...extractToTypeDefAction, notApplicableReason: info.error }, + { ...extractToTypeAliasAction, notApplicableReason: info.error }, + { ...extractToInterfaceAction, notApplicableReason: info.error } + ] + }]; + } + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToExtractType(context, actionName2) { + const { file } = context; + const info = getRangeToExtract(context); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected to find a range to extract"); + const name = getUniqueName("NewType", file); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (changes) => { + switch (actionName2) { + case extractToTypeAliasAction.name: + Debug.assert(!info.isJS, "Invalid actionName/JS combo"); + return doTypeAliasChange(changes, file, name, info); + case extractToTypeDefAction.name: + Debug.assert(info.isJS, "Invalid actionName/JS combo"); + return doTypedefChange(changes, context, file, name, info); + case extractToInterfaceAction.name: + Debug.assert(!info.isJS && !!info.typeElements, "Invalid actionName/JS combo"); + return doInterfaceChange(changes, file, name, info); + default: + Debug.fail("Unexpected action name"); + } + }); + const renameFilename = file.fileName; + const renameLocation = getRenameLocation( + edits, + renameFilename, + name, + /*preferLastLocation*/ + false + ); + return { edits, renameFilename, renameLocation }; + } + }); + } + }); + + // src/services/refactors/helpers.ts + function isRefactorErrorInfo(info) { + return info.error !== void 0; + } + function refactorKindBeginsWith(known, requested) { + if (!requested) + return true; + return known.substr(0, requested.length) === requested; + } + var init_helpers = __esm({ + "src/services/refactors/helpers.ts"() { + "use strict"; + } + }); + + // src/services/refactors/moveToNewFile.ts + function doChange3(oldFile, program, toMove, changes, host, preferences, context) { + const checker = program.getTypeChecker(); + const usage = getUsageInfo(oldFile, toMove.all, checker); + const newFilename = createNewFileName(oldFile, program, context, host); + changes.createNewFile(oldFile, newFilename, getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences)); + addNewFileToTsconfig(program, changes, oldFile.fileName, newFilename, hostGetCanonicalFileName(host)); + } + function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences) { + const checker = program.getTypeChecker(); + const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective); + if (oldFile.externalModuleIndicator === void 0 && oldFile.commonJsModuleIndicator === void 0 && usage.oldImportsNeededByTargetFile.size === 0) { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return [...prologueDirectives, ...toMove.all]; + } + const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(newFilename, program, host, !!oldFile.commonJsModuleIndicator); + const quotePreference = getQuotePreference(oldFile, preferences); + const importsFromNewFile = createOldFileImportsFromTargetFile(oldFile, usage.oldFileImportsFromTargetFile, newFilename, program, host, useEsModuleSyntax, quotePreference); + if (importsFromNewFile) { + insertImports( + changes, + oldFile, + importsFromNewFile, + /*blankLineBetween*/ + true, + preferences + ); + } + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, newFilename, quotePreference); + const imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference); + const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromTargetFile, useEsModuleSyntax); + if (imports.length && body.length) { + return [ + ...prologueDirectives, + ...imports, + 4 /* NewLineTrivia */, + ...body + ]; + } + return [ + ...prologueDirectives, + ...imports, + ...body + ]; + } + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference) { + const copiedOldImports = []; + for (const oldStatement of oldFile.statements) { + forEachImportInStatement(oldStatement, (i) => { + append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); + }); + } + let oldFileDefault; + const oldFileNamedImports = []; + const markSeenTop = nodeSeenTracker(); + newFileImportsFromOldFile.forEach((symbol) => { + if (!symbol.declarations) { + return; + } + for (const decl of symbol.declarations) { + if (!isTopLevelDeclaration(decl)) + continue; + const name = nameOfTopLevelDeclaration(decl); + if (!name) + continue; + const top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) { + addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); + } + if (hasSyntacticModifier(decl, 1024 /* Default */)) { + oldFileDefault = name; + } else { + oldFileNamedImports.push(name.text); + } + } + }); + append(copiedOldImports, makeImportOrRequire(oldFile, oldFileDefault, oldFileNamedImports, getBaseFileName(oldFile.fileName), program, host, useEsModuleSyntax, quotePreference)); + return copiedOldImports; + } + var refactorName4, description, moveToNewFileAction; + var init_moveToNewFile = __esm({ + "src/services/refactors/moveToNewFile.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName4 = "Move to a new file"; + description = getLocaleSpecificMessage(Diagnostics.Move_to_a_new_file); + moveToNewFileAction = { + name: refactorName4, + description, + kind: "refactor.move.newFile" + }; + registerRefactor(refactorName4, { + kinds: [moveToNewFileAction.kind], + getAvailableActions: function getRefactorActionsToMoveToNewFile(context) { + const statements = getStatementsToMove(context); + if (context.preferences.allowTextChangesInNewFiles && statements) { + return [{ name: refactorName4, description, actions: [moveToNewFileAction] }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorName4, + description, + actions: [{ ...moveToNewFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] + }]; + } + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToMoveToNewFile(context, actionName2) { + Debug.assert(actionName2 === refactorName4, "Wrong refactor invoked"); + const statements = Debug.checkDefined(getStatementsToMove(context)); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange3(context.file, context.program, statements, t, context.host, context.preferences, context)); + return { edits, renameFilename: void 0, renameLocation: void 0 }; + } + }); + } + }); + + // src/services/refactors/moveToFile.ts + function doChange4(context, oldFile, targetFile, program, toMove, changes, host, preferences) { + var _a; + const checker = program.getTypeChecker(); + const usage = getUsageInfo(oldFile, toMove.all, checker); + if (!host.fileExists(targetFile) || host.fileExists(targetFile) && ((_a = program.getSourceFile(targetFile)) == null ? void 0 : _a.statements.length) === 0) { + changes.createNewFile(oldFile, targetFile, getNewStatementsAndRemoveFromOldFile2(oldFile, targetFile, usage, changes, toMove, program, host, preferences)); + addNewFileToTsconfig(program, changes, oldFile.fileName, targetFile, hostGetCanonicalFileName(host)); + } else { + const targetSourceFile = Debug.checkDefined(program.getSourceFile(targetFile)); + const importAdder = ts_codefix_exports.createImportAdder(targetSourceFile, context.program, context.preferences, context.host); + getNewStatementsAndRemoveFromOldFile2(oldFile, targetSourceFile, usage, changes, toMove, program, host, preferences, importAdder); + } + } + function getNewStatementsAndRemoveFromOldFile2(oldFile, targetFile, usage, changes, toMove, program, host, preferences, importAdder) { + const checker = program.getTypeChecker(); + const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective); + if (oldFile.externalModuleIndicator === void 0 && oldFile.commonJsModuleIndicator === void 0 && usage.oldImportsNeededByTargetFile.size === 0 && usage.targetFileImportsFromOldFile.size === 0 && typeof targetFile === "string") { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return [...prologueDirectives, ...toMove.all]; + } + const targetFileName = typeof targetFile === "string" ? targetFile : targetFile.fileName; + const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(targetFileName, program, host, !!oldFile.commonJsModuleIndicator); + const quotePreference = getQuotePreference(oldFile, preferences); + const importsFromTargetFile = createOldFileImportsFromTargetFile(oldFile, usage.oldFileImportsFromTargetFile, targetFileName, program, host, useEsModuleSyntax, quotePreference); + if (importsFromTargetFile) { + insertImports( + changes, + oldFile, + importsFromTargetFile, + /*blankLineBetween*/ + true, + preferences + ); + } + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, targetFileName, quotePreference); + const imports = getTargetFileImportsAndAddExportInOldFile(oldFile, targetFileName, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference, importAdder); + const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromTargetFile, useEsModuleSyntax); + if (typeof targetFile !== "string") { + if (targetFile.statements.length > 0) { + changes.insertNodesAfter(targetFile, targetFile.statements[targetFile.statements.length - 1], body); + } + if (imports.length > 0) { + insertImports( + changes, + targetFile, + imports, + /*blankLineBetween*/ + true, + preferences + ); + } + } + if (importAdder) { + importAdder.writeFixes(changes); + } + if (imports.length && body.length) { + return [ + ...prologueDirectives, + ...imports, + 4 /* NewLineTrivia */, + ...body + ]; + } + return [ + ...prologueDirectives, + ...imports, + ...body + ]; + } + function getTargetFileImportsAndAddExportInOldFile(oldFile, targetFile, importsToCopy, targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference, importAdder) { + const copiedOldImports = []; + if (importAdder) { + importsToCopy.forEach((isValidTypeOnlyUseSite, symbol) => { + try { + importAdder.addImportFromExportedSymbol(skipAlias(symbol, checker), isValidTypeOnlyUseSite); + } catch { + for (const oldStatement of oldFile.statements) { + forEachImportInStatement(oldStatement, (i) => { + append(copiedOldImports, filterImport(i, factory.createStringLiteral(moduleSpecifierFromImport(i).text), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); + }); + } + } + }); + } else { + const targetSourceFile = program.getSourceFile(targetFile); + for (const oldStatement of oldFile.statements) { + forEachImportInStatement(oldStatement, (i) => { + var _a, _b; + const moduleSpecifier = moduleSpecifierFromImport(i); + const resolved = (_a = oldFile.resolvedModules) == null ? void 0 : _a.get(moduleSpecifier.text, getModeForUsageLocation(oldFile, moduleSpecifier)); + const fileName = (_b = resolved == null ? void 0 : resolved.resolvedModule) == null ? void 0 : _b.resolvedFileName; + if (fileName && targetSourceFile) { + const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), targetSourceFile, targetSourceFile.path, fileName, createModuleSpecifierResolutionHost(program, host)); + append(copiedOldImports, filterImport(i, makeStringLiteral(newModuleSpecifier, quotePreference), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); + } else { + append(copiedOldImports, filterImport(i, factory.createStringLiteral(moduleSpecifierFromImport(i).text), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); + } + }); + } + } + const targetFileSourceFile = program.getSourceFile(targetFile); + let oldFileDefault; + const oldFileNamedImports = []; + const markSeenTop = nodeSeenTracker(); + targetFileImportsFromOldFile.forEach((symbol) => { + if (!symbol.declarations) { + return; + } + for (const decl of symbol.declarations) { + if (!isTopLevelDeclaration(decl)) + continue; + const name = nameOfTopLevelDeclaration(decl); + if (!name) + continue; + const top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) { + addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); + } + if (importAdder && checker.isUnknownSymbol(symbol)) { + importAdder.addImportFromExportedSymbol(skipAlias(symbol, checker)); + } else { + if (hasSyntacticModifier(decl, 1024 /* Default */)) { + oldFileDefault = name; + } else { + oldFileNamedImports.push(name.text); + } + } + } + }); + 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)); + } + function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { + const cfg = program.getCompilerOptions().configFile; + if (!cfg) + return; + const newFileAbsolutePath = normalizePath(combinePaths(oldFileName, "..", newFileNameWithExtension)); + 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) => 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); + } + } + function deleteMovedStatements(sourceFile, moved, changes) { + for (const { first: first2, afterLast } of moved) { + changes.deleteNodeRangeExcludingEnd(sourceFile, first2, afterLast); + } + } + function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { + for (const statement of oldFile.statements) { + if (contains(toMove, statement)) + continue; + forEachImportInStatement(statement, (i) => deleteUnusedImports(oldFile, i, changes, (name) => toDelete.has(checker.getSymbolAtLocation(name)))); + } + } + function updateImportsInOtherFiles(changes, program, host, oldFile, movedSymbols, targetFileName, quotePreference) { + const checker = program.getTypeChecker(); + for (const sourceFile of program.getSourceFiles()) { + if (sourceFile === oldFile) + continue; + for (const statement of sourceFile.statements) { + forEachImportInStatement(statement, (importNode) => { + if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) + return; + const shouldMove = (name) => { + const symbol = isBindingElement(name.parent) ? getPropertySymbolFromBindingElement(checker, name.parent) : skipAlias(checker.getSymbolAtLocation(name), checker); + return !!symbol && movedSymbols.has(symbol); + }; + deleteUnusedImports(sourceFile, importNode, changes, shouldMove); + const pathToTargetFileWithExtension = resolvePath(getDirectoryPath(oldFile.path), targetFileName); + const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToTargetFileWithExtension, createModuleSpecifierResolutionHost(program, host)); + const newImportDeclaration = filterImport(importNode, makeStringLiteral(newModuleSpecifier, quotePreference), shouldMove); + if (newImportDeclaration) + changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + const ns = getNamespaceLikeImport(importNode); + if (ns) + updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, ns, importNode, quotePreference); + }); + } + } + } + function getNamespaceLikeImport(node) { + switch (node.kind) { + case 271 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 273 /* NamespaceImport */ ? node.importClause.namedBindings.name : void 0; + case 270 /* ImportEqualsDeclaration */: + return node.name; + case 259 /* VariableDeclaration */: + return tryCast(node.name, isIdentifier); + default: + return Debug.assertNever(node, `Unexpected node kind ${node.kind}`); + } + } + function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, oldImportId, oldImportNode, quotePreference) { + const preferredNewNamespaceName = ts_codefix_exports.moduleSpecifierToValidIdentifier(newModuleSpecifier, 99 /* ESNext */); + let needUniqueName = false; + const toChange = []; + ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, (ref) => { + if (!isPropertyAccessExpression(ref.parent)) + return; + needUniqueName = needUniqueName || !!checker.resolveName( + preferredNewNamespaceName, + ref, + 67108863 /* All */, + /*excludeGlobals*/ + true + ); + if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) { + toChange.push(ref); + } + }); + if (toChange.length) { + const newNamespaceName = needUniqueName ? getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; + for (const ref of toChange) { + changes.replaceNode(sourceFile, ref, factory.createIdentifier(newNamespaceName)); + } + changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, preferredNewNamespaceName, newModuleSpecifier, quotePreference)); + } + } + function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier, quotePreference) { + const newNamespaceId = factory.createIdentifier(newNamespaceName); + const newModuleString = makeStringLiteral(newModuleSpecifier, quotePreference); + switch (node.kind) { + case 271 /* ImportDeclaration */: + return factory.createImportDeclaration( + /*modifiers*/ + void 0, + factory.createImportClause( + /*isTypeOnly*/ + false, + /*name*/ + void 0, + factory.createNamespaceImport(newNamespaceId) + ), + newModuleString, + /*assertClause*/ + void 0 + ); + case 270 /* ImportEqualsDeclaration */: + return factory.createImportEqualsDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + newNamespaceId, + factory.createExternalModuleReference(newModuleString) + ); + case 259 /* VariableDeclaration */: + return factory.createVariableDeclaration( + newNamespaceId, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + createRequireCall(newModuleString) + ); + default: + return Debug.assertNever(node, `Unexpected node kind ${node.kind}`); + } + } + function createRequireCall(moduleSpecifier) { + return factory.createCallExpression( + factory.createIdentifier("require"), + /*typeArguments*/ + void 0, + [moduleSpecifier] + ); + } + function moduleSpecifierFromImport(i) { + return i.kind === 271 /* ImportDeclaration */ ? i.moduleSpecifier : i.kind === 270 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]; + } + function forEachImportInStatement(statement, cb) { + if (isImportDeclaration(statement)) { + if (isStringLiteral(statement.moduleSpecifier)) + cb(statement); + } else if (isImportEqualsDeclaration(statement)) { + if (isExternalModuleReference(statement.moduleReference) && isStringLiteralLike(statement.moduleReference.expression)) { + cb(statement); + } + } else if (isVariableStatement(statement)) { + for (const decl of statement.declarationList.declarations) { + if (decl.initializer && isRequireCall( + decl.initializer, + /*requireStringLiteralLikeArgument*/ + true + )) { + cb(decl); + } + } + } + } + function createOldFileImportsFromTargetFile(sourceFile, targetFileNeedExport, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference) { + let defaultImport; + const imports = []; + targetFileNeedExport.forEach((symbol) => { + if (symbol.escapedName === "default" /* Default */) { + defaultImport = factory.createIdentifier(symbolNameNoDefault(symbol)); + } else { + imports.push(symbol.name); + } + }); + return makeImportOrRequire(sourceFile, defaultImport, imports, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference); + } + function makeImportOrRequire(sourceFile, defaultImport, imports, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference) { + const pathToTargetFile = resolvePath(getDirectoryPath(sourceFile.path), targetFileNameWithExtension); + const pathToTargetFileWithCorrectExtension = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToTargetFile, createModuleSpecifierResolutionHost(program, host)); + if (useEs6Imports) { + const specifiers = imports.map((i) => factory.createImportSpecifier( + /*isTypeOnly*/ + false, + /*propertyName*/ + void 0, + factory.createIdentifier(i) + )); + return makeImportIfNecessary(defaultImport, specifiers, pathToTargetFileWithCorrectExtension, quotePreference); + } else { + Debug.assert(!defaultImport, "No default import should exist"); + const bindingElements = imports.map((i) => factory.createBindingElement( + /*dotDotDotToken*/ + void 0, + /*propertyName*/ + void 0, + i + )); + return bindingElements.length ? makeVariableStatement( + factory.createObjectBindingPattern(bindingElements), + /*type*/ + void 0, + createRequireCall(makeStringLiteral(pathToTargetFileWithCorrectExtension, quotePreference)) + ) : void 0; + } + } + function makeVariableStatement(name, type, initializer, flags = 2 /* Const */) { + return factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList([factory.createVariableDeclaration( + name, + /*exclamationToken*/ + void 0, + type, + initializer + )], flags) + ); + } + function addExports(sourceFile, toMove, needExport, useEs6Exports) { + return flatMap(toMove, (statement) => { + if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, (d) => { + var _a; + return needExport.has(Debug.checkDefined((_a = tryCast(d, canHaveSymbol)) == null ? void 0 : _a.symbol)); + })) { + const exports = addExport(getSynthesizedDeepClone(statement), useEs6Exports); + if (exports) + return exports; + } + return getSynthesizedDeepClone(statement); + }); + } + function isExported(sourceFile, decl, useEs6Exports, name) { + var _a; + if (useEs6Exports) { + return !isExpressionStatement(decl) && hasSyntacticModifier(decl, 1 /* Export */) || !!(name && sourceFile.symbol && ((_a = sourceFile.symbol.exports) == null ? void 0 : _a.has(name.escapedText))); + } + return !!sourceFile.symbol && !!sourceFile.symbol.exports && getNamesToExportInCommonJS(decl).some((name2) => sourceFile.symbol.exports.has(escapeLeadingUnderscores(name2))); + } + function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { + switch (importDecl.kind) { + case 271 /* ImportDeclaration */: + deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); + break; + case 270 /* ImportEqualsDeclaration */: + if (isUnused(importDecl.name)) { + changes.delete(sourceFile, importDecl); + } + break; + case 259 /* VariableDeclaration */: + deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); + break; + default: + Debug.assertNever(importDecl, `Unexpected import decl kind ${importDecl.kind}`); + } + } + function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { + if (!importDecl.importClause) + return; + const { name, namedBindings } = importDecl.importClause; + const defaultUnused = !name || isUnused(name); + const namedBindingsUnused = !namedBindings || (namedBindings.kind === 273 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every((e) => isUnused(e.name))); + if (defaultUnused && namedBindingsUnused) { + changes.delete(sourceFile, importDecl); + } else { + if (name && defaultUnused) { + changes.delete(sourceFile, name); + } + if (namedBindings) { + if (namedBindingsUnused) { + changes.replaceNode( + sourceFile, + importDecl.importClause, + factory.updateImportClause( + importDecl.importClause, + importDecl.importClause.isTypeOnly, + name, + /*namedBindings*/ + void 0 + ) + ); + } else if (namedBindings.kind === 274 /* NamedImports */) { + for (const element of namedBindings.elements) { + if (isUnused(element.name)) + changes.delete(sourceFile, element); + } + } + } + } + } + function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { + const { name } = varDecl; + switch (name.kind) { + case 80 /* 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 + ); + } else { + changes.delete(sourceFile, name); + } + } + break; + case 206 /* ArrayBindingPattern */: + break; + case 205 /* 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 + ); + } else { + for (const element of name.elements) { + if (isIdentifier(element.name) && isUnused(element.name)) { + changes.delete(sourceFile, element.name); + } + } + } + break; + } + } + function isTopLevelDeclarationStatement(node) { + Debug.assert(isSourceFile(node.parent), "Node parent should be a SourceFile"); + return isNonVariableTopLevelDeclaration(node) || isVariableStatement(node); + } + function addExport(decl, useEs6Exports) { + return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); + } + function addEs6Export(d) { + const modifiers = canHaveModifiers(d) ? concatenate([factory.createModifier(95 /* ExportKeyword */)], getModifiers(d)) : void 0; + switch (d.kind) { + case 261 /* FunctionDeclaration */: + return factory.updateFunctionDeclaration(d, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + case 262 /* ClassDeclaration */: + const decorators = canHaveDecorators(d) ? getDecorators(d) : void 0; + return factory.updateClassDeclaration(d, concatenate(decorators, modifiers), d.name, d.typeParameters, d.heritageClauses, d.members); + case 242 /* VariableStatement */: + return factory.updateVariableStatement(d, modifiers, d.declarationList); + case 266 /* ModuleDeclaration */: + return factory.updateModuleDeclaration(d, modifiers, d.name, d.body); + case 265 /* EnumDeclaration */: + return factory.updateEnumDeclaration(d, modifiers, d.name, d.members); + case 264 /* TypeAliasDeclaration */: + return factory.updateTypeAliasDeclaration(d, modifiers, d.name, d.typeParameters, d.type); + case 263 /* InterfaceDeclaration */: + return factory.updateInterfaceDeclaration(d, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 270 /* ImportEqualsDeclaration */: + return factory.updateImportEqualsDeclaration(d, modifiers, d.isTypeOnly, d.name, d.moduleReference); + case 243 /* ExpressionStatement */: + return Debug.fail(); + default: + return Debug.assertNever(d, `Unexpected declaration kind ${d.kind}`); + } + } + function addCommonjsExport(decl) { + return [decl, ...getNamesToExportInCommonJS(decl).map(createExportAssignment)]; + } + function createExportAssignment(name) { + return factory.createExpressionStatement( + factory.createBinaryExpression( + factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(name)), + 64 /* EqualsToken */, + factory.createIdentifier(name) + ) + ); + } + function getNamesToExportInCommonJS(decl) { + switch (decl.kind) { + case 261 /* FunctionDeclaration */: + case 262 /* ClassDeclaration */: + return [decl.name.text]; + case 242 /* VariableStatement */: + return mapDefined(decl.declarationList.declarations, (d) => isIdentifier(d.name) ? d.name.text : void 0); + case 266 /* ModuleDeclaration */: + case 265 /* EnumDeclaration */: + case 264 /* TypeAliasDeclaration */: + case 263 /* InterfaceDeclaration */: + case 270 /* ImportEqualsDeclaration */: + return emptyArray; + case 243 /* ExpressionStatement */: + return Debug.fail("Can't export an ExpressionStatement"); + default: + return Debug.assertNever(decl, `Unexpected decl kind ${decl.kind}`); + } + } + function filterImport(i, moduleSpecifier, keep) { + switch (i.kind) { + case 271 /* ImportDeclaration */: { + const clause = i.importClause; + if (!clause) + return void 0; + const defaultImport = clause.name && keep(clause.name) ? clause.name : void 0; + const namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); + return defaultImport || namedBindings ? factory.createImportDeclaration( + /*modifiers*/ + void 0, + factory.createImportClause(clause.isTypeOnly, defaultImport, namedBindings), + getSynthesizedDeepClone(moduleSpecifier), + /*assertClause*/ + void 0 + ) : void 0; + } + case 270 /* ImportEqualsDeclaration */: + return keep(i.name) ? i : void 0; + case 259 /* VariableDeclaration */: { + const name = filterBindingName(i.name, keep); + return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : void 0; + } + default: + return Debug.assertNever(i, `Unexpected import kind ${i.kind}`); + } + } + function filterNamedBindings(namedBindings, keep) { + if (namedBindings.kind === 273 /* NamespaceImport */) { + return keep(namedBindings.name) ? namedBindings : void 0; + } else { + const newElements = namedBindings.elements.filter((e) => keep(e.name)); + return newElements.length ? factory.createNamedImports(newElements) : void 0; + } + } + function filterBindingName(name, keep) { + switch (name.kind) { + case 80 /* Identifier */: + return keep(name) ? name : void 0; + case 206 /* ArrayBindingPattern */: + return name; + case 205 /* ObjectBindingPattern */: { + const newElements = name.elements.filter((prop) => prop.propertyName || !isIdentifier(prop.name) || keep(prop.name)); + return newElements.length ? factory.createObjectBindingPattern(newElements) : void 0; + } + } + } + function nameOfTopLevelDeclaration(d) { + return isExpressionStatement(d) ? tryCast(d.expression.left.name, isIdentifier) : tryCast(d.name, isIdentifier); + } + function getTopLevelDeclarationStatement(d) { + switch (d.kind) { + case 259 /* VariableDeclaration */: + return d.parent.parent; + case 207 /* BindingElement */: + return getTopLevelDeclarationStatement( + cast(d.parent.parent, (p) => isVariableDeclaration(p) || isBindingElement(p)) + ); + default: + return d; + } + } + function addExportToChanges(sourceFile, decl, name, changes, useEs6Exports) { + if (isExported(sourceFile, decl, useEs6Exports, name)) + return; + if (useEs6Exports) { + if (!isExpressionStatement(decl)) + changes.insertExportModifier(sourceFile, decl); + } else { + const names = getNamesToExportInCommonJS(decl); + if (names.length !== 0) + changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); + } + } + function createNewFileName(oldFile, program, context, host) { + const checker = program.getTypeChecker(); + const toMove = getStatementsToMove(context); + let usage; + if (toMove) { + usage = getUsageInfo(oldFile, toMove.all, checker); + 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, + currentDirectory, + host + ) + ) + extension; + return newFileName; + } + return ""; + } + function getRangeToMove(context) { + const { file } = context; + const range = createTextRangeFromSpan(getRefactorContextSpan(context)); + const { statements } = file; + const startNodeIndex = findIndex(statements, (s) => s.end > range.pos); + if (startNodeIndex === -1) + return void 0; + const startStatement = statements[startNodeIndex]; + if (isNamedDeclaration(startStatement) && startStatement.name && rangeContainsRange(startStatement.name, range)) { + return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; + } + if (range.pos > startStatement.getStart(file)) + return void 0; + const afterEndNodeIndex = findIndex(statements, (s) => s.end > range.end, startNodeIndex); + if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) + return void 0; + return { + toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), + afterLast: afterEndNodeIndex === -1 ? void 0 : statements[afterEndNodeIndex] + }; + } + function getStatementsToMove(context) { + const rangeToMove = getRangeToMove(context); + if (rangeToMove === void 0) + return void 0; + const all = []; + const ranges = []; + const { toMove, afterLast } = rangeToMove; + getRangesWhere(toMove, isAllowedStatementToMove, (start, afterEndIndex) => { + for (let i = start; i < afterEndIndex; i++) + all.push(toMove[i]); + ranges.push({ first: toMove[start], afterLast }); + }); + return all.length === 0 ? void 0 : { all, ranges }; + } + function isAllowedStatementToMove(statement) { + return !isPureImport(statement) && !isPrologueDirective(statement); + } + function isPureImport(node) { + switch (node.kind) { + case 271 /* ImportDeclaration */: + return true; + case 270 /* ImportEqualsDeclaration */: + return !hasSyntacticModifier(node, 1 /* Export */); + case 242 /* VariableStatement */: + return node.declarationList.declarations.every((d) => !!d.initializer && isRequireCall( + d.initializer, + /*requireStringLiteralLikeArgument*/ + true + )); + default: + return false; + } + } + function getUsageInfo(oldFile, toMove, checker) { + const movedSymbols = /* @__PURE__ */ new Set(); + const oldImportsNeededByTargetFile = /* @__PURE__ */ new Map(); + const targetFileImportsFromOldFile = /* @__PURE__ */ new Set(); + const containsJsx = find(toMove, (statement) => !!(statement.transformFlags & 2 /* ContainsJsx */)); + const jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx); + if (jsxNamespaceSymbol) { + oldImportsNeededByTargetFile.set(jsxNamespaceSymbol, false); + } + for (const statement of toMove) { + forEachTopLevelDeclaration(statement, (decl) => { + movedSymbols.add(Debug.checkDefined(isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here")); + }); + } + for (const statement of toMove) { + forEachReference(statement, checker, (symbol, isValidTypeOnlyUseSite) => { + if (!symbol.declarations) + return; + for (const decl of symbol.declarations) { + if (isInImport(decl)) { + const prevIsTypeOnly = oldImportsNeededByTargetFile.get(symbol); + oldImportsNeededByTargetFile.set(symbol, prevIsTypeOnly === void 0 ? isValidTypeOnlyUseSite : prevIsTypeOnly && isValidTypeOnlyUseSite); + } else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) { + targetFileImportsFromOldFile.add(symbol); + } + } + }); + } + const unusedImportsFromOldFile = new Set(oldImportsNeededByTargetFile.keys()); + const oldFileImportsFromTargetFile = /* @__PURE__ */ new Set(); + for (const statement of oldFile.statements) { + if (contains(toMove, statement)) + continue; + if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) { + unusedImportsFromOldFile.delete(jsxNamespaceSymbol); + } + forEachReference(statement, checker, (symbol) => { + if (movedSymbols.has(symbol)) + oldFileImportsFromTargetFile.add(symbol); + unusedImportsFromOldFile.delete(symbol); + }); + } + return { movedSymbols, targetFileImportsFromOldFile, oldFileImportsFromTargetFile, oldImportsNeededByTargetFile, unusedImportsFromOldFile }; + function getJsxNamespaceSymbol(containsJsx2) { + if (containsJsx2 === void 0) { + return void 0; + } + const jsxNamespace = checker.getJsxNamespace(containsJsx2); + const jsxNamespaceSymbol2 = checker.resolveName( + jsxNamespace, + containsJsx2, + 1920 /* Namespace */, + /*excludeGlobals*/ + true + ); + return !!jsxNamespaceSymbol2 && some(jsxNamespaceSymbol2.declarations, isInImport) ? jsxNamespaceSymbol2 : void 0; + } + } + function makeUniqueFilename(proposedFilename, extension, inDirectory, host) { + let newFilename = proposedFilename; + for (let i = 1; ; i++) { + const name = combinePaths(inDirectory, newFilename + extension); + if (!host.fileExists(name)) + return newFilename; + newFilename = `${proposedFilename}.${i}`; + } + } + function inferNewFileName(importsFromNewFile, movedSymbols) { + return forEachKey(importsFromNewFile, symbolNameNoDefault) || forEachKey(movedSymbols, symbolNameNoDefault) || "newFile"; + } + function forEachReference(node, checker, onReference) { + node.forEachChild(function cb(node2) { + if (isIdentifier(node2) && !isDeclarationName(node2)) { + const sym = checker.getSymbolAtLocation(node2); + if (sym) + onReference(sym, isValidTypeOnlyAliasUseSite(node2)); + } else { + node2.forEachChild(cb); + } + }); + } + function forEachTopLevelDeclaration(statement, cb) { + switch (statement.kind) { + case 261 /* FunctionDeclaration */: + case 262 /* ClassDeclaration */: + case 266 /* ModuleDeclaration */: + case 265 /* EnumDeclaration */: + case 264 /* TypeAliasDeclaration */: + case 263 /* InterfaceDeclaration */: + case 270 /* ImportEqualsDeclaration */: + return cb(statement); + case 242 /* VariableStatement */: + return firstDefined(statement.declarationList.declarations, (decl) => forEachTopLevelDeclarationInBindingName(decl.name, cb)); + case 243 /* ExpressionStatement */: { + const { expression } = statement; + return isBinaryExpression(expression) && getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : void 0; + } + } + } + function isInImport(decl) { + switch (decl.kind) { + case 270 /* ImportEqualsDeclaration */: + case 275 /* ImportSpecifier */: + case 272 /* ImportClause */: + case 273 /* NamespaceImport */: + return true; + case 259 /* VariableDeclaration */: + return isVariableDeclarationInImport(decl); + case 207 /* BindingElement */: + return isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); + default: + return false; + } + } + function isVariableDeclarationInImport(decl) { + return isSourceFile(decl.parent.parent.parent) && !!decl.initializer && isRequireCall( + decl.initializer, + /*requireStringLiteralLikeArgument*/ + true + ); + } + function isTopLevelDeclaration(node) { + return isNonVariableTopLevelDeclaration(node) && isSourceFile(node.parent) || isVariableDeclaration(node) && isSourceFile(node.parent.parent.parent); + } + function sourceFileOfTopLevelDeclaration(node) { + return isVariableDeclaration(node) ? node.parent.parent.parent : node.parent; + } + function forEachTopLevelDeclarationInBindingName(name, cb) { + switch (name.kind) { + case 80 /* Identifier */: + return cb(cast(name.parent, (x) => isVariableDeclaration(x) || isBindingElement(x))); + case 206 /* ArrayBindingPattern */: + case 205 /* ObjectBindingPattern */: + return firstDefined(name.elements, (em) => isOmittedExpression(em) ? void 0 : forEachTopLevelDeclarationInBindingName(em.name, cb)); + default: + return Debug.assertNever(name, `Unexpected name kind ${name.kind}`); + } + } + function isNonVariableTopLevelDeclaration(node) { + switch (node.kind) { + case 261 /* FunctionDeclaration */: + case 262 /* ClassDeclaration */: + case 266 /* ModuleDeclaration */: + case 265 /* EnumDeclaration */: + case 264 /* TypeAliasDeclaration */: + case 263 /* InterfaceDeclaration */: + case 270 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + var refactorNameForMoveToFile, description2, moveToFileAction; + var init_moveToFile = __esm({ + "src/services/refactors/moveToFile.ts"() { + "use strict"; + init_moduleSpecifiers(); + init_ts4(); + init_refactorProvider(); + refactorNameForMoveToFile = "Move to file"; + description2 = getLocaleSpecificMessage(Diagnostics.Move_to_file); + moveToFileAction = { + name: "Move to file", + description: description2, + kind: "refactor.move.file" + }; + registerRefactor(refactorNameForMoveToFile, { + kinds: [moveToFileAction.kind], + getAvailableActions: function getRefactorActionsToMoveToFile(context, interactiveRefactorArguments) { + const statements = getStatementsToMove(context); + if (!interactiveRefactorArguments) { + return emptyArray; + } + if (context.preferences.allowTextChangesInNewFiles && statements) { + return [{ name: refactorNameForMoveToFile, description: description2, actions: [moveToFileAction] }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorNameForMoveToFile, + description: description2, + actions: [{ ...moveToFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] + }]; + } + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToMoveToFile(context, actionName2, interactiveRefactorArguments) { + Debug.assert(actionName2 === refactorNameForMoveToFile, "Wrong refactor invoked"); + const statements = Debug.checkDefined(getStatementsToMove(context)); + Debug.assert(interactiveRefactorArguments, "No interactive refactor arguments available"); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange4(context, context.file, interactiveRefactorArguments.targetFile, context.program, statements, t, context.host, context.preferences)); + return { edits, renameFilename: void 0, renameLocation: void 0 }; + } + }); + } + }); + + // src/services/refactors/convertOverloadListToSingleSignature.ts + function getRefactorActionsToConvertOverloadsToOneSignature(context) { + const { file, startPosition, program } = context; + const info = getConvertableOverloadListAtPosition(file, startPosition, program); + if (!info) + return emptyArray; + return [{ + name: refactorName5, + description: refactorDescription, + actions: [functionOverloadAction] + }]; + } + function getRefactorEditsToConvertOverloadsToOneSignature(context) { + const { file, startPosition, program } = context; + const signatureDecls = getConvertableOverloadListAtPosition(file, startPosition, program); + if (!signatureDecls) + return void 0; + const checker = program.getTypeChecker(); + const lastDeclaration = signatureDecls[signatureDecls.length - 1]; + let updated = lastDeclaration; + switch (lastDeclaration.kind) { + case 172 /* MethodSignature */: { + updated = factory.updateMethodSignature( + lastDeclaration, + lastDeclaration.modifiers, + lastDeclaration.name, + lastDeclaration.questionToken, + lastDeclaration.typeParameters, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.type + ); + break; + } + case 173 /* MethodDeclaration */: { + updated = factory.updateMethodDeclaration( + lastDeclaration, + lastDeclaration.modifiers, + lastDeclaration.asteriskToken, + lastDeclaration.name, + lastDeclaration.questionToken, + lastDeclaration.typeParameters, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.type, + lastDeclaration.body + ); + break; + } + case 178 /* CallSignature */: { + updated = factory.updateCallSignature( + lastDeclaration, + lastDeclaration.typeParameters, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.type + ); + break; + } + case 175 /* Constructor */: { + updated = factory.updateConstructorDeclaration( + lastDeclaration, + lastDeclaration.modifiers, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.body + ); + break; + } + case 179 /* ConstructSignature */: { + updated = factory.updateConstructSignature( + lastDeclaration, + lastDeclaration.typeParameters, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.type + ); + break; + } + case 261 /* FunctionDeclaration */: { + updated = factory.updateFunctionDeclaration( + lastDeclaration, + lastDeclaration.modifiers, + lastDeclaration.asteriskToken, + lastDeclaration.name, + lastDeclaration.typeParameters, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.type, + lastDeclaration.body + ); + break; + } + default: + return Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring"); + } + if (updated === lastDeclaration) { + return; + } + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => { + t.replaceNodeRange(file, signatureDecls[0], signatureDecls[signatureDecls.length - 1], updated); + }); + return { renameFilename: void 0, renameLocation: void 0, edits }; + function getNewParametersForCombinedSignature(signatureDeclarations) { + const lastSig = signatureDeclarations[signatureDeclarations.length - 1]; + if (isFunctionLikeDeclaration(lastSig) && lastSig.body) { + signatureDeclarations = signatureDeclarations.slice(0, signatureDeclarations.length - 1); + } + return factory.createNodeArray([ + factory.createParameterDeclaration( + /*modifiers*/ + void 0, + factory.createToken(26 /* DotDotDotToken */), + "args", + /*questionToken*/ + void 0, + factory.createUnionTypeNode(map(signatureDeclarations, convertSignatureParametersToTuple)) + ) + ]); + } + function convertSignatureParametersToTuple(decl) { + const members = map(decl.parameters, convertParameterToNamedTupleMember); + return setEmitFlags(factory.createTupleTypeNode(members), some(members, (m) => !!length(getSyntheticLeadingComments(m))) ? 0 /* None */ : 1 /* SingleLine */); + } + function convertParameterToNamedTupleMember(p) { + Debug.assert(isIdentifier(p.name)); + const result = setTextRange(factory.createNamedTupleMember( + p.dotDotDotToken, + p.name, + p.questionToken, + p.type || factory.createKeywordTypeNode(133 /* AnyKeyword */) + ), p); + const parameterDocComment = p.symbol && p.symbol.getDocumentationComment(checker); + if (parameterDocComment) { + const newComment = displayPartsToString(parameterDocComment); + if (newComment.length) { + setSyntheticLeadingComments(result, [{ + text: `* +${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} + `, + kind: 3 /* MultiLineCommentTrivia */, + pos: -1, + end: -1, + hasTrailingNewLine: true, + hasLeadingNewline: true + }]); + } + } + return result; + } + } + function isConvertableSignatureDeclaration(d) { + switch (d.kind) { + case 172 /* MethodSignature */: + case 173 /* MethodDeclaration */: + case 178 /* CallSignature */: + case 175 /* Constructor */: + case 179 /* ConstructSignature */: + case 261 /* FunctionDeclaration */: + return true; + } + return false; + } + function getConvertableOverloadListAtPosition(file, startPosition, program) { + const node = getTokenAtPosition(file, startPosition); + const containingDecl = findAncestor(node, isConvertableSignatureDeclaration); + if (!containingDecl) { + return; + } + if (isFunctionLikeDeclaration(containingDecl) && containingDecl.body && rangeContainsPosition(containingDecl.body, startPosition)) { + return; + } + const checker = program.getTypeChecker(); + const signatureSymbol = containingDecl.symbol; + if (!signatureSymbol) { + return; + } + const decls = signatureSymbol.declarations; + if (length(decls) <= 1) { + return; + } + if (!every(decls, (d) => getSourceFileOfNode(d) === file)) { + return; + } + if (!isConvertableSignatureDeclaration(decls[0])) { + return; + } + const kindOne = decls[0].kind; + if (!every(decls, (d) => d.kind === kindOne)) { + return; + } + const signatureDecls = decls; + if (some(signatureDecls, (d) => !!d.typeParameters || some(d.parameters, (p) => !!p.modifiers || !isIdentifier(p.name)))) { + return; + } + const signatures = mapDefined(signatureDecls, (d) => checker.getSignatureFromDeclaration(d)); + if (length(signatures) !== length(decls)) { + return; + } + const returnOne = checker.getReturnTypeOfSignature(signatures[0]); + if (!every(signatures, (s) => checker.getReturnTypeOfSignature(s) === returnOne)) { + return; + } + return signatureDecls; + } + var refactorName5, refactorDescription, functionOverloadAction; + var init_convertOverloadListToSingleSignature = __esm({ + "src/services/refactors/convertOverloadListToSingleSignature.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName5 = "Convert overload list to single signature"; + refactorDescription = Diagnostics.Convert_overload_list_to_single_signature.message; + functionOverloadAction = { + name: refactorName5, + description: refactorDescription, + kind: "refactor.rewrite.function.overloadList" + }; + registerRefactor(refactorName5, { + kinds: [functionOverloadAction.kind], + getEditsForAction: getRefactorEditsToConvertOverloadsToOneSignature, + getAvailableActions: getRefactorActionsToConvertOverloadsToOneSignature + }); + } + }); + + // src/services/refactors/addOrRemoveBracesToArrowFunction.ts + function getRefactorActionsToRemoveFunctionBraces(context) { + const { file, startPosition, triggerReason } = context; + const info = getConvertibleArrowFunctionAtPosition(file, startPosition, triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + return [{ + name: refactorName6, + description: refactorDescription2, + actions: [ + info.addBraces ? addBracesAction : removeBracesAction + ] + }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorName6, + description: refactorDescription2, + actions: [ + { ...addBracesAction, notApplicableReason: info.error }, + { ...removeBracesAction, notApplicableReason: info.error } + ] + }]; + } + return emptyArray; + } + function getRefactorEditsToRemoveFunctionBraces(context, actionName2) { + const { file, startPosition } = context; + const info = getConvertibleArrowFunctionAtPosition(file, startPosition); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const { expression, returnStatement, func } = info; + let body; + if (actionName2 === addBracesAction.name) { + const returnStatement2 = factory.createReturnStatement(expression); + body = factory.createBlock( + [returnStatement2], + /*multiLine*/ + true + ); + copyLeadingComments( + expression, + returnStatement2, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + true + ); + } else if (actionName2 === removeBracesAction.name && returnStatement) { + const actualExpression = expression || factory.createVoidZero(); + body = needsParentheses(actualExpression) ? factory.createParenthesizedExpression(actualExpression) : actualExpression; + copyTrailingAsLeadingComments( + returnStatement, + body, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + copyLeadingComments( + returnStatement, + body, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + copyTrailingComments( + returnStatement, + body, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + } else { + Debug.fail("invalid action"); + } + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => { + t.replaceNode(file, func.body, body); + }); + return { renameFilename: void 0, renameLocation: void 0, edits }; + } + function getConvertibleArrowFunctionAtPosition(file, startPosition, considerFunctionBodies = true, kind) { + const node = getTokenAtPosition(file, startPosition); + const func = getContainingFunction(node); + if (!func) { + return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_a_containing_arrow_function) + }; + } + if (!isArrowFunction(func)) { + return { + error: getLocaleSpecificMessage(Diagnostics.Containing_function_is_not_an_arrow_function) + }; + } + if (!rangeContainsRange(func, node) || rangeContainsRange(func.body, node) && !considerFunctionBodies) { + return void 0; + } + if (refactorKindBeginsWith(addBracesAction.kind, kind) && isExpression(func.body)) { + return { func, addBraces: true, expression: func.body }; + } else if (refactorKindBeginsWith(removeBracesAction.kind, kind) && isBlock(func.body) && func.body.statements.length === 1) { + const firstStatement = first(func.body.statements); + if (isReturnStatement(firstStatement)) { + return { func, addBraces: false, expression: firstStatement.expression, returnStatement: firstStatement }; + } + } + return void 0; + } + var refactorName6, refactorDescription2, addBracesAction, removeBracesAction; + var init_addOrRemoveBracesToArrowFunction = __esm({ + "src/services/refactors/addOrRemoveBracesToArrowFunction.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName6 = "Add or remove braces in an arrow function"; + refactorDescription2 = Diagnostics.Add_or_remove_braces_in_an_arrow_function.message; + addBracesAction = { + name: "Add braces to arrow function", + description: Diagnostics.Add_braces_to_arrow_function.message, + kind: "refactor.rewrite.arrow.braces.add" + }; + removeBracesAction = { + name: "Remove braces from arrow function", + description: Diagnostics.Remove_braces_from_arrow_function.message, + kind: "refactor.rewrite.arrow.braces.remove" + }; + registerRefactor(refactorName6, { + kinds: [removeBracesAction.kind], + getEditsForAction: getRefactorEditsToRemoveFunctionBraces, + getAvailableActions: getRefactorActionsToRemoveFunctionBraces + }); + } + }); + + // src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts + var ts_refactor_addOrRemoveBracesToArrowFunction_exports = {}; + var init_ts_refactor_addOrRemoveBracesToArrowFunction = __esm({ + "src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts"() { + "use strict"; + init_convertOverloadListToSingleSignature(); + init_addOrRemoveBracesToArrowFunction(); + } + }); + + // src/services/refactors/convertArrowFunctionOrFunctionExpression.ts + function getRefactorActionsToConvertFunctionExpressions(context) { + const { file, startPosition, program, kind } = context; + const info = getFunctionInfo(file, startPosition, program); + if (!info) + return emptyArray; + const { selectedVariableDeclaration, func } = info; + const possibleActions = []; + const errors = []; + if (refactorKindBeginsWith(toNamedFunctionAction.kind, kind)) { + const error = selectedVariableDeclaration || isArrowFunction(func) && isVariableDeclaration(func.parent) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_named_function); + if (error) { + errors.push({ ...toNamedFunctionAction, notApplicableReason: error }); + } else { + possibleActions.push(toNamedFunctionAction); + } + } + if (refactorKindBeginsWith(toAnonymousFunctionAction.kind, kind)) { + const error = !selectedVariableDeclaration && isArrowFunction(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_anonymous_function); + if (error) { + errors.push({ ...toAnonymousFunctionAction, notApplicableReason: error }); + } else { + possibleActions.push(toAnonymousFunctionAction); + } + } + if (refactorKindBeginsWith(toArrowFunctionAction.kind, kind)) { + const error = isFunctionExpression(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_arrow_function); + if (error) { + errors.push({ ...toArrowFunctionAction, notApplicableReason: error }); + } else { + possibleActions.push(toArrowFunctionAction); + } + } + return [{ + name: refactorName7, + description: refactorDescription3, + actions: possibleActions.length === 0 && context.preferences.provideRefactorNotApplicableReason ? errors : possibleActions + }]; + } + function getRefactorEditsToConvertFunctionExpressions(context, actionName2) { + const { file, startPosition, program } = context; + const info = getFunctionInfo(file, startPosition, program); + if (!info) + return void 0; + const { func } = info; + const edits = []; + switch (actionName2) { + case toAnonymousFunctionAction.name: + edits.push(...getEditInfoForConvertToAnonymousFunction(context, func)); + break; + case toNamedFunctionAction.name: + const variableInfo = getVariableInfo(func); + if (!variableInfo) + return void 0; + edits.push(...getEditInfoForConvertToNamedFunction(context, func, variableInfo)); + break; + case toArrowFunctionAction.name: + if (!isFunctionExpression(func)) + return void 0; + edits.push(...getEditInfoForConvertToArrowFunction(context, func)); + break; + default: + return Debug.fail("invalid action"); + } + return { renameFilename: void 0, renameLocation: void 0, edits }; + } + function containingThis(node) { + let containsThis = false; + node.forEachChild(function checkThis(child) { + if (isThis(child)) { + containsThis = true; + return; + } + if (!isClassLike(child) && !isFunctionDeclaration(child) && !isFunctionExpression(child)) { + forEachChild(child, checkThis); + } + }); + return containsThis; + } + function getFunctionInfo(file, startPosition, program) { + const token = getTokenAtPosition(file, startPosition); + const typeChecker = program.getTypeChecker(); + const func = tryGetFunctionFromVariableDeclaration(file, typeChecker, token.parent); + if (func && !containingThis(func.body) && !typeChecker.containsArgumentsReference(func)) { + return { selectedVariableDeclaration: true, func }; + } + const maybeFunc = getContainingFunction(token); + if (maybeFunc && (isFunctionExpression(maybeFunc) || isArrowFunction(maybeFunc)) && !rangeContainsRange(maybeFunc.body, token) && !containingThis(maybeFunc.body) && !typeChecker.containsArgumentsReference(maybeFunc)) { + if (isFunctionExpression(maybeFunc) && isFunctionReferencedInFile(file, typeChecker, maybeFunc)) + return void 0; + return { selectedVariableDeclaration: false, func: maybeFunc }; + } + return void 0; + } + function isSingleVariableDeclaration(parent2) { + return isVariableDeclaration(parent2) || isVariableDeclarationList(parent2) && parent2.declarations.length === 1; + } + function tryGetFunctionFromVariableDeclaration(sourceFile, typeChecker, parent2) { + if (!isSingleVariableDeclaration(parent2)) { + return void 0; + } + const variableDeclaration = isVariableDeclaration(parent2) ? parent2 : first(parent2.declarations); + const initializer = variableDeclaration.initializer; + if (initializer && (isArrowFunction(initializer) || isFunctionExpression(initializer) && !isFunctionReferencedInFile(sourceFile, typeChecker, initializer))) { + return initializer; + } + return void 0; + } + function convertToBlock(body) { + if (isExpression(body)) { + const returnStatement = factory.createReturnStatement(body); + const file = body.getSourceFile(); + setTextRange(returnStatement, body); + suppressLeadingAndTrailingTrivia(returnStatement); + copyTrailingAsLeadingComments( + body, + returnStatement, + file, + /*commentKind*/ + void 0, + /*hasTrailingNewLine*/ + true + ); + return factory.createBlock( + [returnStatement], + /*multiLine*/ + true + ); + } else { + return body; + } + } + function getVariableInfo(func) { + const variableDeclaration = func.parent; + if (!isVariableDeclaration(variableDeclaration) || !isVariableDeclarationInVariableStatement(variableDeclaration)) + return void 0; + const variableDeclarationList = variableDeclaration.parent; + const statement = variableDeclarationList.parent; + if (!isVariableDeclarationList(variableDeclarationList) || !isVariableStatement(statement) || !isIdentifier(variableDeclaration.name)) + return void 0; + return { variableDeclaration, variableDeclarationList, statement, name: variableDeclaration.name }; + } + function getEditInfoForConvertToAnonymousFunction(context, func) { + const { file } = context; + const body = convertToBlock(func.body); + const newNode = factory.createFunctionExpression( + func.modifiers, + func.asteriskToken, + /*name*/ + void 0, + func.typeParameters, + func.parameters, + func.type, + body + ); + return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode)); + } + function getEditInfoForConvertToNamedFunction(context, func, variableInfo) { + const { file } = context; + const body = convertToBlock(func.body); + const { variableDeclaration, variableDeclarationList, statement, name } = variableInfo; + suppressLeadingTrivia(statement); + const modifiersFlags = getCombinedModifierFlags(variableDeclaration) & 1 /* Export */ | getEffectiveModifierFlags(func); + const modifiers = factory.createModifiersFromModifierFlags(modifiersFlags); + const newNode = factory.createFunctionDeclaration(length(modifiers) ? modifiers : void 0, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); + if (variableDeclarationList.declarations.length === 1) { + return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, statement, newNode)); + } else { + return ts_textChanges_exports.ChangeTracker.with(context, (t) => { + t.delete(file, variableDeclaration); + t.insertNodeAfter(file, statement, newNode); + }); + } + } + function getEditInfoForConvertToArrowFunction(context, func) { + const { file } = context; + const statements = func.body.statements; + const head = statements[0]; + let body; + if (canBeConvertedToExpression(func.body, head)) { + body = head.expression; + suppressLeadingAndTrailingTrivia(body); + copyComments(head, body); + } else { + body = func.body; + } + const newNode = factory.createArrowFunction(func.modifiers, func.typeParameters, func.parameters, func.type, factory.createToken(39 /* EqualsGreaterThanToken */), body); + return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode)); + } + function canBeConvertedToExpression(body, head) { + return body.statements.length === 1 && (isReturnStatement(head) && !!head.expression); + } + function isFunctionReferencedInFile(sourceFile, typeChecker, node) { + return !!node.name && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(node.name, typeChecker, sourceFile); + } + var refactorName7, refactorDescription3, toAnonymousFunctionAction, toNamedFunctionAction, toArrowFunctionAction; + var init_convertArrowFunctionOrFunctionExpression = __esm({ + "src/services/refactors/convertArrowFunctionOrFunctionExpression.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName7 = "Convert arrow function or function expression"; + refactorDescription3 = getLocaleSpecificMessage(Diagnostics.Convert_arrow_function_or_function_expression); + toAnonymousFunctionAction = { + name: "Convert to anonymous function", + description: getLocaleSpecificMessage(Diagnostics.Convert_to_anonymous_function), + kind: "refactor.rewrite.function.anonymous" + }; + toNamedFunctionAction = { + name: "Convert to named function", + description: getLocaleSpecificMessage(Diagnostics.Convert_to_named_function), + kind: "refactor.rewrite.function.named" + }; + toArrowFunctionAction = { + name: "Convert to arrow function", + description: getLocaleSpecificMessage(Diagnostics.Convert_to_arrow_function), + kind: "refactor.rewrite.function.arrow" + }; + registerRefactor(refactorName7, { + kinds: [ + toAnonymousFunctionAction.kind, + toNamedFunctionAction.kind, + toArrowFunctionAction.kind + ], + getEditsForAction: getRefactorEditsToConvertFunctionExpressions, + getAvailableActions: getRefactorActionsToConvertFunctionExpressions + }); + } + }); + + // src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts + var ts_refactor_convertArrowFunctionOrFunctionExpression_exports = {}; + var init_ts_refactor_convertArrowFunctionOrFunctionExpression = __esm({ + "src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts"() { + "use strict"; + init_convertArrowFunctionOrFunctionExpression(); + } + }); + + // src/services/refactors/convertParamsToDestructuredObject.ts + function getRefactorActionsToConvertParametersToDestructuredObject(context) { + const { file, startPosition } = context; + const isJSFile = isSourceFileJS(file); + if (isJSFile) + return emptyArray; + const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker()); + if (!functionDeclaration) + return emptyArray; + return [{ + name: refactorName8, + description: refactorDescription4, + actions: [toDestructuredAction] + }]; + } + function getRefactorEditsToConvertParametersToDestructuredObject(context, actionName2) { + Debug.assert(actionName2 === refactorName8, "Unexpected action name"); + const { file, startPosition, program, cancellationToken, host } = context; + const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); + if (!functionDeclaration || !cancellationToken) + return void 0; + const groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken); + if (groupedReferences.valid) { + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange5(file, program, host, t, functionDeclaration, groupedReferences)); + return { renameFilename: void 0, renameLocation: void 0, edits }; + } + return { edits: [] }; + } + function doChange5(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { + const signature = groupedReferences.signature; + const newFunctionDeclarationParams = map(createNewParameters(functionDeclaration, program, host), (param) => getSynthesizedDeepClone(param)); + if (signature) { + const newSignatureParams = map(createNewParameters(signature, program, host), (param) => getSynthesizedDeepClone(param)); + replaceParameters(signature, newSignatureParams); + } + replaceParameters(functionDeclaration, newFunctionDeclarationParams); + const functionCalls = sortAndDeduplicate( + groupedReferences.functionCalls, + /*comparer*/ + (a, b) => compareValues(a.pos, b.pos) + ); + for (const call of functionCalls) { + if (call.arguments && call.arguments.length) { + const newArgument = getSynthesizedDeepClone( + createNewArgument(functionDeclaration, call.arguments), + /*includeTrivia*/ + true + ); + changes.replaceNodeRange( + getSourceFileOfNode(call), + first(call.arguments), + last(call.arguments), + newArgument, + { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include } + ); + } + } + function replaceParameters(declarationOrSignature, parameterDeclarations) { + changes.replaceNodeRangeWithNodes( + sourceFile, + first(declarationOrSignature.parameters), + last(declarationOrSignature.parameters), + parameterDeclarations, + { + joiner: ", ", + // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter + indentation: 0, + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include + } + ); + } + } + function getGroupedReferences(functionDeclaration, program, cancellationToken) { + const functionNames = getFunctionNames(functionDeclaration); + const classNames = isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : []; + const names = deduplicate([...functionNames, ...classNames], equateValues); + const checker = program.getTypeChecker(); + const references = flatMap( + names, + /*mapfn*/ + (name) => ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken) + ); + const groupedReferences = groupReferences(references); + if (!every( + groupedReferences.declarations, + /*callback*/ + (decl) => contains(names, decl) + )) { + groupedReferences.valid = false; + } + return groupedReferences; + function groupReferences(referenceEntries) { + const classReferences = { accessExpressions: [], typeUsages: [] }; + const groupedReferences2 = { functionCalls: [], declarations: [], classReferences, valid: true }; + const functionSymbols = map(functionNames, getSymbolTargetAtLocation); + const classSymbols = map(classNames, getSymbolTargetAtLocation); + const isConstructor = isConstructorDeclaration(functionDeclaration); + const contextualSymbols = map(functionNames, (name) => getSymbolForContextualType(name, checker)); + for (const entry of referenceEntries) { + if (entry.kind === ts_FindAllReferences_exports.EntryKind.Span) { + groupedReferences2.valid = false; + continue; + } + if (contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) { + if (isValidMethodSignature(entry.node.parent)) { + groupedReferences2.signature = entry.node.parent; + continue; + } + const call = entryToFunctionCall(entry); + if (call) { + groupedReferences2.functionCalls.push(call); + continue; + } + } + const contextualSymbol = getSymbolForContextualType(entry.node, checker); + if (contextualSymbol && contains(contextualSymbols, contextualSymbol)) { + const decl = entryToDeclaration(entry); + if (decl) { + groupedReferences2.declarations.push(decl); + continue; + } + } + if (contains(functionSymbols, getSymbolTargetAtLocation(entry.node)) || isNewExpressionTarget(entry.node)) { + const importOrExportReference = entryToImportOrExport(entry); + if (importOrExportReference) { + continue; + } + const decl = entryToDeclaration(entry); + if (decl) { + groupedReferences2.declarations.push(decl); + continue; + } + const call = entryToFunctionCall(entry); + if (call) { + groupedReferences2.functionCalls.push(call); + continue; + } + } + if (isConstructor && contains(classSymbols, getSymbolTargetAtLocation(entry.node))) { + const importOrExportReference = entryToImportOrExport(entry); + if (importOrExportReference) { + continue; + } + const decl = entryToDeclaration(entry); + if (decl) { + groupedReferences2.declarations.push(decl); + continue; + } + const accessExpression = entryToAccessExpression(entry); + if (accessExpression) { + classReferences.accessExpressions.push(accessExpression); + continue; + } + if (isClassDeclaration(functionDeclaration.parent)) { + const type = entryToType(entry); + if (type) { + classReferences.typeUsages.push(type); + continue; + } + } + } + groupedReferences2.valid = false; + } + return groupedReferences2; + } + function getSymbolTargetAtLocation(node) { + const symbol = checker.getSymbolAtLocation(node); + return symbol && getSymbolTarget(symbol, checker); + } + } + function getSymbolForContextualType(node, checker) { + const element = getContainingObjectLiteralElement(node); + if (element) { + const contextualType = checker.getContextualTypeForObjectLiteralElement(element); + const symbol = contextualType == null ? void 0 : contextualType.getSymbol(); + if (symbol && !(getCheckFlags(symbol) & 6 /* Synthetic */)) { + return symbol; + } + } + } + function entryToImportOrExport(entry) { + const node = entry.node; + if (isImportSpecifier(node.parent) || isImportClause(node.parent) || isImportEqualsDeclaration(node.parent) || isNamespaceImport(node.parent)) { + return node; + } + if (isExportSpecifier(node.parent) || isExportAssignment(node.parent)) { + return node; + } + return void 0; + } + function entryToDeclaration(entry) { + if (isDeclaration(entry.node.parent)) { + return entry.node; + } + return void 0; + } + function entryToFunctionCall(entry) { + if (entry.node.parent) { + const functionReference = entry.node; + const parent2 = functionReference.parent; + switch (parent2.kind) { + case 212 /* CallExpression */: + case 213 /* NewExpression */: + const callOrNewExpression = tryCast(parent2, isCallOrNewExpression); + if (callOrNewExpression && callOrNewExpression.expression === functionReference) { + return callOrNewExpression; + } + break; + case 210 /* PropertyAccessExpression */: + const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); + if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { + const callOrNewExpression2 = tryCast(propertyAccessExpression.parent, isCallOrNewExpression); + if (callOrNewExpression2 && callOrNewExpression2.expression === propertyAccessExpression) { + return callOrNewExpression2; + } + } + break; + case 211 /* ElementAccessExpression */: + const elementAccessExpression = tryCast(parent2, isElementAccessExpression); + if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { + const callOrNewExpression2 = tryCast(elementAccessExpression.parent, isCallOrNewExpression); + if (callOrNewExpression2 && callOrNewExpression2.expression === elementAccessExpression) { + return callOrNewExpression2; + } + } + break; + } + } + return void 0; + } + function entryToAccessExpression(entry) { + if (entry.node.parent) { + const reference = entry.node; + const parent2 = reference.parent; + switch (parent2.kind) { + case 210 /* PropertyAccessExpression */: + const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); + if (propertyAccessExpression && propertyAccessExpression.expression === reference) { + return propertyAccessExpression; + } + break; + case 211 /* ElementAccessExpression */: + const elementAccessExpression = tryCast(parent2, isElementAccessExpression); + if (elementAccessExpression && elementAccessExpression.expression === reference) { + return elementAccessExpression; + } + break; + } + } + return void 0; + } + function entryToType(entry) { + const reference = entry.node; + if (getMeaningFromLocation(reference) === 2 /* Type */ || isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) { + return reference; + } + return void 0; + } + function getFunctionDeclarationAtPosition(file, startPosition, checker) { + const node = getTouchingToken(file, startPosition); + const functionDeclaration = getContainingFunctionDeclaration(node); + if (isTopLevelJSDoc(node)) + return void 0; + if (functionDeclaration && isValidFunctionDeclaration(functionDeclaration, checker) && rangeContainsRange(functionDeclaration, node) && !(functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node))) + return functionDeclaration; + return void 0; + } + function isTopLevelJSDoc(node) { + const containingJSDoc = findAncestor(node, isJSDocNode); + if (containingJSDoc) { + const containingNonJSDoc = findAncestor(containingJSDoc, (n) => !isJSDocNode(n)); + return !!containingNonJSDoc && isFunctionLikeDeclaration(containingNonJSDoc); + } + return false; + } + function isValidMethodSignature(node) { + return isMethodSignature(node) && (isInterfaceDeclaration(node.parent) || isTypeLiteralNode(node.parent)); + } + function isValidFunctionDeclaration(functionDeclaration, checker) { + var _a; + if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) + return false; + switch (functionDeclaration.kind) { + case 261 /* FunctionDeclaration */: + return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); + case 173 /* MethodDeclaration */: + if (isObjectLiteralExpression(functionDeclaration.parent)) { + const contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); + return ((_a = contextualSymbol == null ? void 0 : contextualSymbol.declarations) == null ? void 0 : _a.length) === 1 && isSingleImplementation(functionDeclaration, checker); + } + return isSingleImplementation(functionDeclaration, checker); + case 175 /* Constructor */: + if (isClassDeclaration(functionDeclaration.parent)) { + return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker); + } else { + return isValidVariableDeclaration(functionDeclaration.parent.parent) && isSingleImplementation(functionDeclaration, checker); + } + case 217 /* FunctionExpression */: + case 218 /* ArrowFunction */: + return isValidVariableDeclaration(functionDeclaration.parent); + } + return false; + } + function isSingleImplementation(functionDeclaration, checker) { + return !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); + } + function hasNameOrDefault(functionOrClassDeclaration) { + if (!functionOrClassDeclaration.name) { + const defaultKeyword = findModifier(functionOrClassDeclaration, 90 /* DefaultKeyword */); + return !!defaultKeyword; + } + return true; + } + function isValidParameterNodeArray(parameters, checker) { + return getRefactorableParametersLength(parameters) >= minimumParameterLength && every( + parameters, + /*callback*/ + (paramDecl) => isValidParameterDeclaration(paramDecl, checker) + ); + } + function isValidParameterDeclaration(parameterDeclaration, checker) { + if (isRestParameter(parameterDeclaration)) { + const type = checker.getTypeAtLocation(parameterDeclaration); + if (!checker.isArrayType(type) && !checker.isTupleType(type)) + return false; + } + return !parameterDeclaration.modifiers && isIdentifier(parameterDeclaration.name); + } + function isValidVariableDeclaration(node) { + return isVariableDeclaration(node) && isVarConst(node) && isIdentifier(node.name) && !node.type; + } + function hasThisParameter(parameters) { + return parameters.length > 0 && isThis(parameters[0].name); + } + function getRefactorableParametersLength(parameters) { + if (hasThisParameter(parameters)) { + return parameters.length - 1; + } + return parameters.length; + } + function getRefactorableParameters(parameters) { + if (hasThisParameter(parameters)) { + parameters = factory.createNodeArray(parameters.slice(1), parameters.hasTrailingComma); + } + return parameters; + } + function createPropertyOrShorthandAssignment(name, initializer) { + if (isIdentifier(initializer) && getTextOfIdentifierOrLiteral(initializer) === name) { + return factory.createShorthandPropertyAssignment(name); + } + return factory.createPropertyAssignment(name, initializer); + } + function createNewArgument(functionDeclaration, functionArguments) { + const parameters = getRefactorableParameters(functionDeclaration.parameters); + const hasRestParameter2 = isRestParameter(last(parameters)); + const nonRestArguments = hasRestParameter2 ? functionArguments.slice(0, parameters.length - 1) : functionArguments; + const properties = map(nonRestArguments, (arg, i) => { + const parameterName = getParameterName(parameters[i]); + const property = createPropertyOrShorthandAssignment(parameterName, arg); + suppressLeadingAndTrailingTrivia(property.name); + if (isPropertyAssignment(property)) + suppressLeadingAndTrailingTrivia(property.initializer); + copyComments(arg, property); + return property; + }); + if (hasRestParameter2 && functionArguments.length >= parameters.length) { + const restArguments = functionArguments.slice(parameters.length - 1); + const restProperty = factory.createPropertyAssignment(getParameterName(last(parameters)), factory.createArrayLiteralExpression(restArguments)); + properties.push(restProperty); + } + const objectLiteral = factory.createObjectLiteralExpression( + properties, + /*multiLine*/ + false + ); + return objectLiteral; + } + function createNewParameters(functionDeclaration, program, host) { + const checker = program.getTypeChecker(); + const refactorableParameters = getRefactorableParameters(functionDeclaration.parameters); + const bindingElements = map(refactorableParameters, createBindingElementFromParameterDeclaration); + const objectParameterName = factory.createObjectBindingPattern(bindingElements); + const objectParameterType = createParameterTypeNode(refactorableParameters); + let objectInitializer; + if (every(refactorableParameters, isOptionalParameter)) { + objectInitializer = factory.createObjectLiteralExpression(); + } + const objectParameter = factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + objectParameterName, + /*questionToken*/ + void 0, + objectParameterType, + objectInitializer + ); + if (hasThisParameter(functionDeclaration.parameters)) { + const thisParameter = functionDeclaration.parameters[0]; + const newThisParameter = factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + thisParameter.name, + /*questionToken*/ + void 0, + thisParameter.type + ); + suppressLeadingAndTrailingTrivia(newThisParameter.name); + copyComments(thisParameter.name, newThisParameter.name); + if (thisParameter.type) { + suppressLeadingAndTrailingTrivia(newThisParameter.type); + copyComments(thisParameter.type, newThisParameter.type); + } + return factory.createNodeArray([newThisParameter, objectParameter]); + } + return factory.createNodeArray([objectParameter]); + function createBindingElementFromParameterDeclaration(parameterDeclaration) { + const element = factory.createBindingElement( + /*dotDotDotToken*/ + void 0, + /*propertyName*/ + void 0, + getParameterName(parameterDeclaration), + isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? factory.createArrayLiteralExpression() : parameterDeclaration.initializer + ); + suppressLeadingAndTrailingTrivia(element); + if (parameterDeclaration.initializer && element.initializer) { + copyComments(parameterDeclaration.initializer, element.initializer); + } + return element; + } + function createParameterTypeNode(parameters) { + const members = map(parameters, createPropertySignatureFromParameterDeclaration); + const typeNode = addEmitFlags(factory.createTypeLiteralNode(members), 1 /* SingleLine */); + return typeNode; + } + function createPropertySignatureFromParameterDeclaration(parameterDeclaration) { + let parameterType = parameterDeclaration.type; + if (!parameterType && (parameterDeclaration.initializer || isRestParameter(parameterDeclaration))) { + parameterType = getTypeNode3(parameterDeclaration); + } + const propertySignature = factory.createPropertySignature( + /*modifiers*/ + void 0, + getParameterName(parameterDeclaration), + isOptionalParameter(parameterDeclaration) ? factory.createToken(58 /* QuestionToken */) : parameterDeclaration.questionToken, + parameterType + ); + suppressLeadingAndTrailingTrivia(propertySignature); + copyComments(parameterDeclaration.name, propertySignature.name); + if (parameterDeclaration.type && propertySignature.type) { + copyComments(parameterDeclaration.type, propertySignature.type); + } + return propertySignature; + } + function getTypeNode3(node) { + const type = checker.getTypeAtLocation(node); + return getTypeNodeIfAccessible(type, node, program, host); + } + function isOptionalParameter(parameterDeclaration) { + if (isRestParameter(parameterDeclaration)) { + const type = checker.getTypeAtLocation(parameterDeclaration); + return !checker.isTupleType(type); + } + return checker.isOptionalParameter(parameterDeclaration); + } + } + function getParameterName(paramDeclaration) { + return getTextOfIdentifierOrLiteral(paramDeclaration.name); + } + function getClassNames(constructorDeclaration) { + switch (constructorDeclaration.parent.kind) { + case 262 /* ClassDeclaration */: + const classDeclaration = constructorDeclaration.parent; + if (classDeclaration.name) + return [classDeclaration.name]; + const defaultModifier = Debug.checkDefined( + findModifier(classDeclaration, 90 /* DefaultKeyword */), + "Nameless class declaration should be a default export" + ); + return [defaultModifier]; + case 230 /* ClassExpression */: + const classExpression = constructorDeclaration.parent; + const variableDeclaration = constructorDeclaration.parent.parent; + const className = classExpression.name; + if (className) + return [className, variableDeclaration.name]; + return [variableDeclaration.name]; + } + } + function getFunctionNames(functionDeclaration) { + switch (functionDeclaration.kind) { + case 261 /* FunctionDeclaration */: + if (functionDeclaration.name) + return [functionDeclaration.name]; + const defaultModifier = Debug.checkDefined( + findModifier(functionDeclaration, 90 /* DefaultKeyword */), + "Nameless function declaration should be a default export" + ); + return [defaultModifier]; + case 173 /* MethodDeclaration */: + return [functionDeclaration.name]; + case 175 /* Constructor */: + const ctrKeyword = Debug.checkDefined( + findChildOfKind(functionDeclaration, 137 /* ConstructorKeyword */, functionDeclaration.getSourceFile()), + "Constructor declaration should have constructor keyword" + ); + if (functionDeclaration.parent.kind === 230 /* ClassExpression */) { + const variableDeclaration = functionDeclaration.parent.parent; + return [variableDeclaration.name, ctrKeyword]; + } + return [ctrKeyword]; + case 218 /* ArrowFunction */: + return [functionDeclaration.parent.name]; + case 217 /* FunctionExpression */: + if (functionDeclaration.name) + return [functionDeclaration.name, functionDeclaration.parent.name]; + return [functionDeclaration.parent.name]; + default: + return Debug.assertNever(functionDeclaration, `Unexpected function declaration kind ${functionDeclaration.kind}`); + } + } + var refactorName8, minimumParameterLength, refactorDescription4, toDestructuredAction; + var init_convertParamsToDestructuredObject = __esm({ + "src/services/refactors/convertParamsToDestructuredObject.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName8 = "Convert parameters to destructured object"; + minimumParameterLength = 1; + refactorDescription4 = getLocaleSpecificMessage(Diagnostics.Convert_parameters_to_destructured_object); + toDestructuredAction = { + name: refactorName8, + description: refactorDescription4, + kind: "refactor.rewrite.parameters.toDestructured" + }; + registerRefactor(refactorName8, { + kinds: [toDestructuredAction.kind], + getEditsForAction: getRefactorEditsToConvertParametersToDestructuredObject, + getAvailableActions: getRefactorActionsToConvertParametersToDestructuredObject + }); + } + }); + + // src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts + var ts_refactor_convertParamsToDestructuredObject_exports = {}; + var init_ts_refactor_convertParamsToDestructuredObject = __esm({ + "src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts"() { + "use strict"; + init_convertParamsToDestructuredObject(); + } + }); + + // src/services/refactors/convertStringOrTemplateLiteral.ts + function getRefactorActionsToConvertToTemplateString(context) { + const { file, startPosition } = context; + const node = getNodeOrParentOfParentheses(file, startPosition); + const maybeBinary = getParentBinaryExpression(node); + const refactorInfo = { name: refactorName9, description: refactorDescription5, actions: [] }; + if (isBinaryExpression(maybeBinary) && treeToArray(maybeBinary).isValidConcatenation) { + refactorInfo.actions.push(convertStringAction); + return [refactorInfo]; + } else if (context.preferences.provideRefactorNotApplicableReason) { + refactorInfo.actions.push({ + ...convertStringAction, + notApplicableReason: getLocaleSpecificMessage(Diagnostics.Can_only_convert_string_concatenation) + }); + return [refactorInfo]; + } + return emptyArray; + } + function getNodeOrParentOfParentheses(file, startPosition) { + const node = getTokenAtPosition(file, startPosition); + const nestedBinary = getParentBinaryExpression(node); + const isNonStringBinary = !treeToArray(nestedBinary).isValidConcatenation; + if (isNonStringBinary && isParenthesizedExpression(nestedBinary.parent) && isBinaryExpression(nestedBinary.parent.parent)) { + return nestedBinary.parent.parent; + } + return node; + } + function getRefactorEditsToConvertToTemplateString(context, actionName2) { + const { file, startPosition } = context; + const node = getNodeOrParentOfParentheses(file, startPosition); + switch (actionName2) { + case refactorDescription5: + return { edits: getEditsForToTemplateLiteral(context, node) }; + default: + return Debug.fail("invalid action"); + } + } + function getEditsForToTemplateLiteral(context, node) { + const maybeBinary = getParentBinaryExpression(node); + const file = context.file; + const templateLiteral = nodesToTemplate(treeToArray(maybeBinary), file); + const trailingCommentRanges = getTrailingCommentRanges(file.text, maybeBinary.end); + if (trailingCommentRanges) { + const lastComment = trailingCommentRanges[trailingCommentRanges.length - 1]; + const trailingRange = { pos: trailingCommentRanges[0].pos, end: lastComment.end }; + return ts_textChanges_exports.ChangeTracker.with(context, (t) => { + t.deleteRange(file, trailingRange); + t.replaceNode(file, maybeBinary, templateLiteral); + }); + } else { + return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, maybeBinary, templateLiteral)); + } + } + function isNotEqualsOperator(node) { + return node.operatorToken.kind !== 64 /* EqualsToken */; + } + function getParentBinaryExpression(expr) { + const container = findAncestor(expr.parent, (n) => { + switch (n.kind) { + case 210 /* PropertyAccessExpression */: + case 211 /* ElementAccessExpression */: + return false; + case 227 /* TemplateExpression */: + case 225 /* BinaryExpression */: + return !(isBinaryExpression(n.parent) && isNotEqualsOperator(n.parent)); + default: + return "quit"; + } + }); + return container || expr; + } + function treeToArray(current) { + const loop = (current2) => { + if (!isBinaryExpression(current2)) { + return { + nodes: [current2], + operators: [], + validOperators: true, + hasString: isStringLiteral(current2) || isNoSubstitutionTemplateLiteral(current2) + }; + } + const { nodes: nodes2, operators: operators2, hasString: leftHasString, validOperators: leftOperatorValid } = loop(current2.left); + if (!(leftHasString || isStringLiteral(current2.right) || isTemplateExpression(current2.right))) { + return { nodes: [current2], operators: [], hasString: false, validOperators: true }; + } + const currentOperatorValid = current2.operatorToken.kind === 40 /* PlusToken */; + const validOperators2 = leftOperatorValid && currentOperatorValid; + nodes2.push(current2.right); + operators2.push(current2.operatorToken); + return { nodes: nodes2, operators: operators2, hasString: true, validOperators: validOperators2 }; + }; + const { nodes, operators, validOperators, hasString } = loop(current); + return { nodes, operators, isValidConcatenation: validOperators && hasString }; + } + function escapeRawStringForTemplate(s) { + return s.replace(/\\.|[$`]/g, (m) => m[0] === "\\" ? m : "\\" + m); + } + function getRawTextOfTemplate(node) { + const rightShaving = isTemplateHead(node) || isTemplateMiddle(node) ? -2 : -1; + return getTextOfNode(node).slice(1, rightShaving); + } + function concatConsecutiveString(index, nodes) { + const indexes = []; + let text = "", rawText = ""; + while (index < nodes.length) { + const node = nodes[index]; + if (isStringLiteralLike(node)) { + text += node.text; + rawText += escapeRawStringForTemplate(getTextOfNode(node).slice(1, -1)); + indexes.push(index); + index++; + } else if (isTemplateExpression(node)) { + text += node.head.text; + rawText += getRawTextOfTemplate(node.head); + break; + } else { + break; + } + } + return [index, text, rawText, indexes]; + } + function nodesToTemplate({ nodes, operators }, file) { + const copyOperatorComments = copyTrailingOperatorComments(operators, file); + const copyCommentFromStringLiterals = copyCommentFromMultiNode(nodes, file, copyOperatorComments); + const [begin, headText, rawHeadText, headIndexes] = concatConsecutiveString(0, nodes); + if (begin === nodes.length) { + const noSubstitutionTemplateLiteral = factory.createNoSubstitutionTemplateLiteral(headText, rawHeadText); + copyCommentFromStringLiterals(headIndexes, noSubstitutionTemplateLiteral); + return noSubstitutionTemplateLiteral; + } + const templateSpans = []; + const templateHead = factory.createTemplateHead(headText, rawHeadText); + copyCommentFromStringLiterals(headIndexes, templateHead); + for (let i = begin; i < nodes.length; i++) { + const currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); + copyOperatorComments(i, currentNode); + const [newIndex, subsequentText, rawSubsequentText, stringIndexes] = concatConsecutiveString(i + 1, nodes); + i = newIndex - 1; + const isLast = i === nodes.length - 1; + if (isTemplateExpression(currentNode)) { + const spans = map(currentNode.templateSpans, (span, index) => { + copyExpressionComments(span); + 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)); + }); + templateSpans.push(...spans); + } else { + const templatePart = isLast ? factory.createTemplateTail(subsequentText, rawSubsequentText) : factory.createTemplateMiddle(subsequentText, rawSubsequentText); + copyCommentFromStringLiterals(stringIndexes, templatePart); + templateSpans.push(factory.createTemplateSpan(currentNode, templatePart)); + } + } + return factory.createTemplateExpression(templateHead, templateSpans); + } + function copyExpressionComments(node) { + const file = node.getSourceFile(); + copyTrailingComments( + node, + node.expression, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + copyTrailingAsLeadingComments( + node.expression, + node.expression, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + } + function getExpressionFromParenthesesOrExpression(node) { + if (isParenthesizedExpression(node)) { + copyExpressionComments(node); + node = node.expression; + } + return node; + } + var refactorName9, refactorDescription5, convertStringAction, copyTrailingOperatorComments, copyCommentFromMultiNode; + var init_convertStringOrTemplateLiteral = __esm({ + "src/services/refactors/convertStringOrTemplateLiteral.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName9 = "Convert to template string"; + refactorDescription5 = getLocaleSpecificMessage(Diagnostics.Convert_to_template_string); + convertStringAction = { + name: refactorName9, + description: refactorDescription5, + kind: "refactor.rewrite.string" + }; + registerRefactor(refactorName9, { + kinds: [convertStringAction.kind], + getEditsForAction: getRefactorEditsToConvertToTemplateString, + getAvailableActions: getRefactorActionsToConvertToTemplateString + }); + copyTrailingOperatorComments = (operators, file) => (index, targetNode) => { + if (index < operators.length) { + copyTrailingComments( + operators[index], + targetNode, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + } + }; + copyCommentFromMultiNode = (nodes, file, copyOperatorComments) => (indexes, targetNode) => { + while (indexes.length > 0) { + const index = indexes.shift(); + copyTrailingComments( + nodes[index], + targetNode, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + copyOperatorComments(index, targetNode); + } + }; + } + }); + + // src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts + var ts_refactor_convertStringOrTemplateLiteral_exports = {}; + var init_ts_refactor_convertStringOrTemplateLiteral = __esm({ + "src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts"() { + "use strict"; + init_convertStringOrTemplateLiteral(); + } + }); + + // src/services/refactors/convertToOptionalChainExpression.ts + function getRefactorActionsToConvertToOptionalChain(context) { + const info = getInfo3(context, context.triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + return [{ + name: refactorName10, + description: convertToOptionalChainExpressionMessage, + actions: [toOptionalChainAction] + }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorName10, + description: convertToOptionalChainExpressionMessage, + actions: [{ ...toOptionalChainAction, notApplicableReason: info.error }] + }]; + } + return emptyArray; + } + function getRefactorEditsToConvertToOptionalChain(context, actionName2) { + const info = getInfo3(context); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const edits = ts_textChanges_exports.ChangeTracker.with( + context, + (t) => doChange6(context.file, context.program.getTypeChecker(), t, info, actionName2) + ); + return { edits, renameFilename: void 0, renameLocation: void 0 }; + } + function isValidExpression(node) { + return isBinaryExpression(node) || isConditionalExpression(node); + } + function isValidStatement(node) { + return isExpressionStatement(node) || isReturnStatement(node) || isVariableStatement(node); + } + function isValidExpressionOrStatement(node) { + return isValidExpression(node) || isValidStatement(node); + } + function getInfo3(context, considerEmptySpans = true) { + const { file, program } = context; + const span = getRefactorContextSpan(context); + const forEmptySpan = span.length === 0; + if (forEmptySpan && !considerEmptySpans) + return void 0; + const startToken = getTokenAtPosition(file, span.start); + const endToken = findTokenOnLeftOfPosition(file, span.start + span.length); + const adjustedSpan = createTextSpanFromBounds(startToken.pos, endToken && endToken.end >= startToken.pos ? endToken.getEnd() : startToken.getEnd()); + const parent2 = forEmptySpan ? getValidParentNodeOfEmptySpan(startToken) : getValidParentNodeContainingSpan(startToken, adjustedSpan); + const expression = parent2 && isValidExpressionOrStatement(parent2) ? getExpression(parent2) : void 0; + if (!expression) + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; + const checker = program.getTypeChecker(); + return isConditionalExpression(expression) ? getConditionalInfo(expression, checker) : getBinaryInfo(expression); + } + function getConditionalInfo(expression, checker) { + const condition = expression.condition; + const finalExpression = getFinalExpressionInChain(expression.whenTrue); + if (!finalExpression || checker.isNullableType(checker.getTypeAtLocation(finalExpression))) { + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; + } + if ((isPropertyAccessExpression(condition) || isIdentifier(condition)) && getMatchingStart(condition, finalExpression.expression)) { + return { finalExpression, occurrences: [condition], expression }; + } else if (isBinaryExpression(condition)) { + const occurrences = getOccurrencesInExpression(finalExpression.expression, condition); + return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) }; + } + } + function getBinaryInfo(expression) { + if (expression.operatorToken.kind !== 56 /* AmpersandAmpersandToken */) { + return { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_logical_AND_access_chains) }; + } + const finalExpression = getFinalExpressionInChain(expression.right); + if (!finalExpression) + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; + const occurrences = getOccurrencesInExpression(finalExpression.expression, expression.left); + return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) }; + } + function getOccurrencesInExpression(matchTo, expression) { + const occurrences = []; + while (isBinaryExpression(expression) && expression.operatorToken.kind === 56 /* AmpersandAmpersandToken */) { + const match = getMatchingStart(skipParentheses(matchTo), skipParentheses(expression.right)); + if (!match) { + break; + } + occurrences.push(match); + matchTo = match; + expression = expression.left; + } + const finalMatch = getMatchingStart(matchTo, expression); + if (finalMatch) { + occurrences.push(finalMatch); + } + return occurrences.length > 0 ? occurrences : void 0; + } + function getMatchingStart(chain, subchain) { + if (!isIdentifier(subchain) && !isPropertyAccessExpression(subchain) && !isElementAccessExpression(subchain)) { + return void 0; + } + return chainStartsWith(chain, subchain) ? subchain : void 0; + } + function chainStartsWith(chain, subchain) { + while (isCallExpression(chain) || isPropertyAccessExpression(chain) || isElementAccessExpression(chain)) { + if (getTextOfChainNode(chain) === getTextOfChainNode(subchain)) + break; + chain = chain.expression; + } + while (isPropertyAccessExpression(chain) && isPropertyAccessExpression(subchain) || isElementAccessExpression(chain) && isElementAccessExpression(subchain)) { + if (getTextOfChainNode(chain) !== getTextOfChainNode(subchain)) + return false; + chain = chain.expression; + subchain = subchain.expression; + } + return isIdentifier(chain) && isIdentifier(subchain) && chain.getText() === subchain.getText(); + } + function getTextOfChainNode(node) { + if (isIdentifier(node) || isStringOrNumericLiteralLike(node)) { + return node.getText(); + } + if (isPropertyAccessExpression(node)) { + return getTextOfChainNode(node.name); + } + if (isElementAccessExpression(node)) { + return getTextOfChainNode(node.argumentExpression); + } + return void 0; + } + function getValidParentNodeContainingSpan(node, span) { + while (node.parent) { + if (isValidExpressionOrStatement(node) && span.length !== 0 && node.end >= span.start + span.length) { + return node; + } + node = node.parent; + } + return void 0; + } + function getValidParentNodeOfEmptySpan(node) { + while (node.parent) { + if (isValidExpressionOrStatement(node) && !isValidExpressionOrStatement(node.parent)) { + return node; + } + node = node.parent; + } + return void 0; + } + function getExpression(node) { + if (isValidExpression(node)) { + return node; + } + if (isVariableStatement(node)) { + const variable = getSingleVariableOfVariableStatement(node); + const initializer = variable == null ? void 0 : variable.initializer; + return initializer && isValidExpression(initializer) ? initializer : void 0; + } + return node.expression && isValidExpression(node.expression) ? node.expression : void 0; + } + function getFinalExpressionInChain(node) { + node = skipParentheses(node); + if (isBinaryExpression(node)) { + return getFinalExpressionInChain(node.left); + } else if ((isPropertyAccessExpression(node) || isElementAccessExpression(node) || isCallExpression(node)) && !isOptionalChain(node)) { + return node; + } + return void 0; + } + function convertOccurrences(checker, toConvert, occurrences) { + if (isPropertyAccessExpression(toConvert) || isElementAccessExpression(toConvert) || isCallExpression(toConvert)) { + const chain = convertOccurrences(checker, toConvert.expression, occurrences); + const lastOccurrence = occurrences.length > 0 ? occurrences[occurrences.length - 1] : void 0; + const isOccurrence = (lastOccurrence == null ? void 0 : lastOccurrence.getText()) === toConvert.expression.getText(); + if (isOccurrence) + occurrences.pop(); + if (isCallExpression(toConvert)) { + return isOccurrence ? factory.createCallChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.typeArguments, toConvert.arguments) : factory.createCallChain(chain, toConvert.questionDotToken, toConvert.typeArguments, toConvert.arguments); + } else if (isPropertyAccessExpression(toConvert)) { + return isOccurrence ? factory.createPropertyAccessChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.name) : factory.createPropertyAccessChain(chain, toConvert.questionDotToken, toConvert.name); + } else if (isElementAccessExpression(toConvert)) { + return isOccurrence ? factory.createElementAccessChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.argumentExpression) : factory.createElementAccessChain(chain, toConvert.questionDotToken, toConvert.argumentExpression); + } + } + return toConvert; + } + function doChange6(sourceFile, checker, changes, info, _actionName) { + const { finalExpression, occurrences, expression } = info; + const firstOccurrence = occurrences[occurrences.length - 1]; + const convertedChain = convertOccurrences(checker, finalExpression, occurrences); + if (convertedChain && (isPropertyAccessExpression(convertedChain) || isElementAccessExpression(convertedChain) || isCallExpression(convertedChain))) { + if (isBinaryExpression(expression)) { + changes.replaceNodeRange(sourceFile, firstOccurrence, finalExpression, convertedChain); + } else if (isConditionalExpression(expression)) { + changes.replaceNode( + sourceFile, + expression, + factory.createBinaryExpression(convertedChain, factory.createToken(61 /* QuestionQuestionToken */), expression.whenFalse) + ); + } + } + } + var refactorName10, convertToOptionalChainExpressionMessage, toOptionalChainAction; + var init_convertToOptionalChainExpression = __esm({ + "src/services/refactors/convertToOptionalChainExpression.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName10 = "Convert to optional chain expression"; + convertToOptionalChainExpressionMessage = getLocaleSpecificMessage(Diagnostics.Convert_to_optional_chain_expression); + toOptionalChainAction = { + name: refactorName10, + description: convertToOptionalChainExpressionMessage, + kind: "refactor.rewrite.expression.optionalChain" + }; + registerRefactor(refactorName10, { + kinds: [toOptionalChainAction.kind], + getEditsForAction: getRefactorEditsToConvertToOptionalChain, + getAvailableActions: getRefactorActionsToConvertToOptionalChain + }); + } + }); + + // src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts + var ts_refactor_convertToOptionalChainExpression_exports = {}; + var init_ts_refactor_convertToOptionalChainExpression = __esm({ + "src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts"() { + "use strict"; + init_convertToOptionalChainExpression(); + } + }); + + // src/services/refactors/extractSymbol.ts + function getRefactorActionsToExtractSymbol(context) { + const requestedRefactor = context.kind; + const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context), context.triggerReason === "invoked"); + const targetRange = rangeToExtract.targetRange; + if (targetRange === void 0) { + if (!rangeToExtract.errors || rangeToExtract.errors.length === 0 || !context.preferences.provideRefactorNotApplicableReason) { + return emptyArray; + } + const errors = []; + if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { + errors.push({ + name: refactorName11, + description: extractFunctionAction.description, + actions: [{ ...extractFunctionAction, notApplicableReason: getStringError(rangeToExtract.errors) }] + }); + } + if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { + errors.push({ + name: refactorName11, + description: extractConstantAction.description, + actions: [{ ...extractConstantAction, notApplicableReason: getStringError(rangeToExtract.errors) }] + }); + } + return errors; + } + const extractions = getPossibleExtractions(targetRange, context); + if (extractions === void 0) { + return emptyArray; + } + const functionActions = []; + const usedFunctionNames = /* @__PURE__ */ new Map(); + let innermostErrorFunctionAction; + const constantActions = []; + const usedConstantNames = /* @__PURE__ */ new Map(); + let innermostErrorConstantAction; + let i = 0; + for (const { functionExtraction, constantExtraction } of extractions) { + if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { + const description3 = functionExtraction.description; + if (functionExtraction.errors.length === 0) { + if (!usedFunctionNames.has(description3)) { + usedFunctionNames.set(description3, true); + functionActions.push({ + description: description3, + name: `function_scope_${i}`, + kind: extractFunctionAction.kind + }); + } + } else if (!innermostErrorFunctionAction) { + innermostErrorFunctionAction = { + description: description3, + name: `function_scope_${i}`, + notApplicableReason: getStringError(functionExtraction.errors), + kind: extractFunctionAction.kind + }; + } + } + if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { + const description3 = constantExtraction.description; + if (constantExtraction.errors.length === 0) { + if (!usedConstantNames.has(description3)) { + usedConstantNames.set(description3, true); + constantActions.push({ + description: description3, + name: `constant_scope_${i}`, + kind: extractConstantAction.kind + }); + } + } else if (!innermostErrorConstantAction) { + innermostErrorConstantAction = { + description: description3, + name: `constant_scope_${i}`, + notApplicableReason: getStringError(constantExtraction.errors), + kind: extractConstantAction.kind + }; + } + } + i++; + } + const infos = []; + if (functionActions.length) { + infos.push({ + name: refactorName11, + description: getLocaleSpecificMessage(Diagnostics.Extract_function), + actions: functionActions + }); + } else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorFunctionAction) { + infos.push({ + name: refactorName11, + description: getLocaleSpecificMessage(Diagnostics.Extract_function), + actions: [innermostErrorFunctionAction] + }); + } + if (constantActions.length) { + infos.push({ + name: refactorName11, + description: getLocaleSpecificMessage(Diagnostics.Extract_constant), + actions: constantActions + }); + } else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorConstantAction) { + infos.push({ + name: refactorName11, + description: getLocaleSpecificMessage(Diagnostics.Extract_constant), + actions: [innermostErrorConstantAction] + }); + } + return infos.length ? infos : emptyArray; + function getStringError(errors) { + let error = errors[0].messageText; + if (typeof error !== "string") { + error = error.messageText; + } + return error; + } + } + function getRefactorEditsToExtractSymbol(context, actionName2) { + const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context)); + const targetRange = rangeToExtract.targetRange; + const parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName2); + if (parsedFunctionIndexMatch) { + const index = +parsedFunctionIndexMatch[1]; + Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index"); + return getFunctionExtractionAtIndex(targetRange, context, index); + } + const parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName2); + if (parsedConstantIndexMatch) { + const index = +parsedConstantIndexMatch[1]; + Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index"); + return getConstantExtractionAtIndex(targetRange, context, index); + } + Debug.fail("Unrecognized action name"); + } + function getRangeToExtract2(sourceFile, span, invoked = true) { + const { length: length2 } = span; + if (length2 === 0 && !invoked) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractEmpty)] }; + } + const cursorRequest = length2 === 0 && invoked; + const startToken = findFirstNonJsxWhitespaceToken(sourceFile, span.start); + const endToken = findTokenOnLeftOfPosition(sourceFile, textSpanEnd(span)); + const adjustedSpan = startToken && endToken && invoked ? getAdjustedSpanFromNodes(startToken, endToken, sourceFile) : span; + const start = cursorRequest ? getExtractableParent(startToken) : getParentNodeInSpan(startToken, sourceFile, adjustedSpan); + const end = cursorRequest ? start : getParentNodeInSpan(endToken, sourceFile, adjustedSpan); + let rangeFacts = 0 /* None */; + let thisNode; + if (!start || !end) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + } + if (start.flags & 8388608 /* JSDoc */) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractJSDoc)] }; + } + if (start.parent !== end.parent) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + } + if (start !== end) { + if (!isBlockLike(start.parent)) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + } + const statements = []; + for (const statement of start.parent.statements) { + if (statement === start || statements.length) { + const errors2 = checkNode(statement); + if (errors2) { + return { errors: errors2 }; + } + statements.push(statement); + } + if (statement === end) { + break; + } + } + if (!statements.length) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + } + return { targetRange: { range: statements, facts: rangeFacts, thisNode } }; + } + if (isReturnStatement(start) && !start.expression) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + } + const node = refineNode(start); + const errors = checkRootNode(node) || checkNode(node); + if (errors) { + return { errors }; + } + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, thisNode } }; + function refineNode(node2) { + if (isReturnStatement(node2)) { + if (node2.expression) { + return node2.expression; + } + } else if (isVariableStatement(node2) || isVariableDeclarationList(node2)) { + const declarations = isVariableStatement(node2) ? node2.declarationList.declarations : node2.declarations; + let numInitializers = 0; + let lastInitializer; + for (const declaration of declarations) { + if (declaration.initializer) { + numInitializers++; + lastInitializer = declaration.initializer; + } + } + if (numInitializers === 1) { + return lastInitializer; + } + } else if (isVariableDeclaration(node2)) { + if (node2.initializer) { + return node2.initializer; + } + } + return node2; + } + function checkRootNode(node2) { + if (isIdentifier(isExpressionStatement(node2) ? node2.expression : node2)) { + return [createDiagnosticForNode(node2, Messages.cannotExtractIdentifier)]; + } + return void 0; + } + function checkForStaticContext(nodeToCheck, containingClass) { + let current = nodeToCheck; + while (current !== containingClass) { + if (current.kind === 171 /* PropertyDeclaration */) { + if (isStatic(current)) { + rangeFacts |= 32 /* InStaticRegion */; + } + break; + } else if (current.kind === 168 /* Parameter */) { + const ctorOrMethod = getContainingFunction(current); + if (ctorOrMethod.kind === 175 /* Constructor */) { + rangeFacts |= 32 /* InStaticRegion */; + } + break; + } else if (current.kind === 173 /* MethodDeclaration */) { + if (isStatic(current)) { + rangeFacts |= 32 /* InStaticRegion */; + } + } + current = current.parent; + } + } + function checkNode(nodeToCheck) { + let PermittedJumps; + ((PermittedJumps2) => { + PermittedJumps2[PermittedJumps2["None"] = 0] = "None"; + PermittedJumps2[PermittedJumps2["Break"] = 1] = "Break"; + PermittedJumps2[PermittedJumps2["Continue"] = 2] = "Continue"; + PermittedJumps2[PermittedJumps2["Return"] = 4] = "Return"; + })(PermittedJumps || (PermittedJumps = {})); + Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (1)"); + Debug.assert(!positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (2)"); + if (!isStatement(nodeToCheck) && !(isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck)) && !isStringLiteralJsxAttribute(nodeToCheck)) { + return [createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)]; + } + if (nodeToCheck.flags & 16777216 /* Ambient */) { + return [createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)]; + } + const containingClass = getContainingClass(nodeToCheck); + if (containingClass) { + checkForStaticContext(nodeToCheck, containingClass); + } + let errors2; + let permittedJumps = 4 /* Return */; + let seenLabels; + visit(nodeToCheck); + if (rangeFacts & 8 /* UsesThis */) { + const container = getThisContainer( + nodeToCheck, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ); + if (container.kind === 261 /* FunctionDeclaration */ || container.kind === 173 /* MethodDeclaration */ && container.parent.kind === 209 /* ObjectLiteralExpression */ || container.kind === 217 /* FunctionExpression */) { + rangeFacts |= 16 /* UsesThisInFunction */; + } + } + return errors2; + function visit(node2) { + if (errors2) { + return true; + } + if (isDeclaration(node2)) { + const declaringNode = node2.kind === 259 /* VariableDeclaration */ ? node2.parent.parent : node2; + if (hasSyntacticModifier(declaringNode, 1 /* Export */)) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity)); + return true; + } + } + switch (node2.kind) { + case 271 /* ImportDeclaration */: + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractImport)); + return true; + case 276 /* ExportAssignment */: + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity)); + return true; + case 108 /* SuperKeyword */: + if (node2.parent.kind === 212 /* CallExpression */) { + const containingClass2 = getContainingClass(node2); + if (containingClass2 === void 0 || containingClass2.pos < span.start || containingClass2.end >= span.start + span.length) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractSuper)); + return true; + } + } else { + rangeFacts |= 8 /* UsesThis */; + thisNode = node2; + } + break; + case 218 /* ArrowFunction */: + forEachChild(node2, function check(n) { + if (isThis(n)) { + rangeFacts |= 8 /* UsesThis */; + thisNode = node2; + } else if (isClassLike(n) || isFunctionLike(n) && !isArrowFunction(n)) { + return false; + } else { + forEachChild(n, check); + } + }); + case 262 /* ClassDeclaration */: + case 261 /* FunctionDeclaration */: + if (isSourceFile(node2.parent) && node2.parent.externalModuleIndicator === void 0) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.functionWillNotBeVisibleInTheNewScope)); + } + case 230 /* ClassExpression */: + case 217 /* FunctionExpression */: + case 173 /* MethodDeclaration */: + case 175 /* Constructor */: + case 176 /* GetAccessor */: + case 177 /* SetAccessor */: + return false; + } + const savedPermittedJumps = permittedJumps; + switch (node2.kind) { + case 244 /* IfStatement */: + permittedJumps &= ~4 /* Return */; + break; + case 257 /* TryStatement */: + permittedJumps = 0 /* None */; + break; + case 240 /* Block */: + if (node2.parent && node2.parent.kind === 257 /* TryStatement */ && node2.parent.finallyBlock === node2) { + permittedJumps = 4 /* Return */; + } + break; + case 296 /* DefaultClause */: + case 295 /* CaseClause */: + permittedJumps |= 1 /* Break */; + break; + default: + if (isIterationStatement( + node2, + /*lookInLabeledStatements*/ + false + )) { + permittedJumps |= 1 /* Break */ | 2 /* Continue */; + } + break; + } + switch (node2.kind) { + case 196 /* ThisType */: + case 110 /* ThisKeyword */: + rangeFacts |= 8 /* UsesThis */; + thisNode = node2; + break; + case 255 /* LabeledStatement */: { + const label = node2.label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + forEachChild(node2, visit); + seenLabels.pop(); + break; + } + case 251 /* BreakStatement */: + case 250 /* ContinueStatement */: { + const label = node2.label; + if (label) { + if (!contains(seenLabels, label.escapedText)) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); + } + } else { + if (!(permittedJumps & (node2.kind === 251 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); + } + } + break; + } + case 222 /* AwaitExpression */: + rangeFacts |= 4 /* IsAsyncFunction */; + break; + case 228 /* YieldExpression */: + rangeFacts |= 2 /* IsGenerator */; + break; + case 252 /* ReturnStatement */: + if (permittedJumps & 4 /* Return */) { + rangeFacts |= 1 /* HasReturn */; + } else { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalReturnStatement)); + } + break; + default: + forEachChild(node2, visit); + break; + } + permittedJumps = savedPermittedJumps; + } + } + } + function getAdjustedSpanFromNodes(startNode2, endNode2, sourceFile) { + const start = startNode2.getStart(sourceFile); + let end = endNode2.getEnd(); + if (sourceFile.text.charCodeAt(end) === 59 /* semicolon */) { + end++; + } + return { start, length: end - start }; + } + function getStatementOrExpressionRange(node) { + if (isStatement(node)) { + return [node]; + } + if (isExpressionNode(node)) { + return isExpressionStatement(node.parent) ? [node.parent] : node; + } + if (isStringLiteralJsxAttribute(node)) { + return node; + } + return void 0; + } + function isScope(node) { + return isArrowFunction(node) ? isFunctionBody(node.body) : isFunctionLikeDeclaration(node) || isSourceFile(node) || isModuleBlock(node) || isClassLike(node); + } + function collectEnclosingScopes(range) { + let current = isReadonlyArray(range.range) ? first(range.range) : range.range; + if (range.facts & 8 /* UsesThis */ && !(range.facts & 16 /* UsesThisInFunction */)) { + const containingClass = getContainingClass(current); + if (containingClass) { + const containingFunction = findAncestor(current, isFunctionLikeDeclaration); + return containingFunction ? [containingFunction, containingClass] : [containingClass]; + } + } + const scopes = []; + while (true) { + current = current.parent; + if (current.kind === 168 /* Parameter */) { + current = findAncestor(current, (parent2) => isFunctionLikeDeclaration(parent2)).parent; + } + if (isScope(current)) { + scopes.push(current); + if (current.kind === 311 /* SourceFile */) { + return scopes; + } + } + } + } + function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { + const { scopes, readsAndWrites: { target, usagesPerScope, functionErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); + Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + context.cancellationToken.throwIfCancellationRequested(); + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); + } + function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { + const { scopes, readsAndWrites: { target, usagesPerScope, constantErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); + Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); + context.cancellationToken.throwIfCancellationRequested(); + const expression = isExpression(target) ? target : target.statements[0].expression; + return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context); + } + function getPossibleExtractions(targetRange, context) { + const { scopes, readsAndWrites: { functionErrorsPerScope, constantErrorsPerScope } } = getPossibleExtractionsWorker(targetRange, context); + const extractions = scopes.map((scope, i) => { + const functionDescriptionPart = getDescriptionForFunctionInScope(scope); + const constantDescriptionPart = getDescriptionForConstantInScope(scope); + const scopeDescription = isFunctionLikeDeclaration(scope) ? getDescriptionForFunctionLikeDeclaration(scope) : isClassLike(scope) ? getDescriptionForClassLikeDeclaration(scope) : getDescriptionForModuleLikeDeclaration(scope); + let functionDescription; + let constantDescription; + if (scopeDescription === 1 /* Global */) { + functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]); + constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]); + } else if (scopeDescription === 0 /* Module */) { + functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]); + constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]); + } else { + functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]); + constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]); + } + if (i === 0 && !isClassLike(scope)) { + constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]); + } + return { + functionExtraction: { + description: functionDescription, + errors: functionErrorsPerScope[i] + }, + constantExtraction: { + description: constantDescription, + errors: constantErrorsPerScope[i] + } + }; + }); + return extractions; + } + function getPossibleExtractionsWorker(targetRange, context) { + const { file: sourceFile } = context; + const scopes = collectEnclosingScopes(targetRange); + const enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); + const readsAndWrites = collectReadsAndWrites( + targetRange, + scopes, + enclosingTextRange, + sourceFile, + context.program.getTypeChecker(), + context.cancellationToken + ); + return { scopes, readsAndWrites }; + } + function getDescriptionForFunctionInScope(scope) { + return isFunctionLikeDeclaration(scope) ? "inner function" : isClassLike(scope) ? "method" : "function"; + } + function getDescriptionForConstantInScope(scope) { + return isClassLike(scope) ? "readonly field" : "constant"; + } + function getDescriptionForFunctionLikeDeclaration(scope) { + switch (scope.kind) { + case 175 /* Constructor */: + return "constructor"; + case 217 /* FunctionExpression */: + case 261 /* FunctionDeclaration */: + return scope.name ? `function '${scope.name.text}'` : ANONYMOUS; + case 218 /* ArrowFunction */: + return "arrow function"; + case 173 /* MethodDeclaration */: + return `method '${scope.name.getText()}'`; + case 176 /* GetAccessor */: + return `'get ${scope.name.getText()}'`; + case 177 /* SetAccessor */: + return `'set ${scope.name.getText()}'`; + default: + Debug.assertNever(scope, `Unexpected scope kind ${scope.kind}`); + } + } + function getDescriptionForClassLikeDeclaration(scope) { + return scope.kind === 262 /* ClassDeclaration */ ? scope.name ? `class '${scope.name.text}'` : "anonymous class declaration" : scope.name ? `class expression '${scope.name.text}'` : "anonymous class expression"; + } + function getDescriptionForModuleLikeDeclaration(scope) { + return scope.kind === 267 /* ModuleBlock */ ? `namespace '${scope.parent.name.getText()}'` : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; + } + function extractFunctionInScope(node, scope, { usages: usagesInScope, typeParameterUsages, substitutions }, exposedVariableDeclarations, range, context) { + const checker = context.program.getTypeChecker(); + const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); + const importAdder = ts_codefix_exports.createImportAdder(context.file, context.program, context.preferences, context.host); + const file = scope.getSourceFile(); + const functionNameText = getUniqueName(isClassLike(scope) ? "newMethod" : "newFunction", file); + const isJS = isInJSFile(scope); + const functionName = factory.createIdentifier(functionNameText); + let returnType; + const parameters = []; + const callArguments = []; + let writes; + usagesInScope.forEach((usage, name) => { + let typeNode; + if (!isJS) { + let type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); + type = checker.getBaseTypeOfLiteralType(type); + typeNode = ts_codefix_exports.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */); + } + const paramDecl = factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + /*name*/ + name, + /*questionToken*/ + void 0, + typeNode + ); + parameters.push(paramDecl); + if (usage.usage === 2 /* Write */) { + (writes || (writes = [])).push(usage); + } + callArguments.push(factory.createIdentifier(name)); + }); + const typeParametersAndDeclarations = arrayFrom(typeParameterUsages.values(), (type) => ({ type, declaration: getFirstDeclarationBeforePosition(type, context.startPosition) })); + const sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); + const typeParameters = sortedTypeParametersAndDeclarations.length === 0 ? void 0 : mapDefined(sortedTypeParametersAndDeclarations, ({ declaration }) => declaration); + const callTypeArguments = typeParameters !== void 0 ? typeParameters.map((decl) => factory.createTypeReferenceNode( + decl.name, + /*typeArguments*/ + void 0 + )) : void 0; + if (isExpression(node) && !isJS) { + const contextualType = checker.getContextualType(node); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); + } + const { body, returnValueProperty } = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & 1 /* HasReturn */)); + suppressLeadingAndTrailingTrivia(body); + let newFunction; + const callThis = !!(range.facts & 16 /* UsesThisInFunction */); + if (isClassLike(scope)) { + const modifiers = isJS ? [] : [factory.createModifier(123 /* PrivateKeyword */)]; + if (range.facts & 32 /* InStaticRegion */) { + modifiers.push(factory.createModifier(126 /* StaticKeyword */)); + } + if (range.facts & 4 /* IsAsyncFunction */) { + modifiers.push(factory.createModifier(134 /* AsyncKeyword */)); + } + newFunction = factory.createMethodDeclaration( + modifiers.length ? modifiers : void 0, + range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0, + functionName, + /*questionToken*/ + void 0, + typeParameters, + parameters, + returnType, + body + ); + } else { + if (callThis) { + parameters.unshift( + factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + /*name*/ + "this", + /*questionToken*/ + void 0, + checker.typeToTypeNode( + checker.getTypeAtLocation(range.thisNode), + scope, + 1 /* NoTruncation */ + ), + /*initializer*/ + void 0 + ) + ); + } + newFunction = factory.createFunctionDeclaration( + range.facts & 4 /* IsAsyncFunction */ ? [factory.createToken(134 /* AsyncKeyword */)] : void 0, + range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0, + functionName, + typeParameters, + parameters, + returnType, + body + ); + } + const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); + const minInsertionPos = (isReadonlyArray(range.range) ? last(range.range) : range.range).end; + const nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); + if (nodeToInsertBefore) { + changeTracker.insertNodeBefore( + context.file, + nodeToInsertBefore, + newFunction, + /*blankLineBetween*/ + true + ); + } else { + changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); + } + importAdder.writeFixes(changeTracker); + const newNodes = []; + const called = getCalledExpression(scope, range, functionNameText); + if (callThis) { + callArguments.unshift(factory.createIdentifier("this")); + } + let call = factory.createCallExpression( + callThis ? factory.createPropertyAccessExpression( + called, + "call" + ) : called, + callTypeArguments, + // Note that no attempt is made to take advantage of type argument inference + callArguments + ); + if (range.facts & 2 /* IsGenerator */) { + call = factory.createYieldExpression(factory.createToken(42 /* AsteriskToken */), call); + } + if (range.facts & 4 /* IsAsyncFunction */) { + call = factory.createAwaitExpression(call); + } + if (isInJSXContent(node)) { + call = factory.createJsxExpression( + /*dotDotDotToken*/ + void 0, + call + ); + } + if (exposedVariableDeclarations.length && !writes) { + Debug.assert(!returnValueProperty, "Expected no returnValueProperty"); + Debug.assert(!(range.facts & 1 /* HasReturn */), "Expected RangeFacts.HasReturn flag to be unset"); + if (exposedVariableDeclarations.length === 1) { + const variableDeclaration = exposedVariableDeclarations[0]; + newNodes.push(factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + getSynthesizedDeepClone(variableDeclaration.name), + /*exclamationToken*/ + void 0, + /*type*/ + getSynthesizedDeepClone(variableDeclaration.type), + /*initializer*/ + call + )], + variableDeclaration.parent.flags + ) + )); + } else { + const bindingElements = []; + const typeElements = []; + let commonNodeFlags = exposedVariableDeclarations[0].parent.flags; + let sawExplicitType = false; + for (const variableDeclaration of exposedVariableDeclarations) { + bindingElements.push(factory.createBindingElement( + /*dotDotDotToken*/ + void 0, + /*propertyName*/ + void 0, + /*name*/ + getSynthesizedDeepClone(variableDeclaration.name) + )); + const variableType = checker.typeToTypeNode( + checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), + scope, + 1 /* NoTruncation */ + ); + typeElements.push(factory.createPropertySignature( + /*modifiers*/ + void 0, + /*name*/ + variableDeclaration.symbol.name, + /*questionToken*/ + void 0, + /*type*/ + variableType + )); + sawExplicitType = sawExplicitType || variableDeclaration.type !== void 0; + commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; + } + const typeLiteral = sawExplicitType ? factory.createTypeLiteralNode(typeElements) : void 0; + if (typeLiteral) { + setEmitFlags(typeLiteral, 1 /* SingleLine */); + } + newNodes.push(factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + factory.createObjectBindingPattern(bindingElements), + /*exclamationToken*/ + void 0, + /*type*/ + typeLiteral, + /*initializer*/ + call + )], + commonNodeFlags + ) + )); + } + } else if (exposedVariableDeclarations.length || writes) { + if (exposedVariableDeclarations.length) { + for (const variableDeclaration of exposedVariableDeclarations) { + let flags = variableDeclaration.parent.flags; + if (flags & 2 /* Const */) { + flags = flags & ~2 /* Const */ | 1 /* Let */; + } + newNodes.push(factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + variableDeclaration.symbol.name, + /*exclamationToken*/ + void 0, + getTypeDeepCloneUnionUndefined(variableDeclaration.type) + )], + flags + ) + )); + } + } + if (returnValueProperty) { + newNodes.push(factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + returnValueProperty, + /*exclamationToken*/ + void 0, + getTypeDeepCloneUnionUndefined(returnType) + )], + 1 /* Let */ + ) + )); + } + const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (returnValueProperty) { + assignments.unshift(factory.createShorthandPropertyAssignment(returnValueProperty)); + } + if (assignments.length === 1) { + Debug.assert(!returnValueProperty, "Shouldn't have returnValueProperty here"); + newNodes.push(factory.createExpressionStatement(factory.createAssignment(assignments[0].name, call))); + if (range.facts & 1 /* HasReturn */) { + newNodes.push(factory.createReturnStatement()); + } + } else { + newNodes.push(factory.createExpressionStatement(factory.createAssignment(factory.createObjectLiteralExpression(assignments), call))); + if (returnValueProperty) { + newNodes.push(factory.createReturnStatement(factory.createIdentifier(returnValueProperty))); + } + } + } else { + if (range.facts & 1 /* HasReturn */) { + newNodes.push(factory.createReturnStatement(call)); + } else if (isReadonlyArray(range.range)) { + newNodes.push(factory.createExpressionStatement(call)); + } else { + newNodes.push(call); + } + } + if (isReadonlyArray(range.range)) { + changeTracker.replaceNodeRangeWithNodes(context.file, first(range.range), last(range.range), newNodes); + } else { + changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes); + } + const edits = changeTracker.getChanges(); + const renameRange = isReadonlyArray(range.range) ? first(range.range) : range.range; + const renameFilename = renameRange.getSourceFile().fileName; + const renameLocation = getRenameLocation( + edits, + renameFilename, + functionNameText, + /*preferLastLocation*/ + false + ); + return { renameFilename, renameLocation, edits }; + function getTypeDeepCloneUnionUndefined(typeNode) { + if (typeNode === void 0) { + return void 0; + } + const clone2 = getSynthesizedDeepClone(typeNode); + let withoutParens = clone2; + while (isParenthesizedTypeNode(withoutParens)) { + withoutParens = withoutParens.type; + } + return isUnionTypeNode(withoutParens) && find(withoutParens.types, (t) => t.kind === 157 /* UndefinedKeyword */) ? clone2 : factory.createUnionTypeNode([clone2, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); + } + } + function extractConstantInScope(node, scope, { substitutions }, rangeFacts, context) { + const checker = context.program.getTypeChecker(); + const file = scope.getSourceFile(); + const localNameText = isPropertyAccessExpression(node) && !isClassLike(scope) && !checker.resolveName( + node.name.text, + node, + 111551 /* Value */, + /*excludeGlobals*/ + false + ) && !isPrivateIdentifier(node.name) && !identifierToKeywordKind(node.name) ? node.name.text : getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file); + const isJS = isInJSFile(scope); + let variableType = isJS || !checker.isContextSensitive(node) ? void 0 : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); + let initializer = transformConstantInitializer(skipParentheses(node), substitutions); + ({ variableType, initializer } = transformFunctionInitializerAndType(variableType, initializer)); + suppressLeadingAndTrailingTrivia(initializer); + const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); + if (isClassLike(scope)) { + Debug.assert(!isJS, "Cannot extract to a JS class"); + const modifiers = []; + modifiers.push(factory.createModifier(123 /* PrivateKeyword */)); + if (rangeFacts & 32 /* InStaticRegion */) { + modifiers.push(factory.createModifier(126 /* StaticKeyword */)); + } + modifiers.push(factory.createModifier(148 /* ReadonlyKeyword */)); + const newVariable = factory.createPropertyDeclaration( + modifiers, + localNameText, + /*questionOrExclamationToken*/ + void 0, + variableType, + initializer + ); + let localReference = factory.createPropertyAccessExpression( + rangeFacts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.getText()) : factory.createThis(), + factory.createIdentifier(localNameText) + ); + if (isInJSXContent(node)) { + localReference = factory.createJsxExpression( + /*dotDotDotToken*/ + void 0, + localReference + ); + } + const maxInsertionPos = node.pos; + const nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); + changeTracker.insertNodeBefore( + context.file, + nodeToInsertBefore, + newVariable, + /*blankLineBetween*/ + true + ); + changeTracker.replaceNode(context.file, node, localReference); + } else { + const newVariableDeclaration = factory.createVariableDeclaration( + localNameText, + /*exclamationToken*/ + void 0, + variableType, + initializer + ); + const oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); + if (oldVariableDeclaration) { + changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); + const localReference = factory.createIdentifier(localNameText); + changeTracker.replaceNode(context.file, node, localReference); + } else if (node.parent.kind === 243 /* ExpressionStatement */ && scope === findAncestor(node, isScope)) { + const newVariableStatement = factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */) + ); + changeTracker.replaceNode(context.file, node.parent, newVariableStatement); + } else { + const newVariableStatement = factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */) + ); + const nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); + if (nodeToInsertBefore.pos === 0) { + changeTracker.insertNodeAtTopOfFile( + context.file, + newVariableStatement, + /*blankLineBetween*/ + false + ); + } else { + changeTracker.insertNodeBefore( + context.file, + nodeToInsertBefore, + newVariableStatement, + /*blankLineBetween*/ + false + ); + } + if (node.parent.kind === 243 /* ExpressionStatement */) { + changeTracker.delete(context.file, node.parent); + } else { + let localReference = factory.createIdentifier(localNameText); + if (isInJSXContent(node)) { + localReference = factory.createJsxExpression( + /*dotDotDotToken*/ + void 0, + localReference + ); + } + changeTracker.replaceNode(context.file, node, localReference); + } + } + } + const edits = changeTracker.getChanges(); + const renameFilename = node.getSourceFile().fileName; + const renameLocation = getRenameLocation( + edits, + renameFilename, + localNameText, + /*preferLastLocation*/ + true + ); + return { renameFilename, renameLocation, edits }; + function transformFunctionInitializerAndType(variableType2, initializer2) { + if (variableType2 === void 0) + return { variableType: variableType2, initializer: initializer2 }; + if (!isFunctionExpression(initializer2) && !isArrowFunction(initializer2) || !!initializer2.typeParameters) + return { variableType: variableType2, initializer: initializer2 }; + const functionType = checker.getTypeAtLocation(node); + const functionSignature = singleOrUndefined(checker.getSignaturesOfType(functionType, 0 /* Call */)); + if (!functionSignature) + return { variableType: variableType2, initializer: initializer2 }; + if (!!functionSignature.getTypeParameters()) + return { variableType: variableType2, initializer: initializer2 }; + const parameters = []; + let hasAny = false; + for (const p of initializer2.parameters) { + if (p.type) { + parameters.push(p); + } else { + 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, 1 /* NoTruncation */), + p.initializer + )); + } + } + if (hasAny) + return { variableType: variableType2, initializer: initializer2 }; + variableType2 = void 0; + if (isArrowFunction(initializer2)) { + initializer2 = factory.updateArrowFunction( + initializer2, + canHaveModifiers(node) ? getModifiers(node) : void 0, + initializer2.typeParameters, + parameters, + initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), + initializer2.equalsGreaterThanToken, + initializer2.body + ); + } else { + if (functionSignature && !!functionSignature.thisParameter) { + const firstParameter = firstOrUndefined(parameters); + if (!firstParameter || isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this") { + const thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node); + parameters.splice(0, 0, factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "this", + /*questionToken*/ + void 0, + checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */) + )); + } + } + initializer2 = factory.updateFunctionExpression( + initializer2, + canHaveModifiers(node) ? getModifiers(node) : void 0, + initializer2.asteriskToken, + initializer2.name, + initializer2.typeParameters, + parameters, + initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), + initializer2.body + ); + } + return { variableType: variableType2, initializer: initializer2 }; + } + } + function getContainingVariableDeclarationIfInList(node, scope) { + let prevNode; + while (node !== void 0 && node !== scope) { + if (isVariableDeclaration(node) && node.initializer === prevNode && isVariableDeclarationList(node.parent) && node.parent.declarations.length > 1) { + return node; + } + prevNode = node; + node = node.parent; + } + } + function getFirstDeclarationBeforePosition(type, position) { + let firstDeclaration; + const symbol = type.symbol; + if (symbol && symbol.declarations) { + for (const declaration of symbol.declarations) { + if ((firstDeclaration === void 0 || declaration.pos < firstDeclaration.pos) && declaration.pos < position) { + firstDeclaration = declaration; + } + } + } + return firstDeclaration; + } + function compareTypesByDeclarationOrder({ type: type1, declaration: declaration1 }, { type: type2, declaration: declaration2 }) { + return compareProperties(declaration1, declaration2, "pos", compareValues) || compareStringsCaseSensitive( + type1.symbol ? type1.symbol.getName() : "", + type2.symbol ? type2.symbol.getName() : "" + ) || compareValues(type1.id, type2.id); + } + function getCalledExpression(scope, range, functionNameText) { + const functionReference = factory.createIdentifier(functionNameText); + if (isClassLike(scope)) { + const lhs = range.facts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.text) : factory.createThis(); + return factory.createPropertyAccessExpression(lhs, functionReference); + } else { + return functionReference; + } + } + function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn2) { + const hasWritesOrVariableDeclarations = writes !== void 0 || exposedVariableDeclarations.length > 0; + if (isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { + return { body: factory.createBlock( + body.statements, + /*multiLine*/ + true + ), returnValueProperty: void 0 }; + } + let returnValueProperty; + let ignoreReturns = false; + const statements = factory.createNodeArray(isBlock(body) ? body.statements.slice(0) : [isStatement(body) ? body : factory.createReturnStatement(skipParentheses(body))]); + if (hasWritesOrVariableDeclarations || substitutions.size) { + const rewrittenStatements = visitNodes2(statements, visitor, isStatement).slice(); + if (hasWritesOrVariableDeclarations && !hasReturn2 && isStatement(body)) { + const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (assignments.length === 1) { + rewrittenStatements.push(factory.createReturnStatement(assignments[0].name)); + } else { + rewrittenStatements.push(factory.createReturnStatement(factory.createObjectLiteralExpression(assignments))); + } + } + return { body: factory.createBlock( + rewrittenStatements, + /*multiLine*/ + true + ), returnValueProperty }; + } else { + return { body: factory.createBlock( + statements, + /*multiLine*/ + true + ), returnValueProperty: void 0 }; + } + function visitor(node) { + if (!ignoreReturns && isReturnStatement(node) && hasWritesOrVariableDeclarations) { + const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (node.expression) { + if (!returnValueProperty) { + returnValueProperty = "__return"; + } + assignments.unshift(factory.createPropertyAssignment(returnValueProperty, visitNode(node.expression, visitor, isExpression))); + } + if (assignments.length === 1) { + return factory.createReturnStatement(assignments[0].name); + } else { + return factory.createReturnStatement(factory.createObjectLiteralExpression(assignments)); + } + } else { + const oldIgnoreReturns = ignoreReturns; + ignoreReturns = ignoreReturns || isFunctionLikeDeclaration(node) || isClassLike(node); + const substitution = substitutions.get(getNodeId(node).toString()); + const result = substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext); + ignoreReturns = oldIgnoreReturns; + return result; + } + } + } + function transformConstantInitializer(initializer, substitutions) { + return substitutions.size ? visitor(initializer) : initializer; + function visitor(node) { + const substitution = substitutions.get(getNodeId(node).toString()); + return substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext); + } + } + function getStatementsOrClassElements(scope) { + if (isFunctionLikeDeclaration(scope)) { + const body = scope.body; + if (isBlock(body)) { + return body.statements; + } + } else if (isModuleBlock(scope) || isSourceFile(scope)) { + return scope.statements; + } else if (isClassLike(scope)) { + return scope.members; + } else { + assertType(scope); + } + return emptyArray; + } + function getNodeToInsertFunctionBefore(minPos, scope) { + return find(getStatementsOrClassElements(scope), (child) => child.pos >= minPos && isFunctionLikeDeclaration(child) && !isConstructorDeclaration(child)); + } + function getNodeToInsertPropertyBefore(maxPos, scope) { + const members = scope.members; + Debug.assert(members.length > 0, "Found no members"); + let prevMember; + let allProperties = true; + for (const member of members) { + if (member.pos > maxPos) { + return prevMember || members[0]; + } + if (allProperties && !isPropertyDeclaration(member)) { + if (prevMember !== void 0) { + return member; + } + allProperties = false; + } + prevMember = member; + } + if (prevMember === void 0) + return Debug.fail(); + return prevMember; + } + function getNodeToInsertConstantBefore(node, scope) { + Debug.assert(!isClassLike(scope)); + let prevScope; + for (let curr = node; curr !== scope; curr = curr.parent) { + if (isScope(curr)) { + prevScope = curr; + } + } + for (let curr = (prevScope || node).parent; ; curr = curr.parent) { + if (isBlockLike(curr)) { + let prevStatement; + for (const statement of curr.statements) { + if (statement.pos > node.pos) { + break; + } + prevStatement = statement; + } + if (!prevStatement && isCaseClause(curr)) { + Debug.assert(isSwitchStatement(curr.parent.parent), "Grandparent isn't a switch statement"); + return curr.parent.parent; + } + return Debug.checkDefined(prevStatement, "prevStatement failed to get set"); + } + Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); + } + } + function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { + const variableAssignments = map(exposedVariableDeclarations, (v) => factory.createShorthandPropertyAssignment(v.symbol.name)); + const writeAssignments = map(writes, (w) => factory.createShorthandPropertyAssignment(w.symbol.name)); + return variableAssignments === void 0 ? writeAssignments : writeAssignments === void 0 ? variableAssignments : variableAssignments.concat(writeAssignments); + } + function isReadonlyArray(v) { + return isArray(v); + } + function getEnclosingTextRange(targetRange, sourceFile) { + return isReadonlyArray(targetRange.range) ? { pos: first(targetRange.range).getStart(sourceFile), end: last(targetRange.range).getEnd() } : targetRange.range; + } + function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { + const allTypeParameterUsages = /* @__PURE__ */ new Map(); + const usagesPerScope = []; + const substitutionsPerScope = []; + const functionErrorsPerScope = []; + const constantErrorsPerScope = []; + const visibleDeclarationsInExtractedRange = []; + const exposedVariableSymbolSet = /* @__PURE__ */ new Map(); + const exposedVariableDeclarations = []; + let firstExposedNonVariableDeclaration; + const expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && isExpressionStatement(targetRange.range[0]) ? targetRange.range[0].expression : void 0; + let expressionDiagnostic; + if (expression === void 0) { + const statements = targetRange.range; + const start = first(statements).getStart(); + const end = last(statements).end; + expressionDiagnostic = createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); + } else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) { + expressionDiagnostic = createDiagnosticForNode(expression, Messages.uselessConstantType); + } + for (const scope of scopes) { + usagesPerScope.push({ usages: /* @__PURE__ */ new Map(), typeParameterUsages: /* @__PURE__ */ new Map(), substitutions: /* @__PURE__ */ new Map() }); + substitutionsPerScope.push(/* @__PURE__ */ new Map()); + functionErrorsPerScope.push([]); + const constantErrors = []; + if (expressionDiagnostic) { + constantErrors.push(expressionDiagnostic); + } + if (isClassLike(scope) && isInJSFile(scope)) { + constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); + } + if (isArrowFunction(scope) && !isBlock(scope.body)) { + constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction)); + } + constantErrorsPerScope.push(constantErrors); + } + const seenUsages = /* @__PURE__ */ new Map(); + const target = isReadonlyArray(targetRange.range) ? factory.createBlock(targetRange.range) : targetRange.range; + const unmodifiedNode = isReadonlyArray(targetRange.range) ? first(targetRange.range) : targetRange.range; + const inGenericContext = isInGenericContext(unmodifiedNode); + collectUsages(target); + if (inGenericContext && !isReadonlyArray(targetRange.range) && !isJsxAttribute(targetRange.range)) { + const contextualType = checker.getContextualType(targetRange.range); + recordTypeParameterUsages(contextualType); + } + if (allTypeParameterUsages.size > 0) { + const seenTypeParameterUsages = /* @__PURE__ */ new Map(); + let i = 0; + for (let curr = unmodifiedNode; curr !== void 0 && i < scopes.length; curr = curr.parent) { + if (curr === scopes[i]) { + seenTypeParameterUsages.forEach((typeParameter, id) => { + usagesPerScope[i].typeParameterUsages.set(id, typeParameter); + }); + i++; + } + if (isDeclarationWithTypeParameters(curr)) { + for (const typeParameterDecl of getEffectiveTypeParameterDeclarations(curr)) { + const typeParameter = checker.getTypeAtLocation(typeParameterDecl); + if (allTypeParameterUsages.has(typeParameter.id.toString())) { + seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter); + } + } + } + } + Debug.assert(i === scopes.length, "Should have iterated all scopes"); + } + if (visibleDeclarationsInExtractedRange.length) { + const containingLexicalScopeOfExtraction = isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : getEnclosingBlockScopeContainer(scopes[0]); + forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } + for (let i = 0; i < scopes.length; i++) { + const scopeUsages = usagesPerScope[i]; + if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { + const errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + constantErrorsPerScope[i].push(createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); + } + if (targetRange.facts & 16 /* UsesThisInFunction */ && isClassLike(scopes[i])) { + functionErrorsPerScope[i].push(createDiagnosticForNode(targetRange.thisNode, Messages.cannotExtractFunctionsContainingThisToMethod)); + } + let hasWrite = false; + let readonlyClassPropertyWrite; + usagesPerScope[i].usages.forEach((value) => { + if (value.usage === 2 /* Write */) { + hasWrite = true; + if (value.symbol.flags & 106500 /* ClassMember */ && value.symbol.valueDeclaration && hasEffectiveModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) { + readonlyClassPropertyWrite = value.symbol.valueDeclaration; + } + } + }); + Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0, "No variable declarations expected if something was extracted"); + if (hasWrite && !isReadonlyArray(targetRange.range)) { + const diag2 = createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression); + functionErrorsPerScope[i].push(diag2); + constantErrorsPerScope[i].push(diag2); + } else if (readonlyClassPropertyWrite && i > 0) { + const diag2 = createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor); + functionErrorsPerScope[i].push(diag2); + constantErrorsPerScope[i].push(diag2); + } else if (firstExposedNonVariableDeclaration) { + const diag2 = createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity); + functionErrorsPerScope[i].push(diag2); + constantErrorsPerScope[i].push(diag2); + } + } + return { target, usagesPerScope, functionErrorsPerScope, constantErrorsPerScope, exposedVariableDeclarations }; + function isInGenericContext(node) { + return !!findAncestor(node, (n) => isDeclarationWithTypeParameters(n) && getEffectiveTypeParameterDeclarations(n).length !== 0); + } + function recordTypeParameterUsages(type) { + const symbolWalker = checker.getSymbolWalker(() => (cancellationToken.throwIfCancellationRequested(), true)); + const { visitedTypes } = symbolWalker.walkType(type); + for (const visitedType of visitedTypes) { + if (visitedType.isTypeParameter()) { + allTypeParameterUsages.set(visitedType.id.toString(), visitedType); + } + } + } + function collectUsages(node, valueUsage = 1 /* Read */) { + if (inGenericContext) { + const type = checker.getTypeAtLocation(node); + recordTypeParameterUsages(type); + } + if (isDeclaration(node) && node.symbol) { + visibleDeclarationsInExtractedRange.push(node); + } + if (isAssignmentExpression(node)) { + collectUsages(node.left, 2 /* Write */); + collectUsages(node.right); + } else if (isUnaryExpressionWithWrite(node)) { + collectUsages(node.operand, 2 /* Write */); + } else if (isPropertyAccessExpression(node) || isElementAccessExpression(node)) { + forEachChild(node, collectUsages); + } else if (isIdentifier(node)) { + if (!node.parent) { + return; + } + if (isQualifiedName(node.parent) && node !== node.parent.left) { + return; + } + if (isPropertyAccessExpression(node.parent) && node !== node.parent.expression) { + return; + } + recordUsage( + node, + valueUsage, + /*isTypeNode*/ + isPartOfTypeNode(node) + ); + } else { + forEachChild(node, collectUsages); + } + } + function recordUsage(n, usage, isTypeNode2) { + const symbolId = recordUsagebySymbol(n, usage, isTypeNode2); + if (symbolId) { + for (let i = 0; i < scopes.length; i++) { + const substitution = substitutionsPerScope[i].get(symbolId); + if (substitution) { + usagesPerScope[i].substitutions.set(getNodeId(n).toString(), substitution); + } + } + } + } + function recordUsagebySymbol(identifier, usage, isTypeName) { + const symbol = getSymbolReferencedByIdentifier(identifier); + if (!symbol) { + return void 0; + } + const symbolId = getSymbolId(symbol).toString(); + const lastUsage = seenUsages.get(symbolId); + if (lastUsage && lastUsage >= usage) { + return symbolId; + } + seenUsages.set(symbolId, usage); + if (lastUsage) { + for (const perScope of usagesPerScope) { + const prevEntry = perScope.usages.get(identifier.text); + if (prevEntry) { + perScope.usages.set(identifier.text, { usage, symbol, node: identifier }); + } + } + return symbolId; + } + const decls = symbol.getDeclarations(); + const declInFile = decls && find(decls, (d) => d.getSourceFile() === sourceFile); + if (!declInFile) { + return void 0; + } + if (rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) { + return void 0; + } + if (targetRange.facts & 2 /* IsGenerator */ && usage === 2 /* Write */) { + const diag2 = createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators); + for (const errors of functionErrorsPerScope) { + errors.push(diag2); + } + for (const errors of constantErrorsPerScope) { + errors.push(diag2); + } + } + for (let i = 0; i < scopes.length; i++) { + const scope = scopes[i]; + const resolvedSymbol = checker.resolveName( + symbol.name, + scope, + symbol.flags, + /*excludeGlobals*/ + false + ); + if (resolvedSymbol === symbol) { + continue; + } + if (!substitutionsPerScope[i].has(symbolId)) { + const substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName); + if (substitution) { + substitutionsPerScope[i].set(symbolId, substitution); + } else if (isTypeName) { + if (!(symbol.flags & 262144 /* TypeParameter */)) { + const diag2 = createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope); + functionErrorsPerScope[i].push(diag2); + constantErrorsPerScope[i].push(diag2); + } + } else { + usagesPerScope[i].usages.set(identifier.text, { usage, symbol, node: identifier }); + } + } + } + return symbolId; + } + function checkForUsedDeclarations(node) { + if (node === targetRange.range || isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0) { + return; + } + const sym = isIdentifier(node) ? getSymbolReferencedByIdentifier(node) : checker.getSymbolAtLocation(node); + if (sym) { + const decl = find(visibleDeclarationsInExtractedRange, (d) => d.symbol === sym); + if (decl) { + if (isVariableDeclaration(decl)) { + const idString = decl.symbol.id.toString(); + if (!exposedVariableSymbolSet.has(idString)) { + exposedVariableDeclarations.push(decl); + exposedVariableSymbolSet.set(idString, true); + } + } else { + firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; + } + } + } + forEachChild(node, checkForUsedDeclarations); + } + function getSymbolReferencedByIdentifier(identifier) { + return identifier.parent && isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier ? checker.getShorthandAssignmentValueSymbol(identifier.parent) : checker.getSymbolAtLocation(identifier); + } + function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode2) { + if (!symbol) { + return void 0; + } + const decls = symbol.getDeclarations(); + if (decls && decls.some((d) => d.parent === scopeDecl)) { + return factory.createIdentifier(symbol.name); + } + const prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode2); + if (prefix === void 0) { + return void 0; + } + return isTypeNode2 ? factory.createQualifiedName(prefix, factory.createIdentifier(symbol.name)) : factory.createPropertyAccessExpression(prefix, symbol.name); + } + } + function getExtractableParent(node) { + return findAncestor(node, (node2) => node2.parent && isExtractableExpression(node2) && !isBinaryExpression(node2.parent)); + } + function isExtractableExpression(node) { + const { parent: parent2 } = node; + switch (parent2.kind) { + case 305 /* EnumMember */: + return false; + } + switch (node.kind) { + case 11 /* StringLiteral */: + return parent2.kind !== 271 /* ImportDeclaration */ && parent2.kind !== 275 /* ImportSpecifier */; + case 229 /* SpreadElement */: + case 205 /* ObjectBindingPattern */: + case 207 /* BindingElement */: + return false; + case 80 /* Identifier */: + return parent2.kind !== 207 /* BindingElement */ && parent2.kind !== 275 /* ImportSpecifier */ && parent2.kind !== 280 /* ExportSpecifier */; + } + return true; + } + function isBlockLike(node) { + switch (node.kind) { + case 240 /* Block */: + case 311 /* SourceFile */: + case 267 /* ModuleBlock */: + case 295 /* CaseClause */: + return true; + default: + return false; + } + } + function isInJSXContent(node) { + return isStringLiteralJsxAttribute(node) || (isJsxElement(node) || isJsxSelfClosingElement(node) || isJsxFragment(node)) && (isJsxElement(node.parent) || isJsxFragment(node.parent)); + } + function isStringLiteralJsxAttribute(node) { + return isStringLiteral(node) && node.parent && isJsxAttribute(node.parent); + } + var refactorName11, extractConstantAction, extractFunctionAction, Messages, RangeFacts; + var init_extractSymbol = __esm({ + "src/services/refactors/extractSymbol.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName11 = "Extract Symbol"; + extractConstantAction = { + name: "Extract Constant", + description: getLocaleSpecificMessage(Diagnostics.Extract_constant), + kind: "refactor.extract.constant" + }; + extractFunctionAction = { + name: "Extract Function", + description: getLocaleSpecificMessage(Diagnostics.Extract_function), + kind: "refactor.extract.function" + }; + registerRefactor(refactorName11, { + kinds: [ + extractConstantAction.kind, + extractFunctionAction.kind + ], + getEditsForAction: getRefactorEditsToExtractSymbol, + getAvailableActions: getRefactorActionsToExtractSymbol + }); + ((Messages2) => { + function createMessage(message) { + return { message, code: 0, category: 3 /* Message */, key: message }; + } + Messages2.cannotExtractRange = createMessage("Cannot extract range."); + Messages2.cannotExtractImport = createMessage("Cannot extract import statement."); + Messages2.cannotExtractSuper = createMessage("Cannot extract super call."); + Messages2.cannotExtractJSDoc = createMessage("Cannot extract JSDoc."); + Messages2.cannotExtractEmpty = createMessage("Cannot extract empty range."); + Messages2.expressionExpected = createMessage("expression expected."); + Messages2.uselessConstantType = createMessage("No reason to extract constant of type."); + Messages2.statementOrExpressionExpected = createMessage("Statement or expression expected."); + Messages2.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); + Messages2.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); + Messages2.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); + Messages2.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); + Messages2.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); + Messages2.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); + Messages2.cannotExtractIdentifier = createMessage("Select more than a single identifier."); + Messages2.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); + Messages2.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); + Messages2.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); + Messages2.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); + Messages2.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); + Messages2.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); + Messages2.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); + Messages2.cannotExtractFunctionsContainingThisToMethod = createMessage("Cannot extract functions containing this to method"); + })(Messages || (Messages = {})); + RangeFacts = /* @__PURE__ */ ((RangeFacts2) => { + RangeFacts2[RangeFacts2["None"] = 0] = "None"; + RangeFacts2[RangeFacts2["HasReturn"] = 1] = "HasReturn"; + RangeFacts2[RangeFacts2["IsGenerator"] = 2] = "IsGenerator"; + RangeFacts2[RangeFacts2["IsAsyncFunction"] = 4] = "IsAsyncFunction"; + RangeFacts2[RangeFacts2["UsesThis"] = 8] = "UsesThis"; + RangeFacts2[RangeFacts2["UsesThisInFunction"] = 16] = "UsesThisInFunction"; + RangeFacts2[RangeFacts2["InStaticRegion"] = 32] = "InStaticRegion"; + return RangeFacts2; + })(RangeFacts || {}); + } + }); + + // src/services/_namespaces/ts.refactor.extractSymbol.ts + var ts_refactor_extractSymbol_exports = {}; + __export(ts_refactor_extractSymbol_exports, { + Messages: () => Messages, + RangeFacts: () => RangeFacts, + getRangeToExtract: () => getRangeToExtract2, + getRefactorActionsToExtractSymbol: () => getRefactorActionsToExtractSymbol, + getRefactorEditsToExtractSymbol: () => getRefactorEditsToExtractSymbol + }); + var init_ts_refactor_extractSymbol = __esm({ + "src/services/_namespaces/ts.refactor.extractSymbol.ts"() { + "use strict"; + init_extractSymbol(); + } + }); + + // src/services/refactors/generateGetAccessorAndSetAccessor.ts + var actionName, actionDescription, generateGetSetAction; + var init_generateGetAccessorAndSetAccessor = __esm({ + "src/services/refactors/generateGetAccessorAndSetAccessor.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + actionName = "Generate 'get' and 'set' accessors"; + actionDescription = Diagnostics.Generate_get_and_set_accessors.message; + generateGetSetAction = { + name: actionName, + description: actionDescription, + kind: "refactor.rewrite.property.generateAccessors" + }; + registerRefactor(actionName, { + kinds: [generateGetSetAction.kind], + getEditsForAction: function getRefactorActionsToGenerateGetAndSetAccessors(context, actionName2) { + if (!context.endPosition) + return void 0; + const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const edits = ts_codefix_exports.generateAccessorFromProperty(context.file, context.program, context.startPosition, context.endPosition, context, actionName2); + if (!edits) + return void 0; + const renameFilename = context.file.fileName; + const nameNeedRename = info.renameAccessor ? info.accessorName : info.fieldName; + const renameLocationOffset = isIdentifier(nameNeedRename) ? 0 : -1; + const renameLocation = renameLocationOffset + getRenameLocation( + edits, + renameFilename, + nameNeedRename.text, + /*preferLastLocation*/ + isParameter(info.declaration) + ); + return { renameFilename, renameLocation, edits }; + }, + getAvailableActions(context) { + if (!context.endPosition) + return emptyArray; + const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition, context.triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + return [{ + name: actionName, + description: actionDescription, + actions: [generateGetSetAction] + }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: actionName, + description: actionDescription, + actions: [{ ...generateGetSetAction, notApplicableReason: info.error }] + }]; + } + return emptyArray; + } + }); + } + }); + + // src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts + var ts_refactor_generateGetAccessorAndSetAccessor_exports = {}; + var init_ts_refactor_generateGetAccessorAndSetAccessor = __esm({ + "src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts"() { + "use strict"; + init_generateGetAccessorAndSetAccessor(); + } + }); + + // src/services/refactors/inferFunctionReturnType.ts + function getRefactorEditsToInferReturnType(context) { + const info = getInfo4(context); + if (info && !isRefactorErrorInfo(info)) { + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange7(context.file, t, info.declaration, info.returnTypeNode)); + return { renameFilename: void 0, renameLocation: void 0, edits }; + } + return void 0; + } + function getRefactorActionsToInferReturnType(context) { + const info = getInfo4(context); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + return [{ + name: refactorName12, + description: refactorDescription6, + actions: [inferReturnTypeAction] + }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorName12, + description: refactorDescription6, + actions: [{ ...inferReturnTypeAction, notApplicableReason: info.error }] + }]; + } + return emptyArray; + } + function doChange7(sourceFile, changes, declaration, typeNode) { + const closeParen = findChildOfKind(declaration, 22 /* CloseParenToken */, sourceFile); + const needParens = isArrowFunction(declaration) && closeParen === void 0; + const endNode2 = needParens ? first(declaration.parameters) : closeParen; + if (endNode2) { + if (needParens) { + changes.insertNodeBefore(sourceFile, endNode2, factory.createToken(21 /* OpenParenToken */)); + changes.insertNodeAfter(sourceFile, endNode2, factory.createToken(22 /* CloseParenToken */)); + } + changes.insertNodeAt(sourceFile, endNode2.end, typeNode, { prefix: ": " }); + } + } + function getInfo4(context) { + if (isInJSFile(context.file) || !refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind)) + return; + const token = getTokenAtPosition(context.file, context.startPosition); + const declaration = findAncestor(token, (n) => isBlock(n) || n.parent && isArrowFunction(n.parent) && (n.kind === 39 /* EqualsGreaterThanToken */ || n.parent.body === n) ? "quit" : isConvertibleDeclaration(n)); + if (!declaration || !declaration.body || declaration.type) { + return { error: getLocaleSpecificMessage(Diagnostics.Return_type_must_be_inferred_from_a_function) }; + } + const typeChecker = context.program.getTypeChecker(); + const returnType = tryGetReturnType(typeChecker, declaration); + if (!returnType) { + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_determine_function_return_type) }; + } + const returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */); + if (returnTypeNode) { + return { declaration, returnTypeNode }; + } + } + function isConvertibleDeclaration(node) { + switch (node.kind) { + case 261 /* FunctionDeclaration */: + case 217 /* FunctionExpression */: + case 218 /* ArrowFunction */: + case 173 /* MethodDeclaration */: + return true; + default: + return false; + } + } + function tryGetReturnType(typeChecker, node) { + if (typeChecker.isImplementationOfOverload(node)) { + const signatures = typeChecker.getTypeAtLocation(node).getCallSignatures(); + if (signatures.length > 1) { + return typeChecker.getUnionType(mapDefined(signatures, (s) => s.getReturnType())); + } + } + const signature = typeChecker.getSignatureFromDeclaration(node); + if (signature) { + return typeChecker.getReturnTypeOfSignature(signature); + } + } + var refactorName12, refactorDescription6, inferReturnTypeAction; + var init_inferFunctionReturnType = __esm({ + "src/services/refactors/inferFunctionReturnType.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName12 = "Infer function return type"; + refactorDescription6 = Diagnostics.Infer_function_return_type.message; + inferReturnTypeAction = { + name: refactorName12, + description: refactorDescription6, + kind: "refactor.rewrite.function.returnType" + }; + registerRefactor(refactorName12, { + kinds: [inferReturnTypeAction.kind], + getEditsForAction: getRefactorEditsToInferReturnType, + getAvailableActions: getRefactorActionsToInferReturnType + }); + } + }); + + // src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts + var ts_refactor_inferFunctionReturnType_exports = {}; + var init_ts_refactor_inferFunctionReturnType = __esm({ + "src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts"() { + "use strict"; + init_inferFunctionReturnType(); + } + }); + + // src/services/_namespaces/ts.refactor.ts + var ts_refactor_exports = {}; + __export(ts_refactor_exports, { + addExportToChanges: () => addExportToChanges, + addExports: () => addExports, + addNewFileToTsconfig: () => addNewFileToTsconfig, + addOrRemoveBracesToArrowFunction: () => ts_refactor_addOrRemoveBracesToArrowFunction_exports, + convertArrowFunctionOrFunctionExpression: () => ts_refactor_convertArrowFunctionOrFunctionExpression_exports, + convertParamsToDestructuredObject: () => ts_refactor_convertParamsToDestructuredObject_exports, + convertStringOrTemplateLiteral: () => ts_refactor_convertStringOrTemplateLiteral_exports, + convertToOptionalChainExpression: () => ts_refactor_convertToOptionalChainExpression_exports, + createNewFileName: () => createNewFileName, + createOldFileImportsFromTargetFile: () => createOldFileImportsFromTargetFile, + deleteMovedStatements: () => deleteMovedStatements, + deleteUnusedImports: () => deleteUnusedImports, + deleteUnusedOldImports: () => deleteUnusedOldImports, + doChangeNamedToNamespaceOrDefault: () => doChangeNamedToNamespaceOrDefault, + extractSymbol: () => ts_refactor_extractSymbol_exports, + filterImport: () => filterImport, + forEachImportInStatement: () => forEachImportInStatement, + generateGetAccessorAndSetAccessor: () => ts_refactor_generateGetAccessorAndSetAccessor_exports, + getApplicableRefactors: () => getApplicableRefactors, + getEditsForRefactor: () => getEditsForRefactor, + getStatementsToMove: () => getStatementsToMove, + getTopLevelDeclarationStatement: () => getTopLevelDeclarationStatement, + getUsageInfo: () => getUsageInfo, + inferFunctionReturnType: () => ts_refactor_inferFunctionReturnType_exports, + isRefactorErrorInfo: () => isRefactorErrorInfo, + isTopLevelDeclaration: () => isTopLevelDeclaration, + makeImportOrRequire: () => makeImportOrRequire, + moduleSpecifierFromImport: () => moduleSpecifierFromImport, + nameOfTopLevelDeclaration: () => nameOfTopLevelDeclaration, + refactorKindBeginsWith: () => refactorKindBeginsWith, + registerRefactor: () => registerRefactor, + updateImportsInOtherFiles: () => updateImportsInOtherFiles + }); + var init_ts_refactor = __esm({ + "src/services/_namespaces/ts.refactor.ts"() { + "use strict"; + init_refactorProvider(); + init_convertExport(); + init_convertImport(); + init_extractType(); + init_helpers(); + init_moveToNewFile(); + init_moveToFile(); + init_ts_refactor_addOrRemoveBracesToArrowFunction(); + init_ts_refactor_convertArrowFunctionOrFunctionExpression(); + init_ts_refactor_convertParamsToDestructuredObject(); + init_ts_refactor_convertStringOrTemplateLiteral(); + init_ts_refactor_convertToOptionalChainExpression(); + init_ts_refactor_extractSymbol(); + init_ts_refactor_generateGetAccessorAndSetAccessor(); + init_ts_refactor_inferFunctionReturnType(); + } + }); + // src/services/classifier2020.ts function getSemanticClassifications2(program, cancellationToken, sourceFile, span) { const classifications = getEncodedSemanticClassifications2(program, cancellationToken, sourceFile, span); @@ -133835,6 +139721,7 @@ ${lanes.join("\n")} const rootFileNames = host.getScriptFileNames().slice(); const newSettings = host.getCompilationSettings() || getDefaultCompilerOptions2(); const hasInvalidatedResolutions = host.hasInvalidatedResolutions || returnFalse; + const hasInvalidatedLibResolutions = maybeBind(host, host.hasInvalidatedLibResolutions) || returnFalse; const hasChangedAutomaticTypeDirectiveNames = maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames); const projectReferences = (_b = host.getProjectReferences) == null ? void 0 : _b.call(host); let parsedCommandLines; @@ -133865,6 +139752,7 @@ ${lanes.join("\n")} onReleaseOldSourceFile, onReleaseParsedCommandLine, hasInvalidatedResolutions, + hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, trace: maybeBind(host, host.trace), resolveModuleNames: maybeBind(host, host.resolveModuleNames), @@ -133873,6 +139761,7 @@ ${lanes.join("\n")} resolveTypeReferenceDirectives: maybeBind(host, host.resolveTypeReferenceDirectives), resolveModuleNameLiterals: maybeBind(host, host.resolveModuleNameLiterals), resolveTypeReferenceDirectiveReferences: maybeBind(host, host.resolveTypeReferenceDirectiveReferences), + resolveLibrary: maybeBind(host, host.resolveLibrary), useSourceOfProjectReferenceRedirect: maybeBind(host, host.useSourceOfProjectReferenceRedirect), getParsedCommandLine }; @@ -133894,7 +139783,7 @@ ${lanes.join("\n")} onUnRecoverableConfigFileDiagnostic: noop }; const documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); - if (isProgramUptoDate(program, rootFileNames, newSettings, (_path, fileName) => host.getScriptVersion(fileName), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + if (isProgramUptoDate(program, rootFileNames, newSettings, (_path, fileName) => host.getScriptVersion(fileName), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { return; } const options = { @@ -134198,7 +140087,7 @@ ${lanes.join("\n")} const sourceFile = getValidSourceFile(fileName); return DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } - function findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) { + function findRenameLocations(fileName, position, findInStrings, findInComments, preferences) { synchronizeHostData(); const sourceFile = getValidSourceFile(fileName); const node = getAdjustedRenameLocation(getTouchingPropertyName(sourceFile, position)); @@ -134215,11 +140104,13 @@ ${lanes.join("\n")} }; }); } else { + const quotePreference = getQuotePreference(sourceFile, preferences ?? emptyOptions); + const providePrefixAndSuffixTextForRename = typeof preferences === "boolean" ? preferences : preferences == null ? void 0 : preferences.providePrefixAndSuffixTextForRename; return getReferencesWorker2( node, position, { findInStrings, findInComments, providePrefixAndSuffixTextForRename, use: ts_FindAllReferences_exports.FindReferencesUse.Rename }, - (entry, originalNode, checker) => ts_FindAllReferences_exports.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false) + (entry, originalNode, checker) => ts_FindAllReferences_exports.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false, quotePreference) ); } } @@ -134464,6 +140355,7 @@ ${lanes.join("\n")} const token = findPrecedingToken(position, sourceFile); if (!token || token.parent.kind === 311 /* SourceFile */) return void 0; + const jsxTagWordPattern = "[a-zA-Z0-9:\\-\\._$]*"; if (isJsxFragment(token.parent.parent)) { const openFragment = token.parent.parent.openingFragment; const closeFragment = token.parent.parent.closingFragment; @@ -134473,7 +140365,10 @@ ${lanes.join("\n")} const closePos = closeFragment.getStart(sourceFile) + 2; if (position !== openPos && position !== closePos) return void 0; - return { ranges: [{ start: openPos, length: 0 }, { start: closePos, length: 0 }] }; + return { + ranges: [{ start: openPos, length: 0 }, { start: closePos, length: 0 }], + wordPattern: jsxTagWordPattern + }; } else { const tag = findAncestor( token.parent, @@ -134499,7 +140394,8 @@ ${lanes.join("\n")} if (openingTagText !== closeTag.tagName.getText(sourceFile)) return void 0; return { - ranges: [{ start: openTagStart, length: openTagEnd - openTagStart }, { start: closeTagStart, length: closeTagEnd - closeTagStart }] + ranges: [{ start: openTagStart, length: openTagEnd - openTagStart }, { start: closeTagStart, length: closeTagEnd - closeTagStart }], + wordPattern: jsxTagWordPattern }; } } @@ -134801,15 +140697,24 @@ ${lanes.join("\n")} function getSmartSelectionRange2(fileName, position) { return ts_SmartSelectionRange_exports.getSmartSelectionRange(position, syntaxTreeCache.getCurrentSourceFile(fileName)); } - function getApplicableRefactors2(fileName, positionOrRange, preferences = emptyOptions, triggerReason, kind) { + function getApplicableRefactors2(fileName, positionOrRange, preferences = emptyOptions, triggerReason, kind, includeInteractiveActions) { synchronizeHostData(); const file = getValidSourceFile(fileName); - return ts_refactor_exports.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences, emptyOptions, triggerReason, kind)); + return ts_refactor_exports.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences, emptyOptions, triggerReason, kind), includeInteractiveActions); } - function getEditsForRefactor2(fileName, formatOptions, positionOrRange, refactorName13, actionName2, preferences = emptyOptions) { + function getMoveToRefactoringFileSuggestions(fileName, positionOrRange, preferences = emptyOptions) { + synchronizeHostData(); + const sourceFile = getValidSourceFile(fileName); + const allFiles = Debug.checkDefined(program.getSourceFiles()); + const extension = extensionFromPath(fileName); + const files = mapDefined(allFiles, (file) => !(program == null ? void 0 : program.isSourceFileFromExternalLibrary(sourceFile)) && !(sourceFile === getValidSourceFile(file.fileName) || extension === ".ts" /* Ts */ && extensionFromPath(file.fileName) === ".d.ts" /* Dts */ || extension === ".d.ts" /* Dts */ && startsWith(getBaseFileName(file.fileName), "lib.") && extensionFromPath(file.fileName) === ".d.ts" /* Dts */) && extension === extensionFromPath(file.fileName) ? file.fileName : void 0); + const newFileName = createNewFileName(sourceFile, program, getRefactorContext(sourceFile, positionOrRange, preferences, emptyOptions), host); + return { newFileName, files }; + } + function getEditsForRefactor2(fileName, formatOptions, positionOrRange, refactorName13, actionName2, preferences = emptyOptions, interactiveRefactorArguments) { synchronizeHostData(); const file = getValidSourceFile(fileName); - return ts_refactor_exports.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName13, actionName2); + return ts_refactor_exports.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName13, actionName2, interactiveRefactorArguments); } function toLineColumnOffset(fileName, position) { if (position === 0) { @@ -134896,6 +140801,7 @@ ${lanes.join("\n")} updateIsDefinitionOfReferencedSymbols, getApplicableRefactors: getApplicableRefactors2, getEditsForRefactor: getEditsForRefactor2, + getMoveToRefactoringFileSuggestions, toLineColumnOffset, getSourceMapper: () => sourceMapper, clearSourceMapperCache: () => sourceMapper.clearCache(), @@ -135027,6 +140933,7 @@ ${lanes.join("\n")} init_ts4(); init_ts_NavigateTo(); init_ts_NavigationBar(); + init_ts_refactor(); init_classifier(); init_classifier2020(); servicesVersion = "0.8"; @@ -136218,10 +142125,10 @@ ${lanes.join("\n")} () => this.languageService.getSmartSelectionRange(fileName, position) ); } - findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) { + findRenameLocations(fileName, position, findInStrings, findInComments, preferences) { return this.forwardJSONCall( - `findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments}, ${providePrefixAndSuffixTextForRename})`, - () => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) + `findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments})`, + () => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, preferences) ); } /// GET BRACE MATCHING @@ -137658,10 +143565,10 @@ ${lanes.join("\n")} }); // src/services/codeFixProvider.ts - function createCodeFixActionWithoutFixAll(fixName8, changes, description2) { + function createCodeFixActionWithoutFixAll(fixName8, changes, description3) { return createCodeFixActionWorker( fixName8, - diagnosticToString(description2), + diagnosticToString(description3), changes, /*fixId*/ void 0, @@ -137669,14 +143576,14 @@ ${lanes.join("\n")} void 0 ); } - function createCodeFixAction(fixName8, changes, description2, fixId52, fixAllDescription, command) { - return createCodeFixActionWorker(fixName8, diagnosticToString(description2), changes, fixId52, diagnosticToString(fixAllDescription), command); + function createCodeFixAction(fixName8, changes, description3, fixId52, fixAllDescription, command) { + return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId52, diagnosticToString(fixAllDescription), command); } - function createCodeFixActionMaybeFixAll(fixName8, changes, description2, fixId52, fixAllDescription, command) { - return createCodeFixActionWorker(fixName8, diagnosticToString(description2), changes, fixId52, fixAllDescription && diagnosticToString(fixAllDescription), command); + function createCodeFixActionMaybeFixAll(fixName8, changes, description3, fixId52, fixAllDescription, command) { + return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId52, fixAllDescription && diagnosticToString(fixAllDescription), command); } - function createCodeFixActionWorker(fixName8, description2, changes, fixId52, fixAllDescription, command) { - return { fixName: fixName8, description: description2, changes, fixId: fixId52, fixAllDescription, commands: command ? [command] : void 0 }; + function createCodeFixActionWorker(fixName8, description3, changes, fixId52, fixAllDescription, command) { + return { fixName: fixName8, description: description3, changes, fixId: fixId52, fixAllDescription, commands: command ? [command] : void 0 }; } function registerCodeFix(reg) { for (const error of reg.errorCodes) { @@ -138457,7 +144364,7 @@ ${lanes.join("\n")} function hasUsableJSDoc(decl) { return isFunctionLikeDeclaration(decl) ? decl.parameters.some(hasUsableJSDoc) || !decl.type && !!getJSDocReturnType(decl) : !decl.type && !!getJSDocType(decl); } - function doChange(changes, sourceFile, decl) { + function doChange8(changes, sourceFile, decl) { if (isFunctionLikeDeclaration(decl) && (getJSDocReturnType(decl) || decl.parameters.some((p) => !!getJSDocType(p)))) { if (!decl.typeParameters) { const typeParameters = getJSDocTypeParameterDeclarations(decl); @@ -138611,21 +144518,21 @@ ${lanes.join("\n")} const decl = getDeclaration(context.sourceFile, context.span.start); if (!decl) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange(t, context.sourceFile, decl)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange8(t, context.sourceFile, decl)); return [createCodeFixAction(fixId8, changes, Diagnostics.Annotate_with_type_from_JSDoc, fixId8, Diagnostics.Annotate_everything_with_types_from_JSDoc)]; }, fixIds: [fixId8], getAllCodeActions: (context) => codeFixAll(context, errorCodes9, (changes, diag2) => { const decl = getDeclaration(diag2.file, diag2.start); if (decl) - doChange(changes, diag2.file, decl); + doChange8(changes, diag2.file, decl); }) }); } }); // src/services/codefixes/convertFunctionToEs6Class.ts - function doChange2(changes, sourceFile, position, checker, preferences, compilerOptions) { + function doChange9(changes, sourceFile, position, checker, preferences, compilerOptions) { const ctorSymbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, position)); if (!ctorSymbol || !ctorSymbol.valueDeclaration || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { return void 0; @@ -138915,11 +144822,11 @@ ${lanes.join("\n")} registerCodeFix({ errorCodes: errorCodes10, getCodeActions(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange2(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange9(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())); return [createCodeFixAction(fixId9, changes, Diagnostics.Convert_function_to_an_ES2015_class, fixId9, Diagnostics.Convert_all_constructor_functions_to_classes)]; }, fixIds: [fixId9], - getAllCodeActions: (context) => codeFixAll(context, errorCodes10, (changes, err) => doChange2(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())) + getAllCodeActions: (context) => codeFixAll(context, errorCodes10, (changes, err) => doChange9(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())) }); } }); @@ -139970,7 +145877,7 @@ ${lanes.join("\n")} function convertSingleImport(name, moduleSpecifier, checker, identifiers, target, quotePreference) { switch (name.kind) { case 205 /* ObjectBindingPattern */: { - const importSpecifiers = mapAllOrFail(name.elements, (e) => e.dotDotDotToken || e.initializer || e.propertyName && !isIdentifier(e.propertyName) || !isIdentifier(e.name) ? void 0 : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text)); + const importSpecifiers = mapAllOrFail(name.elements, (e) => e.dotDotDotToken || e.initializer || e.propertyName && !isIdentifier(e.propertyName) || !isIdentifier(e.name) ? void 0 : makeImportSpecifier2(e.propertyName && e.propertyName.text, e.name.text)); if (importSpecifiers) { return convertedImports([makeImport( /*defaultImport*/ @@ -140108,12 +146015,12 @@ ${lanes.join("\n")} ) : makeImport( /*defaultImport*/ void 0, - [makeImportSpecifier(propertyName, localName)], + [makeImportSpecifier2(propertyName, localName)], moduleSpecifier, quotePreference ); } - function makeImportSpecifier(propertyName, name) { + function makeImportSpecifier2(propertyName, name) { return factory.createImportSpecifier( /*isTypeOnly*/ false, @@ -140182,7 +146089,7 @@ ${lanes.join("\n")} Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); return isIdentifier(qualifiedName.left) ? qualifiedName : void 0; } - function doChange3(changeTracker, sourceFile, qualifiedName) { + function doChange10(changeTracker, sourceFile, qualifiedName) { const rightText = qualifiedName.right.text; const replacement = factory.createIndexedAccessTypeNode( factory.createTypeReferenceNode( @@ -140208,7 +146115,7 @@ ${lanes.join("\n")} const qualifiedName = getQualifiedName(context.sourceFile, context.span.start); if (!qualifiedName) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange3(t, context.sourceFile, qualifiedName)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange10(t, context.sourceFile, qualifiedName)); const newText = `${qualifiedName.left.text}["${qualifiedName.right.text}"]`; return [createCodeFixAction(fixId11, changes, [Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId11, Diagnostics.Rewrite_all_as_indexed_access_types)]; }, @@ -140216,7 +146123,7 @@ ${lanes.join("\n")} getAllCodeActions: (context) => codeFixAll(context, errorCodes12, (changes, diag2) => { const q = getQualifiedName(diag2.file, diag2.start); if (q) { - doChange3(changes, diag2.file, q); + doChange10(changes, diag2.file, q); } }) }); @@ -140313,7 +146220,7 @@ ${lanes.join("\n")} const { parent: parent2 } = getTokenAtPosition(sourceFile, pos); return isImportSpecifier(parent2) || isImportDeclaration(parent2) && parent2.importClause ? parent2 : void 0; } - function doChange4(changes, sourceFile, declaration) { + function doChange11(changes, sourceFile, declaration) { if (isImportSpecifier(declaration)) { changes.replaceNode(sourceFile, declaration, factory.updateImportSpecifier( declaration, @@ -140417,7 +146324,7 @@ ${lanes.join("\n")} getCodeActions: function getCodeActionsToConvertToTypeOnlyImport(context) { const declaration = getDeclaration2(context.sourceFile, context.span.start); if (declaration) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange4(t, context.sourceFile, declaration)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange11(t, context.sourceFile, declaration)); return [createCodeFixAction(fixId13, changes, Diagnostics.Convert_to_type_only_import, fixId13, Diagnostics.Convert_all_imports_not_used_as_a_value_to_type_only_imports)]; } return void 0; @@ -140427,7 +146334,7 @@ ${lanes.join("\n")} return codeFixAll(context, errorCodes14, (changes, diag2) => { const declaration = getDeclaration2(diag2.file, diag2.start); if (declaration) { - doChange4(changes, diag2.file, declaration); + doChange11(changes, diag2.file, declaration); } }); } @@ -140436,7 +146343,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/convertTypedefToType.ts - function doChange5(changes, node, sourceFile) { + function doChange12(changes, node, sourceFile) { if (isJSDocTypedefTag(node)) { fixSingleTypeDef(changes, node, sourceFile); } @@ -140560,7 +146467,7 @@ ${lanes.join("\n")} ); if (!node) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange5(t, node, context.sourceFile)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange12(t, node, context.sourceFile)); if (changes.length > 0) { return [ createCodeFixAction( @@ -140576,14 +146483,14 @@ ${lanes.join("\n")} getAllCodeActions: (context) => codeFixAll(context, errorCodes15, (changes, diag2) => { const node = getTokenAtPosition(diag2.file, diag2.start); if (node) - doChange5(changes, node, diag2.file); + doChange12(changes, node, diag2.file); }) }); } }); // src/services/codefixes/convertLiteralTypeToMappedType.ts - function getInfo2(sourceFile, pos) { + function getInfo5(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); if (isIdentifier(token)) { const propertySignature = cast(token.parent.parent, isPropertySignature); @@ -140597,7 +146504,7 @@ ${lanes.join("\n")} } return void 0; } - function doChange6(changes, sourceFile, { container, typeNode, constraint, name }) { + function doChange13(changes, sourceFile, { container, typeNode, constraint, name }) { changes.replaceNode(sourceFile, container, factory.createMappedTypeNode( /*readonlyToken*/ void 0, @@ -140628,19 +146535,19 @@ ${lanes.join("\n")} errorCodes: errorCodes16, getCodeActions: function getCodeActionsToConvertLiteralTypeToMappedType(context) { const { sourceFile, span } = context; - const info = getInfo2(sourceFile, span.start); + const info = getInfo5(sourceFile, span.start); if (!info) { return void 0; } const { name, constraint } = info; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange6(t, sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange13(t, sourceFile, info)); return [createCodeFixAction(fixId15, changes, [Diagnostics.Convert_0_to_1_in_0, constraint, name], fixId15, Diagnostics.Convert_all_type_literals_to_mapped_type)]; }, fixIds: [fixId15], getAllCodeActions: (context) => codeFixAll(context, errorCodes16, (changes, diag2) => { - const info = getInfo2(diag2.file, diag2.start); + const info = getInfo5(diag2.file, diag2.start); if (info) { - doChange6(changes, diag2.file, info); + doChange13(changes, diag2.file, info); } }) }); @@ -140997,8 +146904,8 @@ ${lanes.join("\n")} const packageJsonImportFilter = createPackageJsonImportFilter(sourceFile, preferences, host); return getBestFix(getImportFixes(exportInfos, position, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes, sourceFile, program, packageJsonImportFilter, host); } - function codeFixActionToCodeAction({ description: description2, changes, commands }) { - return { description: description2, changes, commands }; + function codeFixActionToCodeAction({ description: description3, changes, commands }) { + return { description: description3, changes, commands }; } function getAllExportInfoForSymbol(importingFile, symbol, symbolName2, moduleSymbol, preferCapitalized, program, host, preferences, cancellationToken) { const getChecker = createGetChecker(program, host); @@ -141973,7 +147880,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixAddMissingConstraint.ts - function getInfo3(program, sourceFile, span) { + function getInfo6(program, sourceFile, span) { const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3) => diag3.start === span.start && diag3.length === span.length); if (diag2 === void 0 || diag2.relatedInformation === void 0) return; @@ -142063,7 +147970,7 @@ ${lanes.join("\n")} errorCodes: errorCodes19, getCodeActions(context) { const { sourceFile, span, program, preferences, host } = context; - const info = getInfo3(program, sourceFile, span); + const info = getInfo6(program, sourceFile, span); if (info === void 0) return; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingConstraint(t, program, preferences, host, sourceFile, info)); @@ -142075,7 +147982,7 @@ ${lanes.join("\n")} const seen = /* @__PURE__ */ new Map(); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { eachDiagnostic(context, errorCodes19, (diag2) => { - const info = getInfo3(program, diag2.file, createTextSpan(diag2.start, diag2.length)); + const info = getInfo6(program, diag2.file, createTextSpan(diag2.start, diag2.length)); if (info) { if (addToSeen(seen, getNodeId(info.declaration))) { return addMissingConstraint(changes, program, preferences, host, diag2.file, info); @@ -142255,7 +148162,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts - function doChange7(changes, sourceFile, node, preferences) { + function doChange14(changes, sourceFile, node, preferences) { const quotePreference = getQuotePreference(sourceFile, preferences); const argumentsExpression = factory.createStringLiteral(node.name.text, quotePreference === 0 /* Single */); changes.replaceNode( @@ -142283,16 +148190,16 @@ ${lanes.join("\n")} getCodeActions(context) { const { sourceFile, span, preferences } = context; const property = getPropertyAccessExpression(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange7(t, context.sourceFile, property, preferences)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange14(t, context.sourceFile, property, preferences)); return [createCodeFixAction(fixId18, changes, [Diagnostics.Use_element_access_for_0, property.name.text], fixId18, Diagnostics.Use_element_access_for_all_undeclared_properties)]; }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes21, (changes, diag2) => doChange7(changes, diag2.file, getPropertyAccessExpression(diag2.file, diag2.start), context.preferences)) + getAllCodeActions: (context) => codeFixAll(context, errorCodes21, (changes, diag2) => doChange14(changes, diag2.file, getPropertyAccessExpression(diag2.file, diag2.start), context.preferences)) }); } }); // src/services/codefixes/fixImplicitThis.ts - function doChange8(changes, sourceFile, pos, checker) { + function doChange15(changes, sourceFile, pos, checker) { const token = getTokenAtPosition(sourceFile, pos); if (!isThis(token)) return void 0; @@ -142347,20 +148254,20 @@ ${lanes.join("\n")} const { sourceFile, program, span } = context; let diagnostic; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => { - diagnostic = doChange8(t, sourceFile, span.start, program.getTypeChecker()); + diagnostic = doChange15(t, sourceFile, span.start, program.getTypeChecker()); }); return diagnostic ? [createCodeFixAction(fixId19, changes, diagnostic, fixId19, Diagnostics.Fix_all_implicit_this_errors)] : emptyArray; }, fixIds: [fixId19], getAllCodeActions: (context) => codeFixAll(context, errorCodes22, (changes, diag2) => { - doChange8(changes, diag2.file, diag2.start, context.program.getTypeChecker()); + doChange15(changes, diag2.file, diag2.start, context.program.getTypeChecker()); }) }); } }); // src/services/codefixes/fixImportNonExportedMember.ts - function getInfo4(sourceFile, pos, program) { + function getInfo7(sourceFile, pos, program) { var _a; const token = getTokenAtPosition(sourceFile, pos); if (isIdentifier(token)) { @@ -142396,7 +148303,7 @@ ${lanes.join("\n")} } return void 0; } - function doChange9(changes, program, { exportName, node, moduleSourceFile }) { + function doChange16(changes, program, { exportName, node, moduleSourceFile }) { const exportDeclaration = tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly); if (exportDeclaration) { updateExport(changes, program, moduleSourceFile, exportDeclaration, [exportName]); @@ -142493,10 +148400,10 @@ ${lanes.join("\n")} fixIds: [fixId20], getCodeActions(context) { const { sourceFile, span, program } = context; - const info = getInfo4(sourceFile, span.start, program); + const info = getInfo7(sourceFile, span.start, program); if (info === void 0) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange9(t, program, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange16(t, program, info)); return [createCodeFixAction(fixId20, changes, [Diagnostics.Export_0_from_module_1, info.exportName.node.text, info.moduleSpecifier], fixId20, Diagnostics.Export_all_referenced_locals)]; }, getAllCodeActions(context) { @@ -142504,7 +148411,7 @@ ${lanes.join("\n")} return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { const exports = /* @__PURE__ */ new Map(); eachDiagnostic(context, errorCodes23, (diag2) => { - const info = getInfo4(diag2.file, diag2.start, program); + const info = getInfo7(diag2.file, diag2.start, program); if (info === void 0) return void 0; const { exportName, node, moduleSourceFile } = info; @@ -142548,7 +148455,7 @@ ${lanes.join("\n")} const token = getTokenAtPosition(sourceFile, pos); return findAncestor(token, (t) => t.kind === 201 /* NamedTupleMember */); } - function doChange10(changes, sourceFile, namedTupleMember) { + function doChange17(changes, sourceFile, namedTupleMember) { if (!namedTupleMember) { return; } @@ -142591,7 +148498,7 @@ ${lanes.join("\n")} getCodeActions: function getCodeActionsToFixIncorrectNamedTupleSyntax(context) { const { sourceFile, span } = context; const namedTupleMember = getNamedTupleMember(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange10(t, sourceFile, namedTupleMember)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange17(t, sourceFile, namedTupleMember)); return [createCodeFixAction(fixId21, changes, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels, fixId21, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels)]; }, fixIds: [fixId21] @@ -142600,7 +148507,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixSpelling.ts - function getInfo5(sourceFile, pos, context, errorCode) { + function getInfo8(sourceFile, pos, context, errorCode) { const node = getTokenAtPosition(sourceFile, pos); const parent2 = node.parent; if ((errorCode === Diagnostics.No_overload_matches_this_call.code || errorCode === Diagnostics.Type_0_is_not_assignable_to_type_1.code) && !isJsxAttribute(parent2)) @@ -142649,7 +148556,7 @@ ${lanes.join("\n")} } return suggestedSymbol === void 0 ? void 0 : { node, suggestedSymbol }; } - function doChange11(changes, sourceFile, node, suggestedSymbol, target) { + function doChange18(changes, sourceFile, node, suggestedSymbol, target) { const suggestion = symbolName(suggestedSymbol); if (!isIdentifierText(suggestion, target) && isPropertyAccessExpression(node.parent)) { const valDecl = suggestedSymbol.valueDeclaration; @@ -142710,20 +148617,20 @@ ${lanes.join("\n")} errorCodes: errorCodes25, getCodeActions(context) { const { sourceFile, errorCode } = context; - const info = getInfo5(sourceFile, context.span.start, context, errorCode); + const info = getInfo8(sourceFile, context.span.start, context, errorCode); if (!info) return void 0; const { node, suggestedSymbol } = info; const target = getEmitScriptTarget(context.host.getCompilationSettings()); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange11(t, sourceFile, node, suggestedSymbol, target)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange18(t, sourceFile, node, suggestedSymbol, target)); return [createCodeFixAction("spelling", changes, [Diagnostics.Change_spelling_to_0, symbolName(suggestedSymbol)], fixId22, Diagnostics.Fix_all_detected_spelling_errors)]; }, fixIds: [fixId22], getAllCodeActions: (context) => codeFixAll(context, errorCodes25, (changes, diag2) => { - const info = getInfo5(diag2.file, diag2.start, context, diag2.code); + const info = getInfo8(diag2.file, diag2.start, context, diag2.code); const target = getEmitScriptTarget(context.host.getCompilationSettings()); if (info) - doChange11(changes, context.sourceFile, info.node, info.suggestedSymbol, target); + doChange18(changes, context.sourceFile, info.node, info.suggestedSymbol, target); }) }); } @@ -142823,7 +148730,7 @@ ${lanes.join("\n")} } return checker.isTypeAssignableTo(exprType, type); } - function getInfo6(checker, sourceFile, position, errorCode) { + function getInfo9(checker, sourceFile, position, errorCode) { const node = getTokenAtPosition(sourceFile, position); if (!node.parent) return void 0; @@ -142945,7 +148852,7 @@ ${lanes.join("\n")} fixIds: [fixIdAddReturnStatement, fixRemoveBracesFromArrowFunctionBody, fixIdWrapTheBlockWithParen], getCodeActions: function getCodeActionsToCorrectReturnValue(context) { const { program, sourceFile, span: { start }, errorCode } = context; - const info = getInfo6(program.getTypeChecker(), sourceFile, start, errorCode); + const info = getInfo9(program.getTypeChecker(), sourceFile, start, errorCode); if (!info) return void 0; if (info.kind === 0 /* MissingReturnStatement */) { @@ -142958,7 +148865,7 @@ ${lanes.join("\n")} } }, getAllCodeActions: (context) => codeFixAll(context, errorCodes26, (changes, diag2) => { - const info = getInfo6(context.program.getTypeChecker(), diag2.file, diag2.start, diag2.code); + const info = getInfo9(context.program.getTypeChecker(), diag2.file, diag2.start, diag2.code); if (!info) return void 0; switch (context.fixId) { @@ -142992,7 +148899,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixAddMissingMember.ts - function getInfo7(sourceFile, tokenPos, errorCode, checker, program) { + function getInfo10(sourceFile, tokenPos, errorCode, checker, program) { var _a; const token = getTokenAtPosition(sourceFile, tokenPos); const parent2 = token.parent; @@ -143547,7 +149454,7 @@ ${lanes.join("\n")} errorCodes: errorCodes27, getCodeActions(context) { const typeChecker = context.program.getTypeChecker(); - const info = getInfo7(context.sourceFile, context.span.start, context.errorCode, typeChecker, context.program); + const info = getInfo10(context.sourceFile, context.span.start, context.errorCode, typeChecker, context.program); if (!info) { return void 0; } @@ -143577,7 +149484,7 @@ ${lanes.join("\n")} const typeDeclToMembers = /* @__PURE__ */ new Map(); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { eachDiagnostic(context, errorCodes27, (diag2) => { - const info = getInfo7(diag2.file, diag2.start, diag2.code, checker, context.program); + const info = getInfo10(diag2.file, diag2.start, diag2.code, checker, context.program); if (!info || !addToSeen(seen, getNodeId(info.parentDeclaration) + "#" + info.token.text)) { return; } @@ -143782,7 +149689,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts - function doChange12(changes, sourceFile, constructor, superCall) { + function doChange19(changes, sourceFile, constructor, superCall) { changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall); changes.delete(sourceFile, superCall); } @@ -143813,7 +149720,7 @@ ${lanes.join("\n")} if (!nodes) return void 0; const { constructor, superCall } = nodes; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange12(t, sourceFile, constructor, superCall)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange19(t, sourceFile, constructor, superCall)); return [createCodeFixAction(fixId26, changes, Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId26, Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)]; }, fixIds: [fixId26], @@ -143826,7 +149733,7 @@ ${lanes.join("\n")} return; const { constructor, superCall } = nodes; if (addToSeen(seenClasses, getNodeId(constructor.parent))) { - doChange12(changes, sourceFile, constructor, superCall); + doChange19(changes, sourceFile, constructor, superCall); } }); } @@ -143840,7 +149747,7 @@ ${lanes.join("\n")} Debug.assert(isConstructorDeclaration(token.parent), "token should be at the constructor declaration"); return token.parent; } - function doChange13(changes, sourceFile, ctr) { + function doChange20(changes, sourceFile, ctr) { const superCall = factory.createExpressionStatement(factory.createCallExpression( factory.createSuper(), /*typeArguments*/ @@ -143863,17 +149770,17 @@ ${lanes.join("\n")} getCodeActions(context) { const { sourceFile, span } = context; const ctr = getNode(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange13(t, sourceFile, ctr)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange20(t, sourceFile, ctr)); return [createCodeFixAction(fixId27, changes, Diagnostics.Add_missing_super_call, fixId27, Diagnostics.Add_all_missing_super_calls)]; }, fixIds: [fixId27], - getAllCodeActions: (context) => codeFixAll(context, errorCodes32, (changes, diag2) => doChange13(changes, context.sourceFile, getNode(diag2.file, diag2.start))) + getAllCodeActions: (context) => codeFixAll(context, errorCodes32, (changes, diag2) => doChange20(changes, context.sourceFile, getNode(diag2.file, diag2.start))) }); } }); // src/services/codefixes/fixEnableJsxFlag.ts - function doChange14(changeTracker, configFile) { + function doChange21(changeTracker, configFile) { setJsonCompilerOptionValue(changeTracker, configFile, "jsx", factory.createStringLiteral("react")); } var fixID, errorCodes33; @@ -143893,7 +149800,7 @@ ${lanes.join("\n")} } const changes = ts_textChanges_exports.ChangeTracker.with( context, - (changeTracker) => doChange14(changeTracker, configFile) + (changeTracker) => doChange21(changeTracker, configFile) ); return [ createCodeFixActionWithoutFixAll(fixID, changes, Diagnostics.Enable_the_jsx_flag_in_your_configuration_file) @@ -143905,14 +149812,14 @@ ${lanes.join("\n")} if (configFile === void 0) { return void 0; } - doChange14(changes, configFile); + doChange21(changes, configFile); }) }); } }); // src/services/codefixes/fixNaNEquality.ts - function getInfo8(program, sourceFile, span) { + function getInfo11(program, sourceFile, span) { const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3) => diag3.start === span.start && diag3.length === span.length); if (diag2 === void 0 || diag2.relatedInformation === void 0) return; @@ -143927,7 +149834,7 @@ ${lanes.join("\n")} } return void 0; } - function doChange15(changes, sourceFile, arg, expression) { + function doChange22(changes, sourceFile, arg, expression) { const callExpression = factory.createCallExpression( factory.createPropertyAccessExpression(factory.createIdentifier("Number"), factory.createIdentifier("isNaN")), /*typeArguments*/ @@ -143959,19 +149866,19 @@ ${lanes.join("\n")} errorCodes: errorCodes34, getCodeActions(context) { const { sourceFile, span, program } = context; - const info = getInfo8(program, sourceFile, span); + const info = getInfo11(program, sourceFile, span); if (info === void 0) return; const { suggestion, expression, arg } = info; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange15(t, sourceFile, arg, expression)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange22(t, sourceFile, arg, expression)); return [createCodeFixAction(fixId28, changes, [Diagnostics.Use_0, suggestion], fixId28, Diagnostics.Use_Number_isNaN_in_all_conditions)]; }, fixIds: [fixId28], getAllCodeActions: (context) => { return codeFixAll(context, errorCodes34, (changes, diag2) => { - const info = getInfo8(context.program, diag2.file, createTextSpan(diag2.start, diag2.length)); + const info = getInfo11(context.program, diag2.file, createTextSpan(diag2.start, diag2.length)); if (info) { - doChange15(changes, diag2.file, info.arg, info.expression); + doChange22(changes, diag2.file, info.arg, info.expression); } }); } @@ -144027,7 +149934,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixPropertyAssignment.ts - function doChange16(changes, sourceFile, node) { + function doChange23(changes, sourceFile, node) { changes.replaceNode(sourceFile, node, factory.createPropertyAssignment(node.name, node.objectAssignmentInitializer)); } function getProperty2(sourceFile, pos) { @@ -144049,10 +149956,10 @@ ${lanes.join("\n")} getCodeActions(context) { const { sourceFile, span } = context; const property = getProperty2(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange16(t, context.sourceFile, property)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange23(t, context.sourceFile, property)); return [createCodeFixAction(fixId29, changes, [Diagnostics.Change_0_to_1, "=", ":"], fixId29, [Diagnostics.Switch_each_misused_0_to_1, "=", ":"])]; }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes35, (changes, diag2) => doChange16(changes, diag2.file, getProperty2(diag2.file, diag2.start))) + getAllCodeActions: (context) => codeFixAll(context, errorCodes35, (changes, diag2) => doChange23(changes, diag2.file, getProperty2(diag2.file, diag2.start))) }); } }); @@ -144108,13 +150015,13 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixForgottenThisPropertyAccess.ts - function getInfo9(sourceFile, pos, diagCode) { + function getInfo12(sourceFile, pos, diagCode) { const node = getTokenAtPosition(sourceFile, pos); if (isIdentifier(node) || isPrivateIdentifier(node)) { return { node, className: diagCode === didYouMeanStaticMemberCode ? getContainingClass(node).name.text : void 0 }; } } - function doChange17(changes, sourceFile, { node, className }) { + function doChange24(changes, sourceFile, { node, className }) { suppressLeadingAndTrailingTrivia(node); changes.replaceNode(sourceFile, node, factory.createPropertyAccessExpression(className ? factory.createIdentifier(className) : factory.createThis(), node)); } @@ -144135,18 +150042,18 @@ ${lanes.join("\n")} errorCodes: errorCodes37, getCodeActions(context) { const { sourceFile } = context; - const info = getInfo9(sourceFile, context.span.start, context.errorCode); + const info = getInfo12(sourceFile, context.span.start, context.errorCode); if (!info) { return void 0; } - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange17(t, sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange24(t, sourceFile, info)); return [createCodeFixAction(fixId31, changes, [Diagnostics.Add_0_to_unresolved_variable, info.className || "this"], fixId31, Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name)]; }, fixIds: [fixId31], getAllCodeActions: (context) => codeFixAll(context, errorCodes37, (changes, diag2) => { - const info = getInfo9(diag2.file, diag2.start, diag2.code); + const info = getInfo12(diag2.file, diag2.start, diag2.code); if (info) - doChange17(changes, context.sourceFile, info); + doChange24(changes, context.sourceFile, info); }) }); } @@ -144156,7 +150063,7 @@ ${lanes.join("\n")} function isValidCharacter(character) { return hasProperty(htmlEntity, character); } - function doChange18(changes, preferences, sourceFile, start, useHtmlEntity) { + function doChange25(changes, preferences, sourceFile, start, useHtmlEntity) { const character = sourceFile.getText()[start]; if (!isValidCharacter(character)) { return; @@ -144181,7 +150088,7 @@ ${lanes.join("\n")} fixIds: [fixIdExpression, fixIdHtmlEntity], getCodeActions(context) { const { sourceFile, preferences, span } = context; - const changeToExpression = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange18( + const changeToExpression = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange25( t, preferences, sourceFile, @@ -144189,7 +150096,7 @@ ${lanes.join("\n")} /*useHtmlEntity*/ false )); - const changeToHtmlEntity = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange18( + const changeToHtmlEntity = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange25( t, preferences, sourceFile, @@ -144203,7 +150110,7 @@ ${lanes.join("\n")} ]; }, getAllCodeActions(context) { - return codeFixAll(context, errorCodes38, (changes, diagnostic) => doChange18(changes, context.preferences, diagnostic.file, diagnostic.start, context.fixId === fixIdHtmlEntity)); + return codeFixAll(context, errorCodes38, (changes, diagnostic) => doChange25(changes, context.preferences, diagnostic.file, diagnostic.start, context.fixId === fixIdHtmlEntity)); } }); htmlEntity = { @@ -144250,7 +150157,7 @@ ${lanes.join("\n")} const changes = ts_textChanges_exports.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]); } - function getInfo10(sourceFile, pos) { + function getInfo13(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); if (token.parent && isJSDocParameterTag(token.parent) && isIdentifier(token.parent.name)) { const jsDocParameterTag = token.parent; @@ -144279,7 +150186,7 @@ ${lanes.join("\n")} getCodeActions: function getCodeActionsToFixUnmatchedParameter(context) { const { sourceFile, span } = context; const actions2 = []; - const info = getInfo10(sourceFile, span.start); + const info = getInfo13(sourceFile, span.start); if (info) { append(actions2, getDeleteAction(context, info)); append(actions2, getRenameAction(context, info)); @@ -144291,7 +150198,7 @@ ${lanes.join("\n")} const tagsToSignature = /* @__PURE__ */ new Map(); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { eachDiagnostic(context, errorCodes39, ({ file, start }) => { - const info = getInfo10(file, start); + const info = getInfo13(file, start); if (info) { tagsToSignature.set(info.signature, append(tagsToSignature.get(info.signature), info.jsDocParameterTag)); } @@ -144714,7 +150621,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixUnreachableCode.ts - function doChange19(changes, sourceFile, start, length2, errorCode) { + function doChange26(changes, sourceFile, start, length2, errorCode) { const token = getTokenAtPosition(sourceFile, start); const statement = findAncestor(token, isStatement); if (statement.getStart(sourceFile) !== token.getStart(sourceFile)) { @@ -144776,17 +150683,17 @@ ${lanes.join("\n")} const syntacticDiagnostics = context.program.getSyntacticDiagnostics(context.sourceFile, context.cancellationToken); if (syntacticDiagnostics.length) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange19(t, context.sourceFile, context.span.start, context.span.length, context.errorCode)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange26(t, context.sourceFile, context.span.start, context.span.length, context.errorCode)); return [createCodeFixAction(fixId33, changes, Diagnostics.Remove_unreachable_code, fixId33, Diagnostics.Remove_all_unreachable_code)]; }, fixIds: [fixId33], - getAllCodeActions: (context) => codeFixAll(context, errorCodes42, (changes, diag2) => doChange19(changes, diag2.file, diag2.start, diag2.length, diag2.code)) + getAllCodeActions: (context) => codeFixAll(context, errorCodes42, (changes, diag2) => doChange26(changes, diag2.file, diag2.start, diag2.length, diag2.code)) }); } }); // src/services/codefixes/fixUnusedLabel.ts - function doChange20(changes, sourceFile, start) { + function doChange27(changes, sourceFile, start) { const token = getTokenAtPosition(sourceFile, start); const labeledStatement = cast(token.parent, isLabeledStatement); const pos = token.getStart(sourceFile); @@ -144810,17 +150717,17 @@ ${lanes.join("\n")} registerCodeFix({ errorCodes: errorCodes43, getCodeActions(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange20(t, context.sourceFile, context.span.start)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange27(t, context.sourceFile, context.span.start)); return [createCodeFixAction(fixId34, changes, Diagnostics.Remove_unused_label, fixId34, Diagnostics.Remove_all_unused_labels)]; }, fixIds: [fixId34], - getAllCodeActions: (context) => codeFixAll(context, errorCodes43, (changes, diag2) => doChange20(changes, diag2.file, diag2.start)) + getAllCodeActions: (context) => codeFixAll(context, errorCodes43, (changes, diag2) => doChange27(changes, diag2.file, diag2.start)) }); } }); // src/services/codefixes/fixJSDocTypes.ts - function doChange21(changes, sourceFile, oldTypeNode, newType, checker) { + function doChange28(changes, sourceFile, oldTypeNode, newType, checker) { changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode( newType, /*enclosingDeclaration*/ @@ -144829,7 +150736,7 @@ ${lanes.join("\n")} void 0 )); } - function getInfo11(sourceFile, pos, checker) { + function getInfo14(sourceFile, pos, checker) { const decl = findAncestor(getTokenAtPosition(sourceFile, pos), isTypeContainer); const typeNode = decl && decl.type; return typeNode && { typeNode, type: getType(checker, typeNode) }; @@ -144887,7 +150794,7 @@ ${lanes.join("\n")} getCodeActions(context) { const { sourceFile } = context; const checker = context.program.getTypeChecker(); - const info = getInfo11(sourceFile, context.span.start, checker); + const info = getInfo14(sourceFile, context.span.start, checker); if (!info) return void 0; const { typeNode, type } = info; @@ -144898,7 +150805,7 @@ ${lanes.join("\n")} } return actions2; function fix(type2, fixId52, fixAllDescription) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange21(t, sourceFile, typeNode, type2, checker)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange28(t, sourceFile, typeNode, type2, checker)); return createCodeFixAction("jdocTypes", changes, [Diagnostics.Change_0_to_1, original, checker.typeToString(type2)], fixId52, fixAllDescription); } }, @@ -144907,12 +150814,12 @@ ${lanes.join("\n")} const { fixId: fixId52, program, sourceFile } = context; const checker = program.getTypeChecker(); return codeFixAll(context, errorCodes44, (changes, err) => { - const info = getInfo11(err.file, err.start, checker); + const info = getInfo14(err.file, err.start, checker); if (!info) return; const { typeNode, type } = info; const fixedType = typeNode.kind === 320 /* JSDocNullableType */ && fixId52 === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; - doChange21(changes, sourceFile, typeNode, fixedType, checker); + doChange28(changes, sourceFile, typeNode, fixedType, checker); }); } }); @@ -144920,7 +150827,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixMissingCallParentheses.ts - function doChange22(changes, sourceFile, name) { + function doChange29(changes, sourceFile, name) { changes.replaceNodeWithText(sourceFile, name, `${name.text}()`); } function getCallName(sourceFile, start) { @@ -144955,13 +150862,13 @@ ${lanes.join("\n")} const callName = getCallName(sourceFile, span.start); if (!callName) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange22(t, context.sourceFile, callName)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange29(t, context.sourceFile, callName)); return [createCodeFixAction(fixId35, changes, Diagnostics.Add_missing_call_parentheses, fixId35, Diagnostics.Add_all_missing_call_parentheses)]; }, getAllCodeActions: (context) => codeFixAll(context, errorCodes45, (changes, diag2) => { const callName = getCallName(diag2.file, diag2.start); if (callName) - doChange22(changes, diag2.file, callName); + doChange29(changes, diag2.file, callName); }) }); } @@ -145003,7 +150910,7 @@ ${lanes.join("\n")} returnType: getReturnType(containingFunction) }; } - function doChange23(changes, sourceFile, { insertBefore, returnType }) { + function doChange30(changes, sourceFile, { insertBefore, returnType }) { if (returnType) { const entityName = getEntityNameFromTypeNode(returnType); if (!entityName || entityName.kind !== 80 /* Identifier */ || entityName.text !== "Promise") { @@ -145031,7 +150938,7 @@ ${lanes.join("\n")} const nodes = getNodes3(sourceFile, span.start); if (!nodes) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange23(t, sourceFile, nodes)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange30(t, sourceFile, nodes)); return [createCodeFixAction(fixId36, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId36, Diagnostics.Add_all_missing_async_modifiers)]; }, fixIds: [fixId36], @@ -145041,7 +150948,7 @@ ${lanes.join("\n")} const nodes = getNodes3(diag2.file, diag2.start); if (!nodes || !addToSeen(seen, getNodeId(nodes.insertBefore))) return; - doChange23(changes, context.sourceFile, nodes); + doChange30(changes, context.sourceFile, nodes); }); } }); @@ -145049,7 +150956,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixPropertyOverrideAccessor.ts - function doChange24(file, start, length2, code, context) { + function doChange31(file, start, length2, code, context) { let startPosition; let endPosition; if (code === Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property.code) { @@ -145090,14 +150997,14 @@ ${lanes.join("\n")} registerCodeFix({ errorCodes: errorCodes47, getCodeActions(context) { - const edits = doChange24(context.sourceFile, context.span.start, context.span.length, context.errorCode, context); + const edits = doChange31(context.sourceFile, context.span.start, context.span.length, context.errorCode, context); if (edits) { return [createCodeFixAction(fixId37, edits, Diagnostics.Generate_get_and_set_accessors, fixId37, Diagnostics.Generate_get_and_set_accessors_for_all_overriding_properties)]; } }, fixIds: [fixId37], getAllCodeActions: (context) => codeFixAll(context, errorCodes47, (changes, diag2) => { - const edits = doChange24(diag2.file, diag2.start, diag2.length, diag2.code, context); + const edits = doChange31(diag2.file, diag2.start, diag2.length, diag2.code, context); if (edits) { for (const edit of edits) { changes.pushRaw(context.sourceFile, edit); @@ -145144,7 +151051,7 @@ ${lanes.join("\n")} } return errorCode; } - function doChange25(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, preferences) { + function doChange32(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, preferences) { if (!isParameterPropertyModifier(token.kind) && token.kind !== 80 /* Identifier */ && token.kind !== 26 /* DotDotDotToken */ && token.kind !== 110 /* ThisKeyword */) { return void 0; } @@ -146088,7 +151995,7 @@ ${lanes.join("\n")} const token = getTokenAtPosition(sourceFile, start); let declaration; const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => { - declaration = doChange25( + declaration = doChange32( changes2, sourceFile, token, @@ -146109,7 +152016,7 @@ ${lanes.join("\n")} const { sourceFile, program, cancellationToken, host, preferences } = context; const markSeen = nodeSeenTracker(); return codeFixAll(context, errorCodes48, (changes, err) => { - doChange25(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences); + doChange32(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences); }); } }); @@ -146117,7 +152024,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixReturnTypeInAsyncFunction.ts - function getInfo12(sourceFile, checker, pos) { + function getInfo15(sourceFile, checker, pos) { if (isInJSFile(sourceFile)) { return void 0; } @@ -146140,7 +152047,7 @@ ${lanes.join("\n")} return { returnTypeNode, returnType, promisedTypeNode, promisedType }; } } - function doChange26(changes, sourceFile, returnTypeNode, promisedTypeNode) { + function doChange33(changes, sourceFile, returnTypeNode, promisedTypeNode) { changes.replaceNode(sourceFile, returnTypeNode, factory.createTypeReferenceNode("Promise", [promisedTypeNode])); } var fixId39, errorCodes49; @@ -146159,12 +152066,12 @@ ${lanes.join("\n")} getCodeActions: function getCodeActionsToFixReturnTypeInAsyncFunction(context) { const { sourceFile, program, span } = context; const checker = program.getTypeChecker(); - const info = getInfo12(sourceFile, program.getTypeChecker(), span.start); + const info = getInfo15(sourceFile, program.getTypeChecker(), span.start); if (!info) { return void 0; } const { returnTypeNode, returnType, promisedTypeNode, promisedType } = info; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange26(t, sourceFile, returnTypeNode, promisedTypeNode)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange33(t, sourceFile, returnTypeNode, promisedTypeNode)); return [createCodeFixAction( fixId39, changes, @@ -146178,9 +152085,9 @@ ${lanes.join("\n")} )]; }, getAllCodeActions: (context) => codeFixAll(context, errorCodes49, (changes, diag2) => { - const info = getInfo12(diag2.file, context.program.getTypeChecker(), diag2.start); + const info = getInfo15(diag2.file, context.program.getTypeChecker(), diag2.start); if (info) { - doChange26(changes, diag2.file, info.returnTypeNode, info.promisedTypeNode); + doChange33(changes, diag2.file, info.returnTypeNode, info.promisedTypeNode); } }) }); @@ -146873,7 +152780,7 @@ ${lanes.join("\n")} return token; } var PreserveOptionalFlags; - var init_helpers = __esm({ + var init_helpers2 = __esm({ "src/services/codefixes/helpers.ts"() { "use strict"; init_ts4(); @@ -147224,7 +153131,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixStrictClassInitialization.ts - function getInfo13(sourceFile, pos) { + function getInfo16(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); if (isIdentifier(token) && isPropertyDeclaration(token.parent)) { const type = getEffectiveTypeAnnotationNode(token.parent); @@ -147342,7 +153249,7 @@ ${lanes.join("\n")} registerCodeFix({ errorCodes: errorCodes51, getCodeActions: function getCodeActionsForStrictClassInitializationErrors(context) { - const info = getInfo13(context.sourceFile, context.span.start); + const info = getInfo16(context.sourceFile, context.span.start); if (!info) return; const result = []; @@ -147354,7 +153261,7 @@ ${lanes.join("\n")} fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], getAllCodeActions: (context) => { return codeFixAll(context, errorCodes51, (changes, diag2) => { - const info = getInfo13(diag2.file, diag2.start); + const info = getInfo16(diag2.file, diag2.start); if (!info) return; switch (context.fixId) { @@ -147381,7 +153288,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/requireInTs.ts - function doChange27(changes, sourceFile, info) { + function doChange34(changes, sourceFile, info) { const { allowSyntheticDefaults, defaultImportName, namedImports, statement, required } = info; changes.replaceNode(sourceFile, statement, defaultImportName && !allowSyntheticDefaults ? factory.createImportEqualsDeclaration( /*modifiers*/ @@ -147404,7 +153311,7 @@ ${lanes.join("\n")} void 0 )); } - function getInfo14(sourceFile, program, pos) { + function getInfo17(sourceFile, program, pos) { const { parent: parent2 } = getTokenAtPosition(sourceFile, pos); if (!isRequireCall( parent2, @@ -147454,18 +153361,18 @@ ${lanes.join("\n")} registerCodeFix({ errorCodes: errorCodes52, getCodeActions(context) { - const info = getInfo14(context.sourceFile, context.program, context.span.start); + const info = getInfo17(context.sourceFile, context.program, context.span.start); if (!info) { return void 0; } - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange27(t, context.sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange34(t, context.sourceFile, info)); return [createCodeFixAction(fixId41, changes, Diagnostics.Convert_require_to_import, fixId41, Diagnostics.Convert_all_require_to_import)]; }, fixIds: [fixId41], getAllCodeActions: (context) => codeFixAll(context, errorCodes52, (changes, diag2) => { - const info = getInfo14(diag2.file, context.program, diag2.start); + const info = getInfo17(diag2.file, context.program, diag2.start); if (info) { - doChange27(changes, context.sourceFile, info); + doChange34(changes, context.sourceFile, info); } }) }); @@ -147473,7 +153380,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/useDefaultImport.ts - function getInfo15(sourceFile, pos) { + function getInfo18(sourceFile, pos) { const name = getTokenAtPosition(sourceFile, pos); if (!isIdentifier(name)) return void 0; @@ -147485,7 +153392,7 @@ ${lanes.join("\n")} return { importNode, name, moduleSpecifier: importNode.moduleSpecifier }; } } - function doChange28(changes, sourceFile, info, preferences) { + function doChange35(changes, sourceFile, info, preferences) { changes.replaceNode(sourceFile, info.importNode, makeImport( info.name, /*namedImports*/ @@ -147506,17 +153413,17 @@ ${lanes.join("\n")} errorCodes: errorCodes53, getCodeActions(context) { const { sourceFile, span: { start } } = context; - const info = getInfo15(sourceFile, start); + const info = getInfo18(sourceFile, start); if (!info) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange28(t, sourceFile, info, context.preferences)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange35(t, sourceFile, info, context.preferences)); return [createCodeFixAction(fixId42, changes, Diagnostics.Convert_to_default_import, fixId42, Diagnostics.Convert_all_to_default_imports)]; }, fixIds: [fixId42], getAllCodeActions: (context) => codeFixAll(context, errorCodes53, (changes, diag2) => { - const info = getInfo15(diag2.file, diag2.start); + const info = getInfo18(diag2.file, diag2.start); if (info) - doChange28(changes, diag2.file, info, context.preferences); + doChange35(changes, diag2.file, info, context.preferences); }) }); } @@ -147564,7 +153471,7 @@ ${lanes.join("\n")} Debug.assert(token.parent.kind === 204 /* ImportType */, "Token parent should be an ImportType"); return token.parent; } - function doChange29(changes, sourceFile, importType) { + function doChange36(changes, sourceFile, importType) { const newTypeNode = factory.updateImportTypeNode( importType, importType.argument, @@ -147590,11 +153497,11 @@ ${lanes.join("\n")} getCodeActions: function getCodeActionsToAddMissingTypeof(context) { const { sourceFile, span } = context; const importType = getImportTypeNode(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange29(t, sourceFile, importType)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange36(t, sourceFile, importType)); return [createCodeFixAction(fixId44, changes, Diagnostics.Add_missing_typeof, fixId44, Diagnostics.Add_missing_typeof)]; }, fixIds: [fixId44], - getAllCodeActions: (context) => codeFixAll(context, errorCodes55, (changes, diag2) => doChange29(changes, context.sourceFile, getImportTypeNode(diag2.file, diag2.start))) + getAllCodeActions: (context) => codeFixAll(context, errorCodes55, (changes, diag2) => doChange36(changes, context.sourceFile, getImportTypeNode(diag2.file, diag2.start))) }); } }); @@ -147613,7 +153520,7 @@ ${lanes.join("\n")} return void 0; return binaryExpr; } - function doChange30(changeTracker, sf, node) { + function doChange37(changeTracker, sf, node) { const jsx = flattenInvalidBinaryExpr(node); if (jsx) changeTracker.replaceNode(sf, node, factory.createJsxFragment(factory.createJsxOpeningFragment(), jsx, factory.createJsxJsxClosingFragment())); @@ -147651,7 +153558,7 @@ ${lanes.join("\n")} const node = findNodeToFix(sourceFile, span.start); if (!node) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange30(t, sourceFile, node)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange37(t, sourceFile, node)); return [createCodeFixAction(fixID2, changes, Diagnostics.Wrap_in_JSX_fragment, fixID2, Diagnostics.Wrap_all_unparented_JSX_in_JSX_fragment)]; }, fixIds: [fixID2], @@ -147659,14 +153566,14 @@ ${lanes.join("\n")} const node = findNodeToFix(context.sourceFile, diag2.start); if (!node) return void 0; - doChange30(changes, context.sourceFile, node); + doChange37(changes, context.sourceFile, node); }) }); } }); // src/services/codefixes/convertToMappedObjectType.ts - function getInfo16(sourceFile, pos) { + function getInfo19(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); const indexSignature = tryCast(token.parent.parent, isIndexSignatureDeclaration); if (!indexSignature) @@ -147679,7 +153586,7 @@ ${lanes.join("\n")} function createTypeAliasFromInterface(declaration, type) { return factory.createTypeAliasDeclaration(declaration.modifiers, declaration.name, declaration.typeParameters, type); } - function doChange31(changes, sourceFile, { indexSignature, container }) { + function doChange38(changes, sourceFile, { indexSignature, container }) { const members = isInterfaceDeclaration(container) ? container.members : container.type.members; const otherMembers = members.filter((member) => !isIndexSignatureDeclaration(member)); const parameter = first(indexSignature.parameters); @@ -147718,18 +153625,18 @@ ${lanes.join("\n")} errorCodes: errorCodes57, getCodeActions: function getCodeActionsToConvertToMappedTypeObject(context) { const { sourceFile, span } = context; - const info = getInfo16(sourceFile, span.start); + const info = getInfo19(sourceFile, span.start); if (!info) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange31(t, sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange38(t, sourceFile, info)); const name = idText(info.container.name); return [createCodeFixAction(fixId45, changes, [Diagnostics.Convert_0_to_mapped_object_type, name], fixId45, [Diagnostics.Convert_0_to_mapped_object_type, name])]; }, fixIds: [fixId45], getAllCodeActions: (context) => codeFixAll(context, errorCodes57, (changes, diag2) => { - const info = getInfo16(diag2.file, diag2.start); + const info = getInfo19(diag2.file, diag2.start); if (info) - doChange31(changes, diag2.file, info); + doChange38(changes, diag2.file, info); }) }); } @@ -147876,7 +153783,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/convertConstToLet.ts - function getInfo17(sourceFile, pos, program) { + function getInfo20(sourceFile, pos, program) { var _a; const checker = program.getTypeChecker(); const symbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, pos)); @@ -147890,7 +153797,7 @@ ${lanes.join("\n")} return; return { symbol, token: constToken }; } - function doChange32(changes, sourceFile, token) { + function doChange39(changes, sourceFile, token) { changes.replaceNode(sourceFile, token, factory.createToken(121 /* LetKeyword */)); } var fixId49, errorCodes61; @@ -147905,10 +153812,10 @@ ${lanes.join("\n")} errorCodes: errorCodes61, getCodeActions: function getCodeActionsToConvertConstToLet(context) { const { sourceFile, span, program } = context; - const info = getInfo17(sourceFile, span.start, program); + const info = getInfo20(sourceFile, span.start, program); if (info === void 0) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange32(t, sourceFile, info.token)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange39(t, sourceFile, info.token)); return [createCodeFixActionMaybeFixAll(fixId49, changes, Diagnostics.Convert_const_to_let, fixId49, Diagnostics.Convert_all_const_to_let)]; }, getAllCodeActions: (context) => { @@ -147916,10 +153823,10 @@ ${lanes.join("\n")} const seen = /* @__PURE__ */ new Map(); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { eachDiagnostic(context, errorCodes61, (diag2) => { - const info = getInfo17(diag2.file, diag2.start, program); + const info = getInfo20(diag2.file, diag2.start, program); if (info) { if (addToSeen(seen, getSymbolId(info.symbol))) { - return doChange32(changes, diag2.file, info.token); + return doChange39(changes, diag2.file, info.token); } } return void 0; @@ -147932,11 +153839,11 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixExpectedComma.ts - function getInfo18(sourceFile, pos, _) { + function getInfo21(sourceFile, pos, _) { const node = getTokenAtPosition(sourceFile, pos); return node.kind === 27 /* SemicolonToken */ && node.parent && (isObjectLiteralExpression(node.parent) || isArrayLiteralExpression(node.parent)) ? { node } : void 0; } - function doChange33(changes, sourceFile, { node }) { + function doChange40(changes, sourceFile, { node }) { const newNode = factory.createToken(28 /* CommaToken */); changes.replaceNode(sourceFile, node, newNode); } @@ -147953,10 +153860,10 @@ ${lanes.join("\n")} errorCodes: errorCodes62, getCodeActions(context) { const { sourceFile } = context; - const info = getInfo18(sourceFile, context.span.start, context.errorCode); + const info = getInfo21(sourceFile, context.span.start, context.errorCode); if (!info) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange33(t, sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange40(t, sourceFile, info)); return [createCodeFixAction( fixId50, changes, @@ -147967,9 +153874,9 @@ ${lanes.join("\n")} }, fixIds: [fixId50], getAllCodeActions: (context) => codeFixAll(context, errorCodes62, (changes, diag2) => { - const info = getInfo18(diag2.file, diag2.start, diag2.code); + const info = getInfo21(diag2.file, diag2.start, diag2.code); if (info) - doChange33(changes, context.sourceFile, info); + doChange40(changes, context.sourceFile, info); }) }); } @@ -148154,7 +154061,7 @@ ${lanes.join("\n")} init_inferFromUsage(); init_fixReturnTypeInAsyncFunction(); init_disableJsDiagnostics(); - init_helpers(); + init_helpers2(); init_generateAccessors(); init_fixInvalidImportSyntax(); init_fixStrictClassInitialization(); @@ -148662,11 +154569,11 @@ ${lanes.join("\n")} } } const dotDotDot = !isObject && dotDotDotToken ? "..." : ""; - const description2 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : ""; - return `@param {${dotDotDot}${type}} ${paramName} ${description2}`; + const description3 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : ""; + return `@param {${dotDotDot}${type}} ${paramName} ${description3}`; } else { - const description2 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : ""; - return `@param ${paramName} ${description2}`; + const description3 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : ""; + return `@param ${paramName} ${description3}`; } } function getJSDocParamNameWithInitializer(paramName, initializer) { @@ -149991,7 +155898,7 @@ ${lanes.join("\n")} ) : isEqualityOperatorKind(previousToken.kind) && isBinaryExpression(parent2) && isEqualityOperatorKind(parent2.operatorToken.kind) ? ( // completion at `x ===/**/` should be for the right side checker.getTypeAtLocation(parent2.left) - ) : checker.getContextualType(previousToken); + ) : checker.getContextualType(previousToken, 4 /* Completions */) || checker.getContextualType(previousToken); } } function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { @@ -151166,7 +157073,7 @@ ${lanes.join("\n")} return true; } } - return isDeclarationName(contextToken2) && !isShorthandPropertyAssignment(contextToken2.parent) && !isJsxAttribute(contextToken2.parent) && !((isClassLike(contextToken2.parent) || isInterfaceDeclaration(contextToken2.parent)) && (contextToken2 !== previousToken || position > previousToken.end)); + return isDeclarationName(contextToken2) && !isShorthandPropertyAssignment(contextToken2.parent) && !isJsxAttribute(contextToken2.parent) && !((isClassLike(contextToken2.parent) || isInterfaceDeclaration(contextToken2.parent) || isTypeParameterDeclaration(contextToken2.parent)) && (contextToken2 !== previousToken || position > previousToken.end)); } function isPreviousPropertyDeclarationTerminated(contextToken2, position2) { return contextToken2.kind !== 64 /* EqualsToken */ && (contextToken2.kind === 27 /* SemicolonToken */ || !positionsAreOnSameLine(contextToken2.end, position2, sourceFile)); @@ -153603,8 +159510,8 @@ ${lanes.join("\n")} const { displayParts, symbolKind } = ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning); return { displayParts, kind: symbolKind }; } - function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText) { - return { ...entryToDocumentSpan(entry), ...providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker) }; + function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText, quotePreference) { + return { ...entryToDocumentSpan(entry), ...providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker, quotePreference) }; } function toReferencedSymbolEntry(entry, symbol) { const referenceEntry = toReferenceEntry(entry); @@ -153640,7 +159547,7 @@ ${lanes.join("\n")} }; } } - function getPrefixAndSuffixText(entry, originalNode, checker) { + function getPrefixAndSuffixText(entry, originalNode, checker, quotePreference) { if (entry.kind !== 0 /* Span */ && isIdentifier(originalNode)) { const { node, kind } = entry; const parent2 = node.parent; @@ -153671,6 +159578,10 @@ ${lanes.join("\n")} return originalNode === entry.node || checker.getSymbolAtLocation(originalNode) === checker.getSymbolAtLocation(entry.node) ? { prefixText: name + " as " } : { suffixText: " as " + name }; } } + if (entry.kind !== 0 /* Span */ && isNumericLiteral(entry.node) && isAccessExpression(entry.node.parent)) { + const quote2 = getQuoteFromPreference(quotePreference); + return { prefixText: quote2, suffixText: quote2 }; + } return emptyOptions; } function toImplementationLocation(entry, checker) { @@ -157520,5113 +163431,6 @@ ${lanes.join("\n")} } }); - // src/services/refactorProvider.ts - function registerRefactor(name, refactor) { - refactors.set(name, refactor); - } - function getApplicableRefactors(context) { - return arrayFrom(flatMapIterator(refactors.values(), (refactor) => { - var _a; - return context.cancellationToken && context.cancellationToken.isCancellationRequested() || !((_a = refactor.kinds) == null ? void 0 : _a.some((kind) => refactorKindBeginsWith(kind, context.kind))) ? void 0 : refactor.getAvailableActions(context); - })); - } - function getEditsForRefactor(context, refactorName13, actionName2) { - const refactor = refactors.get(refactorName13); - return refactor && refactor.getEditsForAction(context, actionName2); - } - var refactors; - var init_refactorProvider = __esm({ - "src/services/refactorProvider.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactors = /* @__PURE__ */ new Map(); - } - }); - - // src/services/refactors/convertExport.ts - function getInfo19(context, considerPartialSpans = true) { - const { file, program } = context; - const span = getRefactorContextSpan(context); - const token = getTokenAtPosition(file, span.start); - const exportNode = !!(token.parent && getSyntacticModifierFlags(token.parent) & 1 /* Export */) && considerPartialSpans ? token.parent : getParentNodeInSpan(token, file, span); - if (!exportNode || !isSourceFile(exportNode.parent) && !(isModuleBlock(exportNode.parent) && isAmbientModule(exportNode.parent.parent))) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_export_statement) }; - } - const checker = program.getTypeChecker(); - const exportingModuleSymbol = getExportingModuleSymbol(exportNode.parent, checker); - const flags = getSyntacticModifierFlags(exportNode) || (isExportAssignment(exportNode) && !exportNode.isExportEquals ? 1025 /* ExportDefault */ : 0 /* None */); - const wasDefault = !!(flags & 1024 /* Default */); - if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { - return { error: getLocaleSpecificMessage(Diagnostics.This_file_already_has_a_default_export) }; - } - const noSymbolError = (id) => isIdentifier(id) && checker.getSymbolAtLocation(id) ? void 0 : { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_named_export) }; - switch (exportNode.kind) { - case 261 /* FunctionDeclaration */: - case 262 /* ClassDeclaration */: - case 263 /* InterfaceDeclaration */: - case 265 /* EnumDeclaration */: - case 264 /* TypeAliasDeclaration */: - case 266 /* ModuleDeclaration */: { - const node = exportNode; - if (!node.name) - return void 0; - return noSymbolError(node.name) || { exportNode: node, exportName: node.name, wasDefault, exportingModuleSymbol }; - } - case 242 /* VariableStatement */: { - const vs = exportNode; - if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { - return void 0; - } - const decl = first(vs.declarationList.declarations); - if (!decl.initializer) - return void 0; - Debug.assert(!wasDefault, "Can't have a default flag here"); - return noSymbolError(decl.name) || { exportNode: vs, exportName: decl.name, wasDefault, exportingModuleSymbol }; - } - case 276 /* ExportAssignment */: { - const node = exportNode; - if (node.isExportEquals) - return void 0; - return noSymbolError(node.expression) || { exportNode: node, exportName: node.expression, wasDefault, exportingModuleSymbol }; - } - default: - return void 0; - } - } - function doChange34(exportingSourceFile, program, info, changes, cancellationToken) { - changeExport(exportingSourceFile, info, changes, program.getTypeChecker()); - changeImports(program, info, changes, cancellationToken); - } - function changeExport(exportingSourceFile, { wasDefault, exportNode, exportName }, changes, checker) { - if (wasDefault) { - if (isExportAssignment(exportNode) && !exportNode.isExportEquals) { - const exp = exportNode.expression; - const spec = makeExportSpecifier(exp.text, exp.text); - changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports([spec]) - )); - } else { - changes.delete(exportingSourceFile, Debug.checkDefined(findModifier(exportNode, 90 /* DefaultKeyword */), "Should find a default keyword in modifier list")); - } - } else { - const exportKeyword = Debug.checkDefined(findModifier(exportNode, 95 /* ExportKeyword */), "Should find an export keyword in modifier list"); - switch (exportNode.kind) { - case 261 /* FunctionDeclaration */: - case 262 /* ClassDeclaration */: - case 263 /* InterfaceDeclaration */: - changes.insertNodeAfter(exportingSourceFile, exportKeyword, factory.createToken(90 /* DefaultKeyword */)); - break; - case 242 /* VariableStatement */: - const decl = first(exportNode.declarationList.declarations); - if (!ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile) && !decl.type) { - changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDefault(Debug.checkDefined(decl.initializer, "Initializer was previously known to be present"))); - break; - } - case 265 /* EnumDeclaration */: - case 264 /* TypeAliasDeclaration */: - case 266 /* ModuleDeclaration */: - changes.deleteModifier(exportingSourceFile, exportKeyword); - changes.insertNodeAfter(exportingSourceFile, exportNode, factory.createExportDefault(factory.createIdentifier(exportName.text))); - break; - default: - Debug.fail(`Unexpected exportNode kind ${exportNode.kind}`); - } - } - } - function changeImports(program, { wasDefault, exportName, exportingModuleSymbol }, changes, cancellationToken) { - const checker = program.getTypeChecker(); - const exportSymbol = Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol"); - ts_FindAllReferences_exports.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, (ref) => { - if (exportName === ref) - return; - const importingSourceFile = ref.getSourceFile(); - if (wasDefault) { - changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); - } else { - changeNamedToDefaultImport(importingSourceFile, ref, changes); - } - }); - } - function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { - const { parent: parent2 } = ref; - switch (parent2.kind) { - case 210 /* PropertyAccessExpression */: - changes.replaceNode(importingSourceFile, ref, factory.createIdentifier(exportName)); - break; - case 275 /* ImportSpecifier */: - case 280 /* ExportSpecifier */: { - const spec = parent2; - changes.replaceNode(importingSourceFile, spec, makeImportSpecifier2(exportName, spec.name.text)); - break; - } - case 272 /* ImportClause */: { - const clause = parent2; - Debug.assert(clause.name === ref, "Import clause name should match provided ref"); - const spec = makeImportSpecifier2(exportName, ref.text); - const { namedBindings } = clause; - if (!namedBindings) { - changes.replaceNode(importingSourceFile, ref, factory.createNamedImports([spec])); - } else if (namedBindings.kind === 273 /* NamespaceImport */) { - changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); - const quotePreference = isStringLiteral(clause.parent.moduleSpecifier) ? quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; - const newImport = makeImport( - /*defaultImport*/ - void 0, - [makeImportSpecifier2(exportName, ref.text)], - clause.parent.moduleSpecifier, - quotePreference - ); - changes.insertNodeAfter(importingSourceFile, clause.parent, newImport); - } else { - changes.delete(importingSourceFile, ref); - changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec); - } - break; - } - case 204 /* ImportType */: - const importTypeNode = parent2; - changes.replaceNode(importingSourceFile, parent2, factory.createImportTypeNode(importTypeNode.argument, importTypeNode.assertions, factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); - break; - default: - Debug.failBadSyntaxKind(parent2); - } - } - function changeNamedToDefaultImport(importingSourceFile, ref, changes) { - const parent2 = ref.parent; - switch (parent2.kind) { - case 210 /* PropertyAccessExpression */: - changes.replaceNode(importingSourceFile, ref, factory.createIdentifier("default")); - break; - case 275 /* ImportSpecifier */: { - const defaultImport = factory.createIdentifier(parent2.name.text); - if (parent2.parent.elements.length === 1) { - changes.replaceNode(importingSourceFile, parent2.parent, defaultImport); - } else { - changes.delete(importingSourceFile, parent2); - changes.insertNodeBefore(importingSourceFile, parent2.parent, defaultImport); - } - break; - } - case 280 /* ExportSpecifier */: { - changes.replaceNode(importingSourceFile, parent2, makeExportSpecifier("default", parent2.name.text)); - break; - } - default: - Debug.assertNever(parent2, `Unexpected parent kind ${parent2.kind}`); - } - } - function makeImportSpecifier2(propertyName, name) { - return factory.createImportSpecifier( - /*isTypeOnly*/ - false, - propertyName === name ? void 0 : factory.createIdentifier(propertyName), - factory.createIdentifier(name) - ); - } - function makeExportSpecifier(propertyName, name) { - return factory.createExportSpecifier( - /*isTypeOnly*/ - false, - propertyName === name ? void 0 : factory.createIdentifier(propertyName), - factory.createIdentifier(name) - ); - } - function getExportingModuleSymbol(parent2, checker) { - if (isSourceFile(parent2)) { - return parent2.symbol; - } - const symbol = parent2.parent.symbol; - if (symbol.valueDeclaration && isExternalModuleAugmentation(symbol.valueDeclaration)) { - return checker.getMergedSymbol(symbol); - } - return symbol; - } - var refactorName, defaultToNamedAction, namedToDefaultAction; - var init_convertExport = __esm({ - "src/services/refactors/convertExport.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName = "Convert export"; - defaultToNamedAction = { - name: "Convert default export to named export", - description: Diagnostics.Convert_default_export_to_named_export.message, - kind: "refactor.rewrite.export.named" - }; - namedToDefaultAction = { - name: "Convert named export to default export", - description: Diagnostics.Convert_named_export_to_default_export.message, - kind: "refactor.rewrite.export.default" - }; - registerRefactor(refactorName, { - kinds: [ - defaultToNamedAction.kind, - namedToDefaultAction.kind - ], - getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndDefaultExports(context) { - const info = getInfo19(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - const action = info.wasDefault ? defaultToNamedAction : namedToDefaultAction; - return [{ name: refactorName, description: action.description, actions: [action] }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [ - { name: refactorName, description: Diagnostics.Convert_default_export_to_named_export.message, actions: [ - { ...defaultToNamedAction, notApplicableReason: info.error }, - { ...namedToDefaultAction, notApplicableReason: info.error } - ] } - ]; - } - return emptyArray; - }, - getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndDefaultExports(context, actionName2) { - Debug.assert(actionName2 === defaultToNamedAction.name || actionName2 === namedToDefaultAction.name, "Unexpected action name"); - const info = getInfo19(context); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange34(context.file, context.program, info, t, context.cancellationToken)); - return { edits, renameFilename: void 0, renameLocation: void 0 }; - } - }); - } - }); - - // src/services/refactors/convertImport.ts - function getImportConversionInfo(context, considerPartialSpans = true) { - const { file } = context; - const span = getRefactorContextSpan(context); - const token = getTokenAtPosition(file, span.start); - const importDecl = considerPartialSpans ? findAncestor(token, isImportDeclaration) : getParentNodeInSpan(token, file, span); - if (!importDecl || !isImportDeclaration(importDecl)) - return { error: "Selection is not an import declaration." }; - const end = span.start + span.length; - const nextToken = findNextToken(importDecl, importDecl.parent, file); - if (nextToken && end > nextToken.getStart()) - return void 0; - const { importClause } = importDecl; - if (!importClause) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_import_clause) }; - } - if (!importClause.namedBindings) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_namespace_import_or_named_imports) }; - } - if (importClause.namedBindings.kind === 273 /* NamespaceImport */) { - return { convertTo: 0 /* Named */, import: importClause.namedBindings }; - } - const shouldUseDefault = getShouldUseDefault(context.program, importClause); - return shouldUseDefault ? { convertTo: 1 /* Default */, import: importClause.namedBindings } : { convertTo: 2 /* Namespace */, import: importClause.namedBindings }; - } - function getShouldUseDefault(program, importClause) { - return getAllowSyntheticDefaultImports(program.getCompilerOptions()) && isExportEqualsModule(importClause.parent.moduleSpecifier, program.getTypeChecker()); - } - function doChange35(sourceFile, program, changes, info) { - const checker = program.getTypeChecker(); - if (info.convertTo === 0 /* Named */) { - doChangeNamespaceToNamed(sourceFile, checker, changes, info.import, getAllowSyntheticDefaultImports(program.getCompilerOptions())); - } else { - doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, info.import, info.convertTo === 1 /* Default */); - } - } - function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { - let usedAsNamespaceOrDefault = false; - const nodesToReplace = []; - const conflictingNames = /* @__PURE__ */ new Map(); - ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, (id) => { - if (!isPropertyAccessOrQualifiedName(id.parent)) { - usedAsNamespaceOrDefault = true; - } else { - const exportName = getRightOfPropertyAccessOrQualifiedName(id.parent).text; - if (checker.resolveName( - exportName, - id, - 67108863 /* All */, - /*excludeGlobals*/ - true - )) { - conflictingNames.set(exportName, true); - } - Debug.assert(getLeftOfPropertyAccessOrQualifiedName(id.parent) === id, "Parent expression should match id"); - nodesToReplace.push(id.parent); - } - }); - const exportNameToImportName = /* @__PURE__ */ new Map(); - for (const propertyAccessOrQualifiedName of nodesToReplace) { - const exportName = getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName).text; - let importName = exportNameToImportName.get(exportName); - if (importName === void 0) { - exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? getUniqueName(exportName, sourceFile) : exportName); - } - changes.replaceNode(sourceFile, propertyAccessOrQualifiedName, factory.createIdentifier(importName)); - } - const importSpecifiers = []; - exportNameToImportName.forEach((name, propertyName) => { - importSpecifiers.push(factory.createImportSpecifier( - /*isTypeOnly*/ - false, - name === propertyName ? void 0 : factory.createIdentifier(propertyName), - factory.createIdentifier(name) - )); - }); - const importDecl = toConvert.parent.parent; - if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) { - changes.insertNodeAfter(sourceFile, importDecl, updateImport( - importDecl, - /*defaultImportName*/ - void 0, - importSpecifiers - )); - } else { - changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? factory.createIdentifier(toConvert.name.text) : void 0, importSpecifiers)); - } - } - function getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { - return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.name : propertyAccessOrQualifiedName.right; - } - function getLeftOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { - return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.expression : propertyAccessOrQualifiedName.left; - } - function doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, toConvert, shouldUseDefault = getShouldUseDefault(program, toConvert.parent)) { - const checker = program.getTypeChecker(); - const importDecl = toConvert.parent.parent; - const { moduleSpecifier } = importDecl; - const toConvertSymbols = /* @__PURE__ */ new Set(); - toConvert.elements.forEach((namedImport) => { - const symbol = checker.getSymbolAtLocation(namedImport.name); - if (symbol) { - toConvertSymbols.add(symbol); - } - }); - const preferredName = moduleSpecifier && isStringLiteral(moduleSpecifier) ? ts_codefix_exports.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 99 /* ESNext */) : "module"; - function hasNamespaceNameConflict(namedImport) { - return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(namedImport.name, checker, sourceFile, (id) => { - const symbol = checker.resolveName( - preferredName, - id, - 67108863 /* All */, - /*excludeGlobals*/ - true - ); - if (symbol) { - if (toConvertSymbols.has(symbol)) { - return isExportSpecifier(id.parent); - } - return true; - } - return false; - }); - } - const namespaceNameConflicts = toConvert.elements.some(hasNamespaceNameConflict); - const namespaceImportName = namespaceNameConflicts ? getUniqueName(preferredName, sourceFile) : preferredName; - const neededNamedImports = /* @__PURE__ */ new Set(); - for (const element of toConvert.elements) { - const propertyName = (element.propertyName || element.name).text; - ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, (id) => { - const access = factory.createPropertyAccessExpression(factory.createIdentifier(namespaceImportName), propertyName); - if (isShorthandPropertyAssignment(id.parent)) { - changes.replaceNode(sourceFile, id.parent, factory.createPropertyAssignment(id.text, access)); - } else if (isExportSpecifier(id.parent)) { - neededNamedImports.add(element); - } else { - changes.replaceNode(sourceFile, id, access); - } - }); - } - changes.replaceNode(sourceFile, toConvert, shouldUseDefault ? factory.createIdentifier(namespaceImportName) : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName))); - if (neededNamedImports.size) { - const newNamedImports = 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*/ - void 0, - newNamedImports - )); - } - } - function isExportEqualsModule(moduleSpecifier, checker) { - const externalModule = checker.resolveExternalModuleName(moduleSpecifier); - if (!externalModule) - return false; - const exportEquals = checker.resolveExternalModuleSymbol(externalModule); - return externalModule !== exportEquals; - } - function updateImport(old, defaultImportName, elements) { - return factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - /*isTypeOnly*/ - false, - defaultImportName, - elements && elements.length ? factory.createNamedImports(elements) : void 0 - ), - old.moduleSpecifier, - /*assertClause*/ - void 0 - ); - } - var refactorName2, actions; - var init_convertImport = __esm({ - "src/services/refactors/convertImport.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName2 = "Convert import"; - actions = { - [0 /* Named */]: { - name: "Convert namespace import to named imports", - description: Diagnostics.Convert_namespace_import_to_named_imports.message, - kind: "refactor.rewrite.import.named" - }, - [2 /* Namespace */]: { - name: "Convert named imports to namespace import", - description: Diagnostics.Convert_named_imports_to_namespace_import.message, - kind: "refactor.rewrite.import.namespace" - }, - [1 /* Default */]: { - name: "Convert named imports to default import", - description: Diagnostics.Convert_named_imports_to_default_import.message, - kind: "refactor.rewrite.import.default" - } - }; - registerRefactor(refactorName2, { - kinds: getOwnValues(actions).map((a) => a.kind), - getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndNamespacedImports(context) { - const info = getImportConversionInfo(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - const action = actions[info.convertTo]; - return [{ name: refactorName2, description: action.description, actions: [action] }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return getOwnValues(actions).map((action) => ({ - name: refactorName2, - description: action.description, - actions: [{ ...action, notApplicableReason: info.error }] - })); - } - return emptyArray; - }, - getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndNamespacedImports(context, actionName2) { - Debug.assert(some(getOwnValues(actions), (action) => action.name === actionName2), "Unexpected action name"); - const info = getImportConversionInfo(context); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange35(context.file, context.program, t, info)); - return { edits, renameFilename: void 0, renameLocation: void 0 }; - } - }); - } - }); - - // src/services/refactors/extractType.ts - function getRangeToExtract(context, considerEmptySpans = true) { - const { file, startPosition } = context; - const isJS = isSourceFileJS(file); - const current = getTokenAtPosition(file, startPosition); - 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))); - if (!selection || !isTypeNode(selection)) - return { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) }; - const checker = context.program.getTypeChecker(); - const enclosingNode = getEnclosingNode(selection, isJS); - if (enclosingNode === void 0) - return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }; - const typeParameters = collectTypeParameters(checker, selection, enclosingNode, file); - if (!typeParameters) - return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }; - const typeElements = flattenTypeLiteralNodeReference(checker, selection); - return { isJS, selection, enclosingNode, typeParameters, typeElements }; - } - function flattenTypeLiteralNodeReference(checker, node) { - if (!node) - return void 0; - if (isIntersectionTypeNode(node)) { - const result = []; - const seen = /* @__PURE__ */ new Map(); - for (const type of node.types) { - const flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type); - if (!flattenedTypeMembers || !flattenedTypeMembers.every((type2) => type2.name && addToSeen(seen, getNameFromPropertyName(type2.name)))) { - return void 0; - } - addRange(result, flattenedTypeMembers); - } - return result; - } else if (isParenthesizedTypeNode(node)) { - return flattenTypeLiteralNodeReference(checker, node.type); - } else if (isTypeLiteralNode(node)) { - return node.members; - } - return void 0; - } - function rangeContainsSkipTrivia(r1, node, file) { - return rangeContainsStartEnd(r1, skipTrivia(file.text, node.pos), node.end); - } - function collectTypeParameters(checker, selection, enclosingNode, file) { - const result = []; - return visitor(selection) ? void 0 : result; - function visitor(node) { - if (isTypeReferenceNode(node)) { - if (isIdentifier(node.typeName)) { - const typeName = node.typeName; - const symbol = checker.resolveName( - typeName.text, - typeName, - 262144 /* TypeParameter */, - /*excludeGlobals*/ - true - ); - for (const decl of (symbol == null ? void 0 : symbol.declarations) || emptyArray) { - if (isTypeParameterDeclaration(decl) && decl.getSourceFile() === file) { - if (decl.name.escapedText === typeName.escapedText && rangeContainsSkipTrivia(decl, selection, file)) { - return true; - } - if (rangeContainsSkipTrivia(enclosingNode, decl, file) && !rangeContainsSkipTrivia(selection, decl, file)) { - pushIfUnique(result, decl); - break; - } - } - } - } - } else if (isInferTypeNode(node)) { - const conditionalTypeNode = findAncestor(node, (n) => isConditionalTypeNode(n) && rangeContainsSkipTrivia(n.extendsType, node, file)); - if (!conditionalTypeNode || !rangeContainsSkipTrivia(selection, conditionalTypeNode, file)) { - return true; - } - } else if (isTypePredicateNode(node) || isThisTypeNode(node)) { - const functionLikeNode = findAncestor(node.parent, isFunctionLike); - if (functionLikeNode && functionLikeNode.type && rangeContainsSkipTrivia(functionLikeNode.type, node, file) && !rangeContainsSkipTrivia(selection, functionLikeNode, file)) { - return true; - } - } else if (isTypeQueryNode(node)) { - if (isIdentifier(node.exprName)) { - const symbol = checker.resolveName( - node.exprName.text, - node.exprName, - 111551 /* Value */, - /*excludeGlobals*/ - false - ); - if ((symbol == null ? void 0 : symbol.valueDeclaration) && rangeContainsSkipTrivia(enclosingNode, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) { - return true; - } - } else { - if (isThisIdentifier(node.exprName.left) && !rangeContainsSkipTrivia(selection, node.parent, file)) { - return true; - } - } - } - if (file && isTupleTypeNode(node) && getLineAndCharacterOfPosition(file, node.pos).line === getLineAndCharacterOfPosition(file, node.end).line) { - setEmitFlags(node, 1 /* SingleLine */); - } - return forEachChild(node, visitor); - } - } - function doTypeAliasChange(changes, file, name, info) { - const { enclosingNode, selection, typeParameters } = info; - const newTypeNode = factory.createTypeAliasDeclaration( - /*modifiers*/ - void 0, - name, - typeParameters.map((id) => factory.updateTypeParameterDeclaration( - id, - id.modifiers, - id.name, - id.constraint, - /*defaultType*/ - void 0 - )), - selection - ); - changes.insertNodeBefore( - file, - enclosingNode, - ignoreSourceNewlines(newTypeNode), - /*blankLineBetween*/ - true - ); - changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( - id.name, - /*typeArguments*/ - void 0 - ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace }); - } - function doInterfaceChange(changes, file, name, info) { - var _a; - const { enclosingNode, selection, typeParameters, typeElements } = info; - const newTypeNode = factory.createInterfaceDeclaration( - /*modifiers*/ - void 0, - name, - typeParameters, - /*heritageClauses*/ - void 0, - typeElements - ); - setTextRange(newTypeNode, (_a = typeElements[0]) == null ? void 0 : _a.parent); - changes.insertNodeBefore( - file, - enclosingNode, - ignoreSourceNewlines(newTypeNode), - /*blankLineBetween*/ - true - ); - changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( - id.name, - /*typeArguments*/ - void 0 - ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace }); - } - function doTypedefChange(changes, context, file, name, info) { - var _a; - const { enclosingNode, selection, typeParameters } = info; - setEmitFlags(selection, 3072 /* NoComments */ | 4096 /* NoNestedComments */); - const node = factory.createJSDocTypedefTag( - factory.createIdentifier("typedef"), - factory.createJSDocTypeExpression(selection), - factory.createIdentifier(name) - ); - const templates = []; - forEach(typeParameters, (typeParameter) => { - const constraint = getEffectiveConstraintOfTypeParameter(typeParameter); - const parameter = factory.createTypeParameterDeclaration( - /*modifiers*/ - void 0, - typeParameter.name - ); - const template = factory.createJSDocTemplateTag( - factory.createIdentifier("template"), - constraint && cast(constraint, isJSDocTypeExpression), - [parameter] - ); - templates.push(template); - }); - const jsDoc = factory.createJSDocComment( - /*comment*/ - void 0, - factory.createNodeArray(concatenate(templates, [node])) - ); - if (isJSDoc(enclosingNode)) { - const pos = enclosingNode.getStart(file); - const newLineCharacter = getNewLineOrDefaultFromHost(context.host, (_a = context.formatContext) == null ? void 0 : _a.options); - changes.insertNodeAt(file, enclosingNode.getStart(file), jsDoc, { - suffix: newLineCharacter + newLineCharacter + file.text.slice(getPrecedingNonSpaceCharacterPosition(file.text, pos - 1), pos) - }); - } else { - changes.insertNodeBefore( - file, - enclosingNode, - jsDoc, - /*blankLineBetween*/ - true - ); - } - changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( - id.name, - /*typeArguments*/ - void 0 - )))); - } - function getEnclosingNode(node, isJS) { - return findAncestor(node, isStatement) || (isJS ? findAncestor(node, isJSDoc) : void 0); - } - var refactorName3, extractToTypeAliasAction, extractToInterfaceAction, extractToTypeDefAction; - var init_extractType = __esm({ - "src/services/refactors/extractType.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName3 = "Extract type"; - extractToTypeAliasAction = { - name: "Extract to type alias", - description: getLocaleSpecificMessage(Diagnostics.Extract_to_type_alias), - kind: "refactor.extract.type" - }; - extractToInterfaceAction = { - name: "Extract to interface", - description: getLocaleSpecificMessage(Diagnostics.Extract_to_interface), - kind: "refactor.extract.interface" - }; - extractToTypeDefAction = { - name: "Extract to typedef", - description: getLocaleSpecificMessage(Diagnostics.Extract_to_typedef), - kind: "refactor.extract.typedef" - }; - registerRefactor(refactorName3, { - kinds: [ - extractToTypeAliasAction.kind, - extractToInterfaceAction.kind, - extractToTypeDefAction.kind - ], - getAvailableActions: function getRefactorActionsToExtractType(context) { - const info = getRangeToExtract(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - return [{ - name: refactorName3, - description: getLocaleSpecificMessage(Diagnostics.Extract_type), - actions: info.isJS ? [extractToTypeDefAction] : append([extractToTypeAliasAction], info.typeElements && extractToInterfaceAction) - }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorName3, - description: getLocaleSpecificMessage(Diagnostics.Extract_type), - actions: [ - { ...extractToTypeDefAction, notApplicableReason: info.error }, - { ...extractToTypeAliasAction, notApplicableReason: info.error }, - { ...extractToInterfaceAction, notApplicableReason: info.error } - ] - }]; - } - return emptyArray; - }, - getEditsForAction: function getRefactorEditsToExtractType(context, actionName2) { - const { file } = context; - const info = getRangeToExtract(context); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected to find a range to extract"); - const name = getUniqueName("NewType", file); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (changes) => { - switch (actionName2) { - case extractToTypeAliasAction.name: - Debug.assert(!info.isJS, "Invalid actionName/JS combo"); - return doTypeAliasChange(changes, file, name, info); - case extractToTypeDefAction.name: - Debug.assert(info.isJS, "Invalid actionName/JS combo"); - return doTypedefChange(changes, context, file, name, info); - case extractToInterfaceAction.name: - Debug.assert(!info.isJS && !!info.typeElements, "Invalid actionName/JS combo"); - return doInterfaceChange(changes, file, name, info); - default: - Debug.fail("Unexpected action name"); - } - }); - const renameFilename = file.fileName; - const renameLocation = getRenameLocation( - edits, - renameFilename, - name, - /*preferLastLocation*/ - false - ); - return { edits, renameFilename, renameLocation }; - } - }); - } - }); - - // src/services/refactors/helpers.ts - function isRefactorErrorInfo(info) { - return info.error !== void 0; - } - function refactorKindBeginsWith(known, requested) { - if (!requested) - return true; - return known.substr(0, requested.length) === requested; - } - var init_helpers2 = __esm({ - "src/services/refactors/helpers.ts"() { - "use strict"; - } - }); - - // src/services/refactors/moveToNewFile.ts - function getRangeToMove(context) { - const { file } = context; - const range = createTextRangeFromSpan(getRefactorContextSpan(context)); - const { statements } = file; - const startNodeIndex = findIndex(statements, (s) => s.end > range.pos); - if (startNodeIndex === -1) - return void 0; - const startStatement = statements[startNodeIndex]; - if (isNamedDeclaration(startStatement) && startStatement.name && rangeContainsRange(startStatement.name, range)) { - return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; - } - if (range.pos > startStatement.getStart(file)) - return void 0; - const afterEndNodeIndex = findIndex(statements, (s) => s.end > range.end, startNodeIndex); - if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) - return void 0; - return { - toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), - afterLast: afterEndNodeIndex === -1 ? void 0 : statements[afterEndNodeIndex] - }; - } - function doChange36(oldFile, program, toMove, changes, host, preferences) { - const checker = program.getTypeChecker(); - const usage = getUsageInfo(oldFile, toMove.all, checker); - 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.oldFileImportsFromNewFile, usage.movedSymbols), - extension, - currentDirectory, - host - ) - ) + extension; - changes.createNewFile(oldFile, newFilename, getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences)); - addNewFileToTsconfig(program, changes, oldFile.fileName, newFilename, hostGetCanonicalFileName(host)); - } - function getStatementsToMove(context) { - const rangeToMove = getRangeToMove(context); - if (rangeToMove === void 0) - return void 0; - const all = []; - const ranges = []; - const { toMove, afterLast } = rangeToMove; - getRangesWhere(toMove, isAllowedStatementToMove, (start, afterEndIndex) => { - for (let i = start; i < afterEndIndex; i++) - all.push(toMove[i]); - ranges.push({ first: toMove[start], afterLast }); - }); - return all.length === 0 ? void 0 : { all, ranges }; - } - function isAllowedStatementToMove(statement) { - return !isPureImport(statement) && !isPrologueDirective(statement); - } - function isPureImport(node) { - switch (node.kind) { - case 271 /* ImportDeclaration */: - return true; - case 270 /* ImportEqualsDeclaration */: - return !hasSyntacticModifier(node, 1 /* Export */); - case 242 /* VariableStatement */: - return node.declarationList.declarations.every((d) => !!d.initializer && isRequireCall( - d.initializer, - /*requireStringLiteralLikeArgument*/ - true - )); - default: - return false; - } - } - function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { - const cfg = program.getCompilerOptions().configFile; - if (!cfg) - return; - const newFileAbsolutePath = normalizePath(combinePaths(oldFileName, "..", newFileNameWithExtension)); - 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) => 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); - } - } - function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences) { - const checker = program.getTypeChecker(); - const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective); - if (oldFile.externalModuleIndicator === void 0 && oldFile.commonJsModuleIndicator === void 0 && usage.oldImportsNeededByNewFile.size() === 0) { - deleteMovedStatements(oldFile, toMove.ranges, changes); - return [...prologueDirectives, ...toMove.all]; - } - const useEsModuleSyntax = !!oldFile.externalModuleIndicator; - const quotePreference = getQuotePreference(oldFile, preferences); - const importsFromNewFile = createOldFileImportsFromNewFile(oldFile, usage.oldFileImportsFromNewFile, newFilename, program, host, useEsModuleSyntax, quotePreference); - if (importsFromNewFile) { - insertImports( - changes, - oldFile, - importsFromNewFile, - /*blankLineBetween*/ - true, - preferences - ); - } - deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); - deleteMovedStatements(oldFile, toMove.ranges, changes); - updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, newFilename, quotePreference); - const imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference); - const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEsModuleSyntax); - if (imports.length && body.length) { - return [ - ...prologueDirectives, - ...imports, - 4 /* NewLineTrivia */, - ...body - ]; - } - return [ - ...prologueDirectives, - ...imports, - ...body - ]; - } - function deleteMovedStatements(sourceFile, moved, changes) { - for (const { first: first2, afterLast } of moved) { - changes.deleteNodeRangeExcludingEnd(sourceFile, first2, afterLast); - } - } - function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { - for (const statement of oldFile.statements) { - if (contains(toMove, statement)) - continue; - forEachImportInStatement(statement, (i) => deleteUnusedImports(oldFile, i, changes, (name) => toDelete.has(checker.getSymbolAtLocation(name)))); - } - } - function updateImportsInOtherFiles(changes, program, host, oldFile, movedSymbols, newFilename, quotePreference) { - const checker = program.getTypeChecker(); - for (const sourceFile of program.getSourceFiles()) { - if (sourceFile === oldFile) - continue; - for (const statement of sourceFile.statements) { - forEachImportInStatement(statement, (importNode) => { - if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) - return; - const shouldMove = (name) => { - const symbol = isBindingElement(name.parent) ? getPropertySymbolFromBindingElement(checker, name.parent) : skipAlias(checker.getSymbolAtLocation(name), checker); - return !!symbol && movedSymbols.has(symbol); - }; - deleteUnusedImports(sourceFile, importNode, changes, shouldMove); - const pathToNewFileWithExtension = resolvePath(getDirectoryPath(oldFile.path), newFilename); - const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToNewFileWithExtension, createModuleSpecifierResolutionHost(program, host)); - const newImportDeclaration = filterImport(importNode, makeStringLiteral(newModuleSpecifier, quotePreference), shouldMove); - if (newImportDeclaration) - changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); - const ns = getNamespaceLikeImport(importNode); - if (ns) - updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, ns, importNode, quotePreference); - }); - } - } - } - function getNamespaceLikeImport(node) { - switch (node.kind) { - case 271 /* ImportDeclaration */: - return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 273 /* NamespaceImport */ ? node.importClause.namedBindings.name : void 0; - case 270 /* ImportEqualsDeclaration */: - return node.name; - case 259 /* VariableDeclaration */: - return tryCast(node.name, isIdentifier); - default: - return Debug.assertNever(node, `Unexpected node kind ${node.kind}`); - } - } - function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, oldImportId, oldImportNode, quotePreference) { - const preferredNewNamespaceName = ts_codefix_exports.moduleSpecifierToValidIdentifier(newModuleSpecifier, 99 /* ESNext */); - let needUniqueName = false; - const toChange = []; - ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, (ref) => { - if (!isPropertyAccessExpression(ref.parent)) - return; - needUniqueName = needUniqueName || !!checker.resolveName( - preferredNewNamespaceName, - ref, - 67108863 /* All */, - /*excludeGlobals*/ - true - ); - if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) { - toChange.push(ref); - } - }); - if (toChange.length) { - const newNamespaceName = needUniqueName ? getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; - for (const ref of toChange) { - changes.replaceNode(sourceFile, ref, factory.createIdentifier(newNamespaceName)); - } - changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, preferredNewNamespaceName, newModuleSpecifier, quotePreference)); - } - } - function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier, quotePreference) { - const newNamespaceId = factory.createIdentifier(newNamespaceName); - const newModuleString = makeStringLiteral(newModuleSpecifier, quotePreference); - switch (node.kind) { - case 271 /* ImportDeclaration */: - return factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - /*isTypeOnly*/ - false, - /*name*/ - void 0, - factory.createNamespaceImport(newNamespaceId) - ), - newModuleString, - /*assertClause*/ - void 0 - ); - case 270 /* ImportEqualsDeclaration */: - return factory.createImportEqualsDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - newNamespaceId, - factory.createExternalModuleReference(newModuleString) - ); - case 259 /* VariableDeclaration */: - return factory.createVariableDeclaration( - newNamespaceId, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - createRequireCall(newModuleString) - ); - default: - return Debug.assertNever(node, `Unexpected node kind ${node.kind}`); - } - } - function moduleSpecifierFromImport(i) { - return i.kind === 271 /* ImportDeclaration */ ? i.moduleSpecifier : i.kind === 270 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]; - } - function forEachImportInStatement(statement, cb) { - if (isImportDeclaration(statement)) { - if (isStringLiteral(statement.moduleSpecifier)) - cb(statement); - } else if (isImportEqualsDeclaration(statement)) { - if (isExternalModuleReference(statement.moduleReference) && isStringLiteralLike(statement.moduleReference.expression)) { - cb(statement); - } - } else if (isVariableStatement(statement)) { - for (const decl of statement.declarationList.declarations) { - if (decl.initializer && isRequireCall( - decl.initializer, - /*requireStringLiteralLikeArgument*/ - true - )) { - cb(decl); - } - } - } - } - function createOldFileImportsFromNewFile(sourceFile, newFileNeedExport, newFileNameWithExtension, program, host, useEs6Imports, quotePreference) { - let defaultImport; - const imports = []; - newFileNeedExport.forEach((symbol) => { - if (symbol.escapedName === "default" /* Default */) { - defaultImport = factory.createIdentifier(symbolNameNoDefault(symbol)); - } else { - imports.push(symbol.name); - } - }); - return makeImportOrRequire(sourceFile, defaultImport, imports, newFileNameWithExtension, program, host, useEs6Imports, quotePreference); - } - function makeImportOrRequire(sourceFile, defaultImport, imports, newFileNameWithExtension, program, host, useEs6Imports, quotePreference) { - const pathToNewFile = resolvePath(getDirectoryPath(sourceFile.path), newFileNameWithExtension); - const pathToNewFileWithCorrectExtension = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToNewFile, createModuleSpecifierResolutionHost(program, host)); - if (useEs6Imports) { - const specifiers = imports.map((i) => factory.createImportSpecifier( - /*isTypeOnly*/ - false, - /*propertyName*/ - void 0, - factory.createIdentifier(i) - )); - return makeImportIfNecessary(defaultImport, specifiers, pathToNewFileWithCorrectExtension, quotePreference); - } else { - Debug.assert(!defaultImport, "No default import should exist"); - const bindingElements = imports.map((i) => factory.createBindingElement( - /*dotDotDotToken*/ - void 0, - /*propertyName*/ - void 0, - i - )); - return bindingElements.length ? makeVariableStatement( - factory.createObjectBindingPattern(bindingElements), - /*type*/ - void 0, - createRequireCall(makeStringLiteral(pathToNewFileWithCorrectExtension, quotePreference)) - ) : void 0; - } - } - function makeVariableStatement(name, type, initializer, flags = 2 /* Const */) { - return factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([factory.createVariableDeclaration( - name, - /*exclamationToken*/ - void 0, - type, - initializer - )], flags) - ); - } - function createRequireCall(moduleSpecifier) { - return factory.createCallExpression( - factory.createIdentifier("require"), - /*typeArguments*/ - void 0, - [moduleSpecifier] - ); - } - function addExports(sourceFile, toMove, needExport, useEs6Exports) { - return flatMap(toMove, (statement) => { - if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, (d) => { - var _a; - return needExport.has(Debug.checkDefined((_a = tryCast(d, canHaveSymbol)) == null ? void 0 : _a.symbol)); - })) { - const exports = addExport(statement, useEs6Exports); - if (exports) - return exports; - } - return statement; - }); - } - function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { - switch (importDecl.kind) { - case 271 /* ImportDeclaration */: - deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); - break; - case 270 /* ImportEqualsDeclaration */: - if (isUnused(importDecl.name)) { - changes.delete(sourceFile, importDecl); - } - break; - case 259 /* VariableDeclaration */: - deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); - break; - default: - Debug.assertNever(importDecl, `Unexpected import decl kind ${importDecl.kind}`); - } - } - function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { - if (!importDecl.importClause) - return; - const { name, namedBindings } = importDecl.importClause; - const defaultUnused = !name || isUnused(name); - const namedBindingsUnused = !namedBindings || (namedBindings.kind === 273 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every((e) => isUnused(e.name))); - if (defaultUnused && namedBindingsUnused) { - changes.delete(sourceFile, importDecl); - } else { - if (name && defaultUnused) { - changes.delete(sourceFile, name); - } - if (namedBindings) { - if (namedBindingsUnused) { - changes.replaceNode( - sourceFile, - importDecl.importClause, - factory.updateImportClause( - importDecl.importClause, - importDecl.importClause.isTypeOnly, - name, - /*namedBindings*/ - void 0 - ) - ); - } else if (namedBindings.kind === 274 /* NamedImports */) { - for (const element of namedBindings.elements) { - if (isUnused(element.name)) - changes.delete(sourceFile, element); - } - } - } - } - } - function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { - const { name } = varDecl; - switch (name.kind) { - case 80 /* 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 - ); - } else { - changes.delete(sourceFile, name); - } - } - break; - case 206 /* ArrayBindingPattern */: - break; - case 205 /* 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 - ); - } else { - for (const element of name.elements) { - if (isIdentifier(element.name) && isUnused(element.name)) { - changes.delete(sourceFile, element.name); - } - } - } - break; - } - } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference) { - const copiedOldImports = []; - for (const oldStatement of oldFile.statements) { - forEachImportInStatement(oldStatement, (i) => { - append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); - }); - } - let oldFileDefault; - const oldFileNamedImports = []; - const markSeenTop = nodeSeenTracker(); - newFileImportsFromOldFile.forEach((symbol) => { - if (!symbol.declarations) { - return; - } - for (const decl of symbol.declarations) { - if (!isTopLevelDeclaration(decl)) - continue; - const name = nameOfTopLevelDeclaration(decl); - if (!name) - continue; - const top = getTopLevelDeclarationStatement(decl); - if (markSeenTop(top)) { - addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); - } - if (hasSyntacticModifier(decl, 1024 /* Default */)) { - oldFileDefault = name; - } else { - oldFileNamedImports.push(name.text); - } - } - }); - append(copiedOldImports, makeImportOrRequire(oldFile, oldFileDefault, oldFileNamedImports, getBaseFileName(oldFile.fileName), program, host, useEsModuleSyntax, quotePreference)); - return copiedOldImports; - } - function makeUniqueFilename(proposedFilename, extension, inDirectory, host) { - let newFilename = proposedFilename; - for (let i = 1; ; i++) { - const name = combinePaths(inDirectory, newFilename + extension); - if (!host.fileExists(name)) - return newFilename; - newFilename = `${proposedFilename}.${i}`; - } - } - function inferNewFilename(importsFromNewFile, movedSymbols) { - return importsFromNewFile.forEachEntry(symbolNameNoDefault) || movedSymbols.forEachEntry(symbolNameNoDefault) || "newFile"; - } - function getUsageInfo(oldFile, toMove, checker) { - const movedSymbols = new SymbolSet(); - const oldImportsNeededByNewFile = new SymbolSet(); - const newFileImportsFromOldFile = new SymbolSet(); - const containsJsx = find(toMove, (statement) => !!(statement.transformFlags & 2 /* ContainsJsx */)); - const jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx); - if (jsxNamespaceSymbol) { - oldImportsNeededByNewFile.add(jsxNamespaceSymbol); - } - for (const statement of toMove) { - forEachTopLevelDeclaration(statement, (decl) => { - movedSymbols.add(Debug.checkDefined(isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here")); - }); - } - for (const statement of toMove) { - forEachReference(statement, checker, (symbol) => { - if (!symbol.declarations) - return; - for (const decl of symbol.declarations) { - if (isInImport(decl)) { - oldImportsNeededByNewFile.add(symbol); - } else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) { - newFileImportsFromOldFile.add(symbol); - } - } - }); - } - const unusedImportsFromOldFile = oldImportsNeededByNewFile.clone(); - const oldFileImportsFromNewFile = new SymbolSet(); - for (const statement of oldFile.statements) { - if (contains(toMove, statement)) - continue; - if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) { - unusedImportsFromOldFile.delete(jsxNamespaceSymbol); - } - forEachReference(statement, checker, (symbol) => { - if (movedSymbols.has(symbol)) - oldFileImportsFromNewFile.add(symbol); - unusedImportsFromOldFile.delete(symbol); - }); - } - return { movedSymbols, newFileImportsFromOldFile, oldFileImportsFromNewFile, oldImportsNeededByNewFile, unusedImportsFromOldFile }; - function getJsxNamespaceSymbol(containsJsx2) { - if (containsJsx2 === void 0) { - return void 0; - } - const jsxNamespace = checker.getJsxNamespace(containsJsx2); - const jsxNamespaceSymbol2 = checker.resolveName( - jsxNamespace, - containsJsx2, - 1920 /* Namespace */, - /*excludeGlobals*/ - true - ); - return !!jsxNamespaceSymbol2 && some(jsxNamespaceSymbol2.declarations, isInImport) ? jsxNamespaceSymbol2 : void 0; - } - } - function isInImport(decl) { - switch (decl.kind) { - case 270 /* ImportEqualsDeclaration */: - case 275 /* ImportSpecifier */: - case 272 /* ImportClause */: - case 273 /* NamespaceImport */: - return true; - case 259 /* VariableDeclaration */: - return isVariableDeclarationInImport(decl); - case 207 /* BindingElement */: - return isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); - default: - return false; - } - } - function isVariableDeclarationInImport(decl) { - return isSourceFile(decl.parent.parent.parent) && !!decl.initializer && isRequireCall( - decl.initializer, - /*requireStringLiteralLikeArgument*/ - true - ); - } - function filterImport(i, moduleSpecifier, keep) { - switch (i.kind) { - case 271 /* ImportDeclaration */: { - const clause = i.importClause; - if (!clause) - return void 0; - const defaultImport = clause.name && keep(clause.name) ? clause.name : void 0; - const namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); - return defaultImport || namedBindings ? factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause(clause.isTypeOnly, defaultImport, namedBindings), - moduleSpecifier, - /*assertClause*/ - void 0 - ) : void 0; - } - case 270 /* ImportEqualsDeclaration */: - return keep(i.name) ? i : void 0; - case 259 /* VariableDeclaration */: { - const name = filterBindingName(i.name, keep); - return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : void 0; - } - default: - return Debug.assertNever(i, `Unexpected import kind ${i.kind}`); - } - } - function filterNamedBindings(namedBindings, keep) { - if (namedBindings.kind === 273 /* NamespaceImport */) { - return keep(namedBindings.name) ? namedBindings : void 0; - } else { - const newElements = namedBindings.elements.filter((e) => keep(e.name)); - return newElements.length ? factory.createNamedImports(newElements) : void 0; - } - } - function filterBindingName(name, keep) { - switch (name.kind) { - case 80 /* Identifier */: - return keep(name) ? name : void 0; - case 206 /* ArrayBindingPattern */: - return name; - case 205 /* ObjectBindingPattern */: { - const newElements = name.elements.filter((prop) => prop.propertyName || !isIdentifier(prop.name) || keep(prop.name)); - return newElements.length ? factory.createObjectBindingPattern(newElements) : void 0; - } - } - } - function forEachReference(node, checker, onReference) { - node.forEachChild(function cb(node2) { - if (isIdentifier(node2) && !isDeclarationName(node2)) { - const sym = checker.getSymbolAtLocation(node2); - if (sym) - onReference(sym); - } else { - node2.forEachChild(cb); - } - }); - } - function isTopLevelDeclaration(node) { - return isNonVariableTopLevelDeclaration(node) && isSourceFile(node.parent) || isVariableDeclaration(node) && isSourceFile(node.parent.parent.parent); - } - function sourceFileOfTopLevelDeclaration(node) { - return isVariableDeclaration(node) ? node.parent.parent.parent : node.parent; - } - function isTopLevelDeclarationStatement(node) { - Debug.assert(isSourceFile(node.parent), "Node parent should be a SourceFile"); - return isNonVariableTopLevelDeclaration(node) || isVariableStatement(node); - } - function isNonVariableTopLevelDeclaration(node) { - switch (node.kind) { - case 261 /* FunctionDeclaration */: - case 262 /* ClassDeclaration */: - case 266 /* ModuleDeclaration */: - case 265 /* EnumDeclaration */: - case 264 /* TypeAliasDeclaration */: - case 263 /* InterfaceDeclaration */: - case 270 /* ImportEqualsDeclaration */: - return true; - default: - return false; - } - } - function forEachTopLevelDeclaration(statement, cb) { - switch (statement.kind) { - case 261 /* FunctionDeclaration */: - case 262 /* ClassDeclaration */: - case 266 /* ModuleDeclaration */: - case 265 /* EnumDeclaration */: - case 264 /* TypeAliasDeclaration */: - case 263 /* InterfaceDeclaration */: - case 270 /* ImportEqualsDeclaration */: - return cb(statement); - case 242 /* VariableStatement */: - return firstDefined(statement.declarationList.declarations, (decl) => forEachTopLevelDeclarationInBindingName(decl.name, cb)); - case 243 /* ExpressionStatement */: { - const { expression } = statement; - return isBinaryExpression(expression) && getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : void 0; - } - } - } - function forEachTopLevelDeclarationInBindingName(name, cb) { - switch (name.kind) { - case 80 /* Identifier */: - return cb(cast(name.parent, (x) => isVariableDeclaration(x) || isBindingElement(x))); - case 206 /* ArrayBindingPattern */: - case 205 /* ObjectBindingPattern */: - return firstDefined(name.elements, (em) => isOmittedExpression(em) ? void 0 : forEachTopLevelDeclarationInBindingName(em.name, cb)); - default: - return Debug.assertNever(name, `Unexpected name kind ${name.kind}`); - } - } - function nameOfTopLevelDeclaration(d) { - return isExpressionStatement(d) ? tryCast(d.expression.left.name, isIdentifier) : tryCast(d.name, isIdentifier); - } - function getTopLevelDeclarationStatement(d) { - switch (d.kind) { - case 259 /* VariableDeclaration */: - return d.parent.parent; - case 207 /* BindingElement */: - return getTopLevelDeclarationStatement( - cast(d.parent.parent, (p) => isVariableDeclaration(p) || isBindingElement(p)) - ); - default: - return d; - } - } - function addExportToChanges(sourceFile, decl, name, changes, useEs6Exports) { - if (isExported(sourceFile, decl, useEs6Exports, name)) - return; - if (useEs6Exports) { - if (!isExpressionStatement(decl)) - changes.insertExportModifier(sourceFile, decl); - } else { - const names = getNamesToExportInCommonJS(decl); - if (names.length !== 0) - changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); - } - } - function isExported(sourceFile, decl, useEs6Exports, name) { - var _a; - if (useEs6Exports) { - return !isExpressionStatement(decl) && hasSyntacticModifier(decl, 1 /* Export */) || !!(name && ((_a = sourceFile.symbol.exports) == null ? void 0 : _a.has(name.escapedText))); - } - return !!sourceFile.symbol && !!sourceFile.symbol.exports && getNamesToExportInCommonJS(decl).some((name2) => sourceFile.symbol.exports.has(escapeLeadingUnderscores(name2))); - } - function addExport(decl, useEs6Exports) { - return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); - } - function addEs6Export(d) { - const modifiers = canHaveModifiers(d) ? concatenate([factory.createModifier(95 /* ExportKeyword */)], getModifiers(d)) : void 0; - switch (d.kind) { - case 261 /* FunctionDeclaration */: - return factory.updateFunctionDeclaration(d, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); - case 262 /* ClassDeclaration */: - const decorators = canHaveDecorators(d) ? getDecorators(d) : void 0; - return factory.updateClassDeclaration(d, concatenate(decorators, modifiers), d.name, d.typeParameters, d.heritageClauses, d.members); - case 242 /* VariableStatement */: - return factory.updateVariableStatement(d, modifiers, d.declarationList); - case 266 /* ModuleDeclaration */: - return factory.updateModuleDeclaration(d, modifiers, d.name, d.body); - case 265 /* EnumDeclaration */: - return factory.updateEnumDeclaration(d, modifiers, d.name, d.members); - case 264 /* TypeAliasDeclaration */: - return factory.updateTypeAliasDeclaration(d, modifiers, d.name, d.typeParameters, d.type); - case 263 /* InterfaceDeclaration */: - return factory.updateInterfaceDeclaration(d, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 270 /* ImportEqualsDeclaration */: - return factory.updateImportEqualsDeclaration(d, modifiers, d.isTypeOnly, d.name, d.moduleReference); - case 243 /* ExpressionStatement */: - return Debug.fail(); - default: - return Debug.assertNever(d, `Unexpected declaration kind ${d.kind}`); - } - } - function addCommonjsExport(decl) { - return [decl, ...getNamesToExportInCommonJS(decl).map(createExportAssignment)]; - } - function getNamesToExportInCommonJS(decl) { - switch (decl.kind) { - case 261 /* FunctionDeclaration */: - case 262 /* ClassDeclaration */: - return [decl.name.text]; - case 242 /* VariableStatement */: - return mapDefined(decl.declarationList.declarations, (d) => isIdentifier(d.name) ? d.name.text : void 0); - case 266 /* ModuleDeclaration */: - case 265 /* EnumDeclaration */: - case 264 /* TypeAliasDeclaration */: - case 263 /* InterfaceDeclaration */: - case 270 /* ImportEqualsDeclaration */: - return emptyArray; - case 243 /* ExpressionStatement */: - return Debug.fail("Can't export an ExpressionStatement"); - default: - return Debug.assertNever(decl, `Unexpected decl kind ${decl.kind}`); - } - } - function createExportAssignment(name) { - return factory.createExpressionStatement( - factory.createBinaryExpression( - factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(name)), - 64 /* EqualsToken */, - factory.createIdentifier(name) - ) - ); - } - var refactorName4, description, moveToNewFileAction, SymbolSet; - var init_moveToNewFile = __esm({ - "src/services/refactors/moveToNewFile.ts"() { - "use strict"; - init_moduleSpecifiers(); - init_ts4(); - init_ts_refactor(); - refactorName4 = "Move to a new file"; - description = getLocaleSpecificMessage(Diagnostics.Move_to_a_new_file); - moveToNewFileAction = { - name: refactorName4, - description, - kind: "refactor.move.newFile" - }; - registerRefactor(refactorName4, { - kinds: [moveToNewFileAction.kind], - getAvailableActions: function getRefactorActionsToMoveToNewFile(context) { - const statements = getStatementsToMove(context); - if (context.preferences.allowTextChangesInNewFiles && statements) { - return [{ name: refactorName4, description, actions: [moveToNewFileAction] }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorName4, - description, - actions: [{ ...moveToNewFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] - }]; - } - return emptyArray; - }, - getEditsForAction: function getRefactorEditsToMoveToNewFile(context, actionName2) { - Debug.assert(actionName2 === refactorName4, "Wrong refactor invoked"); - const statements = Debug.checkDefined(getStatementsToMove(context)); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange36(context.file, context.program, statements, t, context.host, context.preferences)); - return { edits, renameFilename: void 0, renameLocation: void 0 }; - } - }); - SymbolSet = class { - constructor() { - this.map = /* @__PURE__ */ new Map(); - } - add(symbol) { - this.map.set(String(getSymbolId(symbol)), symbol); - } - has(symbol) { - return this.map.has(String(getSymbolId(symbol))); - } - delete(symbol) { - this.map.delete(String(getSymbolId(symbol))); - } - forEach(cb) { - this.map.forEach(cb); - } - forEachEntry(cb) { - return forEachEntry(this.map, cb); - } - clone() { - const clone2 = new SymbolSet(); - copyEntries(this.map, clone2.map); - return clone2; - } - size() { - return this.map.size; - } - }; - } - }); - - // src/services/refactors/convertOverloadListToSingleSignature.ts - function getRefactorActionsToConvertOverloadsToOneSignature(context) { - const { file, startPosition, program } = context; - const info = getConvertableOverloadListAtPosition(file, startPosition, program); - if (!info) - return emptyArray; - return [{ - name: refactorName5, - description: refactorDescription, - actions: [functionOverloadAction] - }]; - } - function getRefactorEditsToConvertOverloadsToOneSignature(context) { - const { file, startPosition, program } = context; - const signatureDecls = getConvertableOverloadListAtPosition(file, startPosition, program); - if (!signatureDecls) - return void 0; - const checker = program.getTypeChecker(); - const lastDeclaration = signatureDecls[signatureDecls.length - 1]; - let updated = lastDeclaration; - switch (lastDeclaration.kind) { - case 172 /* MethodSignature */: { - updated = factory.updateMethodSignature( - lastDeclaration, - lastDeclaration.modifiers, - lastDeclaration.name, - lastDeclaration.questionToken, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type - ); - break; - } - case 173 /* MethodDeclaration */: { - updated = factory.updateMethodDeclaration( - lastDeclaration, - lastDeclaration.modifiers, - lastDeclaration.asteriskToken, - lastDeclaration.name, - lastDeclaration.questionToken, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type, - lastDeclaration.body - ); - break; - } - case 178 /* CallSignature */: { - updated = factory.updateCallSignature( - lastDeclaration, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type - ); - break; - } - case 175 /* Constructor */: { - updated = factory.updateConstructorDeclaration( - lastDeclaration, - lastDeclaration.modifiers, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.body - ); - break; - } - case 179 /* ConstructSignature */: { - updated = factory.updateConstructSignature( - lastDeclaration, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type - ); - break; - } - case 261 /* FunctionDeclaration */: { - updated = factory.updateFunctionDeclaration( - lastDeclaration, - lastDeclaration.modifiers, - lastDeclaration.asteriskToken, - lastDeclaration.name, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type, - lastDeclaration.body - ); - break; - } - default: - return Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring"); - } - if (updated === lastDeclaration) { - return; - } - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => { - t.replaceNodeRange(file, signatureDecls[0], signatureDecls[signatureDecls.length - 1], updated); - }); - return { renameFilename: void 0, renameLocation: void 0, edits }; - function getNewParametersForCombinedSignature(signatureDeclarations) { - const lastSig = signatureDeclarations[signatureDeclarations.length - 1]; - if (isFunctionLikeDeclaration(lastSig) && lastSig.body) { - signatureDeclarations = signatureDeclarations.slice(0, signatureDeclarations.length - 1); - } - return factory.createNodeArray([ - factory.createParameterDeclaration( - /*modifiers*/ - void 0, - factory.createToken(26 /* DotDotDotToken */), - "args", - /*questionToken*/ - void 0, - factory.createUnionTypeNode(map(signatureDeclarations, convertSignatureParametersToTuple)) - ) - ]); - } - function convertSignatureParametersToTuple(decl) { - const members = map(decl.parameters, convertParameterToNamedTupleMember); - return setEmitFlags(factory.createTupleTypeNode(members), some(members, (m) => !!length(getSyntheticLeadingComments(m))) ? 0 /* None */ : 1 /* SingleLine */); - } - function convertParameterToNamedTupleMember(p) { - Debug.assert(isIdentifier(p.name)); - const result = setTextRange(factory.createNamedTupleMember( - p.dotDotDotToken, - p.name, - p.questionToken, - p.type || factory.createKeywordTypeNode(133 /* AnyKeyword */) - ), p); - const parameterDocComment = p.symbol && p.symbol.getDocumentationComment(checker); - if (parameterDocComment) { - const newComment = displayPartsToString(parameterDocComment); - if (newComment.length) { - setSyntheticLeadingComments(result, [{ - text: `* -${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} - `, - kind: 3 /* MultiLineCommentTrivia */, - pos: -1, - end: -1, - hasTrailingNewLine: true, - hasLeadingNewline: true - }]); - } - } - return result; - } - } - function isConvertableSignatureDeclaration(d) { - switch (d.kind) { - case 172 /* MethodSignature */: - case 173 /* MethodDeclaration */: - case 178 /* CallSignature */: - case 175 /* Constructor */: - case 179 /* ConstructSignature */: - case 261 /* FunctionDeclaration */: - return true; - } - return false; - } - function getConvertableOverloadListAtPosition(file, startPosition, program) { - const node = getTokenAtPosition(file, startPosition); - const containingDecl = findAncestor(node, isConvertableSignatureDeclaration); - if (!containingDecl) { - return; - } - if (isFunctionLikeDeclaration(containingDecl) && containingDecl.body && rangeContainsPosition(containingDecl.body, startPosition)) { - return; - } - const checker = program.getTypeChecker(); - const signatureSymbol = containingDecl.symbol; - if (!signatureSymbol) { - return; - } - const decls = signatureSymbol.declarations; - if (length(decls) <= 1) { - return; - } - if (!every(decls, (d) => getSourceFileOfNode(d) === file)) { - return; - } - if (!isConvertableSignatureDeclaration(decls[0])) { - return; - } - const kindOne = decls[0].kind; - if (!every(decls, (d) => d.kind === kindOne)) { - return; - } - const signatureDecls = decls; - if (some(signatureDecls, (d) => !!d.typeParameters || some(d.parameters, (p) => !!p.modifiers || !isIdentifier(p.name)))) { - return; - } - const signatures = mapDefined(signatureDecls, (d) => checker.getSignatureFromDeclaration(d)); - if (length(signatures) !== length(decls)) { - return; - } - const returnOne = checker.getReturnTypeOfSignature(signatures[0]); - if (!every(signatures, (s) => checker.getReturnTypeOfSignature(s) === returnOne)) { - return; - } - return signatureDecls; - } - var refactorName5, refactorDescription, functionOverloadAction; - var init_convertOverloadListToSingleSignature = __esm({ - "src/services/refactors/convertOverloadListToSingleSignature.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName5 = "Convert overload list to single signature"; - refactorDescription = Diagnostics.Convert_overload_list_to_single_signature.message; - functionOverloadAction = { - name: refactorName5, - description: refactorDescription, - kind: "refactor.rewrite.function.overloadList" - }; - registerRefactor(refactorName5, { - kinds: [functionOverloadAction.kind], - getEditsForAction: getRefactorEditsToConvertOverloadsToOneSignature, - getAvailableActions: getRefactorActionsToConvertOverloadsToOneSignature - }); - } - }); - - // src/services/refactors/addOrRemoveBracesToArrowFunction.ts - function getRefactorActionsToRemoveFunctionBraces(context) { - const { file, startPosition, triggerReason } = context; - const info = getConvertibleArrowFunctionAtPosition(file, startPosition, triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - return [{ - name: refactorName6, - description: refactorDescription2, - actions: [ - info.addBraces ? addBracesAction : removeBracesAction - ] - }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorName6, - description: refactorDescription2, - actions: [ - { ...addBracesAction, notApplicableReason: info.error }, - { ...removeBracesAction, notApplicableReason: info.error } - ] - }]; - } - return emptyArray; - } - function getRefactorEditsToRemoveFunctionBraces(context, actionName2) { - const { file, startPosition } = context; - const info = getConvertibleArrowFunctionAtPosition(file, startPosition); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const { expression, returnStatement, func } = info; - let body; - if (actionName2 === addBracesAction.name) { - const returnStatement2 = factory.createReturnStatement(expression); - body = factory.createBlock( - [returnStatement2], - /*multiLine*/ - true - ); - copyLeadingComments( - expression, - returnStatement2, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - true - ); - } else if (actionName2 === removeBracesAction.name && returnStatement) { - const actualExpression = expression || factory.createVoidZero(); - body = needsParentheses(actualExpression) ? factory.createParenthesizedExpression(actualExpression) : actualExpression; - copyTrailingAsLeadingComments( - returnStatement, - body, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - copyLeadingComments( - returnStatement, - body, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - copyTrailingComments( - returnStatement, - body, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - } else { - Debug.fail("invalid action"); - } - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => { - t.replaceNode(file, func.body, body); - }); - return { renameFilename: void 0, renameLocation: void 0, edits }; - } - function getConvertibleArrowFunctionAtPosition(file, startPosition, considerFunctionBodies = true, kind) { - const node = getTokenAtPosition(file, startPosition); - const func = getContainingFunction(node); - if (!func) { - return { - error: getLocaleSpecificMessage(Diagnostics.Could_not_find_a_containing_arrow_function) - }; - } - if (!isArrowFunction(func)) { - return { - error: getLocaleSpecificMessage(Diagnostics.Containing_function_is_not_an_arrow_function) - }; - } - if (!rangeContainsRange(func, node) || rangeContainsRange(func.body, node) && !considerFunctionBodies) { - return void 0; - } - if (refactorKindBeginsWith(addBracesAction.kind, kind) && isExpression(func.body)) { - return { func, addBraces: true, expression: func.body }; - } else if (refactorKindBeginsWith(removeBracesAction.kind, kind) && isBlock(func.body) && func.body.statements.length === 1) { - const firstStatement = first(func.body.statements); - if (isReturnStatement(firstStatement)) { - return { func, addBraces: false, expression: firstStatement.expression, returnStatement: firstStatement }; - } - } - return void 0; - } - var refactorName6, refactorDescription2, addBracesAction, removeBracesAction; - var init_addOrRemoveBracesToArrowFunction = __esm({ - "src/services/refactors/addOrRemoveBracesToArrowFunction.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName6 = "Add or remove braces in an arrow function"; - refactorDescription2 = Diagnostics.Add_or_remove_braces_in_an_arrow_function.message; - addBracesAction = { - name: "Add braces to arrow function", - description: Diagnostics.Add_braces_to_arrow_function.message, - kind: "refactor.rewrite.arrow.braces.add" - }; - removeBracesAction = { - name: "Remove braces from arrow function", - description: Diagnostics.Remove_braces_from_arrow_function.message, - kind: "refactor.rewrite.arrow.braces.remove" - }; - registerRefactor(refactorName6, { - kinds: [removeBracesAction.kind], - getEditsForAction: getRefactorEditsToRemoveFunctionBraces, - getAvailableActions: getRefactorActionsToRemoveFunctionBraces - }); - } - }); - - // src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts - var ts_refactor_addOrRemoveBracesToArrowFunction_exports = {}; - var init_ts_refactor_addOrRemoveBracesToArrowFunction = __esm({ - "src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts"() { - "use strict"; - init_convertOverloadListToSingleSignature(); - init_addOrRemoveBracesToArrowFunction(); - } - }); - - // src/services/refactors/convertArrowFunctionOrFunctionExpression.ts - function getRefactorActionsToConvertFunctionExpressions(context) { - const { file, startPosition, program, kind } = context; - const info = getFunctionInfo(file, startPosition, program); - if (!info) - return emptyArray; - const { selectedVariableDeclaration, func } = info; - const possibleActions = []; - const errors = []; - if (refactorKindBeginsWith(toNamedFunctionAction.kind, kind)) { - const error = selectedVariableDeclaration || isArrowFunction(func) && isVariableDeclaration(func.parent) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_named_function); - if (error) { - errors.push({ ...toNamedFunctionAction, notApplicableReason: error }); - } else { - possibleActions.push(toNamedFunctionAction); - } - } - if (refactorKindBeginsWith(toAnonymousFunctionAction.kind, kind)) { - const error = !selectedVariableDeclaration && isArrowFunction(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_anonymous_function); - if (error) { - errors.push({ ...toAnonymousFunctionAction, notApplicableReason: error }); - } else { - possibleActions.push(toAnonymousFunctionAction); - } - } - if (refactorKindBeginsWith(toArrowFunctionAction.kind, kind)) { - const error = isFunctionExpression(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_arrow_function); - if (error) { - errors.push({ ...toArrowFunctionAction, notApplicableReason: error }); - } else { - possibleActions.push(toArrowFunctionAction); - } - } - return [{ - name: refactorName7, - description: refactorDescription3, - actions: possibleActions.length === 0 && context.preferences.provideRefactorNotApplicableReason ? errors : possibleActions - }]; - } - function getRefactorEditsToConvertFunctionExpressions(context, actionName2) { - const { file, startPosition, program } = context; - const info = getFunctionInfo(file, startPosition, program); - if (!info) - return void 0; - const { func } = info; - const edits = []; - switch (actionName2) { - case toAnonymousFunctionAction.name: - edits.push(...getEditInfoForConvertToAnonymousFunction(context, func)); - break; - case toNamedFunctionAction.name: - const variableInfo = getVariableInfo(func); - if (!variableInfo) - return void 0; - edits.push(...getEditInfoForConvertToNamedFunction(context, func, variableInfo)); - break; - case toArrowFunctionAction.name: - if (!isFunctionExpression(func)) - return void 0; - edits.push(...getEditInfoForConvertToArrowFunction(context, func)); - break; - default: - return Debug.fail("invalid action"); - } - return { renameFilename: void 0, renameLocation: void 0, edits }; - } - function containingThis(node) { - let containsThis = false; - node.forEachChild(function checkThis(child) { - if (isThis(child)) { - containsThis = true; - return; - } - if (!isClassLike(child) && !isFunctionDeclaration(child) && !isFunctionExpression(child)) { - forEachChild(child, checkThis); - } - }); - return containsThis; - } - function getFunctionInfo(file, startPosition, program) { - const token = getTokenAtPosition(file, startPosition); - const typeChecker = program.getTypeChecker(); - const func = tryGetFunctionFromVariableDeclaration(file, typeChecker, token.parent); - if (func && !containingThis(func.body) && !typeChecker.containsArgumentsReference(func)) { - return { selectedVariableDeclaration: true, func }; - } - const maybeFunc = getContainingFunction(token); - if (maybeFunc && (isFunctionExpression(maybeFunc) || isArrowFunction(maybeFunc)) && !rangeContainsRange(maybeFunc.body, token) && !containingThis(maybeFunc.body) && !typeChecker.containsArgumentsReference(maybeFunc)) { - if (isFunctionExpression(maybeFunc) && isFunctionReferencedInFile(file, typeChecker, maybeFunc)) - return void 0; - return { selectedVariableDeclaration: false, func: maybeFunc }; - } - return void 0; - } - function isSingleVariableDeclaration(parent2) { - return isVariableDeclaration(parent2) || isVariableDeclarationList(parent2) && parent2.declarations.length === 1; - } - function tryGetFunctionFromVariableDeclaration(sourceFile, typeChecker, parent2) { - if (!isSingleVariableDeclaration(parent2)) { - return void 0; - } - const variableDeclaration = isVariableDeclaration(parent2) ? parent2 : first(parent2.declarations); - const initializer = variableDeclaration.initializer; - if (initializer && (isArrowFunction(initializer) || isFunctionExpression(initializer) && !isFunctionReferencedInFile(sourceFile, typeChecker, initializer))) { - return initializer; - } - return void 0; - } - function convertToBlock(body) { - if (isExpression(body)) { - const returnStatement = factory.createReturnStatement(body); - const file = body.getSourceFile(); - setTextRange(returnStatement, body); - suppressLeadingAndTrailingTrivia(returnStatement); - copyTrailingAsLeadingComments( - body, - returnStatement, - file, - /*commentKind*/ - void 0, - /*hasTrailingNewLine*/ - true - ); - return factory.createBlock( - [returnStatement], - /*multiLine*/ - true - ); - } else { - return body; - } - } - function getVariableInfo(func) { - const variableDeclaration = func.parent; - if (!isVariableDeclaration(variableDeclaration) || !isVariableDeclarationInVariableStatement(variableDeclaration)) - return void 0; - const variableDeclarationList = variableDeclaration.parent; - const statement = variableDeclarationList.parent; - if (!isVariableDeclarationList(variableDeclarationList) || !isVariableStatement(statement) || !isIdentifier(variableDeclaration.name)) - return void 0; - return { variableDeclaration, variableDeclarationList, statement, name: variableDeclaration.name }; - } - function getEditInfoForConvertToAnonymousFunction(context, func) { - const { file } = context; - const body = convertToBlock(func.body); - const newNode = factory.createFunctionExpression( - func.modifiers, - func.asteriskToken, - /*name*/ - void 0, - func.typeParameters, - func.parameters, - func.type, - body - ); - return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode)); - } - function getEditInfoForConvertToNamedFunction(context, func, variableInfo) { - const { file } = context; - const body = convertToBlock(func.body); - const { variableDeclaration, variableDeclarationList, statement, name } = variableInfo; - suppressLeadingTrivia(statement); - const modifiersFlags = getCombinedModifierFlags(variableDeclaration) & 1 /* Export */ | getEffectiveModifierFlags(func); - const modifiers = factory.createModifiersFromModifierFlags(modifiersFlags); - const newNode = factory.createFunctionDeclaration(length(modifiers) ? modifiers : void 0, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); - if (variableDeclarationList.declarations.length === 1) { - return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, statement, newNode)); - } else { - return ts_textChanges_exports.ChangeTracker.with(context, (t) => { - t.delete(file, variableDeclaration); - t.insertNodeAfter(file, statement, newNode); - }); - } - } - function getEditInfoForConvertToArrowFunction(context, func) { - const { file } = context; - const statements = func.body.statements; - const head = statements[0]; - let body; - if (canBeConvertedToExpression(func.body, head)) { - body = head.expression; - suppressLeadingAndTrailingTrivia(body); - copyComments(head, body); - } else { - body = func.body; - } - const newNode = factory.createArrowFunction(func.modifiers, func.typeParameters, func.parameters, func.type, factory.createToken(39 /* EqualsGreaterThanToken */), body); - return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode)); - } - function canBeConvertedToExpression(body, head) { - return body.statements.length === 1 && (isReturnStatement(head) && !!head.expression); - } - function isFunctionReferencedInFile(sourceFile, typeChecker, node) { - return !!node.name && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(node.name, typeChecker, sourceFile); - } - var refactorName7, refactorDescription3, toAnonymousFunctionAction, toNamedFunctionAction, toArrowFunctionAction; - var init_convertArrowFunctionOrFunctionExpression = __esm({ - "src/services/refactors/convertArrowFunctionOrFunctionExpression.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName7 = "Convert arrow function or function expression"; - refactorDescription3 = getLocaleSpecificMessage(Diagnostics.Convert_arrow_function_or_function_expression); - toAnonymousFunctionAction = { - name: "Convert to anonymous function", - description: getLocaleSpecificMessage(Diagnostics.Convert_to_anonymous_function), - kind: "refactor.rewrite.function.anonymous" - }; - toNamedFunctionAction = { - name: "Convert to named function", - description: getLocaleSpecificMessage(Diagnostics.Convert_to_named_function), - kind: "refactor.rewrite.function.named" - }; - toArrowFunctionAction = { - name: "Convert to arrow function", - description: getLocaleSpecificMessage(Diagnostics.Convert_to_arrow_function), - kind: "refactor.rewrite.function.arrow" - }; - registerRefactor(refactorName7, { - kinds: [ - toAnonymousFunctionAction.kind, - toNamedFunctionAction.kind, - toArrowFunctionAction.kind - ], - getEditsForAction: getRefactorEditsToConvertFunctionExpressions, - getAvailableActions: getRefactorActionsToConvertFunctionExpressions - }); - } - }); - - // src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts - var ts_refactor_convertArrowFunctionOrFunctionExpression_exports = {}; - var init_ts_refactor_convertArrowFunctionOrFunctionExpression = __esm({ - "src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts"() { - "use strict"; - init_convertArrowFunctionOrFunctionExpression(); - } - }); - - // src/services/refactors/convertParamsToDestructuredObject.ts - function getRefactorActionsToConvertParametersToDestructuredObject(context) { - const { file, startPosition } = context; - const isJSFile = isSourceFileJS(file); - if (isJSFile) - return emptyArray; - const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker()); - if (!functionDeclaration) - return emptyArray; - return [{ - name: refactorName8, - description: refactorDescription4, - actions: [toDestructuredAction] - }]; - } - function getRefactorEditsToConvertParametersToDestructuredObject(context, actionName2) { - Debug.assert(actionName2 === refactorName8, "Unexpected action name"); - const { file, startPosition, program, cancellationToken, host } = context; - const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); - if (!functionDeclaration || !cancellationToken) - return void 0; - const groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken); - if (groupedReferences.valid) { - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange37(file, program, host, t, functionDeclaration, groupedReferences)); - return { renameFilename: void 0, renameLocation: void 0, edits }; - } - return { edits: [] }; - } - function doChange37(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { - const signature = groupedReferences.signature; - const newFunctionDeclarationParams = map(createNewParameters(functionDeclaration, program, host), (param) => getSynthesizedDeepClone(param)); - if (signature) { - const newSignatureParams = map(createNewParameters(signature, program, host), (param) => getSynthesizedDeepClone(param)); - replaceParameters(signature, newSignatureParams); - } - replaceParameters(functionDeclaration, newFunctionDeclarationParams); - const functionCalls = sortAndDeduplicate( - groupedReferences.functionCalls, - /*comparer*/ - (a, b) => compareValues(a.pos, b.pos) - ); - for (const call of functionCalls) { - if (call.arguments && call.arguments.length) { - const newArgument = getSynthesizedDeepClone( - createNewArgument(functionDeclaration, call.arguments), - /*includeTrivia*/ - true - ); - changes.replaceNodeRange( - getSourceFileOfNode(call), - first(call.arguments), - last(call.arguments), - newArgument, - { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include } - ); - } - } - function replaceParameters(declarationOrSignature, parameterDeclarations) { - changes.replaceNodeRangeWithNodes( - sourceFile, - first(declarationOrSignature.parameters), - last(declarationOrSignature.parameters), - parameterDeclarations, - { - joiner: ", ", - // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter - indentation: 0, - leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include - } - ); - } - } - function getGroupedReferences(functionDeclaration, program, cancellationToken) { - const functionNames = getFunctionNames(functionDeclaration); - const classNames = isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : []; - const names = deduplicate([...functionNames, ...classNames], equateValues); - const checker = program.getTypeChecker(); - const references = flatMap( - names, - /*mapfn*/ - (name) => ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken) - ); - const groupedReferences = groupReferences(references); - if (!every( - groupedReferences.declarations, - /*callback*/ - (decl) => contains(names, decl) - )) { - groupedReferences.valid = false; - } - return groupedReferences; - function groupReferences(referenceEntries) { - const classReferences = { accessExpressions: [], typeUsages: [] }; - const groupedReferences2 = { functionCalls: [], declarations: [], classReferences, valid: true }; - const functionSymbols = map(functionNames, getSymbolTargetAtLocation); - const classSymbols = map(classNames, getSymbolTargetAtLocation); - const isConstructor = isConstructorDeclaration(functionDeclaration); - const contextualSymbols = map(functionNames, (name) => getSymbolForContextualType(name, checker)); - for (const entry of referenceEntries) { - if (entry.kind === ts_FindAllReferences_exports.EntryKind.Span) { - groupedReferences2.valid = false; - continue; - } - if (contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) { - if (isValidMethodSignature(entry.node.parent)) { - groupedReferences2.signature = entry.node.parent; - continue; - } - const call = entryToFunctionCall(entry); - if (call) { - groupedReferences2.functionCalls.push(call); - continue; - } - } - const contextualSymbol = getSymbolForContextualType(entry.node, checker); - if (contextualSymbol && contains(contextualSymbols, contextualSymbol)) { - const decl = entryToDeclaration(entry); - if (decl) { - groupedReferences2.declarations.push(decl); - continue; - } - } - if (contains(functionSymbols, getSymbolTargetAtLocation(entry.node)) || isNewExpressionTarget(entry.node)) { - const importOrExportReference = entryToImportOrExport(entry); - if (importOrExportReference) { - continue; - } - const decl = entryToDeclaration(entry); - if (decl) { - groupedReferences2.declarations.push(decl); - continue; - } - const call = entryToFunctionCall(entry); - if (call) { - groupedReferences2.functionCalls.push(call); - continue; - } - } - if (isConstructor && contains(classSymbols, getSymbolTargetAtLocation(entry.node))) { - const importOrExportReference = entryToImportOrExport(entry); - if (importOrExportReference) { - continue; - } - const decl = entryToDeclaration(entry); - if (decl) { - groupedReferences2.declarations.push(decl); - continue; - } - const accessExpression = entryToAccessExpression(entry); - if (accessExpression) { - classReferences.accessExpressions.push(accessExpression); - continue; - } - if (isClassDeclaration(functionDeclaration.parent)) { - const type = entryToType(entry); - if (type) { - classReferences.typeUsages.push(type); - continue; - } - } - } - groupedReferences2.valid = false; - } - return groupedReferences2; - } - function getSymbolTargetAtLocation(node) { - const symbol = checker.getSymbolAtLocation(node); - return symbol && getSymbolTarget(symbol, checker); - } - } - function getSymbolForContextualType(node, checker) { - const element = getContainingObjectLiteralElement(node); - if (element) { - const contextualType = checker.getContextualTypeForObjectLiteralElement(element); - const symbol = contextualType == null ? void 0 : contextualType.getSymbol(); - if (symbol && !(getCheckFlags(symbol) & 6 /* Synthetic */)) { - return symbol; - } - } - } - function entryToImportOrExport(entry) { - const node = entry.node; - if (isImportSpecifier(node.parent) || isImportClause(node.parent) || isImportEqualsDeclaration(node.parent) || isNamespaceImport(node.parent)) { - return node; - } - if (isExportSpecifier(node.parent) || isExportAssignment(node.parent)) { - return node; - } - return void 0; - } - function entryToDeclaration(entry) { - if (isDeclaration(entry.node.parent)) { - return entry.node; - } - return void 0; - } - function entryToFunctionCall(entry) { - if (entry.node.parent) { - const functionReference = entry.node; - const parent2 = functionReference.parent; - switch (parent2.kind) { - case 212 /* CallExpression */: - case 213 /* NewExpression */: - const callOrNewExpression = tryCast(parent2, isCallOrNewExpression); - if (callOrNewExpression && callOrNewExpression.expression === functionReference) { - return callOrNewExpression; - } - break; - case 210 /* PropertyAccessExpression */: - const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); - if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { - const callOrNewExpression2 = tryCast(propertyAccessExpression.parent, isCallOrNewExpression); - if (callOrNewExpression2 && callOrNewExpression2.expression === propertyAccessExpression) { - return callOrNewExpression2; - } - } - break; - case 211 /* ElementAccessExpression */: - const elementAccessExpression = tryCast(parent2, isElementAccessExpression); - if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { - const callOrNewExpression2 = tryCast(elementAccessExpression.parent, isCallOrNewExpression); - if (callOrNewExpression2 && callOrNewExpression2.expression === elementAccessExpression) { - return callOrNewExpression2; - } - } - break; - } - } - return void 0; - } - function entryToAccessExpression(entry) { - if (entry.node.parent) { - const reference = entry.node; - const parent2 = reference.parent; - switch (parent2.kind) { - case 210 /* PropertyAccessExpression */: - const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); - if (propertyAccessExpression && propertyAccessExpression.expression === reference) { - return propertyAccessExpression; - } - break; - case 211 /* ElementAccessExpression */: - const elementAccessExpression = tryCast(parent2, isElementAccessExpression); - if (elementAccessExpression && elementAccessExpression.expression === reference) { - return elementAccessExpression; - } - break; - } - } - return void 0; - } - function entryToType(entry) { - const reference = entry.node; - if (getMeaningFromLocation(reference) === 2 /* Type */ || isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) { - return reference; - } - return void 0; - } - function getFunctionDeclarationAtPosition(file, startPosition, checker) { - const node = getTouchingToken(file, startPosition); - const functionDeclaration = getContainingFunctionDeclaration(node); - if (isTopLevelJSDoc(node)) - return void 0; - if (functionDeclaration && isValidFunctionDeclaration(functionDeclaration, checker) && rangeContainsRange(functionDeclaration, node) && !(functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node))) - return functionDeclaration; - return void 0; - } - function isTopLevelJSDoc(node) { - const containingJSDoc = findAncestor(node, isJSDocNode); - if (containingJSDoc) { - const containingNonJSDoc = findAncestor(containingJSDoc, (n) => !isJSDocNode(n)); - return !!containingNonJSDoc && isFunctionLikeDeclaration(containingNonJSDoc); - } - return false; - } - function isValidMethodSignature(node) { - return isMethodSignature(node) && (isInterfaceDeclaration(node.parent) || isTypeLiteralNode(node.parent)); - } - function isValidFunctionDeclaration(functionDeclaration, checker) { - var _a; - if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) - return false; - switch (functionDeclaration.kind) { - case 261 /* FunctionDeclaration */: - return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); - case 173 /* MethodDeclaration */: - if (isObjectLiteralExpression(functionDeclaration.parent)) { - const contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); - return ((_a = contextualSymbol == null ? void 0 : contextualSymbol.declarations) == null ? void 0 : _a.length) === 1 && isSingleImplementation(functionDeclaration, checker); - } - return isSingleImplementation(functionDeclaration, checker); - case 175 /* Constructor */: - if (isClassDeclaration(functionDeclaration.parent)) { - return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker); - } else { - return isValidVariableDeclaration(functionDeclaration.parent.parent) && isSingleImplementation(functionDeclaration, checker); - } - case 217 /* FunctionExpression */: - case 218 /* ArrowFunction */: - return isValidVariableDeclaration(functionDeclaration.parent); - } - return false; - } - function isSingleImplementation(functionDeclaration, checker) { - return !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); - } - function hasNameOrDefault(functionOrClassDeclaration) { - if (!functionOrClassDeclaration.name) { - const defaultKeyword = findModifier(functionOrClassDeclaration, 90 /* DefaultKeyword */); - return !!defaultKeyword; - } - return true; - } - function isValidParameterNodeArray(parameters, checker) { - return getRefactorableParametersLength(parameters) >= minimumParameterLength && every( - parameters, - /*callback*/ - (paramDecl) => isValidParameterDeclaration(paramDecl, checker) - ); - } - function isValidParameterDeclaration(parameterDeclaration, checker) { - if (isRestParameter(parameterDeclaration)) { - const type = checker.getTypeAtLocation(parameterDeclaration); - if (!checker.isArrayType(type) && !checker.isTupleType(type)) - return false; - } - return !parameterDeclaration.modifiers && isIdentifier(parameterDeclaration.name); - } - function isValidVariableDeclaration(node) { - return isVariableDeclaration(node) && isVarConst(node) && isIdentifier(node.name) && !node.type; - } - function hasThisParameter(parameters) { - return parameters.length > 0 && isThis(parameters[0].name); - } - function getRefactorableParametersLength(parameters) { - if (hasThisParameter(parameters)) { - return parameters.length - 1; - } - return parameters.length; - } - function getRefactorableParameters(parameters) { - if (hasThisParameter(parameters)) { - parameters = factory.createNodeArray(parameters.slice(1), parameters.hasTrailingComma); - } - return parameters; - } - function createPropertyOrShorthandAssignment(name, initializer) { - if (isIdentifier(initializer) && getTextOfIdentifierOrLiteral(initializer) === name) { - return factory.createShorthandPropertyAssignment(name); - } - return factory.createPropertyAssignment(name, initializer); - } - function createNewArgument(functionDeclaration, functionArguments) { - const parameters = getRefactorableParameters(functionDeclaration.parameters); - const hasRestParameter2 = isRestParameter(last(parameters)); - const nonRestArguments = hasRestParameter2 ? functionArguments.slice(0, parameters.length - 1) : functionArguments; - const properties = map(nonRestArguments, (arg, i) => { - const parameterName = getParameterName(parameters[i]); - const property = createPropertyOrShorthandAssignment(parameterName, arg); - suppressLeadingAndTrailingTrivia(property.name); - if (isPropertyAssignment(property)) - suppressLeadingAndTrailingTrivia(property.initializer); - copyComments(arg, property); - return property; - }); - if (hasRestParameter2 && functionArguments.length >= parameters.length) { - const restArguments = functionArguments.slice(parameters.length - 1); - const restProperty = factory.createPropertyAssignment(getParameterName(last(parameters)), factory.createArrayLiteralExpression(restArguments)); - properties.push(restProperty); - } - const objectLiteral = factory.createObjectLiteralExpression( - properties, - /*multiLine*/ - false - ); - return objectLiteral; - } - function createNewParameters(functionDeclaration, program, host) { - const checker = program.getTypeChecker(); - const refactorableParameters = getRefactorableParameters(functionDeclaration.parameters); - const bindingElements = map(refactorableParameters, createBindingElementFromParameterDeclaration); - const objectParameterName = factory.createObjectBindingPattern(bindingElements); - const objectParameterType = createParameterTypeNode(refactorableParameters); - let objectInitializer; - if (every(refactorableParameters, isOptionalParameter)) { - objectInitializer = factory.createObjectLiteralExpression(); - } - const objectParameter = factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - objectParameterName, - /*questionToken*/ - void 0, - objectParameterType, - objectInitializer - ); - if (hasThisParameter(functionDeclaration.parameters)) { - const thisParameter = functionDeclaration.parameters[0]; - const newThisParameter = factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - thisParameter.name, - /*questionToken*/ - void 0, - thisParameter.type - ); - suppressLeadingAndTrailingTrivia(newThisParameter.name); - copyComments(thisParameter.name, newThisParameter.name); - if (thisParameter.type) { - suppressLeadingAndTrailingTrivia(newThisParameter.type); - copyComments(thisParameter.type, newThisParameter.type); - } - return factory.createNodeArray([newThisParameter, objectParameter]); - } - return factory.createNodeArray([objectParameter]); - function createBindingElementFromParameterDeclaration(parameterDeclaration) { - const element = factory.createBindingElement( - /*dotDotDotToken*/ - void 0, - /*propertyName*/ - void 0, - getParameterName(parameterDeclaration), - isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? factory.createArrayLiteralExpression() : parameterDeclaration.initializer - ); - suppressLeadingAndTrailingTrivia(element); - if (parameterDeclaration.initializer && element.initializer) { - copyComments(parameterDeclaration.initializer, element.initializer); - } - return element; - } - function createParameterTypeNode(parameters) { - const members = map(parameters, createPropertySignatureFromParameterDeclaration); - const typeNode = addEmitFlags(factory.createTypeLiteralNode(members), 1 /* SingleLine */); - return typeNode; - } - function createPropertySignatureFromParameterDeclaration(parameterDeclaration) { - let parameterType = parameterDeclaration.type; - if (!parameterType && (parameterDeclaration.initializer || isRestParameter(parameterDeclaration))) { - parameterType = getTypeNode3(parameterDeclaration); - } - const propertySignature = factory.createPropertySignature( - /*modifiers*/ - void 0, - getParameterName(parameterDeclaration), - isOptionalParameter(parameterDeclaration) ? factory.createToken(58 /* QuestionToken */) : parameterDeclaration.questionToken, - parameterType - ); - suppressLeadingAndTrailingTrivia(propertySignature); - copyComments(parameterDeclaration.name, propertySignature.name); - if (parameterDeclaration.type && propertySignature.type) { - copyComments(parameterDeclaration.type, propertySignature.type); - } - return propertySignature; - } - function getTypeNode3(node) { - const type = checker.getTypeAtLocation(node); - return getTypeNodeIfAccessible(type, node, program, host); - } - function isOptionalParameter(parameterDeclaration) { - if (isRestParameter(parameterDeclaration)) { - const type = checker.getTypeAtLocation(parameterDeclaration); - return !checker.isTupleType(type); - } - return checker.isOptionalParameter(parameterDeclaration); - } - } - function getParameterName(paramDeclaration) { - return getTextOfIdentifierOrLiteral(paramDeclaration.name); - } - function getClassNames(constructorDeclaration) { - switch (constructorDeclaration.parent.kind) { - case 262 /* ClassDeclaration */: - const classDeclaration = constructorDeclaration.parent; - if (classDeclaration.name) - return [classDeclaration.name]; - const defaultModifier = Debug.checkDefined( - findModifier(classDeclaration, 90 /* DefaultKeyword */), - "Nameless class declaration should be a default export" - ); - return [defaultModifier]; - case 230 /* ClassExpression */: - const classExpression = constructorDeclaration.parent; - const variableDeclaration = constructorDeclaration.parent.parent; - const className = classExpression.name; - if (className) - return [className, variableDeclaration.name]; - return [variableDeclaration.name]; - } - } - function getFunctionNames(functionDeclaration) { - switch (functionDeclaration.kind) { - case 261 /* FunctionDeclaration */: - if (functionDeclaration.name) - return [functionDeclaration.name]; - const defaultModifier = Debug.checkDefined( - findModifier(functionDeclaration, 90 /* DefaultKeyword */), - "Nameless function declaration should be a default export" - ); - return [defaultModifier]; - case 173 /* MethodDeclaration */: - return [functionDeclaration.name]; - case 175 /* Constructor */: - const ctrKeyword = Debug.checkDefined( - findChildOfKind(functionDeclaration, 137 /* ConstructorKeyword */, functionDeclaration.getSourceFile()), - "Constructor declaration should have constructor keyword" - ); - if (functionDeclaration.parent.kind === 230 /* ClassExpression */) { - const variableDeclaration = functionDeclaration.parent.parent; - return [variableDeclaration.name, ctrKeyword]; - } - return [ctrKeyword]; - case 218 /* ArrowFunction */: - return [functionDeclaration.parent.name]; - case 217 /* FunctionExpression */: - if (functionDeclaration.name) - return [functionDeclaration.name, functionDeclaration.parent.name]; - return [functionDeclaration.parent.name]; - default: - return Debug.assertNever(functionDeclaration, `Unexpected function declaration kind ${functionDeclaration.kind}`); - } - } - var refactorName8, minimumParameterLength, refactorDescription4, toDestructuredAction; - var init_convertParamsToDestructuredObject = __esm({ - "src/services/refactors/convertParamsToDestructuredObject.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName8 = "Convert parameters to destructured object"; - minimumParameterLength = 1; - refactorDescription4 = getLocaleSpecificMessage(Diagnostics.Convert_parameters_to_destructured_object); - toDestructuredAction = { - name: refactorName8, - description: refactorDescription4, - kind: "refactor.rewrite.parameters.toDestructured" - }; - registerRefactor(refactorName8, { - kinds: [toDestructuredAction.kind], - getEditsForAction: getRefactorEditsToConvertParametersToDestructuredObject, - getAvailableActions: getRefactorActionsToConvertParametersToDestructuredObject - }); - } - }); - - // src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts - var ts_refactor_convertParamsToDestructuredObject_exports = {}; - var init_ts_refactor_convertParamsToDestructuredObject = __esm({ - "src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts"() { - "use strict"; - init_convertParamsToDestructuredObject(); - } - }); - - // src/services/refactors/convertStringOrTemplateLiteral.ts - function getRefactorActionsToConvertToTemplateString(context) { - const { file, startPosition } = context; - const node = getNodeOrParentOfParentheses(file, startPosition); - const maybeBinary = getParentBinaryExpression(node); - const refactorInfo = { name: refactorName9, description: refactorDescription5, actions: [] }; - if (isBinaryExpression(maybeBinary) && treeToArray(maybeBinary).isValidConcatenation) { - refactorInfo.actions.push(convertStringAction); - return [refactorInfo]; - } else if (context.preferences.provideRefactorNotApplicableReason) { - refactorInfo.actions.push({ - ...convertStringAction, - notApplicableReason: getLocaleSpecificMessage(Diagnostics.Can_only_convert_string_concatenation) - }); - return [refactorInfo]; - } - return emptyArray; - } - function getNodeOrParentOfParentheses(file, startPosition) { - const node = getTokenAtPosition(file, startPosition); - const nestedBinary = getParentBinaryExpression(node); - const isNonStringBinary = !treeToArray(nestedBinary).isValidConcatenation; - if (isNonStringBinary && isParenthesizedExpression(nestedBinary.parent) && isBinaryExpression(nestedBinary.parent.parent)) { - return nestedBinary.parent.parent; - } - return node; - } - function getRefactorEditsToConvertToTemplateString(context, actionName2) { - const { file, startPosition } = context; - const node = getNodeOrParentOfParentheses(file, startPosition); - switch (actionName2) { - case refactorDescription5: - return { edits: getEditsForToTemplateLiteral(context, node) }; - default: - return Debug.fail("invalid action"); - } - } - function getEditsForToTemplateLiteral(context, node) { - const maybeBinary = getParentBinaryExpression(node); - const file = context.file; - const templateLiteral = nodesToTemplate(treeToArray(maybeBinary), file); - const trailingCommentRanges = getTrailingCommentRanges(file.text, maybeBinary.end); - if (trailingCommentRanges) { - const lastComment = trailingCommentRanges[trailingCommentRanges.length - 1]; - const trailingRange = { pos: trailingCommentRanges[0].pos, end: lastComment.end }; - return ts_textChanges_exports.ChangeTracker.with(context, (t) => { - t.deleteRange(file, trailingRange); - t.replaceNode(file, maybeBinary, templateLiteral); - }); - } else { - return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, maybeBinary, templateLiteral)); - } - } - function isNotEqualsOperator(node) { - return node.operatorToken.kind !== 64 /* EqualsToken */; - } - function getParentBinaryExpression(expr) { - const container = findAncestor(expr.parent, (n) => { - switch (n.kind) { - case 210 /* PropertyAccessExpression */: - case 211 /* ElementAccessExpression */: - return false; - case 227 /* TemplateExpression */: - case 225 /* BinaryExpression */: - return !(isBinaryExpression(n.parent) && isNotEqualsOperator(n.parent)); - default: - return "quit"; - } - }); - return container || expr; - } - function treeToArray(current) { - const loop = (current2) => { - if (!isBinaryExpression(current2)) { - return { - nodes: [current2], - operators: [], - validOperators: true, - hasString: isStringLiteral(current2) || isNoSubstitutionTemplateLiteral(current2) - }; - } - const { nodes: nodes2, operators: operators2, hasString: leftHasString, validOperators: leftOperatorValid } = loop(current2.left); - if (!(leftHasString || isStringLiteral(current2.right) || isTemplateExpression(current2.right))) { - return { nodes: [current2], operators: [], hasString: false, validOperators: true }; - } - const currentOperatorValid = current2.operatorToken.kind === 40 /* PlusToken */; - const validOperators2 = leftOperatorValid && currentOperatorValid; - nodes2.push(current2.right); - operators2.push(current2.operatorToken); - return { nodes: nodes2, operators: operators2, hasString: true, validOperators: validOperators2 }; - }; - const { nodes, operators, validOperators, hasString } = loop(current); - return { nodes, operators, isValidConcatenation: validOperators && hasString }; - } - function escapeRawStringForTemplate(s) { - return s.replace(/\\.|[$`]/g, (m) => m[0] === "\\" ? m : "\\" + m); - } - function getRawTextOfTemplate(node) { - const rightShaving = isTemplateHead(node) || isTemplateMiddle(node) ? -2 : -1; - return getTextOfNode(node).slice(1, rightShaving); - } - function concatConsecutiveString(index, nodes) { - const indexes = []; - let text = "", rawText = ""; - while (index < nodes.length) { - const node = nodes[index]; - if (isStringLiteralLike(node)) { - text += node.text; - rawText += escapeRawStringForTemplate(getTextOfNode(node).slice(1, -1)); - indexes.push(index); - index++; - } else if (isTemplateExpression(node)) { - text += node.head.text; - rawText += getRawTextOfTemplate(node.head); - break; - } else { - break; - } - } - return [index, text, rawText, indexes]; - } - function nodesToTemplate({ nodes, operators }, file) { - const copyOperatorComments = copyTrailingOperatorComments(operators, file); - const copyCommentFromStringLiterals = copyCommentFromMultiNode(nodes, file, copyOperatorComments); - const [begin, headText, rawHeadText, headIndexes] = concatConsecutiveString(0, nodes); - if (begin === nodes.length) { - const noSubstitutionTemplateLiteral = factory.createNoSubstitutionTemplateLiteral(headText, rawHeadText); - copyCommentFromStringLiterals(headIndexes, noSubstitutionTemplateLiteral); - return noSubstitutionTemplateLiteral; - } - const templateSpans = []; - const templateHead = factory.createTemplateHead(headText, rawHeadText); - copyCommentFromStringLiterals(headIndexes, templateHead); - for (let i = begin; i < nodes.length; i++) { - const currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); - copyOperatorComments(i, currentNode); - const [newIndex, subsequentText, rawSubsequentText, stringIndexes] = concatConsecutiveString(i + 1, nodes); - i = newIndex - 1; - const isLast = i === nodes.length - 1; - if (isTemplateExpression(currentNode)) { - const spans = map(currentNode.templateSpans, (span, index) => { - copyExpressionComments(span); - 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)); - }); - templateSpans.push(...spans); - } else { - const templatePart = isLast ? factory.createTemplateTail(subsequentText, rawSubsequentText) : factory.createTemplateMiddle(subsequentText, rawSubsequentText); - copyCommentFromStringLiterals(stringIndexes, templatePart); - templateSpans.push(factory.createTemplateSpan(currentNode, templatePart)); - } - } - return factory.createTemplateExpression(templateHead, templateSpans); - } - function copyExpressionComments(node) { - const file = node.getSourceFile(); - copyTrailingComments( - node, - node.expression, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - copyTrailingAsLeadingComments( - node.expression, - node.expression, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - } - function getExpressionFromParenthesesOrExpression(node) { - if (isParenthesizedExpression(node)) { - copyExpressionComments(node); - node = node.expression; - } - return node; - } - var refactorName9, refactorDescription5, convertStringAction, copyTrailingOperatorComments, copyCommentFromMultiNode; - var init_convertStringOrTemplateLiteral = __esm({ - "src/services/refactors/convertStringOrTemplateLiteral.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName9 = "Convert to template string"; - refactorDescription5 = getLocaleSpecificMessage(Diagnostics.Convert_to_template_string); - convertStringAction = { - name: refactorName9, - description: refactorDescription5, - kind: "refactor.rewrite.string" - }; - registerRefactor(refactorName9, { - kinds: [convertStringAction.kind], - getEditsForAction: getRefactorEditsToConvertToTemplateString, - getAvailableActions: getRefactorActionsToConvertToTemplateString - }); - copyTrailingOperatorComments = (operators, file) => (index, targetNode) => { - if (index < operators.length) { - copyTrailingComments( - operators[index], - targetNode, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - } - }; - copyCommentFromMultiNode = (nodes, file, copyOperatorComments) => (indexes, targetNode) => { - while (indexes.length > 0) { - const index = indexes.shift(); - copyTrailingComments( - nodes[index], - targetNode, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - copyOperatorComments(index, targetNode); - } - }; - } - }); - - // src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts - var ts_refactor_convertStringOrTemplateLiteral_exports = {}; - var init_ts_refactor_convertStringOrTemplateLiteral = __esm({ - "src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts"() { - "use strict"; - init_convertStringOrTemplateLiteral(); - } - }); - - // src/services/refactors/convertToOptionalChainExpression.ts - function getRefactorActionsToConvertToOptionalChain(context) { - const info = getInfo20(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - return [{ - name: refactorName10, - description: convertToOptionalChainExpressionMessage, - actions: [toOptionalChainAction] - }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorName10, - description: convertToOptionalChainExpressionMessage, - actions: [{ ...toOptionalChainAction, notApplicableReason: info.error }] - }]; - } - return emptyArray; - } - function getRefactorEditsToConvertToOptionalChain(context, actionName2) { - const info = getInfo20(context); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_textChanges_exports.ChangeTracker.with( - context, - (t) => doChange38(context.file, context.program.getTypeChecker(), t, info, actionName2) - ); - return { edits, renameFilename: void 0, renameLocation: void 0 }; - } - function isValidExpression(node) { - return isBinaryExpression(node) || isConditionalExpression(node); - } - function isValidStatement(node) { - return isExpressionStatement(node) || isReturnStatement(node) || isVariableStatement(node); - } - function isValidExpressionOrStatement(node) { - return isValidExpression(node) || isValidStatement(node); - } - function getInfo20(context, considerEmptySpans = true) { - const { file, program } = context; - const span = getRefactorContextSpan(context); - const forEmptySpan = span.length === 0; - if (forEmptySpan && !considerEmptySpans) - return void 0; - const startToken = getTokenAtPosition(file, span.start); - const endToken = findTokenOnLeftOfPosition(file, span.start + span.length); - const adjustedSpan = createTextSpanFromBounds(startToken.pos, endToken && endToken.end >= startToken.pos ? endToken.getEnd() : startToken.getEnd()); - const parent2 = forEmptySpan ? getValidParentNodeOfEmptySpan(startToken) : getValidParentNodeContainingSpan(startToken, adjustedSpan); - const expression = parent2 && isValidExpressionOrStatement(parent2) ? getExpression(parent2) : void 0; - if (!expression) - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; - const checker = program.getTypeChecker(); - return isConditionalExpression(expression) ? getConditionalInfo(expression, checker) : getBinaryInfo(expression); - } - function getConditionalInfo(expression, checker) { - const condition = expression.condition; - const finalExpression = getFinalExpressionInChain(expression.whenTrue); - if (!finalExpression || checker.isNullableType(checker.getTypeAtLocation(finalExpression))) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; - } - if ((isPropertyAccessExpression(condition) || isIdentifier(condition)) && getMatchingStart(condition, finalExpression.expression)) { - return { finalExpression, occurrences: [condition], expression }; - } else if (isBinaryExpression(condition)) { - const occurrences = getOccurrencesInExpression(finalExpression.expression, condition); - return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) }; - } - } - function getBinaryInfo(expression) { - if (expression.operatorToken.kind !== 56 /* AmpersandAmpersandToken */) { - return { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_logical_AND_access_chains) }; - } - const finalExpression = getFinalExpressionInChain(expression.right); - if (!finalExpression) - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; - const occurrences = getOccurrencesInExpression(finalExpression.expression, expression.left); - return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) }; - } - function getOccurrencesInExpression(matchTo, expression) { - const occurrences = []; - while (isBinaryExpression(expression) && expression.operatorToken.kind === 56 /* AmpersandAmpersandToken */) { - const match = getMatchingStart(skipParentheses(matchTo), skipParentheses(expression.right)); - if (!match) { - break; - } - occurrences.push(match); - matchTo = match; - expression = expression.left; - } - const finalMatch = getMatchingStart(matchTo, expression); - if (finalMatch) { - occurrences.push(finalMatch); - } - return occurrences.length > 0 ? occurrences : void 0; - } - function getMatchingStart(chain, subchain) { - if (!isIdentifier(subchain) && !isPropertyAccessExpression(subchain) && !isElementAccessExpression(subchain)) { - return void 0; - } - return chainStartsWith(chain, subchain) ? subchain : void 0; - } - function chainStartsWith(chain, subchain) { - while (isCallExpression(chain) || isPropertyAccessExpression(chain) || isElementAccessExpression(chain)) { - if (getTextOfChainNode(chain) === getTextOfChainNode(subchain)) - break; - chain = chain.expression; - } - while (isPropertyAccessExpression(chain) && isPropertyAccessExpression(subchain) || isElementAccessExpression(chain) && isElementAccessExpression(subchain)) { - if (getTextOfChainNode(chain) !== getTextOfChainNode(subchain)) - return false; - chain = chain.expression; - subchain = subchain.expression; - } - return isIdentifier(chain) && isIdentifier(subchain) && chain.getText() === subchain.getText(); - } - function getTextOfChainNode(node) { - if (isIdentifier(node) || isStringOrNumericLiteralLike(node)) { - return node.getText(); - } - if (isPropertyAccessExpression(node)) { - return getTextOfChainNode(node.name); - } - if (isElementAccessExpression(node)) { - return getTextOfChainNode(node.argumentExpression); - } - return void 0; - } - function getValidParentNodeContainingSpan(node, span) { - while (node.parent) { - if (isValidExpressionOrStatement(node) && span.length !== 0 && node.end >= span.start + span.length) { - return node; - } - node = node.parent; - } - return void 0; - } - function getValidParentNodeOfEmptySpan(node) { - while (node.parent) { - if (isValidExpressionOrStatement(node) && !isValidExpressionOrStatement(node.parent)) { - return node; - } - node = node.parent; - } - return void 0; - } - function getExpression(node) { - if (isValidExpression(node)) { - return node; - } - if (isVariableStatement(node)) { - const variable = getSingleVariableOfVariableStatement(node); - const initializer = variable == null ? void 0 : variable.initializer; - return initializer && isValidExpression(initializer) ? initializer : void 0; - } - return node.expression && isValidExpression(node.expression) ? node.expression : void 0; - } - function getFinalExpressionInChain(node) { - node = skipParentheses(node); - if (isBinaryExpression(node)) { - return getFinalExpressionInChain(node.left); - } else if ((isPropertyAccessExpression(node) || isElementAccessExpression(node) || isCallExpression(node)) && !isOptionalChain(node)) { - return node; - } - return void 0; - } - function convertOccurrences(checker, toConvert, occurrences) { - if (isPropertyAccessExpression(toConvert) || isElementAccessExpression(toConvert) || isCallExpression(toConvert)) { - const chain = convertOccurrences(checker, toConvert.expression, occurrences); - const lastOccurrence = occurrences.length > 0 ? occurrences[occurrences.length - 1] : void 0; - const isOccurrence = (lastOccurrence == null ? void 0 : lastOccurrence.getText()) === toConvert.expression.getText(); - if (isOccurrence) - occurrences.pop(); - if (isCallExpression(toConvert)) { - return isOccurrence ? factory.createCallChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.typeArguments, toConvert.arguments) : factory.createCallChain(chain, toConvert.questionDotToken, toConvert.typeArguments, toConvert.arguments); - } else if (isPropertyAccessExpression(toConvert)) { - return isOccurrence ? factory.createPropertyAccessChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.name) : factory.createPropertyAccessChain(chain, toConvert.questionDotToken, toConvert.name); - } else if (isElementAccessExpression(toConvert)) { - return isOccurrence ? factory.createElementAccessChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.argumentExpression) : factory.createElementAccessChain(chain, toConvert.questionDotToken, toConvert.argumentExpression); - } - } - return toConvert; - } - function doChange38(sourceFile, checker, changes, info, _actionName) { - const { finalExpression, occurrences, expression } = info; - const firstOccurrence = occurrences[occurrences.length - 1]; - const convertedChain = convertOccurrences(checker, finalExpression, occurrences); - if (convertedChain && (isPropertyAccessExpression(convertedChain) || isElementAccessExpression(convertedChain) || isCallExpression(convertedChain))) { - if (isBinaryExpression(expression)) { - changes.replaceNodeRange(sourceFile, firstOccurrence, finalExpression, convertedChain); - } else if (isConditionalExpression(expression)) { - changes.replaceNode( - sourceFile, - expression, - factory.createBinaryExpression(convertedChain, factory.createToken(61 /* QuestionQuestionToken */), expression.whenFalse) - ); - } - } - } - var refactorName10, convertToOptionalChainExpressionMessage, toOptionalChainAction; - var init_convertToOptionalChainExpression = __esm({ - "src/services/refactors/convertToOptionalChainExpression.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName10 = "Convert to optional chain expression"; - convertToOptionalChainExpressionMessage = getLocaleSpecificMessage(Diagnostics.Convert_to_optional_chain_expression); - toOptionalChainAction = { - name: refactorName10, - description: convertToOptionalChainExpressionMessage, - kind: "refactor.rewrite.expression.optionalChain" - }; - registerRefactor(refactorName10, { - kinds: [toOptionalChainAction.kind], - getEditsForAction: getRefactorEditsToConvertToOptionalChain, - getAvailableActions: getRefactorActionsToConvertToOptionalChain - }); - } - }); - - // src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts - var ts_refactor_convertToOptionalChainExpression_exports = {}; - var init_ts_refactor_convertToOptionalChainExpression = __esm({ - "src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts"() { - "use strict"; - init_convertToOptionalChainExpression(); - } - }); - - // src/services/refactors/extractSymbol.ts - function getRefactorActionsToExtractSymbol(context) { - const requestedRefactor = context.kind; - const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context), context.triggerReason === "invoked"); - const targetRange = rangeToExtract.targetRange; - if (targetRange === void 0) { - if (!rangeToExtract.errors || rangeToExtract.errors.length === 0 || !context.preferences.provideRefactorNotApplicableReason) { - return emptyArray; - } - const errors = []; - if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { - errors.push({ - name: refactorName11, - description: extractFunctionAction.description, - actions: [{ ...extractFunctionAction, notApplicableReason: getStringError(rangeToExtract.errors) }] - }); - } - if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { - errors.push({ - name: refactorName11, - description: extractConstantAction.description, - actions: [{ ...extractConstantAction, notApplicableReason: getStringError(rangeToExtract.errors) }] - }); - } - return errors; - } - const extractions = getPossibleExtractions(targetRange, context); - if (extractions === void 0) { - return emptyArray; - } - const functionActions = []; - const usedFunctionNames = /* @__PURE__ */ new Map(); - let innermostErrorFunctionAction; - const constantActions = []; - const usedConstantNames = /* @__PURE__ */ new Map(); - let innermostErrorConstantAction; - let i = 0; - for (const { functionExtraction, constantExtraction } of extractions) { - if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { - const description2 = functionExtraction.description; - if (functionExtraction.errors.length === 0) { - if (!usedFunctionNames.has(description2)) { - usedFunctionNames.set(description2, true); - functionActions.push({ - description: description2, - name: `function_scope_${i}`, - kind: extractFunctionAction.kind - }); - } - } else if (!innermostErrorFunctionAction) { - innermostErrorFunctionAction = { - description: description2, - name: `function_scope_${i}`, - notApplicableReason: getStringError(functionExtraction.errors), - kind: extractFunctionAction.kind - }; - } - } - if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { - const description2 = constantExtraction.description; - if (constantExtraction.errors.length === 0) { - if (!usedConstantNames.has(description2)) { - usedConstantNames.set(description2, true); - constantActions.push({ - description: description2, - name: `constant_scope_${i}`, - kind: extractConstantAction.kind - }); - } - } else if (!innermostErrorConstantAction) { - innermostErrorConstantAction = { - description: description2, - name: `constant_scope_${i}`, - notApplicableReason: getStringError(constantExtraction.errors), - kind: extractConstantAction.kind - }; - } - } - i++; - } - const infos = []; - if (functionActions.length) { - infos.push({ - name: refactorName11, - description: getLocaleSpecificMessage(Diagnostics.Extract_function), - actions: functionActions - }); - } else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorFunctionAction) { - infos.push({ - name: refactorName11, - description: getLocaleSpecificMessage(Diagnostics.Extract_function), - actions: [innermostErrorFunctionAction] - }); - } - if (constantActions.length) { - infos.push({ - name: refactorName11, - description: getLocaleSpecificMessage(Diagnostics.Extract_constant), - actions: constantActions - }); - } else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorConstantAction) { - infos.push({ - name: refactorName11, - description: getLocaleSpecificMessage(Diagnostics.Extract_constant), - actions: [innermostErrorConstantAction] - }); - } - return infos.length ? infos : emptyArray; - function getStringError(errors) { - let error = errors[0].messageText; - if (typeof error !== "string") { - error = error.messageText; - } - return error; - } - } - function getRefactorEditsToExtractSymbol(context, actionName2) { - const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context)); - const targetRange = rangeToExtract.targetRange; - const parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName2); - if (parsedFunctionIndexMatch) { - const index = +parsedFunctionIndexMatch[1]; - Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index"); - return getFunctionExtractionAtIndex(targetRange, context, index); - } - const parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName2); - if (parsedConstantIndexMatch) { - const index = +parsedConstantIndexMatch[1]; - Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index"); - return getConstantExtractionAtIndex(targetRange, context, index); - } - Debug.fail("Unrecognized action name"); - } - function getRangeToExtract2(sourceFile, span, invoked = true) { - const { length: length2 } = span; - if (length2 === 0 && !invoked) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractEmpty)] }; - } - const cursorRequest = length2 === 0 && invoked; - const startToken = findFirstNonJsxWhitespaceToken(sourceFile, span.start); - const endToken = findTokenOnLeftOfPosition(sourceFile, textSpanEnd(span)); - const adjustedSpan = startToken && endToken && invoked ? getAdjustedSpanFromNodes(startToken, endToken, sourceFile) : span; - const start = cursorRequest ? getExtractableParent(startToken) : getParentNodeInSpan(startToken, sourceFile, adjustedSpan); - const end = cursorRequest ? start : getParentNodeInSpan(endToken, sourceFile, adjustedSpan); - let rangeFacts = 0 /* None */; - let thisNode; - if (!start || !end) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; - } - if (start.flags & 8388608 /* JSDoc */) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractJSDoc)] }; - } - if (start.parent !== end.parent) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; - } - if (start !== end) { - if (!isBlockLike(start.parent)) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; - } - const statements = []; - for (const statement of start.parent.statements) { - if (statement === start || statements.length) { - const errors2 = checkNode(statement); - if (errors2) { - return { errors: errors2 }; - } - statements.push(statement); - } - if (statement === end) { - break; - } - } - if (!statements.length) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; - } - return { targetRange: { range: statements, facts: rangeFacts, thisNode } }; - } - if (isReturnStatement(start) && !start.expression) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; - } - const node = refineNode(start); - const errors = checkRootNode(node) || checkNode(node); - if (errors) { - return { errors }; - } - return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, thisNode } }; - function refineNode(node2) { - if (isReturnStatement(node2)) { - if (node2.expression) { - return node2.expression; - } - } else if (isVariableStatement(node2) || isVariableDeclarationList(node2)) { - const declarations = isVariableStatement(node2) ? node2.declarationList.declarations : node2.declarations; - let numInitializers = 0; - let lastInitializer; - for (const declaration of declarations) { - if (declaration.initializer) { - numInitializers++; - lastInitializer = declaration.initializer; - } - } - if (numInitializers === 1) { - return lastInitializer; - } - } else if (isVariableDeclaration(node2)) { - if (node2.initializer) { - return node2.initializer; - } - } - return node2; - } - function checkRootNode(node2) { - if (isIdentifier(isExpressionStatement(node2) ? node2.expression : node2)) { - return [createDiagnosticForNode(node2, Messages.cannotExtractIdentifier)]; - } - return void 0; - } - function checkForStaticContext(nodeToCheck, containingClass) { - let current = nodeToCheck; - while (current !== containingClass) { - if (current.kind === 171 /* PropertyDeclaration */) { - if (isStatic(current)) { - rangeFacts |= 32 /* InStaticRegion */; - } - break; - } else if (current.kind === 168 /* Parameter */) { - const ctorOrMethod = getContainingFunction(current); - if (ctorOrMethod.kind === 175 /* Constructor */) { - rangeFacts |= 32 /* InStaticRegion */; - } - break; - } else if (current.kind === 173 /* MethodDeclaration */) { - if (isStatic(current)) { - rangeFacts |= 32 /* InStaticRegion */; - } - } - current = current.parent; - } - } - function checkNode(nodeToCheck) { - let PermittedJumps; - ((PermittedJumps2) => { - PermittedJumps2[PermittedJumps2["None"] = 0] = "None"; - PermittedJumps2[PermittedJumps2["Break"] = 1] = "Break"; - PermittedJumps2[PermittedJumps2["Continue"] = 2] = "Continue"; - PermittedJumps2[PermittedJumps2["Return"] = 4] = "Return"; - })(PermittedJumps || (PermittedJumps = {})); - Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (1)"); - Debug.assert(!positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (2)"); - if (!isStatement(nodeToCheck) && !(isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck)) && !isStringLiteralJsxAttribute(nodeToCheck)) { - return [createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)]; - } - if (nodeToCheck.flags & 16777216 /* Ambient */) { - return [createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)]; - } - const containingClass = getContainingClass(nodeToCheck); - if (containingClass) { - checkForStaticContext(nodeToCheck, containingClass); - } - let errors2; - let permittedJumps = 4 /* Return */; - let seenLabels; - visit(nodeToCheck); - if (rangeFacts & 8 /* UsesThis */) { - const container = getThisContainer( - nodeToCheck, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); - if (container.kind === 261 /* FunctionDeclaration */ || container.kind === 173 /* MethodDeclaration */ && container.parent.kind === 209 /* ObjectLiteralExpression */ || container.kind === 217 /* FunctionExpression */) { - rangeFacts |= 16 /* UsesThisInFunction */; - } - } - return errors2; - function visit(node2) { - if (errors2) { - return true; - } - if (isDeclaration(node2)) { - const declaringNode = node2.kind === 259 /* VariableDeclaration */ ? node2.parent.parent : node2; - if (hasSyntacticModifier(declaringNode, 1 /* Export */)) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity)); - return true; - } - } - switch (node2.kind) { - case 271 /* ImportDeclaration */: - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractImport)); - return true; - case 276 /* ExportAssignment */: - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity)); - return true; - case 108 /* SuperKeyword */: - if (node2.parent.kind === 212 /* CallExpression */) { - const containingClass2 = getContainingClass(node2); - if (containingClass2 === void 0 || containingClass2.pos < span.start || containingClass2.end >= span.start + span.length) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractSuper)); - return true; - } - } else { - rangeFacts |= 8 /* UsesThis */; - thisNode = node2; - } - break; - case 218 /* ArrowFunction */: - forEachChild(node2, function check(n) { - if (isThis(n)) { - rangeFacts |= 8 /* UsesThis */; - thisNode = node2; - } else if (isClassLike(n) || isFunctionLike(n) && !isArrowFunction(n)) { - return false; - } else { - forEachChild(n, check); - } - }); - case 262 /* ClassDeclaration */: - case 261 /* FunctionDeclaration */: - if (isSourceFile(node2.parent) && node2.parent.externalModuleIndicator === void 0) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.functionWillNotBeVisibleInTheNewScope)); - } - case 230 /* ClassExpression */: - case 217 /* FunctionExpression */: - case 173 /* MethodDeclaration */: - case 175 /* Constructor */: - case 176 /* GetAccessor */: - case 177 /* SetAccessor */: - return false; - } - const savedPermittedJumps = permittedJumps; - switch (node2.kind) { - case 244 /* IfStatement */: - permittedJumps &= ~4 /* Return */; - break; - case 257 /* TryStatement */: - permittedJumps = 0 /* None */; - break; - case 240 /* Block */: - if (node2.parent && node2.parent.kind === 257 /* TryStatement */ && node2.parent.finallyBlock === node2) { - permittedJumps = 4 /* Return */; - } - break; - case 296 /* DefaultClause */: - case 295 /* CaseClause */: - permittedJumps |= 1 /* Break */; - break; - default: - if (isIterationStatement( - node2, - /*lookInLabeledStatements*/ - false - )) { - permittedJumps |= 1 /* Break */ | 2 /* Continue */; - } - break; - } - switch (node2.kind) { - case 196 /* ThisType */: - case 110 /* ThisKeyword */: - rangeFacts |= 8 /* UsesThis */; - thisNode = node2; - break; - case 255 /* LabeledStatement */: { - const label = node2.label; - (seenLabels || (seenLabels = [])).push(label.escapedText); - forEachChild(node2, visit); - seenLabels.pop(); - break; - } - case 251 /* BreakStatement */: - case 250 /* ContinueStatement */: { - const label = node2.label; - if (label) { - if (!contains(seenLabels, label.escapedText)) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); - } - } else { - if (!(permittedJumps & (node2.kind === 251 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); - } - } - break; - } - case 222 /* AwaitExpression */: - rangeFacts |= 4 /* IsAsyncFunction */; - break; - case 228 /* YieldExpression */: - rangeFacts |= 2 /* IsGenerator */; - break; - case 252 /* ReturnStatement */: - if (permittedJumps & 4 /* Return */) { - rangeFacts |= 1 /* HasReturn */; - } else { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalReturnStatement)); - } - break; - default: - forEachChild(node2, visit); - break; - } - permittedJumps = savedPermittedJumps; - } - } - } - function getAdjustedSpanFromNodes(startNode2, endNode2, sourceFile) { - const start = startNode2.getStart(sourceFile); - let end = endNode2.getEnd(); - if (sourceFile.text.charCodeAt(end) === 59 /* semicolon */) { - end++; - } - return { start, length: end - start }; - } - function getStatementOrExpressionRange(node) { - if (isStatement(node)) { - return [node]; - } - if (isExpressionNode(node)) { - return isExpressionStatement(node.parent) ? [node.parent] : node; - } - if (isStringLiteralJsxAttribute(node)) { - return node; - } - return void 0; - } - function isScope(node) { - return isArrowFunction(node) ? isFunctionBody(node.body) : isFunctionLikeDeclaration(node) || isSourceFile(node) || isModuleBlock(node) || isClassLike(node); - } - function collectEnclosingScopes(range) { - let current = isReadonlyArray(range.range) ? first(range.range) : range.range; - if (range.facts & 8 /* UsesThis */ && !(range.facts & 16 /* UsesThisInFunction */)) { - const containingClass = getContainingClass(current); - if (containingClass) { - const containingFunction = findAncestor(current, isFunctionLikeDeclaration); - return containingFunction ? [containingFunction, containingClass] : [containingClass]; - } - } - const scopes = []; - while (true) { - current = current.parent; - if (current.kind === 168 /* Parameter */) { - current = findAncestor(current, (parent2) => isFunctionLikeDeclaration(parent2)).parent; - } - if (isScope(current)) { - scopes.push(current); - if (current.kind === 311 /* SourceFile */) { - return scopes; - } - } - } - } - function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { - const { scopes, readsAndWrites: { target, usagesPerScope, functionErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); - Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); - context.cancellationToken.throwIfCancellationRequested(); - return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); - } - function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { - const { scopes, readsAndWrites: { target, usagesPerScope, constantErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); - Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); - Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); - context.cancellationToken.throwIfCancellationRequested(); - const expression = isExpression(target) ? target : target.statements[0].expression; - return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context); - } - function getPossibleExtractions(targetRange, context) { - const { scopes, readsAndWrites: { functionErrorsPerScope, constantErrorsPerScope } } = getPossibleExtractionsWorker(targetRange, context); - const extractions = scopes.map((scope, i) => { - const functionDescriptionPart = getDescriptionForFunctionInScope(scope); - const constantDescriptionPart = getDescriptionForConstantInScope(scope); - const scopeDescription = isFunctionLikeDeclaration(scope) ? getDescriptionForFunctionLikeDeclaration(scope) : isClassLike(scope) ? getDescriptionForClassLikeDeclaration(scope) : getDescriptionForModuleLikeDeclaration(scope); - let functionDescription; - let constantDescription; - if (scopeDescription === 1 /* Global */) { - functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]); - constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]); - } else if (scopeDescription === 0 /* Module */) { - functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]); - constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]); - } else { - functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]); - constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]); - } - if (i === 0 && !isClassLike(scope)) { - constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]); - } - return { - functionExtraction: { - description: functionDescription, - errors: functionErrorsPerScope[i] - }, - constantExtraction: { - description: constantDescription, - errors: constantErrorsPerScope[i] - } - }; - }); - return extractions; - } - function getPossibleExtractionsWorker(targetRange, context) { - const { file: sourceFile } = context; - const scopes = collectEnclosingScopes(targetRange); - const enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); - const readsAndWrites = collectReadsAndWrites( - targetRange, - scopes, - enclosingTextRange, - sourceFile, - context.program.getTypeChecker(), - context.cancellationToken - ); - return { scopes, readsAndWrites }; - } - function getDescriptionForFunctionInScope(scope) { - return isFunctionLikeDeclaration(scope) ? "inner function" : isClassLike(scope) ? "method" : "function"; - } - function getDescriptionForConstantInScope(scope) { - return isClassLike(scope) ? "readonly field" : "constant"; - } - function getDescriptionForFunctionLikeDeclaration(scope) { - switch (scope.kind) { - case 175 /* Constructor */: - return "constructor"; - case 217 /* FunctionExpression */: - case 261 /* FunctionDeclaration */: - return scope.name ? `function '${scope.name.text}'` : ANONYMOUS; - case 218 /* ArrowFunction */: - return "arrow function"; - case 173 /* MethodDeclaration */: - return `method '${scope.name.getText()}'`; - case 176 /* GetAccessor */: - return `'get ${scope.name.getText()}'`; - case 177 /* SetAccessor */: - return `'set ${scope.name.getText()}'`; - default: - Debug.assertNever(scope, `Unexpected scope kind ${scope.kind}`); - } - } - function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 262 /* ClassDeclaration */ ? scope.name ? `class '${scope.name.text}'` : "anonymous class declaration" : scope.name ? `class expression '${scope.name.text}'` : "anonymous class expression"; - } - function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 267 /* ModuleBlock */ ? `namespace '${scope.parent.name.getText()}'` : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; - } - function extractFunctionInScope(node, scope, { usages: usagesInScope, typeParameterUsages, substitutions }, exposedVariableDeclarations, range, context) { - const checker = context.program.getTypeChecker(); - const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); - const importAdder = ts_codefix_exports.createImportAdder(context.file, context.program, context.preferences, context.host); - const file = scope.getSourceFile(); - const functionNameText = getUniqueName(isClassLike(scope) ? "newMethod" : "newFunction", file); - const isJS = isInJSFile(scope); - const functionName = factory.createIdentifier(functionNameText); - let returnType; - const parameters = []; - const callArguments = []; - let writes; - usagesInScope.forEach((usage, name) => { - let typeNode; - if (!isJS) { - let type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); - type = checker.getBaseTypeOfLiteralType(type); - typeNode = ts_codefix_exports.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */); - } - const paramDecl = factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - /*name*/ - name, - /*questionToken*/ - void 0, - typeNode - ); - parameters.push(paramDecl); - if (usage.usage === 2 /* Write */) { - (writes || (writes = [])).push(usage); - } - callArguments.push(factory.createIdentifier(name)); - }); - const typeParametersAndDeclarations = arrayFrom(typeParameterUsages.values(), (type) => ({ type, declaration: getFirstDeclarationBeforePosition(type, context.startPosition) })); - const sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); - const typeParameters = sortedTypeParametersAndDeclarations.length === 0 ? void 0 : mapDefined(sortedTypeParametersAndDeclarations, ({ declaration }) => declaration); - const callTypeArguments = typeParameters !== void 0 ? typeParameters.map((decl) => factory.createTypeReferenceNode( - decl.name, - /*typeArguments*/ - void 0 - )) : void 0; - if (isExpression(node) && !isJS) { - const contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); - } - const { body, returnValueProperty } = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & 1 /* HasReturn */)); - suppressLeadingAndTrailingTrivia(body); - let newFunction; - const callThis = !!(range.facts & 16 /* UsesThisInFunction */); - if (isClassLike(scope)) { - const modifiers = isJS ? [] : [factory.createModifier(123 /* PrivateKeyword */)]; - if (range.facts & 32 /* InStaticRegion */) { - modifiers.push(factory.createModifier(126 /* StaticKeyword */)); - } - if (range.facts & 4 /* IsAsyncFunction */) { - modifiers.push(factory.createModifier(134 /* AsyncKeyword */)); - } - newFunction = factory.createMethodDeclaration( - modifiers.length ? modifiers : void 0, - range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0, - functionName, - /*questionToken*/ - void 0, - typeParameters, - parameters, - returnType, - body - ); - } else { - if (callThis) { - parameters.unshift( - factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - /*name*/ - "this", - /*questionToken*/ - void 0, - checker.typeToTypeNode( - checker.getTypeAtLocation(range.thisNode), - scope, - 1 /* NoTruncation */ - ), - /*initializer*/ - void 0 - ) - ); - } - newFunction = factory.createFunctionDeclaration( - range.facts & 4 /* IsAsyncFunction */ ? [factory.createToken(134 /* AsyncKeyword */)] : void 0, - range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0, - functionName, - typeParameters, - parameters, - returnType, - body - ); - } - const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); - const minInsertionPos = (isReadonlyArray(range.range) ? last(range.range) : range.range).end; - const nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); - if (nodeToInsertBefore) { - changeTracker.insertNodeBefore( - context.file, - nodeToInsertBefore, - newFunction, - /*blankLineBetween*/ - true - ); - } else { - changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); - } - importAdder.writeFixes(changeTracker); - const newNodes = []; - const called = getCalledExpression(scope, range, functionNameText); - if (callThis) { - callArguments.unshift(factory.createIdentifier("this")); - } - let call = factory.createCallExpression( - callThis ? factory.createPropertyAccessExpression( - called, - "call" - ) : called, - callTypeArguments, - // Note that no attempt is made to take advantage of type argument inference - callArguments - ); - if (range.facts & 2 /* IsGenerator */) { - call = factory.createYieldExpression(factory.createToken(42 /* AsteriskToken */), call); - } - if (range.facts & 4 /* IsAsyncFunction */) { - call = factory.createAwaitExpression(call); - } - if (isInJSXContent(node)) { - call = factory.createJsxExpression( - /*dotDotDotToken*/ - void 0, - call - ); - } - if (exposedVariableDeclarations.length && !writes) { - Debug.assert(!returnValueProperty, "Expected no returnValueProperty"); - Debug.assert(!(range.facts & 1 /* HasReturn */), "Expected RangeFacts.HasReturn flag to be unset"); - if (exposedVariableDeclarations.length === 1) { - const variableDeclaration = exposedVariableDeclarations[0]; - newNodes.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - getSynthesizedDeepClone(variableDeclaration.name), - /*exclamationToken*/ - void 0, - /*type*/ - getSynthesizedDeepClone(variableDeclaration.type), - /*initializer*/ - call - )], - variableDeclaration.parent.flags - ) - )); - } else { - const bindingElements = []; - const typeElements = []; - let commonNodeFlags = exposedVariableDeclarations[0].parent.flags; - let sawExplicitType = false; - for (const variableDeclaration of exposedVariableDeclarations) { - bindingElements.push(factory.createBindingElement( - /*dotDotDotToken*/ - void 0, - /*propertyName*/ - void 0, - /*name*/ - getSynthesizedDeepClone(variableDeclaration.name) - )); - const variableType = checker.typeToTypeNode( - checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), - scope, - 1 /* NoTruncation */ - ); - typeElements.push(factory.createPropertySignature( - /*modifiers*/ - void 0, - /*name*/ - variableDeclaration.symbol.name, - /*questionToken*/ - void 0, - /*type*/ - variableType - )); - sawExplicitType = sawExplicitType || variableDeclaration.type !== void 0; - commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; - } - const typeLiteral = sawExplicitType ? factory.createTypeLiteralNode(typeElements) : void 0; - if (typeLiteral) { - setEmitFlags(typeLiteral, 1 /* SingleLine */); - } - newNodes.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - factory.createObjectBindingPattern(bindingElements), - /*exclamationToken*/ - void 0, - /*type*/ - typeLiteral, - /*initializer*/ - call - )], - commonNodeFlags - ) - )); - } - } else if (exposedVariableDeclarations.length || writes) { - if (exposedVariableDeclarations.length) { - for (const variableDeclaration of exposedVariableDeclarations) { - let flags = variableDeclaration.parent.flags; - if (flags & 2 /* Const */) { - flags = flags & ~2 /* Const */ | 1 /* Let */; - } - newNodes.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - variableDeclaration.symbol.name, - /*exclamationToken*/ - void 0, - getTypeDeepCloneUnionUndefined(variableDeclaration.type) - )], - flags - ) - )); - } - } - if (returnValueProperty) { - newNodes.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - returnValueProperty, - /*exclamationToken*/ - void 0, - getTypeDeepCloneUnionUndefined(returnType) - )], - 1 /* Let */ - ) - )); - } - const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); - if (returnValueProperty) { - assignments.unshift(factory.createShorthandPropertyAssignment(returnValueProperty)); - } - if (assignments.length === 1) { - Debug.assert(!returnValueProperty, "Shouldn't have returnValueProperty here"); - newNodes.push(factory.createExpressionStatement(factory.createAssignment(assignments[0].name, call))); - if (range.facts & 1 /* HasReturn */) { - newNodes.push(factory.createReturnStatement()); - } - } else { - newNodes.push(factory.createExpressionStatement(factory.createAssignment(factory.createObjectLiteralExpression(assignments), call))); - if (returnValueProperty) { - newNodes.push(factory.createReturnStatement(factory.createIdentifier(returnValueProperty))); - } - } - } else { - if (range.facts & 1 /* HasReturn */) { - newNodes.push(factory.createReturnStatement(call)); - } else if (isReadonlyArray(range.range)) { - newNodes.push(factory.createExpressionStatement(call)); - } else { - newNodes.push(call); - } - } - if (isReadonlyArray(range.range)) { - changeTracker.replaceNodeRangeWithNodes(context.file, first(range.range), last(range.range), newNodes); - } else { - changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes); - } - const edits = changeTracker.getChanges(); - const renameRange = isReadonlyArray(range.range) ? first(range.range) : range.range; - const renameFilename = renameRange.getSourceFile().fileName; - const renameLocation = getRenameLocation( - edits, - renameFilename, - functionNameText, - /*preferLastLocation*/ - false - ); - return { renameFilename, renameLocation, edits }; - function getTypeDeepCloneUnionUndefined(typeNode) { - if (typeNode === void 0) { - return void 0; - } - const clone2 = getSynthesizedDeepClone(typeNode); - let withoutParens = clone2; - while (isParenthesizedTypeNode(withoutParens)) { - withoutParens = withoutParens.type; - } - return isUnionTypeNode(withoutParens) && find(withoutParens.types, (t) => t.kind === 157 /* UndefinedKeyword */) ? clone2 : factory.createUnionTypeNode([clone2, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); - } - } - function extractConstantInScope(node, scope, { substitutions }, rangeFacts, context) { - const checker = context.program.getTypeChecker(); - const file = scope.getSourceFile(); - const localNameText = isPropertyAccessExpression(node) && !isClassLike(scope) && !checker.resolveName( - node.name.text, - node, - 111551 /* Value */, - /*excludeGlobals*/ - false - ) && !isPrivateIdentifier(node.name) && !identifierToKeywordKind(node.name) ? node.name.text : getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file); - const isJS = isInJSFile(scope); - let variableType = isJS || !checker.isContextSensitive(node) ? void 0 : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); - let initializer = transformConstantInitializer(skipParentheses(node), substitutions); - ({ variableType, initializer } = transformFunctionInitializerAndType(variableType, initializer)); - suppressLeadingAndTrailingTrivia(initializer); - const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); - if (isClassLike(scope)) { - Debug.assert(!isJS, "Cannot extract to a JS class"); - const modifiers = []; - modifiers.push(factory.createModifier(123 /* PrivateKeyword */)); - if (rangeFacts & 32 /* InStaticRegion */) { - modifiers.push(factory.createModifier(126 /* StaticKeyword */)); - } - modifiers.push(factory.createModifier(148 /* ReadonlyKeyword */)); - const newVariable = factory.createPropertyDeclaration( - modifiers, - localNameText, - /*questionOrExclamationToken*/ - void 0, - variableType, - initializer - ); - let localReference = factory.createPropertyAccessExpression( - rangeFacts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.getText()) : factory.createThis(), - factory.createIdentifier(localNameText) - ); - if (isInJSXContent(node)) { - localReference = factory.createJsxExpression( - /*dotDotDotToken*/ - void 0, - localReference - ); - } - const maxInsertionPos = node.pos; - const nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); - changeTracker.insertNodeBefore( - context.file, - nodeToInsertBefore, - newVariable, - /*blankLineBetween*/ - true - ); - changeTracker.replaceNode(context.file, node, localReference); - } else { - const newVariableDeclaration = factory.createVariableDeclaration( - localNameText, - /*exclamationToken*/ - void 0, - variableType, - initializer - ); - const oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); - if (oldVariableDeclaration) { - changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); - const localReference = factory.createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference); - } else if (node.parent.kind === 243 /* ExpressionStatement */ && scope === findAncestor(node, isScope)) { - const newVariableStatement = factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */) - ); - changeTracker.replaceNode(context.file, node.parent, newVariableStatement); - } else { - const newVariableStatement = factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */) - ); - const nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); - if (nodeToInsertBefore.pos === 0) { - changeTracker.insertNodeAtTopOfFile( - context.file, - newVariableStatement, - /*blankLineBetween*/ - false - ); - } else { - changeTracker.insertNodeBefore( - context.file, - nodeToInsertBefore, - newVariableStatement, - /*blankLineBetween*/ - false - ); - } - if (node.parent.kind === 243 /* ExpressionStatement */) { - changeTracker.delete(context.file, node.parent); - } else { - let localReference = factory.createIdentifier(localNameText); - if (isInJSXContent(node)) { - localReference = factory.createJsxExpression( - /*dotDotDotToken*/ - void 0, - localReference - ); - } - changeTracker.replaceNode(context.file, node, localReference); - } - } - } - const edits = changeTracker.getChanges(); - const renameFilename = node.getSourceFile().fileName; - const renameLocation = getRenameLocation( - edits, - renameFilename, - localNameText, - /*preferLastLocation*/ - true - ); - return { renameFilename, renameLocation, edits }; - function transformFunctionInitializerAndType(variableType2, initializer2) { - if (variableType2 === void 0) - return { variableType: variableType2, initializer: initializer2 }; - if (!isFunctionExpression(initializer2) && !isArrowFunction(initializer2) || !!initializer2.typeParameters) - return { variableType: variableType2, initializer: initializer2 }; - const functionType = checker.getTypeAtLocation(node); - const functionSignature = singleOrUndefined(checker.getSignaturesOfType(functionType, 0 /* Call */)); - if (!functionSignature) - return { variableType: variableType2, initializer: initializer2 }; - if (!!functionSignature.getTypeParameters()) - return { variableType: variableType2, initializer: initializer2 }; - const parameters = []; - let hasAny = false; - for (const p of initializer2.parameters) { - if (p.type) { - parameters.push(p); - } else { - 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, 1 /* NoTruncation */), - p.initializer - )); - } - } - if (hasAny) - return { variableType: variableType2, initializer: initializer2 }; - variableType2 = void 0; - if (isArrowFunction(initializer2)) { - initializer2 = factory.updateArrowFunction( - initializer2, - canHaveModifiers(node) ? getModifiers(node) : void 0, - initializer2.typeParameters, - parameters, - initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), - initializer2.equalsGreaterThanToken, - initializer2.body - ); - } else { - if (functionSignature && !!functionSignature.thisParameter) { - const firstParameter = firstOrUndefined(parameters); - if (!firstParameter || isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this") { - const thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node); - parameters.splice(0, 0, factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "this", - /*questionToken*/ - void 0, - checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */) - )); - } - } - initializer2 = factory.updateFunctionExpression( - initializer2, - canHaveModifiers(node) ? getModifiers(node) : void 0, - initializer2.asteriskToken, - initializer2.name, - initializer2.typeParameters, - parameters, - initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), - initializer2.body - ); - } - return { variableType: variableType2, initializer: initializer2 }; - } - } - function getContainingVariableDeclarationIfInList(node, scope) { - let prevNode; - while (node !== void 0 && node !== scope) { - if (isVariableDeclaration(node) && node.initializer === prevNode && isVariableDeclarationList(node.parent) && node.parent.declarations.length > 1) { - return node; - } - prevNode = node; - node = node.parent; - } - } - function getFirstDeclarationBeforePosition(type, position) { - let firstDeclaration; - const symbol = type.symbol; - if (symbol && symbol.declarations) { - for (const declaration of symbol.declarations) { - if ((firstDeclaration === void 0 || declaration.pos < firstDeclaration.pos) && declaration.pos < position) { - firstDeclaration = declaration; - } - } - } - return firstDeclaration; - } - function compareTypesByDeclarationOrder({ type: type1, declaration: declaration1 }, { type: type2, declaration: declaration2 }) { - return compareProperties(declaration1, declaration2, "pos", compareValues) || compareStringsCaseSensitive( - type1.symbol ? type1.symbol.getName() : "", - type2.symbol ? type2.symbol.getName() : "" - ) || compareValues(type1.id, type2.id); - } - function getCalledExpression(scope, range, functionNameText) { - const functionReference = factory.createIdentifier(functionNameText); - if (isClassLike(scope)) { - const lhs = range.facts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.text) : factory.createThis(); - return factory.createPropertyAccessExpression(lhs, functionReference); - } else { - return functionReference; - } - } - function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn2) { - const hasWritesOrVariableDeclarations = writes !== void 0 || exposedVariableDeclarations.length > 0; - if (isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { - return { body: factory.createBlock( - body.statements, - /*multiLine*/ - true - ), returnValueProperty: void 0 }; - } - let returnValueProperty; - let ignoreReturns = false; - const statements = factory.createNodeArray(isBlock(body) ? body.statements.slice(0) : [isStatement(body) ? body : factory.createReturnStatement(skipParentheses(body))]); - if (hasWritesOrVariableDeclarations || substitutions.size) { - const rewrittenStatements = visitNodes2(statements, visitor, isStatement).slice(); - if (hasWritesOrVariableDeclarations && !hasReturn2 && isStatement(body)) { - const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); - if (assignments.length === 1) { - rewrittenStatements.push(factory.createReturnStatement(assignments[0].name)); - } else { - rewrittenStatements.push(factory.createReturnStatement(factory.createObjectLiteralExpression(assignments))); - } - } - return { body: factory.createBlock( - rewrittenStatements, - /*multiLine*/ - true - ), returnValueProperty }; - } else { - return { body: factory.createBlock( - statements, - /*multiLine*/ - true - ), returnValueProperty: void 0 }; - } - function visitor(node) { - if (!ignoreReturns && isReturnStatement(node) && hasWritesOrVariableDeclarations) { - const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); - if (node.expression) { - if (!returnValueProperty) { - returnValueProperty = "__return"; - } - assignments.unshift(factory.createPropertyAssignment(returnValueProperty, visitNode(node.expression, visitor, isExpression))); - } - if (assignments.length === 1) { - return factory.createReturnStatement(assignments[0].name); - } else { - return factory.createReturnStatement(factory.createObjectLiteralExpression(assignments)); - } - } else { - const oldIgnoreReturns = ignoreReturns; - ignoreReturns = ignoreReturns || isFunctionLikeDeclaration(node) || isClassLike(node); - const substitution = substitutions.get(getNodeId(node).toString()); - const result = substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext); - ignoreReturns = oldIgnoreReturns; - return result; - } - } - } - function transformConstantInitializer(initializer, substitutions) { - return substitutions.size ? visitor(initializer) : initializer; - function visitor(node) { - const substitution = substitutions.get(getNodeId(node).toString()); - return substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext); - } - } - function getStatementsOrClassElements(scope) { - if (isFunctionLikeDeclaration(scope)) { - const body = scope.body; - if (isBlock(body)) { - return body.statements; - } - } else if (isModuleBlock(scope) || isSourceFile(scope)) { - return scope.statements; - } else if (isClassLike(scope)) { - return scope.members; - } else { - assertType(scope); - } - return emptyArray; - } - function getNodeToInsertFunctionBefore(minPos, scope) { - return find(getStatementsOrClassElements(scope), (child) => child.pos >= minPos && isFunctionLikeDeclaration(child) && !isConstructorDeclaration(child)); - } - function getNodeToInsertPropertyBefore(maxPos, scope) { - const members = scope.members; - Debug.assert(members.length > 0, "Found no members"); - let prevMember; - let allProperties = true; - for (const member of members) { - if (member.pos > maxPos) { - return prevMember || members[0]; - } - if (allProperties && !isPropertyDeclaration(member)) { - if (prevMember !== void 0) { - return member; - } - allProperties = false; - } - prevMember = member; - } - if (prevMember === void 0) - return Debug.fail(); - return prevMember; - } - function getNodeToInsertConstantBefore(node, scope) { - Debug.assert(!isClassLike(scope)); - let prevScope; - for (let curr = node; curr !== scope; curr = curr.parent) { - if (isScope(curr)) { - prevScope = curr; - } - } - for (let curr = (prevScope || node).parent; ; curr = curr.parent) { - if (isBlockLike(curr)) { - let prevStatement; - for (const statement of curr.statements) { - if (statement.pos > node.pos) { - break; - } - prevStatement = statement; - } - if (!prevStatement && isCaseClause(curr)) { - Debug.assert(isSwitchStatement(curr.parent.parent), "Grandparent isn't a switch statement"); - return curr.parent.parent; - } - return Debug.checkDefined(prevStatement, "prevStatement failed to get set"); - } - Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); - } - } - function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { - const variableAssignments = map(exposedVariableDeclarations, (v) => factory.createShorthandPropertyAssignment(v.symbol.name)); - const writeAssignments = map(writes, (w) => factory.createShorthandPropertyAssignment(w.symbol.name)); - return variableAssignments === void 0 ? writeAssignments : writeAssignments === void 0 ? variableAssignments : variableAssignments.concat(writeAssignments); - } - function isReadonlyArray(v) { - return isArray(v); - } - function getEnclosingTextRange(targetRange, sourceFile) { - return isReadonlyArray(targetRange.range) ? { pos: first(targetRange.range).getStart(sourceFile), end: last(targetRange.range).getEnd() } : targetRange.range; - } - function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { - const allTypeParameterUsages = /* @__PURE__ */ new Map(); - const usagesPerScope = []; - const substitutionsPerScope = []; - const functionErrorsPerScope = []; - const constantErrorsPerScope = []; - const visibleDeclarationsInExtractedRange = []; - const exposedVariableSymbolSet = /* @__PURE__ */ new Map(); - const exposedVariableDeclarations = []; - let firstExposedNonVariableDeclaration; - const expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && isExpressionStatement(targetRange.range[0]) ? targetRange.range[0].expression : void 0; - let expressionDiagnostic; - if (expression === void 0) { - const statements = targetRange.range; - const start = first(statements).getStart(); - const end = last(statements).end; - expressionDiagnostic = createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); - } else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) { - expressionDiagnostic = createDiagnosticForNode(expression, Messages.uselessConstantType); - } - for (const scope of scopes) { - usagesPerScope.push({ usages: /* @__PURE__ */ new Map(), typeParameterUsages: /* @__PURE__ */ new Map(), substitutions: /* @__PURE__ */ new Map() }); - substitutionsPerScope.push(/* @__PURE__ */ new Map()); - functionErrorsPerScope.push([]); - const constantErrors = []; - if (expressionDiagnostic) { - constantErrors.push(expressionDiagnostic); - } - if (isClassLike(scope) && isInJSFile(scope)) { - constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); - } - if (isArrowFunction(scope) && !isBlock(scope.body)) { - constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction)); - } - constantErrorsPerScope.push(constantErrors); - } - const seenUsages = /* @__PURE__ */ new Map(); - const target = isReadonlyArray(targetRange.range) ? factory.createBlock(targetRange.range) : targetRange.range; - const unmodifiedNode = isReadonlyArray(targetRange.range) ? first(targetRange.range) : targetRange.range; - const inGenericContext = isInGenericContext(unmodifiedNode); - collectUsages(target); - if (inGenericContext && !isReadonlyArray(targetRange.range) && !isJsxAttribute(targetRange.range)) { - const contextualType = checker.getContextualType(targetRange.range); - recordTypeParameterUsages(contextualType); - } - if (allTypeParameterUsages.size > 0) { - const seenTypeParameterUsages = /* @__PURE__ */ new Map(); - let i = 0; - for (let curr = unmodifiedNode; curr !== void 0 && i < scopes.length; curr = curr.parent) { - if (curr === scopes[i]) { - seenTypeParameterUsages.forEach((typeParameter, id) => { - usagesPerScope[i].typeParameterUsages.set(id, typeParameter); - }); - i++; - } - if (isDeclarationWithTypeParameters(curr)) { - for (const typeParameterDecl of getEffectiveTypeParameterDeclarations(curr)) { - const typeParameter = checker.getTypeAtLocation(typeParameterDecl); - if (allTypeParameterUsages.has(typeParameter.id.toString())) { - seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter); - } - } - } - } - Debug.assert(i === scopes.length, "Should have iterated all scopes"); - } - if (visibleDeclarationsInExtractedRange.length) { - const containingLexicalScopeOfExtraction = isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : getEnclosingBlockScopeContainer(scopes[0]); - forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); - } - for (let i = 0; i < scopes.length; i++) { - const scopeUsages = usagesPerScope[i]; - if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { - const errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; - constantErrorsPerScope[i].push(createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); - } - if (targetRange.facts & 16 /* UsesThisInFunction */ && isClassLike(scopes[i])) { - functionErrorsPerScope[i].push(createDiagnosticForNode(targetRange.thisNode, Messages.cannotExtractFunctionsContainingThisToMethod)); - } - let hasWrite = false; - let readonlyClassPropertyWrite; - usagesPerScope[i].usages.forEach((value) => { - if (value.usage === 2 /* Write */) { - hasWrite = true; - if (value.symbol.flags & 106500 /* ClassMember */ && value.symbol.valueDeclaration && hasEffectiveModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) { - readonlyClassPropertyWrite = value.symbol.valueDeclaration; - } - } - }); - Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0, "No variable declarations expected if something was extracted"); - if (hasWrite && !isReadonlyArray(targetRange.range)) { - const diag2 = createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression); - functionErrorsPerScope[i].push(diag2); - constantErrorsPerScope[i].push(diag2); - } else if (readonlyClassPropertyWrite && i > 0) { - const diag2 = createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor); - functionErrorsPerScope[i].push(diag2); - constantErrorsPerScope[i].push(diag2); - } else if (firstExposedNonVariableDeclaration) { - const diag2 = createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity); - functionErrorsPerScope[i].push(diag2); - constantErrorsPerScope[i].push(diag2); - } - } - return { target, usagesPerScope, functionErrorsPerScope, constantErrorsPerScope, exposedVariableDeclarations }; - function isInGenericContext(node) { - return !!findAncestor(node, (n) => isDeclarationWithTypeParameters(n) && getEffectiveTypeParameterDeclarations(n).length !== 0); - } - function recordTypeParameterUsages(type) { - const symbolWalker = checker.getSymbolWalker(() => (cancellationToken.throwIfCancellationRequested(), true)); - const { visitedTypes } = symbolWalker.walkType(type); - for (const visitedType of visitedTypes) { - if (visitedType.isTypeParameter()) { - allTypeParameterUsages.set(visitedType.id.toString(), visitedType); - } - } - } - function collectUsages(node, valueUsage = 1 /* Read */) { - if (inGenericContext) { - const type = checker.getTypeAtLocation(node); - recordTypeParameterUsages(type); - } - if (isDeclaration(node) && node.symbol) { - visibleDeclarationsInExtractedRange.push(node); - } - if (isAssignmentExpression(node)) { - collectUsages(node.left, 2 /* Write */); - collectUsages(node.right); - } else if (isUnaryExpressionWithWrite(node)) { - collectUsages(node.operand, 2 /* Write */); - } else if (isPropertyAccessExpression(node) || isElementAccessExpression(node)) { - forEachChild(node, collectUsages); - } else if (isIdentifier(node)) { - if (!node.parent) { - return; - } - if (isQualifiedName(node.parent) && node !== node.parent.left) { - return; - } - if (isPropertyAccessExpression(node.parent) && node !== node.parent.expression) { - return; - } - recordUsage( - node, - valueUsage, - /*isTypeNode*/ - isPartOfTypeNode(node) - ); - } else { - forEachChild(node, collectUsages); - } - } - function recordUsage(n, usage, isTypeNode2) { - const symbolId = recordUsagebySymbol(n, usage, isTypeNode2); - if (symbolId) { - for (let i = 0; i < scopes.length; i++) { - const substitution = substitutionsPerScope[i].get(symbolId); - if (substitution) { - usagesPerScope[i].substitutions.set(getNodeId(n).toString(), substitution); - } - } - } - } - function recordUsagebySymbol(identifier, usage, isTypeName) { - const symbol = getSymbolReferencedByIdentifier(identifier); - if (!symbol) { - return void 0; - } - const symbolId = getSymbolId(symbol).toString(); - const lastUsage = seenUsages.get(symbolId); - if (lastUsage && lastUsage >= usage) { - return symbolId; - } - seenUsages.set(symbolId, usage); - if (lastUsage) { - for (const perScope of usagesPerScope) { - const prevEntry = perScope.usages.get(identifier.text); - if (prevEntry) { - perScope.usages.set(identifier.text, { usage, symbol, node: identifier }); - } - } - return symbolId; - } - const decls = symbol.getDeclarations(); - const declInFile = decls && find(decls, (d) => d.getSourceFile() === sourceFile); - if (!declInFile) { - return void 0; - } - if (rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) { - return void 0; - } - if (targetRange.facts & 2 /* IsGenerator */ && usage === 2 /* Write */) { - const diag2 = createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators); - for (const errors of functionErrorsPerScope) { - errors.push(diag2); - } - for (const errors of constantErrorsPerScope) { - errors.push(diag2); - } - } - for (let i = 0; i < scopes.length; i++) { - const scope = scopes[i]; - const resolvedSymbol = checker.resolveName( - symbol.name, - scope, - symbol.flags, - /*excludeGlobals*/ - false - ); - if (resolvedSymbol === symbol) { - continue; - } - if (!substitutionsPerScope[i].has(symbolId)) { - const substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName); - if (substitution) { - substitutionsPerScope[i].set(symbolId, substitution); - } else if (isTypeName) { - if (!(symbol.flags & 262144 /* TypeParameter */)) { - const diag2 = createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope); - functionErrorsPerScope[i].push(diag2); - constantErrorsPerScope[i].push(diag2); - } - } else { - usagesPerScope[i].usages.set(identifier.text, { usage, symbol, node: identifier }); - } - } - } - return symbolId; - } - function checkForUsedDeclarations(node) { - if (node === targetRange.range || isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0) { - return; - } - const sym = isIdentifier(node) ? getSymbolReferencedByIdentifier(node) : checker.getSymbolAtLocation(node); - if (sym) { - const decl = find(visibleDeclarationsInExtractedRange, (d) => d.symbol === sym); - if (decl) { - if (isVariableDeclaration(decl)) { - const idString = decl.symbol.id.toString(); - if (!exposedVariableSymbolSet.has(idString)) { - exposedVariableDeclarations.push(decl); - exposedVariableSymbolSet.set(idString, true); - } - } else { - firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; - } - } - } - forEachChild(node, checkForUsedDeclarations); - } - function getSymbolReferencedByIdentifier(identifier) { - return identifier.parent && isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier ? checker.getShorthandAssignmentValueSymbol(identifier.parent) : checker.getSymbolAtLocation(identifier); - } - function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode2) { - if (!symbol) { - return void 0; - } - const decls = symbol.getDeclarations(); - if (decls && decls.some((d) => d.parent === scopeDecl)) { - return factory.createIdentifier(symbol.name); - } - const prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode2); - if (prefix === void 0) { - return void 0; - } - return isTypeNode2 ? factory.createQualifiedName(prefix, factory.createIdentifier(symbol.name)) : factory.createPropertyAccessExpression(prefix, symbol.name); - } - } - function getExtractableParent(node) { - return findAncestor(node, (node2) => node2.parent && isExtractableExpression(node2) && !isBinaryExpression(node2.parent)); - } - function isExtractableExpression(node) { - const { parent: parent2 } = node; - switch (parent2.kind) { - case 305 /* EnumMember */: - return false; - } - switch (node.kind) { - case 11 /* StringLiteral */: - return parent2.kind !== 271 /* ImportDeclaration */ && parent2.kind !== 275 /* ImportSpecifier */; - case 229 /* SpreadElement */: - case 205 /* ObjectBindingPattern */: - case 207 /* BindingElement */: - return false; - case 80 /* Identifier */: - return parent2.kind !== 207 /* BindingElement */ && parent2.kind !== 275 /* ImportSpecifier */ && parent2.kind !== 280 /* ExportSpecifier */; - } - return true; - } - function isBlockLike(node) { - switch (node.kind) { - case 240 /* Block */: - case 311 /* SourceFile */: - case 267 /* ModuleBlock */: - case 295 /* CaseClause */: - return true; - default: - return false; - } - } - function isInJSXContent(node) { - return isStringLiteralJsxAttribute(node) || (isJsxElement(node) || isJsxSelfClosingElement(node) || isJsxFragment(node)) && (isJsxElement(node.parent) || isJsxFragment(node.parent)); - } - function isStringLiteralJsxAttribute(node) { - return isStringLiteral(node) && node.parent && isJsxAttribute(node.parent); - } - var refactorName11, extractConstantAction, extractFunctionAction, Messages, RangeFacts; - var init_extractSymbol = __esm({ - "src/services/refactors/extractSymbol.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName11 = "Extract Symbol"; - extractConstantAction = { - name: "Extract Constant", - description: getLocaleSpecificMessage(Diagnostics.Extract_constant), - kind: "refactor.extract.constant" - }; - extractFunctionAction = { - name: "Extract Function", - description: getLocaleSpecificMessage(Diagnostics.Extract_function), - kind: "refactor.extract.function" - }; - registerRefactor(refactorName11, { - kinds: [ - extractConstantAction.kind, - extractFunctionAction.kind - ], - getEditsForAction: getRefactorEditsToExtractSymbol, - getAvailableActions: getRefactorActionsToExtractSymbol - }); - ((Messages2) => { - function createMessage(message) { - return { message, code: 0, category: 3 /* Message */, key: message }; - } - Messages2.cannotExtractRange = createMessage("Cannot extract range."); - Messages2.cannotExtractImport = createMessage("Cannot extract import statement."); - Messages2.cannotExtractSuper = createMessage("Cannot extract super call."); - Messages2.cannotExtractJSDoc = createMessage("Cannot extract JSDoc."); - Messages2.cannotExtractEmpty = createMessage("Cannot extract empty range."); - Messages2.expressionExpected = createMessage("expression expected."); - Messages2.uselessConstantType = createMessage("No reason to extract constant of type."); - Messages2.statementOrExpressionExpected = createMessage("Statement or expression expected."); - Messages2.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); - Messages2.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); - Messages2.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); - Messages2.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); - Messages2.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); - Messages2.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); - Messages2.cannotExtractIdentifier = createMessage("Select more than a single identifier."); - Messages2.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); - Messages2.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); - Messages2.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); - Messages2.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); - Messages2.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); - Messages2.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); - Messages2.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); - Messages2.cannotExtractFunctionsContainingThisToMethod = createMessage("Cannot extract functions containing this to method"); - })(Messages || (Messages = {})); - RangeFacts = /* @__PURE__ */ ((RangeFacts2) => { - RangeFacts2[RangeFacts2["None"] = 0] = "None"; - RangeFacts2[RangeFacts2["HasReturn"] = 1] = "HasReturn"; - RangeFacts2[RangeFacts2["IsGenerator"] = 2] = "IsGenerator"; - RangeFacts2[RangeFacts2["IsAsyncFunction"] = 4] = "IsAsyncFunction"; - RangeFacts2[RangeFacts2["UsesThis"] = 8] = "UsesThis"; - RangeFacts2[RangeFacts2["UsesThisInFunction"] = 16] = "UsesThisInFunction"; - RangeFacts2[RangeFacts2["InStaticRegion"] = 32] = "InStaticRegion"; - return RangeFacts2; - })(RangeFacts || {}); - } - }); - - // src/services/_namespaces/ts.refactor.extractSymbol.ts - var ts_refactor_extractSymbol_exports = {}; - __export(ts_refactor_extractSymbol_exports, { - Messages: () => Messages, - RangeFacts: () => RangeFacts, - getRangeToExtract: () => getRangeToExtract2, - getRefactorActionsToExtractSymbol: () => getRefactorActionsToExtractSymbol, - getRefactorEditsToExtractSymbol: () => getRefactorEditsToExtractSymbol - }); - var init_ts_refactor_extractSymbol = __esm({ - "src/services/_namespaces/ts.refactor.extractSymbol.ts"() { - "use strict"; - init_extractSymbol(); - } - }); - - // src/services/refactors/generateGetAccessorAndSetAccessor.ts - var actionName, actionDescription, generateGetSetAction; - var init_generateGetAccessorAndSetAccessor = __esm({ - "src/services/refactors/generateGetAccessorAndSetAccessor.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - actionName = "Generate 'get' and 'set' accessors"; - actionDescription = Diagnostics.Generate_get_and_set_accessors.message; - generateGetSetAction = { - name: actionName, - description: actionDescription, - kind: "refactor.rewrite.property.generateAccessors" - }; - registerRefactor(actionName, { - kinds: [generateGetSetAction.kind], - getEditsForAction: function getRefactorActionsToGenerateGetAndSetAccessors(context, actionName2) { - if (!context.endPosition) - return void 0; - const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_codefix_exports.generateAccessorFromProperty(context.file, context.program, context.startPosition, context.endPosition, context, actionName2); - if (!edits) - return void 0; - const renameFilename = context.file.fileName; - const nameNeedRename = info.renameAccessor ? info.accessorName : info.fieldName; - const renameLocationOffset = isIdentifier(nameNeedRename) ? 0 : -1; - const renameLocation = renameLocationOffset + getRenameLocation( - edits, - renameFilename, - nameNeedRename.text, - /*preferLastLocation*/ - isParameter(info.declaration) - ); - return { renameFilename, renameLocation, edits }; - }, - getAvailableActions(context) { - if (!context.endPosition) - return emptyArray; - const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition, context.triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - return [{ - name: actionName, - description: actionDescription, - actions: [generateGetSetAction] - }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: actionName, - description: actionDescription, - actions: [{ ...generateGetSetAction, notApplicableReason: info.error }] - }]; - } - return emptyArray; - } - }); - } - }); - - // src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts - var ts_refactor_generateGetAccessorAndSetAccessor_exports = {}; - var init_ts_refactor_generateGetAccessorAndSetAccessor = __esm({ - "src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts"() { - "use strict"; - init_generateGetAccessorAndSetAccessor(); - } - }); - - // src/services/refactors/inferFunctionReturnType.ts - function getRefactorEditsToInferReturnType(context) { - const info = getInfo21(context); - if (info && !isRefactorErrorInfo(info)) { - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange39(context.file, t, info.declaration, info.returnTypeNode)); - return { renameFilename: void 0, renameLocation: void 0, edits }; - } - return void 0; - } - function getRefactorActionsToInferReturnType(context) { - const info = getInfo21(context); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - return [{ - name: refactorName12, - description: refactorDescription6, - actions: [inferReturnTypeAction] - }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorName12, - description: refactorDescription6, - actions: [{ ...inferReturnTypeAction, notApplicableReason: info.error }] - }]; - } - return emptyArray; - } - function doChange39(sourceFile, changes, declaration, typeNode) { - const closeParen = findChildOfKind(declaration, 22 /* CloseParenToken */, sourceFile); - const needParens = isArrowFunction(declaration) && closeParen === void 0; - const endNode2 = needParens ? first(declaration.parameters) : closeParen; - if (endNode2) { - if (needParens) { - changes.insertNodeBefore(sourceFile, endNode2, factory.createToken(21 /* OpenParenToken */)); - changes.insertNodeAfter(sourceFile, endNode2, factory.createToken(22 /* CloseParenToken */)); - } - changes.insertNodeAt(sourceFile, endNode2.end, typeNode, { prefix: ": " }); - } - } - function getInfo21(context) { - if (isInJSFile(context.file) || !refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind)) - return; - const token = getTokenAtPosition(context.file, context.startPosition); - const declaration = findAncestor(token, (n) => isBlock(n) || n.parent && isArrowFunction(n.parent) && (n.kind === 39 /* EqualsGreaterThanToken */ || n.parent.body === n) ? "quit" : isConvertibleDeclaration(n)); - if (!declaration || !declaration.body || declaration.type) { - return { error: getLocaleSpecificMessage(Diagnostics.Return_type_must_be_inferred_from_a_function) }; - } - const typeChecker = context.program.getTypeChecker(); - const returnType = tryGetReturnType(typeChecker, declaration); - if (!returnType) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_determine_function_return_type) }; - } - const returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */); - if (returnTypeNode) { - return { declaration, returnTypeNode }; - } - } - function isConvertibleDeclaration(node) { - switch (node.kind) { - case 261 /* FunctionDeclaration */: - case 217 /* FunctionExpression */: - case 218 /* ArrowFunction */: - case 173 /* MethodDeclaration */: - return true; - default: - return false; - } - } - function tryGetReturnType(typeChecker, node) { - if (typeChecker.isImplementationOfOverload(node)) { - const signatures = typeChecker.getTypeAtLocation(node).getCallSignatures(); - if (signatures.length > 1) { - return typeChecker.getUnionType(mapDefined(signatures, (s) => s.getReturnType())); - } - } - const signature = typeChecker.getSignatureFromDeclaration(node); - if (signature) { - return typeChecker.getReturnTypeOfSignature(signature); - } - } - var refactorName12, refactorDescription6, inferReturnTypeAction; - var init_inferFunctionReturnType = __esm({ - "src/services/refactors/inferFunctionReturnType.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName12 = "Infer function return type"; - refactorDescription6 = Diagnostics.Infer_function_return_type.message; - inferReturnTypeAction = { - name: refactorName12, - description: refactorDescription6, - kind: "refactor.rewrite.function.returnType" - }; - registerRefactor(refactorName12, { - kinds: [inferReturnTypeAction.kind], - getEditsForAction: getRefactorEditsToInferReturnType, - getAvailableActions: getRefactorActionsToInferReturnType - }); - } - }); - - // src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts - var ts_refactor_inferFunctionReturnType_exports = {}; - var init_ts_refactor_inferFunctionReturnType = __esm({ - "src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts"() { - "use strict"; - init_inferFunctionReturnType(); - } - }); - - // src/services/_namespaces/ts.refactor.ts - var ts_refactor_exports = {}; - __export(ts_refactor_exports, { - addOrRemoveBracesToArrowFunction: () => ts_refactor_addOrRemoveBracesToArrowFunction_exports, - convertArrowFunctionOrFunctionExpression: () => ts_refactor_convertArrowFunctionOrFunctionExpression_exports, - convertParamsToDestructuredObject: () => ts_refactor_convertParamsToDestructuredObject_exports, - convertStringOrTemplateLiteral: () => ts_refactor_convertStringOrTemplateLiteral_exports, - convertToOptionalChainExpression: () => ts_refactor_convertToOptionalChainExpression_exports, - doChangeNamedToNamespaceOrDefault: () => doChangeNamedToNamespaceOrDefault, - extractSymbol: () => ts_refactor_extractSymbol_exports, - generateGetAccessorAndSetAccessor: () => ts_refactor_generateGetAccessorAndSetAccessor_exports, - getApplicableRefactors: () => getApplicableRefactors, - getEditsForRefactor: () => getEditsForRefactor, - inferFunctionReturnType: () => ts_refactor_inferFunctionReturnType_exports, - isRefactorErrorInfo: () => isRefactorErrorInfo, - refactorKindBeginsWith: () => refactorKindBeginsWith, - registerRefactor: () => registerRefactor - }); - var init_ts_refactor = __esm({ - "src/services/_namespaces/ts.refactor.ts"() { - "use strict"; - init_refactorProvider(); - init_convertExport(); - init_convertImport(); - init_extractType(); - init_helpers2(); - init_moveToNewFile(); - init_ts_refactor_addOrRemoveBracesToArrowFunction(); - init_ts_refactor_convertArrowFunctionOrFunctionExpression(); - init_ts_refactor_convertParamsToDestructuredObject(); - init_ts_refactor_convertStringOrTemplateLiteral(); - init_ts_refactor_convertToOptionalChainExpression(); - init_ts_refactor_extractSymbol(); - init_ts_refactor_generateGetAccessorAndSetAccessor(); - init_ts_refactor_inferFunctionReturnType(); - } - }); - // src/services/rename.ts function getRenameInfo(program, sourceFile, position, preferences) { const node = getAdjustedRenameLocation(getTouchingPropertyName(sourceFile, position)); @@ -163825,7 +164629,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} displayParts.push(spacePart()); displayParts.push(operatorPart(64 /* EqualsToken */)); displayParts.push(spacePart()); - addRange(displayParts, typeToDisplayParts(typeChecker, isConstTypeReference(location.parent) ? typeChecker.getTypeAtLocation(location.parent) : typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); + addRange(displayParts, typeToDisplayParts(typeChecker, location.parent && isConstTypeReference(location.parent) ? typeChecker.getTypeAtLocation(location.parent) : typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { prefixNextMeaning(); @@ -163901,12 +164705,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } if (symbol.flags & 2097152 /* Alias */) { prefixNextMeaning(); - if (!hasAddedSymbolInfo) { + if (!hasAddedSymbolInfo || documentation.length === 0 && tags.length === 0) { const resolvedSymbol = typeChecker.getAliasedSymbol(symbol); if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { const resolvedNode = resolvedSymbol.declarations[0]; const declarationName = getNameOfDeclaration(resolvedNode); - if (declarationName) { + if (declarationName && !hasAddedSymbolInfo) { const isExternalModuleDeclaration = isModuleWithStringLiteralName(resolvedNode) && hasSyntacticModifier(resolvedNode, 2 /* Ambient */); const shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind( @@ -164446,16 +165250,6 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getMembersOrProperties(node) { return isObjectLiteralExpression(node) ? node.properties : node.members; } - function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { - return changesToText.newFileChangesWorker( - /*oldFile*/ - void 0, - scriptKind, - statements, - newLineCharacter, - formatContext - ); - } function applyChanges(text, changes) { for (let i = changes.length - 1; i >= 0; i--) { const { span, newText } = changes[i]; @@ -164813,7 +165607,6 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} this.newLineCharacter = newLineCharacter; this.formatContext = formatContext; this.changes = []; - this.newFiles = []; this.classesWithNodesInsertedAtStart = /* @__PURE__ */ new Map(); // Set implemented as Map this.deletedNodes = []; @@ -164929,6 +165722,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} this.insertNodeAt(sourceFile, pos, insert, options); } } + insertStatementsInNewFile(fileName, statements, oldFile) { + if (!this.newFileChanges) { + this.newFileChanges = createMultiMap(); + } + this.newFileChanges.add(fileName, { oldFile, statements }); + } insertFirstParameter(sourceFile, parameters, newParam) { const p0 = firstOrUndefined(parameters); if (p0) { @@ -165324,13 +166123,15 @@ ${options.prefix}` : "\n" : options.prefix this.finishDeleteDeclarations(); this.finishClassesWithNodesInsertedAtStart(); const changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); - for (const { oldFile, fileName, statements } of this.newFiles) { - changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); + if (this.newFileChanges) { + this.newFileChanges.forEach((insertions, fileName) => { + changes.push(changesToText.newFileChanges(fileName, insertions, this.newLineCharacter, this.formatContext)); + }); } return changes; } createNewFile(oldFile, fileName, statements) { - this.newFiles.push({ oldFile, fileName, statements }); + this.insertStatementsInNewFile(fileName, statements, oldFile); } }; ((changesToText2) => { @@ -165343,8 +166144,9 @@ ${options.prefix}` : "\n" : options.prefix } const textChanges2 = mapDefined(normalized, (c) => { const span = createTextSpanFromRange(c.range); - const newText = computeNewText(c, sourceFile, newLineCharacter, formatContext, validate); - if (span.length === newText.length && stringContainsAt(sourceFile.text, newText, span.start)) { + const targetSourceFile = c.kind === 1 /* ReplaceWithSingleNode */ ? getSourceFileOfNode(getOriginalNode(c.node)) ?? c.sourceFile : c.kind === 2 /* ReplaceWithMultipleNodes */ ? getSourceFileOfNode(getOriginalNode(c.nodes[0])) ?? c.sourceFile : c.sourceFile; + const newText = computeNewText(c, targetSourceFile, sourceFile, newLineCharacter, formatContext, validate); + if (span.length === newText.length && stringContainsAt(targetSourceFile.text, newText, span.start)) { return void 0; } return createTextChange(span, newText); @@ -165353,13 +166155,13 @@ ${options.prefix}` : "\n" : options.prefix }); } changesToText2.getTextChangesFromChanges = getTextChangesFromChanges; - function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { - const text = newFileChangesWorker(oldFile, getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); + function newFileChanges(fileName, insertions, newLineCharacter, formatContext) { + const text = newFileChangesWorker(getScriptKindFromFileName(fileName), insertions, newLineCharacter, formatContext); return { fileName, textChanges: [createTextChange(createTextSpan(0, 0), text)], isNewFile: true }; } changesToText2.newFileChanges = newFileChanges; - function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { - const nonFormattedText = statements.map((s) => s === 4 /* NewLineTrivia */ ? "" : getNonformattedText(s, oldFile, newLineCharacter).text).join(newLineCharacter); + function newFileChangesWorker(scriptKind, insertions, newLineCharacter, formatContext) { + const nonFormattedText = flatMap(insertions, (insertion) => insertion.statements.map((s) => s === 4 /* NewLineTrivia */ ? "" : getNonformattedText(s, insertion.oldFile, newLineCharacter).text)).join(newLineCharacter); const sourceFile = createSourceFile( "any file name", nonFormattedText, @@ -165372,7 +166174,7 @@ ${options.prefix}` : "\n" : options.prefix return applyChanges(nonFormattedText, changes) + newLineCharacter; } changesToText2.newFileChangesWorker = newFileChangesWorker; - function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { + function computeNewText(change, targetSourceFile, sourceFile, newLineCharacter, formatContext, validate) { var _a; if (change.kind === 0 /* Remove */) { return ""; @@ -165381,17 +166183,17 @@ ${options.prefix}` : "\n" : options.prefix return change.text; } const { options = {}, range: { pos } } = change; - const format = (n) => getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); + const format = (n) => getFormattedTextOfNode(n, targetSourceFile, sourceFile, pos, options, newLineCharacter, formatContext, validate); const text = change.kind === 2 /* ReplaceWithMultipleNodes */ ? change.nodes.map((n) => removeSuffix(format(n), newLineCharacter)).join(((_a = change.options) == null ? void 0 : _a.joiner) || newLineCharacter) : format(change.node); - const noIndent = options.indentation !== void 0 || getLineStartPositionForPosition(pos, sourceFile) === pos ? text : text.replace(/^\s+/, ""); + const noIndent = options.indentation !== void 0 || getLineStartPositionForPosition(pos, targetSourceFile) === pos ? text : text.replace(/^\s+/, ""); return (options.prefix || "") + noIndent + (!options.suffix || endsWith(noIndent, options.suffix) ? "" : options.suffix); } - function getFormattedTextOfNode(nodeIn, sourceFile, pos, { indentation, prefix, delta }, newLineCharacter, formatContext, validate) { - const { node, text } = getNonformattedText(nodeIn, sourceFile, newLineCharacter); + function getFormattedTextOfNode(nodeIn, targetSourceFile, sourceFile, pos, { indentation, prefix, delta }, newLineCharacter, formatContext, validate) { + const { node, text } = getNonformattedText(nodeIn, targetSourceFile, newLineCharacter); if (validate) validate(node, text); - const formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile); - const initialIndentation = indentation !== void 0 ? indentation : ts_formatting_exports.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || getLineStartPositionForPosition(pos, sourceFile) === pos); + const formatOptions = getFormatCodeSettingsForWriting(formatContext, targetSourceFile); + const initialIndentation = indentation !== void 0 ? indentation : ts_formatting_exports.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || getLineStartPositionForPosition(pos, targetSourceFile) === pos); if (delta === void 0) { delta = ts_formatting_exports.SmartIndenter.shouldIndentChildNode(formatOptions, nodeIn) ? formatOptions.indentSize || 0 : 0; } @@ -165401,7 +166203,7 @@ ${options.prefix}` : "\n" : options.prefix return getLineAndCharacterOfPosition(this, pos2); } }; - const changes = ts_formatting_exports.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, { ...formatContext, options: formatOptions }); + const changes = ts_formatting_exports.formatNodeGivenIndentation(node, file, targetSourceFile.languageVariant, initialIndentation, delta, { ...formatContext, options: formatOptions }); return applyChanges(text, changes); } function getNonformattedText(node, sourceFile, newLineCharacter) { @@ -165562,7 +166364,6 @@ ${options.prefix}` : "\n" : options.prefix assignPositionsToNode: () => assignPositionsToNode, createWriter: () => createWriter, deleteNode: () => deleteNode, - getNewFileText: () => getNewFileText, isThisTypeAnnotatable: () => isThisTypeAnnotatable, isValidLocationToAddComment: () => isValidLocationToAddComment }); @@ -168487,9 +169288,9 @@ ${options.prefix}` : "\n" : options.prefix init_ts5(); init_deprecate(); addObjectAllocatorPatcher((objectAllocator2) => { - const Identifier73 = objectAllocator2.getIdentifierConstructor(); - if (!hasProperty(Identifier73.prototype, "originalKeywordKind")) { - Object.defineProperty(Identifier73.prototype, "originalKeywordKind", { + const Identifier74 = objectAllocator2.getIdentifierConstructor(); + if (!hasProperty(Identifier74.prototype, "originalKeywordKind")) { + Object.defineProperty(Identifier74.prototype, "originalKeywordKind", { get: deprecate(function() { return identifierToKeywordKind(this); }, { @@ -168501,8 +169302,8 @@ ${options.prefix}` : "\n" : options.prefix }) }); } - if (!hasProperty(Identifier73.prototype, "isInJSDocNamespace")) { - Object.defineProperty(Identifier73.prototype, "isInJSDocNamespace", { + if (!hasProperty(Identifier74.prototype, "isInJSDocNamespace")) { + Object.defineProperty(Identifier74.prototype, "isInJSDocNamespace", { get: deprecate(function() { return this.flags & 2048 /* IdentifierIsInJSDocNamespace */ ? true : void 0; }, { @@ -168571,19 +169372,6 @@ ${options.prefix}` : "\n" : options.prefix } return { command, remaining: remaining - toSlice }; } - function endsWith2(str, suffix, caseSensitive) { - const expectedPos = str.length - suffix.length; - return expectedPos >= 0 && (str.indexOf(suffix, expectedPos) === expectedPos || !caseSensitive && compareStringsCaseInsensitive(str.substr(expectedPos), suffix) === 0 /* EqualTo */); - } - function isPackageOrBowerJson(fileName, caseSensitive) { - return endsWith2(fileName, "/package.json", caseSensitive) || endsWith2(fileName, "/bower.json", caseSensitive); - } - function sameFiles(a, b, caseSensitive) { - return a === b || !caseSensitive && compareStringsCaseInsensitive(a, b) === 0 /* EqualTo */; - } - function getDetailWatchInfo(projectName, watchers) { - return `Project: ${projectName} watcher already invoked: ${watchers == null ? void 0 : watchers.isInvoked}`; - } function typingsName(packageName) { return `@types/${packageName}@ts${versionMajorMinor}`; } @@ -168614,13 +169402,10 @@ ${options.prefix}` : "\n" : options.prefix this.installRunCount = 1; this.inFlightRequestCount = 0; this.latestDistTag = "latest"; - this.toCanonicalFileName = createGetCanonicalFileName(installTypingHost.useCaseSensitiveFileNames); - this.globalCachePackageJsonPath = combinePaths(globalCachePath, "package.json"); const isLoggingEnabled = this.log.isEnabled(); if (isLoggingEnabled) { this.log.writeLine(`Global cache location '${globalCachePath}', safe file path '${safeListPath}', types map path ${typesMapLocation}`); } - this.watchFactory = getWatchFactory(this.installTypingHost, isLoggingEnabled ? 2 /* Verbose */ : 0 /* None */, (s) => this.log.writeLine(s), getDetailWatchInfo); this.processCacheLocation(this.globalCachePath); } closeProject(req) { @@ -168637,8 +169422,8 @@ ${options.prefix}` : "\n" : options.prefix } return; } - clearMap(watchers, closeFileWatcher); this.projectWatchers.delete(projectName); + this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files: [] }); if (this.log.isEnabled()) { this.log.writeLine(`Closing file watchers for project '${projectName}' - done.`); } @@ -168671,7 +169456,7 @@ ${options.prefix}` : "\n" : options.prefix if (this.log.isEnabled()) { this.log.writeLine(`Finished typings discovery: ${JSON.stringify(discoverTypingsResult)}`); } - this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch, req.projectRootPath, req.watchOptions); + this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch); if (discoverTypingsResult.newTypingNames.length) { this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames); } else { @@ -168872,75 +169657,19 @@ ${options.prefix}` : "\n" : options.prefix host.createDirectory(directory); } } - watchFiles(projectName, files, projectRootPath, options) { + watchFiles(projectName, files) { if (!files.length) { this.closeWatchers(projectName); return; } - let watchers = this.projectWatchers.get(projectName); - const toRemove = /* @__PURE__ */ new Map(); - if (!watchers) { - watchers = /* @__PURE__ */ new Map(); - this.projectWatchers.set(projectName, watchers); + const existing = this.projectWatchers.get(projectName); + const newSet = new Set(files); + if (!existing || forEachKey(newSet, (s) => !existing.has(s)) || forEachKey(existing, (s) => !newSet.has(s))) { + this.projectWatchers.set(projectName, newSet); + this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files }); } else { - copyEntries(watchers, toRemove); + this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files: void 0 }); } - watchers.isInvoked = false; - const isLoggingEnabled = this.log.isEnabled(); - const createProjectWatcher = (path, projectWatcherType) => { - const canonicalPath = this.toCanonicalFileName(path); - toRemove.delete(canonicalPath); - if (watchers.has(canonicalPath)) { - return; - } - if (isLoggingEnabled) { - this.log.writeLine(`${projectWatcherType}:: Added:: WatchInfo: ${path}`); - } - const watcher = projectWatcherType === "FileWatcher" /* FileWatcher */ ? this.watchFactory.watchFile(path, () => { - if (!watchers.isInvoked) { - watchers.isInvoked = true; - this.sendResponse({ projectName, kind: ActionInvalidate }); - } - }, 2e3 /* High */, options, projectName, watchers) : this.watchFactory.watchDirectory(path, (f) => { - if (watchers.isInvoked || !fileExtensionIs(f, ".json" /* Json */)) { - return; - } - if (isPackageOrBowerJson(f, this.installTypingHost.useCaseSensitiveFileNames) && !sameFiles(f, this.globalCachePackageJsonPath, this.installTypingHost.useCaseSensitiveFileNames)) { - watchers.isInvoked = true; - this.sendResponse({ projectName, kind: ActionInvalidate }); - } - }, 1 /* Recursive */, options, projectName, watchers); - watchers.set(canonicalPath, isLoggingEnabled ? { - close: () => { - this.log.writeLine(`${projectWatcherType}:: Closed:: WatchInfo: ${path}`); - watcher.close(); - } - } : watcher); - }; - for (const file of files) { - if (file.endsWith("/package.json") || file.endsWith("/bower.json")) { - createProjectWatcher(file, "FileWatcher" /* FileWatcher */); - continue; - } - if (containsPath(projectRootPath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) { - const subDirectory = file.indexOf(directorySeparator, projectRootPath.length + 1); - if (subDirectory !== -1) { - createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */); - } else { - createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); - } - continue; - } - if (containsPath(this.globalCachePath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) { - createProjectWatcher(this.globalCachePath, "DirectoryWatcher" /* DirectoryWatcher */); - continue; - } - createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); - } - toRemove.forEach((watch, path) => { - watch.close(); - watchers.delete(path); - }); } createSetTypings(request, typings) { return { @@ -169013,7 +169742,6 @@ ${options.prefix}` : "\n" : options.prefix true ).concat(project.getExcludedFiles()), compilerOptions: project.getCompilationSettings(), - watchOptions: project.projectService.getWatchOptions(project), typeAcquisition, unresolvedImports, projectRootPath: project.getCurrentDirectory(), @@ -169293,6 +170021,7 @@ ${options.prefix}` : "\n" : options.prefix CommandTypes2["GetSupportedCodeFixes"] = "getSupportedCodeFixes"; CommandTypes2["GetApplicableRefactors"] = "getApplicableRefactors"; CommandTypes2["GetEditsForRefactor"] = "getEditsForRefactor"; + CommandTypes2["GetMoveToRefactoringFileSuggestions"] = "getMoveToRefactoringFileSuggestions"; CommandTypes2["GetEditsForRefactorFull"] = "getEditsForRefactor-full"; CommandTypes2["OrganizeImports"] = "organizeImports"; CommandTypes2["OrganizeImportsFull"] = "organizeImports-full"; @@ -170290,34 +171019,49 @@ ${options.prefix}` : "\n" : options.prefix updateProjectIfDirty(this); return hasOneOrMoreJsAndNoTsFiles(this); } - static resolveModule(moduleName, initialDir, host, log, logErrors) { - const resolvedPath = normalizeSlashes(host.resolvePath(combinePaths(initialDir, "node_modules"))); - log(`Loading ${moduleName} from ${initialDir} (resolved to ${resolvedPath})`); - const result = host.require(resolvedPath, moduleName); - if (result.error) { - const err = result.error.stack || result.error.message || JSON.stringify(result.error); - (logErrors || log)(`Failed to load module '${moduleName}' from ${resolvedPath}: ${err}`); - return void 0; - } - return result.module; + static resolveModule(moduleName, initialDir, host, log) { + return Project3.importServicePluginSync({ name: moduleName }, [initialDir], host, log).resolvedModule; } /** @internal */ - static async importServicePluginAsync(moduleName, initialDir, host, log, logErrors) { - Debug.assertIsDefined(host.importPlugin); - const resolvedPath = combinePaths(initialDir, "node_modules"); - log(`Dynamically importing ${moduleName} from ${initialDir} (resolved to ${resolvedPath})`); - let result; - try { - result = await host.importPlugin(resolvedPath, moduleName); - } catch (e) { - result = { module: void 0, error: e }; - } - if (result.error) { + static importServicePluginSync(pluginConfigEntry, searchPaths, host, log) { + Debug.assertIsDefined(host.require); + let errorLogs; + let resolvedModule; + for (const initialDir of searchPaths) { + const resolvedPath = normalizeSlashes(host.resolvePath(combinePaths(initialDir, "node_modules"))); + log(`Loading ${pluginConfigEntry.name} from ${initialDir} (resolved to ${resolvedPath})`); + const result = host.require(resolvedPath, pluginConfigEntry.name); + if (!result.error) { + resolvedModule = result.module; + break; + } const err = result.error.stack || result.error.message || JSON.stringify(result.error); - (logErrors || log)(`Failed to dynamically import module '${moduleName}' from ${resolvedPath}: ${err}`); - return void 0; + (errorLogs ?? (errorLogs = [])).push(`Failed to load module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`); } - return result.module; + return { pluginConfigEntry, resolvedModule, errorLogs }; + } + /** @internal */ + static async importServicePluginAsync(pluginConfigEntry, searchPaths, host, log) { + Debug.assertIsDefined(host.importPlugin); + let errorLogs; + let resolvedModule; + for (const initialDir of searchPaths) { + const resolvedPath = combinePaths(initialDir, "node_modules"); + log(`Dynamically importing ${pluginConfigEntry.name} from ${initialDir} (resolved to ${resolvedPath})`); + let result; + try { + result = await host.importPlugin(resolvedPath, pluginConfigEntry.name); + } catch (e) { + result = { module: void 0, error: e }; + } + if (!result.error) { + resolvedModule = result.module; + break; + } + const err = result.error.stack || result.error.message || JSON.stringify(result.error); + (errorLogs ?? (errorLogs = [])).push(`Failed to dynamically import module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`); + } + return { pluginConfigEntry, resolvedModule, errorLogs }; } isKnownTypesPackageName(name) { return this.typingsCache.isKnownTypesPackageName(name); @@ -170444,6 +171188,10 @@ ${options.prefix}` : "\n" : options.prefix reusedNames ); } + /** @internal */ + resolveLibrary(libraryName, resolveFrom, options, libFileName) { + return this.resolutionCache.resolveLibrary(libraryName, resolveFrom, options, libFileName); + } directoryExists(path) { return this.directoryStructureHost.directoryExists(path); } @@ -170705,6 +171453,8 @@ ${options.prefix}` : "\n" : options.prefix return path === options.configFilePath ? options.configFile : this.getSourceFile(path); } close() { + this.projectService.typingsCache.onProjectClosed(this); + this.closeWatchingTypingLocations(); if (this.program) { for (const f of this.program.getSourceFiles()) { this.detachScriptInfoIfNotRoot(f.fileName); @@ -170995,6 +171745,89 @@ ${options.prefix}` : "\n" : options.prefix } } /** @internal */ + closeWatchingTypingLocations() { + if (this.typingWatchers) + clearMap(this.typingWatchers, closeFileWatcher); + this.typingWatchers = void 0; + } + /** @internal */ + onTypingInstallerWatchInvoke() { + this.typingWatchers.isInvoked = true; + this.projectService.updateTypingsForProject({ projectName: this.getProjectName(), kind: ActionInvalidate }); + } + /** @internal */ + watchTypingLocations(files) { + if (!files) { + this.typingWatchers.isInvoked = false; + return; + } + if (!files.length) { + this.closeWatchingTypingLocations(); + return; + } + const toRemove = new Map(this.typingWatchers); + if (!this.typingWatchers) + this.typingWatchers = /* @__PURE__ */ new Map(); + this.typingWatchers.isInvoked = false; + const createProjectWatcher = (path, typingsWatcherType) => { + const canonicalPath = this.toPath(path); + toRemove.delete(canonicalPath); + if (!this.typingWatchers.has(canonicalPath)) { + this.typingWatchers.set( + canonicalPath, + typingsWatcherType === "FileWatcher" /* FileWatcher */ ? this.projectService.watchFactory.watchFile( + path, + () => !this.typingWatchers.isInvoked ? this.onTypingInstallerWatchInvoke() : this.writeLog(`TypingWatchers already invoked`), + 2e3 /* 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, ".json" /* 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(); + }, + 1 /* Recursive */, + this.projectService.getWatchOptions(this), + WatchType.TypingInstallerLocationDirectory, + this + ) + ); + } + }; + for (const file of files) { + const basename = getBaseFileName(file); + if (basename === "package.json" || basename === "bower.json") { + createProjectWatcher(file, "FileWatcher" /* FileWatcher */); + continue; + } + if (containsPath(this.currentDirectory, file, this.currentDirectory, !this.useCaseSensitiveFileNames())) { + const subDirectory = file.indexOf(directorySeparator, this.currentDirectory.length + 1); + if (subDirectory !== -1) { + createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */); + } else { + createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); + } + continue; + } + if (containsPath(this.projectService.typingsInstaller.globalTypingsCacheLocation, file, this.currentDirectory, !this.useCaseSensitiveFileNames())) { + createProjectWatcher(this.projectService.typingsInstaller.globalTypingsCacheLocation, "DirectoryWatcher" /* DirectoryWatcher */); + continue; + } + createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); + } + toRemove.forEach((watch, path) => { + watch.close(); + this.typingWatchers.delete(path); + }); + } + /** @internal */ getCurrentProgram() { return this.program; } @@ -171008,7 +171841,9 @@ ${options.prefix}` : "\n" : options.prefix Debug.assert(!this.isClosed(), "Called update graph worker of closed project"); this.writeLog(`Starting updateGraphWorker: Project: ${this.getProjectName()}`); const start = timestamp(); - this.hasInvalidatedResolutions = this.resolutionCache.createHasInvalidatedResolutions(returnFalse); + const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = this.resolutionCache.createHasInvalidatedResolutions(returnFalse, returnFalse); + this.hasInvalidatedResolutions = hasInvalidatedResolutions; + this.hasInvalidatedLibResolutions = hasInvalidatedLibResolutions; this.resolutionCache.startCachingPerDirectoryResolution(); this.program = this.languageService.getProgram(); this.dirty = false; @@ -171299,7 +172134,7 @@ ${options.prefix}` : "\n" : options.prefix if (changesAffectModuleResolution(oldOptions, compilerOptions)) { this.cachedUnresolvedImportsPerFile.clear(); this.lastCachedUnresolvedImportsList = void 0; - this.resolutionCache.clear(); + this.resolutionCache.onChangesAffectModuleResolution(); this.moduleSpecifierCache.clear(); } this.markAsDirty(); @@ -171425,7 +172260,7 @@ ${options.prefix}` : "\n" : options.prefix combinePaths(this.projectService.getExecutingFilePath(), "../../..") ]; } - enableGlobalPlugins(options, pluginConfigOverrides) { + enableGlobalPlugins(options) { if (!this.projectService.globalPlugins.length) return; const host = this.projectService.host; @@ -171440,67 +172275,13 @@ ${options.prefix}` : "\n" : options.prefix if (options.plugins && options.plugins.some((p) => p.name === globalPluginName)) continue; this.projectService.logger.info(`Loading global plugin ${globalPluginName}`); - this.enablePlugin({ name: globalPluginName, global: true }, searchPaths, pluginConfigOverrides); + this.enablePlugin({ name: globalPluginName, global: true }, searchPaths); } } - /** - * Performs the initial steps of enabling a plugin by finding and instantiating the module for a plugin synchronously using 'require'. - * - * @internal - */ - beginEnablePluginSync(pluginConfigEntry, searchPaths, pluginConfigOverrides) { - Debug.assertIsDefined(this.projectService.host.require); - let errorLogs; - const log = (message) => this.projectService.logger.info(message); - const logError = (message) => { - (errorLogs ?? (errorLogs = [])).push(message); - }; - const resolvedModule = firstDefined(searchPaths, (searchPath) => Project3.resolveModule(pluginConfigEntry.name, searchPath, this.projectService.host, log, logError)); - return { pluginConfigEntry, pluginConfigOverrides, resolvedModule, errorLogs }; - } - /** - * Performs the initial steps of enabling a plugin by finding and instantiating the module for a plugin asynchronously using dynamic `import`. - * - * @internal - */ - async beginEnablePluginAsync(pluginConfigEntry, searchPaths, pluginConfigOverrides) { - Debug.assertIsDefined(this.projectService.host.importPlugin); - let errorLogs; - const log = (message) => this.projectService.logger.info(message); - const logError = (message) => { - (errorLogs ?? (errorLogs = [])).push(message); - }; - let resolvedModule; - for (const searchPath of searchPaths) { - resolvedModule = await Project3.importServicePluginAsync(pluginConfigEntry.name, searchPath, this.projectService.host, log, logError); - if (resolvedModule !== void 0) { - break; - } - } - return { pluginConfigEntry, pluginConfigOverrides, resolvedModule, errorLogs }; - } - /** - * Performs the remaining steps of enabling a plugin after its module has been instantiated. - * - * @internal - */ - endEnablePlugin({ pluginConfigEntry, pluginConfigOverrides, resolvedModule, errorLogs }) { - if (resolvedModule) { - const configurationOverride = pluginConfigOverrides && pluginConfigOverrides.get(pluginConfigEntry.name); - if (configurationOverride) { - const pluginName = pluginConfigEntry.name; - pluginConfigEntry = configurationOverride; - pluginConfigEntry.name = pluginName; - } - this.enableProxy(resolvedModule, pluginConfigEntry); - } else { - forEach(errorLogs, (message) => this.projectService.logger.info(message)); - this.projectService.logger.info(`Couldn't find ${pluginConfigEntry.name}`); - } - } - enablePlugin(pluginConfigEntry, searchPaths, pluginConfigOverrides) { - this.projectService.requestEnablePlugin(this, pluginConfigEntry, searchPaths, pluginConfigOverrides); + enablePlugin(pluginConfigEntry, searchPaths) { + this.projectService.requestEnablePlugin(this, pluginConfigEntry, searchPaths); } + /** @internal */ enableProxy(pluginModuleFactory, configEntry) { try { if (typeof pluginModuleFactory !== "function") { @@ -171694,7 +172475,7 @@ ${options.prefix}` : "\n" : options.prefix }; InferredProject2 = class extends Project3 { /** @internal */ - constructor(projectService, documentRegistry, compilerOptions, watchOptions, projectRootPath, currentDirectory, pluginConfigOverrides, typeAcquisition) { + constructor(projectService, documentRegistry, compilerOptions, watchOptions, projectRootPath, currentDirectory, typeAcquisition) { super( projectService.newInferredProjectName(), 0 /* Inferred */, @@ -171718,7 +172499,7 @@ ${options.prefix}` : "\n" : options.prefix if (!projectRootPath && !projectService.useSingleInferredProject) { this.canonicalCurrentDirectory = projectService.toCanonicalFileName(this.currentDirectory); } - this.enableGlobalPlugins(this.getCompilerOptions(), pluginConfigOverrides); + this.enableGlobalPlugins(this.getCompilerOptions()); } toggleJsInferredProject(isJsInferredProject) { if (isJsInferredProject !== this._isJsInferredProject) { @@ -171747,13 +172528,18 @@ ${options.prefix}` : "\n" : options.prefix /*isJsInferredProject*/ true ); + } else if (this.isOrphan() && this._isJsInferredProject && !info.isJavaScript()) { + this.toggleJsInferredProject( + /*isJsInferredProject*/ + false + ); } super.addRoot(info); } removeRoot(info) { this.projectService.stopWatchingConfigFilesForInferredProjectRoot(info); super.removeRoot(info); - if (this._isJsInferredProject && info.isJavaScript()) { + if (!this.isOrphan() && this._isJsInferredProject && info.isJavaScript()) { if (every(this.getRootScriptInfos(), (rootInfo) => !rootInfo.isJavaScript())) { this.toggleJsInferredProject( /*isJsInferredProject*/ @@ -172179,7 +172965,7 @@ ${options.prefix}` : "\n" : options.prefix return (_a = this.getCurrentProgram()) == null ? void 0 : _a.forEachResolvedProjectReference(cb); } /** @internal */ - enablePluginsWithOptions(options, pluginConfigOverrides) { + enablePluginsWithOptions(options) { var _a; this.plugins.length = 0; if (!((_a = options.plugins) == null ? void 0 : _a.length) && !this.projectService.globalPlugins.length) @@ -172197,10 +172983,10 @@ ${options.prefix}` : "\n" : options.prefix } if (options.plugins) { for (const pluginConfigEntry of options.plugins) { - this.enablePlugin(pluginConfigEntry, searchPaths, pluginConfigOverrides); + this.enablePlugin(pluginConfigEntry, searchPaths); } } - return this.enableGlobalPlugins(options, pluginConfigOverrides); + return this.enableGlobalPlugins(options); } /** * Get the errors that dont have any file name associated @@ -172293,7 +173079,7 @@ ${options.prefix}` : "\n" : options.prefix }; ExternalProject2 = class extends Project3 { /** @internal */ - constructor(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath, pluginConfigOverrides, watchOptions) { + constructor(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath, watchOptions) { super( externalProjectName, 2 /* External */, @@ -172311,7 +173097,7 @@ ${options.prefix}` : "\n" : options.prefix this.externalProjectName = externalProjectName; this.compileOnSaveEnabled = compileOnSaveEnabled; this.excludedFiles = []; - this.enableGlobalPlugins(this.getCompilerOptions(), pluginConfigOverrides); + this.enableGlobalPlugins(this.getCompilerOptions()); } updateGraph() { const result = super.updateGraph(); @@ -172491,7 +173277,7 @@ ${options.prefix}` : "\n" : options.prefix (potentialProjectRef) => callbackRefProject(project, cb, potentialProjectRef) ); } - function getDetailWatchInfo2(watchType, project) { + function getDetailWatchInfo(watchType, project) { return `${isString(project) ? `Config: ${project} ` : project ? `Project: ${project.getProjectName()} ` : ""}WatchType: ${watchType}`; } function isScriptInfoWatchedFromNodeModules(info) { @@ -172756,7 +173542,7 @@ ${options.prefix}` : "\n" : options.prefix this.watchFactory = this.serverMode !== 0 /* Semantic */ ? { watchFile: returnNoopFileWatcher, watchDirectory: returnNoopFileWatcher - } : getWatchFactory(this.host, watchLogLevel, log, getDetailWatchInfo2); + } : getWatchFactory(this.host, watchLogLevel, log, getDetailWatchInfo); } toPath(fileName) { return toPath(fileName, this.currentDirectory, this.toCanonicalFileName); @@ -172842,6 +173628,11 @@ ${options.prefix}` : "\n" : options.prefix } } /** @internal */ + watchTypingLocations(response) { + var _a; + (_a = this.findProject(response.projectName)) == null ? void 0 : _a.watchTypingLocations(response.files); + } + /** @internal */ delayEnsureProjectForOpenFiles() { if (!this.openFiles.size) return; @@ -173673,7 +174464,6 @@ ${options.prefix}` : "\n" : options.prefix options.compileOnSave === void 0 ? true : options.compileOnSave, /*projectFilePath*/ void 0, - this.currentPluginConfigOverrides, watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions ); project.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors); @@ -173822,7 +174612,7 @@ ${options.prefix}` : "\n" : options.prefix project.enableLanguageService(); this.watchWildcards(configFilename, configFileExistenceInfo, project); } - project.enablePluginsWithOptions(compilerOptions, this.currentPluginConfigOverrides); + project.enablePluginsWithOptions(compilerOptions); const filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles()); this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave, parsedCommandLine.watchOptions); (_b = tracing) == null ? void 0 : _b.pop(); @@ -174163,7 +174953,7 @@ ${options.prefix}` : "\n" : options.prefix typeAcquisition = this.typeAcquisitionForInferredProjects; } watchOptionsAndErrors = watchOptionsAndErrors || void 0; - const project = new InferredProject2(this, this.documentRegistry, compilerOptions, watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions, projectRootPath, currentDirectory, this.currentPluginConfigOverrides, typeAcquisition); + const project = new InferredProject2(this, this.documentRegistry, compilerOptions, watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions, projectRootPath, currentDirectory, typeAcquisition); project.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors); if (isSingleInferredProject) { this.inferredProjects.unshift(project); @@ -175390,8 +176180,11 @@ Dynamic files must always be opened with service's current directory or service } return false; } - /** @internal */ - requestEnablePlugin(project, pluginConfigEntry, searchPaths, pluginConfigOverrides) { + /** + * Performs the initial steps of enabling a plugin by finding and instantiating the module for a plugin either asynchronously or synchronously + * @internal + */ + requestEnablePlugin(project, pluginConfigEntry, searchPaths) { if (!this.host.importPlugin && !this.host.require) { this.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); return; @@ -175402,7 +176195,12 @@ Dynamic files must always be opened with service's current directory or service return; } if (this.host.importPlugin) { - const importPromise = project.beginEnablePluginAsync(pluginConfigEntry, searchPaths, pluginConfigOverrides); + const importPromise = Project3.importServicePluginAsync( + pluginConfigEntry, + searchPaths, + this.host, + (s) => this.logger.info(s) + ); this.pendingPluginEnablements ?? (this.pendingPluginEnablements = /* @__PURE__ */ new Map()); let promises = this.pendingPluginEnablements.get(project); if (!promises) @@ -175410,7 +176208,31 @@ Dynamic files must always be opened with service's current directory or service promises.push(importPromise); return; } - project.endEnablePlugin(project.beginEnablePluginSync(pluginConfigEntry, searchPaths, pluginConfigOverrides)); + this.endEnablePlugin(project, Project3.importServicePluginSync( + pluginConfigEntry, + searchPaths, + this.host, + (s) => this.logger.info(s) + )); + } + /** + * Performs the remaining steps of enabling a plugin after its module has been instantiated. + * @internal + */ + endEnablePlugin(project, { pluginConfigEntry, resolvedModule, errorLogs }) { + var _a; + if (resolvedModule) { + const configurationOverride = (_a = this.currentPluginConfigOverrides) == null ? void 0 : _a.get(pluginConfigEntry.name); + if (configurationOverride) { + const pluginName = pluginConfigEntry.name; + pluginConfigEntry = configurationOverride; + pluginConfigEntry.name = pluginName; + } + project.enableProxy(resolvedModule, pluginConfigEntry); + } else { + forEach(errorLogs, (message) => this.logger.info(message)); + this.logger.info(`Couldn't find ${pluginConfigEntry.name}`); + } } /** @internal */ hasNewPluginEnablementRequests() { @@ -175464,7 +176286,7 @@ Dynamic files must always be opened with service's current directory or service return; } for (const result of results) { - project.endEnablePlugin(result); + this.endEnablePlugin(project, result); } this.delayUpdateProjectGraph(project); } @@ -175804,7 +176626,7 @@ Dynamic files must always be opened with service's current directory or service const verboseLogging = logger.hasLevel(3 /* verbose */); const json = JSON.stringify(msg); if (verboseLogging) { - logger.info(`${msg.type}:${indent2(json)}`); + logger.info(`${msg.type}:${indent2(JSON.stringify(msg, void 0, " "))}`); } const len = byteLength(json, "utf8"); return `Content-Length: ${1 + len}\r @@ -175832,14 +176654,14 @@ ${json}${newLine}`; function createDocumentSpanSet() { return createSet(({ textSpan }) => textSpan.start + 100003 * textSpan.length, documentSpansEqual); } - function getRenameLocationsWorker(projects, defaultProject, initialLocation, findInStrings, findInComments, { providePrefixAndSuffixTextForRename }) { + function getRenameLocationsWorker(projects, defaultProject, initialLocation, findInStrings, findInComments, preferences) { const perProjectResults = getPerProjectReferences( projects, defaultProject, initialLocation, /*isForRename*/ true, - (project, position) => project.getLanguageService().findRenameLocations(position.fileName, position.pos, findInStrings, findInComments, providePrefixAndSuffixTextForRename), + (project, position) => project.getLanguageService().findRenameLocations(position.fileName, position.pos, findInStrings, findInComments, preferences), (renameLocation, cb) => cb(documentSpanLocation(renameLocation)) ); if (isArray(perProjectResults)) { @@ -176273,6 +177095,7 @@ ${json}${newLine}`; "applyCodeActionCommand" /* ApplyCodeActionCommand */, "getSupportedCodeFixes" /* GetSupportedCodeFixes */, "getApplicableRefactors" /* GetApplicableRefactors */, + "getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */, "getEditsForRefactor" /* GetEditsForRefactor */, "getEditsForRefactor-full" /* GetEditsForRefactorFull */, "organizeImports" /* OrganizeImports */, @@ -176818,6 +177641,9 @@ ${json}${newLine}`; true )); }, + ["getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */]: (request) => { + return this.requiredResponse(this.getMoveToRefactoringFileSuggestions(request.arguments)); + }, ["getEditsForRefactor-full" /* GetEditsForRefactorFull */]: (request) => { return this.requiredResponse(this.getEditsForRefactor( request.arguments, @@ -176950,7 +177776,7 @@ ${json}${newLine}`; })); this.host = opts.host; this.cancellationToken = opts.cancellationToken; - this.typingsInstaller = opts.typingsInstaller; + this.typingsInstaller = opts.typingsInstaller || nullTypingsInstaller; this.byteLength = opts.byteLength; this.hrtime = opts.hrtime; this.logger = opts.logger; @@ -178546,7 +179372,7 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter getApplicableRefactors(args) { const { file, project } = this.getFileAndProject(args); const scriptInfo = project.getScriptInfoForNormalizedPath(file); - return project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file), args.triggerReason, args.kind); + return project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file), args.triggerReason, args.kind, args.includeInteractiveActions); } getEditsForRefactor(args, simplifiedResult) { const { file, project } = this.getFileAndProject(args); @@ -178557,7 +179383,8 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter this.extractPositionOrRange(args, scriptInfo), args.refactor, args.action, - this.getPreferences(file) + this.getPreferences(file), + args.interactiveRefactorArguments ); if (result === void 0) { return { @@ -178571,10 +179398,18 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const renameScriptInfo = project.getScriptInfoForNormalizedPath(toNormalizedPath(renameFilename)); mappedRenameLocation = getLocationInNewDocument(getSnapshotText(renameScriptInfo.getSnapshot()), renameFilename, renameLocation, edits); } - return { renameLocation: mappedRenameLocation, renameFilename, edits: this.mapTextChangesToCodeEdits(edits) }; - } else { - return result; + return { + renameLocation: mappedRenameLocation, + renameFilename, + edits: this.mapTextChangesToCodeEdits(edits) + }; } + return result; + } + getMoveToRefactoringFileSuggestions(args) { + const { file, project } = this.getFileAndProject(args); + const scriptInfo = project.getScriptInfoForNormalizedPath(file); + return project.getLanguageService().getMoveToRefactoringFileSuggestions(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file)); } organizeImports(args, simplifiedResult) { Debug.assert(args.scope.type === "file"); @@ -178679,11 +179514,11 @@ ${e.message}`; } return { startPosition, endPosition }; } - mapCodeAction({ description: description2, changes, commands }) { - return { description: description2, changes: this.mapTextChangesToCodeEdits(changes), commands }; + mapCodeAction({ description: description3, changes, commands }) { + return { description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands }; } - mapCodeFixAction({ fixName: fixName8, description: description2, changes, commands, fixId: fixId52, fixAllDescription }) { - return { fixName: fixName8, description: description2, changes: this.mapTextChangesToCodeEdits(changes), commands, fixId: fixId52, fixAllDescription }; + mapCodeFixAction({ fixName: fixName8, description: description3, changes, commands, fixId: fixId52, fixAllDescription }) { + return { fixName: fixName8, description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands, fixId: fixId52, fixAllDescription }; } mapTextChangesToCodeEdits(textChanges2) { return textChanges2.map((change) => this.mapTextChangeToCodeEdit(change)); @@ -179761,6 +180596,7 @@ ${e.message}`; ActionInvalidate: () => ActionInvalidate, ActionPackageInstalled: () => ActionPackageInstalled, ActionSet: () => ActionSet, + ActionWatchTypingLocations: () => ActionWatchTypingLocations, Arguments: () => Arguments, AutoImportProviderProject: () => AutoImportProviderProject, CharRangeSection: () => CharRangeSection, @@ -180252,6 +181088,7 @@ ${e.message}`; createMemberAccessForPropertyName: () => createMemberAccessForPropertyName, createModeAwareCache: () => createModeAwareCache, createModeAwareCacheKey: () => createModeAwareCacheKey, + createModuleNotFoundChain: () => createModuleNotFoundChain, createModuleResolutionCache: () => createModuleResolutionCache, createModuleResolutionLoader: () => createModuleResolutionLoader, createModuleSpecifierResolutionHost: () => createModuleSpecifierResolutionHost, @@ -180386,6 +181223,7 @@ ${e.message}`; fileExtensionIs: () => fileExtensionIs, fileExtensionIsOneOf: () => fileExtensionIsOneOf, fileIncludeReasonToDiagnostics: () => fileIncludeReasonToDiagnostics, + fileShouldUseJavaScriptRequire: () => fileShouldUseJavaScriptRequire, filter: () => filter, filterMutate: () => filterMutate, filterSemanticDiagnostics: () => filterSemanticDiagnostics, @@ -180621,6 +181459,7 @@ ${e.message}`; getImportNeedsImportStarHelper: () => getImportNeedsImportStarHelper, getIndentSize: () => getIndentSize, getIndentString: () => getIndentString, + getInferredLibraryNameResolveFrom: () => getInferredLibraryNameResolveFrom, getInitializedVariables: () => getInitializedVariables, getInitializerOfBinaryExpression: () => getInitializerOfBinaryExpression, getInitializerOfBindingOrAssignmentElement: () => getInitializerOfBindingOrAssignmentElement, @@ -180741,6 +181580,7 @@ ${e.message}`; getOperatorAssociativity: () => getOperatorAssociativity, getOperatorPrecedence: () => getOperatorPrecedence, getOptionFromName: () => getOptionFromName, + getOptionsForLibraryResolution: () => getOptionsForLibraryResolution, getOptionsNameMap: () => getOptionsNameMap, getOrCreateEmitNode: () => getOrCreateEmitNode, getOrCreateExternalHelpersModuleNameIfNeeded: () => getOrCreateExternalHelpersModuleNameIfNeeded, @@ -181131,7 +181971,6 @@ ${e.message}`; isEmptyObjectLiteral: () => isEmptyObjectLiteral, isEmptyStatement: () => isEmptyStatement, isEmptyStringLiteral: () => isEmptyStringLiteral, - isEndOfDeclarationMarker: () => isEndOfDeclarationMarker, isEntityName: () => isEntityName, isEntityNameExpression: () => isEntityNameExpression, isEnumConst: () => isEnumConst, @@ -181362,7 +182201,6 @@ ${e.message}`; isLogicalOrCoalescingBinaryOperator: () => isLogicalOrCoalescingBinaryOperator, isMappedTypeNode: () => isMappedTypeNode, isMemberName: () => isMemberName, - isMergeDeclarationMarker: () => isMergeDeclarationMarker, isMetaProperty: () => isMetaProperty, isMethodDeclaration: () => isMethodDeclaration, isMethodOrAccessor: () => isMethodOrAccessor, @@ -181852,6 +182690,7 @@ ${e.message}`; resolutionExtensionIsTSOrJson: () => resolutionExtensionIsTSOrJson, resolveConfigFileProjectName: () => resolveConfigFileProjectName, resolveJSModule: () => resolveJSModule, + resolveLibrary: () => resolveLibrary, resolveModuleName: () => resolveModuleName, resolveModuleNameFromCache: () => resolveModuleNameFromCache, resolvePackageNameToPackageJson: () => resolvePackageNameToPackageJson, @@ -182148,6 +182987,7 @@ ${e.message}`; ActionInvalidate: () => ActionInvalidate, ActionPackageInstalled: () => ActionPackageInstalled, ActionSet: () => ActionSet, + ActionWatchTypingLocations: () => ActionWatchTypingLocations, Arguments: () => Arguments, AutoImportProviderProject: () => AutoImportProviderProject, CharRangeSection: () => CharRangeSection, @@ -182627,6 +183467,7 @@ ${e.message}`; createMemberAccessForPropertyName: () => createMemberAccessForPropertyName, createModeAwareCache: () => createModeAwareCache, createModeAwareCacheKey: () => createModeAwareCacheKey, + createModuleNotFoundChain: () => createModuleNotFoundChain, createModuleResolutionCache: () => createModuleResolutionCache, createModuleResolutionLoader: () => createModuleResolutionLoader, createModuleSpecifierResolutionHost: () => createModuleSpecifierResolutionHost, @@ -182761,6 +183602,7 @@ ${e.message}`; fileExtensionIs: () => fileExtensionIs, fileExtensionIsOneOf: () => fileExtensionIsOneOf, fileIncludeReasonToDiagnostics: () => fileIncludeReasonToDiagnostics, + fileShouldUseJavaScriptRequire: () => fileShouldUseJavaScriptRequire, filter: () => filter, filterMutate: () => filterMutate, filterSemanticDiagnostics: () => filterSemanticDiagnostics, @@ -182996,6 +183838,7 @@ ${e.message}`; getImportNeedsImportStarHelper: () => getImportNeedsImportStarHelper, getIndentSize: () => getIndentSize, getIndentString: () => getIndentString, + getInferredLibraryNameResolveFrom: () => getInferredLibraryNameResolveFrom, getInitializedVariables: () => getInitializedVariables, getInitializerOfBinaryExpression: () => getInitializerOfBinaryExpression, getInitializerOfBindingOrAssignmentElement: () => getInitializerOfBindingOrAssignmentElement, @@ -183116,6 +183959,7 @@ ${e.message}`; getOperatorAssociativity: () => getOperatorAssociativity, getOperatorPrecedence: () => getOperatorPrecedence, getOptionFromName: () => getOptionFromName, + getOptionsForLibraryResolution: () => getOptionsForLibraryResolution, getOptionsNameMap: () => getOptionsNameMap, getOrCreateEmitNode: () => getOrCreateEmitNode, getOrCreateExternalHelpersModuleNameIfNeeded: () => getOrCreateExternalHelpersModuleNameIfNeeded, @@ -183506,7 +184350,6 @@ ${e.message}`; isEmptyObjectLiteral: () => isEmptyObjectLiteral, isEmptyStatement: () => isEmptyStatement, isEmptyStringLiteral: () => isEmptyStringLiteral, - isEndOfDeclarationMarker: () => isEndOfDeclarationMarker, isEntityName: () => isEntityName, isEntityNameExpression: () => isEntityNameExpression, isEnumConst: () => isEnumConst, @@ -183737,7 +184580,6 @@ ${e.message}`; isLogicalOrCoalescingBinaryOperator: () => isLogicalOrCoalescingBinaryOperator, isMappedTypeNode: () => isMappedTypeNode, isMemberName: () => isMemberName, - isMergeDeclarationMarker: () => isMergeDeclarationMarker, isMetaProperty: () => isMetaProperty, isMethodDeclaration: () => isMethodDeclaration, isMethodOrAccessor: () => isMethodOrAccessor, @@ -184227,6 +185069,7 @@ ${e.message}`; resolutionExtensionIsTSOrJson: () => resolutionExtensionIsTSOrJson, resolveConfigFileProjectName: () => resolveConfigFileProjectName, resolveJSModule: () => resolveJSModule, + resolveLibrary: () => resolveLibrary, resolveModuleName: () => resolveModuleName, resolveModuleNameFromCache: () => resolveModuleNameFromCache, resolvePackageNameToPackageJson: () => resolvePackageNameToPackageJson, diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index ff62845a28f..862560ba05a 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -407,10 +407,8 @@ declare namespace ts { NotEmittedStatement = 358, PartiallyEmittedExpression = 359, CommaListExpression = 360, - MergeDeclarationMarker = 361, - EndOfDeclarationMarker = 362, - SyntheticReferenceExpression = 363, - Count = 364, + SyntheticReferenceExpression = 361, + Count = 362, FirstAssignment = 64, LastAssignment = 79, FirstCompoundAssignment = 65, @@ -552,7 +550,7 @@ declare namespace ts { 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 | ShorthandPropertyAssignment | SpreadAssignment | SwitchStatement | ThrowStatement | TryStatement | TypeAliasDeclaration | TypeParameterDeclaration | VariableDeclaration | VariableStatement | WhileStatement | WithStatement; + 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; @@ -646,7 +644,7 @@ declare namespace ts { type EntityName = Identifier | QualifiedName; type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | PrivateIdentifier; type MemberName = Identifier | PrivateIdentifier; - type DeclarationName = Identifier | PrivateIdentifier | StringLiteralLike | NumericLiteral | ComputedPropertyName | ElementAccessExpression | BindingPattern | EntityNameExpression; + type DeclarationName = PropertyName | JsxAttributeName | StringLiteralLike | ElementAccessExpression | BindingPattern | EntityNameExpression; interface Declaration extends Node { _declarationBrand: any; } @@ -831,7 +829,7 @@ declare namespace ts { readonly body?: FunctionBody | undefined; } /** For when we encounter a semicolon in a class declaration. ES6 allows these as class elements. */ - interface SemicolonClassElement extends ClassElement { + interface SemicolonClassElement extends ClassElement, JSDocContainer { readonly kind: SyntaxKind.SemicolonClassElement; readonly parent: ClassLikeDeclaration; } @@ -993,7 +991,7 @@ declare namespace ts { readonly kind: SyntaxKind.StringLiteral; } type StringLiteralLike = StringLiteral | NoSubstitutionTemplateLiteral; - type PropertyNameLiteral = Identifier | StringLiteralLike | NumericLiteral; + type PropertyNameLiteral = Identifier | StringLiteralLike | NumericLiteral | JsxNamespacedName; interface TemplateLiteralTypeNode extends TypeNode { kind: SyntaxKind.TemplateLiteralType; readonly head: TemplateHead; @@ -1352,14 +1350,14 @@ declare namespace ts { type JsxAttributeName = Identifier | JsxNamespacedName; type JsxTagNameExpression = Identifier | ThisExpression | JsxTagNamePropertyAccess | JsxNamespacedName; interface JsxTagNamePropertyAccess extends PropertyAccessExpression { - readonly expression: JsxTagNameExpression; + readonly expression: Identifier | ThisExpression | JsxTagNamePropertyAccess; } interface JsxAttributes extends PrimaryExpression, Declaration { readonly properties: NodeArray; readonly kind: SyntaxKind.JsxAttributes; readonly parent: JsxOpeningLikeElement; } - interface JsxNamespacedName extends PrimaryExpression { + interface JsxNamespacedName extends Node { readonly kind: SyntaxKind.JsxNamespacedName; readonly name: Identifier; readonly namespace: Identifier; @@ -3501,9 +3499,8 @@ declare namespace ts { ReuseTempVariableScope = 1048576, CustomPrologue = 2097152, NoHoisting = 4194304, - HasEndOfDeclarationMarker = 8388608, - Iterator = 16777216, - NoAsciiEscaping = 33554432 + Iterator = 8388608, + NoAsciiEscaping = 16777216 } interface EmitHelperBase { readonly name: string; @@ -4774,6 +4771,26 @@ declare namespace ts { 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 */ @@ -5222,7 +5239,7 @@ declare namespace ts { * 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): ModuleResolutionCache; + 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; @@ -5876,8 +5893,9 @@ declare namespace ts { 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; + readonly kind: ActionSet | ActionInvalidate | EventTypesRegistry | ActionPackageInstalled | EventBeginInstallTypes | EventEndInstallTypes | EventInitializationFailed | ActionWatchTypingLocations; } interface TypingInstallerRequestWithProjectName { readonly projectName: string; @@ -5886,7 +5904,6 @@ declare namespace ts { readonly fileNames: string[]; readonly projectRootPath: Path; readonly compilerOptions: CompilerOptions; - readonly watchOptions?: WatchOptions; readonly typeAcquisition: TypeAcquisition; readonly unresolvedImports: SortedReadonlyArray; readonly cachePath?: string; @@ -5938,8 +5955,6 @@ declare namespace ts { writeFile(path: string, content: string): void; createDirectory(path: string): void; getCurrentDirectory?(): string; - watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: WatchOptions): FileWatcher; - watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: WatchOptions): FileWatcher; } interface SetTypings extends ProjectResponse { readonly typeAcquisition: TypeAcquisition; @@ -5948,6 +5963,11 @@ declare namespace ts { 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; /** @@ -6153,6 +6173,8 @@ declare namespace ts { 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; @@ -6198,8 +6220,18 @@ declare namespace ts { applyCodeActionCommand(fileName: string, action: CodeActionCommand[]): Promise; /** @deprecated `fileName` will be ignored */ applyCodeActionCommand(fileName: string, action: CodeActionCommand | CodeActionCommand[]): Promise; - getApplicableRefactors(fileName: string, positionOrRange: number | TextRange, preferences: UserPreferences | undefined, triggerReason?: RefactorTriggerReason, kind?: string): ApplicableRefactorInfo[]; - getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; + /** + * @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, includeInteractiveActions?: 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; @@ -6470,6 +6502,11 @@ declare namespace ts { * 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 @@ -6702,6 +6739,9 @@ declare namespace ts { interface DocCommentTemplateOptions { readonly generateReturnInDocTemplate?: boolean; } + interface InteractiveRefactorArguments { + targetFile: string; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; diff --git a/lib/typescript.js b/lib/typescript.js index 1b800b1d093..0f968a2e363 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -35,7 +35,7 @@ var ts = (() => { "src/compiler/corePublic.ts"() { "use strict"; versionMajorMinor = "5.1"; - version = "5.1.0-beta"; + version = "5.1.1-rc"; Comparison = /* @__PURE__ */ ((Comparison3) => { Comparison3[Comparison3["LessThan"] = -1] = "LessThan"; Comparison3[Comparison3["EqualTo"] = 0] = "EqualTo"; @@ -3886,10 +3886,8 @@ ${lanes.join("\n")} SyntaxKind5[SyntaxKind5["NotEmittedStatement"] = 358] = "NotEmittedStatement"; SyntaxKind5[SyntaxKind5["PartiallyEmittedExpression"] = 359] = "PartiallyEmittedExpression"; SyntaxKind5[SyntaxKind5["CommaListExpression"] = 360] = "CommaListExpression"; - SyntaxKind5[SyntaxKind5["MergeDeclarationMarker"] = 361] = "MergeDeclarationMarker"; - SyntaxKind5[SyntaxKind5["EndOfDeclarationMarker"] = 362] = "EndOfDeclarationMarker"; - SyntaxKind5[SyntaxKind5["SyntheticReferenceExpression"] = 363] = "SyntheticReferenceExpression"; - SyntaxKind5[SyntaxKind5["Count"] = 364] = "Count"; + SyntaxKind5[SyntaxKind5["SyntheticReferenceExpression"] = 361] = "SyntheticReferenceExpression"; + SyntaxKind5[SyntaxKind5["Count"] = 362] = "Count"; SyntaxKind5[SyntaxKind5["FirstAssignment"] = 64 /* EqualsToken */] = "FirstAssignment"; SyntaxKind5[SyntaxKind5["LastAssignment"] = 79 /* CaretEqualsToken */] = "LastAssignment"; SyntaxKind5[SyntaxKind5["FirstCompoundAssignment"] = 65 /* PlusEqualsToken */] = "FirstCompoundAssignment"; @@ -4990,9 +4988,8 @@ ${lanes.join("\n")} EmitFlags3[EmitFlags3["ReuseTempVariableScope"] = 1048576] = "ReuseTempVariableScope"; EmitFlags3[EmitFlags3["CustomPrologue"] = 2097152] = "CustomPrologue"; EmitFlags3[EmitFlags3["NoHoisting"] = 4194304] = "NoHoisting"; - EmitFlags3[EmitFlags3["HasEndOfDeclarationMarker"] = 8388608] = "HasEndOfDeclarationMarker"; - EmitFlags3[EmitFlags3["Iterator"] = 16777216] = "Iterator"; - EmitFlags3[EmitFlags3["NoAsciiEscaping"] = 33554432] = "NoAsciiEscaping"; + EmitFlags3[EmitFlags3["Iterator"] = 8388608] = "Iterator"; + EmitFlags3[EmitFlags3["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; return EmitFlags3; })(EmitFlags || {}); InternalEmitFlags = /* @__PURE__ */ ((InternalEmitFlags3) => { @@ -8288,6 +8285,7 @@ ${lanes.join("\n")} List_of_folders_to_include_type_definitions_from: diag(6161, 3 /* Message */, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), Disable_size_limitations_on_JavaScript_projects: diag(6162, 3 /* Message */, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), The_character_set_of_the_input_files: diag(6163, 3 /* Message */, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1: diag(6164, 3 /* Message */, "Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1_6164", "Skipping module '{0}' that looks like an absolute URI, target file types: {1}."), Do_not_truncate_error_messages: diag(6165, 3 /* Message */, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), Output_directory_for_generated_declaration_files: diag(6166, 3 /* Message */, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, 3 /* Message */, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), @@ -8767,6 +8765,7 @@ ${lanes.join("\n")} You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder: diag(8036, 1 /* Error */, "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036", "You cannot rename elements that are defined in another 'node_modules' folder."), Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files: diag(8037, 1 /* Error */, "Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files_8037", "Type satisfaction expressions can only be used in TypeScript files."), Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export: diag(8038, 1 /* Error */, "Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export_8038", "Decorators may not appear after 'export' or 'export default' if they also appear before 'export'."), + A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag: diag(8039, 1 /* Error */, "A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag_8039", "A JSDoc '@template' tag may not follow a '@typedef', '@callback', or '@overload' tag"), Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, 1 /* Error */, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."), Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, 1 /* Error */, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."), JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17e3, 1 /* Error */, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), @@ -9018,6 +9017,7 @@ ${lanes.join("\n")} Use_Number_isNaN_in_all_conditions: diag(95175, 3 /* Message */, "Use_Number_isNaN_in_all_conditions_95175", "Use `Number.isNaN` in all conditions."), Convert_typedef_to_TypeScript_type: diag(95176, 3 /* Message */, "Convert_typedef_to_TypeScript_type_95176", "Convert typedef to TypeScript type."), Convert_all_typedef_to_TypeScript_types: diag(95177, 3 /* Message */, "Convert_all_typedef_to_TypeScript_types_95177", "Convert all typedef to TypeScript types."), + Move_to_file: diag(95178, 3 /* Message */, "Move_to_file_95178", "Move to file"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, 1 /* Error */, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, 1 /* Error */, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, 1 /* Error */, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -12388,7 +12388,6 @@ ${lanes.join("\n")} case 283 /* JsxElement */: case 284 /* JsxSelfClosingElement */: case 287 /* JsxFragment */: - case 294 /* JsxNamespacedName */: case 214 /* TaggedTemplateExpression */: case 208 /* ArrayLiteralExpression */: case 216 /* ParenthesizedExpression */: @@ -12654,7 +12653,7 @@ ${lanes.join("\n")} return kind === 261 /* FunctionDeclaration */ || kind === 281 /* MissingDeclaration */ || kind === 262 /* ClassDeclaration */ || kind === 263 /* InterfaceDeclaration */ || kind === 264 /* TypeAliasDeclaration */ || kind === 265 /* EnumDeclaration */ || kind === 266 /* ModuleDeclaration */ || kind === 271 /* ImportDeclaration */ || kind === 270 /* ImportEqualsDeclaration */ || kind === 277 /* ExportDeclaration */ || kind === 276 /* ExportAssignment */ || kind === 269 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 251 /* BreakStatement */ || kind === 250 /* ContinueStatement */ || kind === 258 /* DebuggerStatement */ || kind === 245 /* DoStatement */ || kind === 243 /* ExpressionStatement */ || kind === 241 /* EmptyStatement */ || kind === 248 /* ForInStatement */ || kind === 249 /* ForOfStatement */ || kind === 247 /* ForStatement */ || kind === 244 /* IfStatement */ || kind === 255 /* LabeledStatement */ || kind === 252 /* ReturnStatement */ || kind === 254 /* SwitchStatement */ || kind === 256 /* ThrowStatement */ || kind === 257 /* TryStatement */ || kind === 242 /* VariableStatement */ || kind === 246 /* WhileStatement */ || kind === 253 /* WithStatement */ || kind === 358 /* NotEmittedStatement */ || kind === 362 /* EndOfDeclarationMarker */ || kind === 361 /* MergeDeclarationMarker */; + return kind === 251 /* BreakStatement */ || kind === 250 /* ContinueStatement */ || kind === 258 /* DebuggerStatement */ || kind === 245 /* DoStatement */ || kind === 243 /* ExpressionStatement */ || kind === 241 /* EmptyStatement */ || kind === 248 /* ForInStatement */ || kind === 249 /* ForOfStatement */ || kind === 247 /* ForStatement */ || kind === 244 /* IfStatement */ || kind === 255 /* LabeledStatement */ || kind === 252 /* ReturnStatement */ || kind === 254 /* SwitchStatement */ || kind === 256 /* ThrowStatement */ || kind === 257 /* TryStatement */ || kind === 242 /* VariableStatement */ || kind === 246 /* WhileStatement */ || kind === 253 /* WithStatement */ || kind === 358 /* NotEmittedStatement */; } function isDeclaration(node) { if (node.kind === 167 /* TypeParameter */) { @@ -12952,7 +12951,39 @@ ${lanes.join("\n")} return oldRef.path === newRef.path && !oldRef.prepend === !newRef.prepend && !oldRef.circular === !newRef.circular; } function moduleResolutionIsEqualTo(oldResolution, newResolution) { - 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); + 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; + } + function createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageName) { + var _a, _b; + const node10Result = (_b = (_a = sourceFile.resolvedModules) == null ? void 0 : _a.get(moduleReference, mode)) == null ? void 0 : _b.node10Result; + const result = node10Result ? chainDiagnosticMessages( + /*details*/ + void 0, + 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 + ) : host.typesPackageExists(packageName) ? chainDiagnosticMessages( + /*details*/ + void 0, + 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*/ + void 0, + 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*/ + void 0, + 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 ? void 0 : packageName }); + return result; } function packageIdIsEqual(a, b) { return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; @@ -13629,7 +13660,7 @@ ${lanes.join("\n")} } switch (node.kind) { case 11 /* StringLiteral */: { - const escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString : flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + const escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString : flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; if (node.singleQuote) { return "'" + escapeText(node.text, 39 /* singleQuote */) + "'"; } else { @@ -13640,7 +13671,7 @@ ${lanes.join("\n")} case 16 /* TemplateHead */: case 17 /* TemplateMiddle */: case 18 /* TemplateTail */: { - const escapeText = flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; + const escapeText = flags & 1 /* NeverAsciiEscape */ || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? escapeString : escapeNonAsciiString; const rawText = node.rawText ?? escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */)); switch (node.kind) { case 15 /* NoSubstitutionTemplateLiteral */: @@ -13736,7 +13767,7 @@ ${lanes.join("\n")} return kind === 1 /* CommonJS */ || kind === 100 /* Node16 */ || kind === 199 /* NodeNext */; } function isEffectiveExternalModule(node, compilerOptions) { - return isExternalModule(node) || getIsolatedModules(compilerOptions) || isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator; + return isExternalModule(node) || isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator; } function isEffectiveStrictModeSourceFile(node, compilerOptions) { switch (node.scriptKind) { @@ -13899,6 +13930,8 @@ ${lanes.join("\n")} if (isStringOrNumericLiteralLike(name.expression)) return escapeLeadingUnderscores(name.expression.text); return void 0; + case 294 /* JsxNamespacedName */: + return getEscapedTextOfJsxNamespacedName(name); default: return Debug.assertNever(name); } @@ -15390,6 +15423,7 @@ ${lanes.join("\n")} case 171 /* PropertyDeclaration */: case 170 /* PropertySignature */: case 252 /* ReturnStatement */: + case 239 /* SemicolonClassElement */: case 177 /* SetAccessor */: case 303 /* ShorthandPropertyAssignment */: case 304 /* SpreadAssignment */: @@ -15863,6 +15897,8 @@ ${lanes.join("\n")} return nameExpression.operand.text; } return void 0; + case 294 /* JsxNamespacedName */: + return getEscapedTextOfJsxNamespacedName(name); default: return Debug.assertNever(name); } @@ -15879,16 +15915,16 @@ ${lanes.join("\n")} } } function getTextOfIdentifierOrLiteral(node) { - return isMemberName(node) ? idText(node) : node.text; + return isMemberName(node) ? idText(node) : isJsxNamespacedName(node) ? getTextOfJsxNamespacedName(node) : node.text; } function getEscapedTextOfIdentifierOrLiteral(node) { - return isMemberName(node) ? node.escapedText : escapeLeadingUnderscores(node.text); + return isMemberName(node) ? node.escapedText : isJsxNamespacedName(node) ? getEscapedTextOfJsxNamespacedName(node) : escapeLeadingUnderscores(node.text); } function getPropertyNameForUniqueESSymbol(symbol) { return `__@${getSymbolId(symbol)}@${symbol.escapedName}`; } - function getSymbolNameForPrivateIdentifier(containingClassSymbol, description2) { - return `__#${getSymbolId(containingClassSymbol)}@${description2}`; + function getSymbolNameForPrivateIdentifier(containingClassSymbol, description3) { + return `__#${getSymbolId(containingClassSymbol)}@${description3}`; } function isKnownSymbol(symbol) { return startsWith(symbol.escapedName, "__@"); @@ -17112,6 +17148,8 @@ ${lanes.join("\n")} } } else if (isIdentifier(expr)) { return unescapeLeadingUnderscores(expr.escapedText); + } else if (isJsxNamespacedName(expr)) { + return getTextOfJsxNamespacedName(expr); } return void 0; } @@ -19288,7 +19326,7 @@ ${lanes.join("\n")} supportedTSExtensions = [[".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */], [".cts" /* Cts */, ".d.cts" /* Dcts */], [".mts" /* Mts */, ".d.mts" /* Dmts */]]; supportedTSExtensionsFlat = flatten(supportedTSExtensions); supportedTSExtensionsWithJson = [...supportedTSExtensions, [".json" /* Json */]]; - supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */, ".cts" /* Cts */, ".mts" /* Mts */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".cts" /* Cts */, ".mts" /* Mts */]; + supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */, ".cts" /* Cts */, ".mts" /* Mts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; supportedJSExtensions = [[".js" /* Js */, ".jsx" /* Jsx */], [".mjs" /* Mjs */], [".cjs" /* Cjs */]]; supportedJSExtensionsFlat = flatten(supportedJSExtensions); allSupportedExtensions = [[".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".js" /* Js */, ".jsx" /* Jsx */], [".cts" /* Cts */, ".d.cts" /* Dcts */, ".cjs" /* Cjs */], [".mts" /* Mts */, ".d.mts" /* Dmts */, ".mjs" /* Mjs */]]; @@ -20416,8 +20454,6 @@ ${lanes.join("\n")} updatePartiallyEmittedExpression, createCommaListExpression, updateCommaListExpression, - createEndOfDeclarationMarker, - createMergeDeclarationMarker, createSyntheticReferenceExpression, updateSyntheticReferenceExpression, cloneNode, @@ -23485,20 +23521,8 @@ ${lanes.join("\n")} function updateCommaListExpression(node, elements) { return node.elements !== elements ? update(createCommaListExpression(elements), node) : node; } - function createEndOfDeclarationMarker(original) { - const node = createBaseNode(362 /* EndOfDeclarationMarker */); - node.emitNode = {}; - node.original = original; - return node; - } - function createMergeDeclarationMarker(original) { - const node = createBaseNode(361 /* MergeDeclarationMarker */); - node.emitNode = {}; - node.original = original; - return node; - } function createSyntheticReferenceExpression(expression, thisArg) { - const node = createBaseNode(363 /* SyntheticReferenceExpression */); + const node = createBaseNode(361 /* SyntheticReferenceExpression */); node.expression = expression; node.thisArg = thisArg; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.thisArg); @@ -23890,8 +23914,8 @@ ${lanes.join("\n")} function inlineExpressions(expressions) { return expressions.length > 10 ? createCommaListExpression(expressions) : reduceLeft(expressions, factory2.createComma); } - function getName(node, allowComments, allowSourceMaps, emitFlags = 0) { - const nodeName = getNameOfDeclaration(node); + function getName(node, allowComments, allowSourceMaps, emitFlags = 0, ignoreAssignedName) { + const nodeName = ignoreAssignedName ? node && getNonAssignedNameOfDeclaration(node) : getNameOfDeclaration(node); if (nodeName && isIdentifier(nodeName) && !isGeneratedIdentifier(nodeName)) { const name = setParent(setTextRange(cloneNode(nodeName), nodeName), nodeName.parent); emitFlags |= getEmitFlags(nodeName); @@ -23908,8 +23932,8 @@ ${lanes.join("\n")} function getInternalName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */ | 65536 /* InternalName */); } - function getLocalName(node, allowComments, allowSourceMaps) { - return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */); + function getLocalName(node, allowComments, allowSourceMaps, ignoreAssignedName) { + return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */, ignoreAssignedName); } function getExportName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps, 16384 /* ExportName */); @@ -26348,13 +26372,7 @@ ${lanes.join("\n")} return node.kind === 358 /* NotEmittedStatement */; } function isSyntheticReference(node) { - return node.kind === 363 /* SyntheticReferenceExpression */; - } - function isMergeDeclarationMarker(node) { - return node.kind === 361 /* MergeDeclarationMarker */; - } - function isEndOfDeclarationMarker(node) { - return node.kind === 362 /* EndOfDeclarationMarker */; + return node.kind === 361 /* SyntheticReferenceExpression */; } function isExternalModuleReference(node) { return node.kind === 282 /* ExternalModuleReference */; @@ -29670,8 +29688,13 @@ ${lanes.join("\n")} return tokenIsIdentifierOrKeyword(token()) || token() === 19 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; + case 25 /* JSDocComment */: + return true; + case 26 /* Count */: + return Debug.fail("ParsingContext.Count used as a context"); + default: + Debug.assertNever(parsingContext2, "Non-exhaustive case in 'isListElement'."); } - return Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { Debug.assert(token() === 19 /* OpenBraceToken */); @@ -29765,7 +29788,8 @@ ${lanes.join("\n")} return false; } function isInSomeParsingContext() { - for (let kind = 0; kind < 25 /* Count */; kind++) { + Debug.assert(parsingContext, "Missing parsing context"); + for (let kind = 0; kind < 26 /* Count */; kind++) { if (parsingContext & 1 << kind) { if (isListElement2( kind, @@ -30024,7 +30048,9 @@ ${lanes.join("\n")} return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); case 24 /* AssertEntries */: return parseErrorAtCurrentToken(Diagnostics.Identifier_or_string_literal_expected); - case 25 /* Count */: + case 25 /* JSDocComment */: + return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); + case 26 /* Count */: return Debug.fail("ParsingContext.Count used as a context"); default: Debug.assertNever(context); @@ -32075,7 +32101,11 @@ ${lanes.join("\n")} } function parseJsxElementName() { const pos = getNodePos(); - let expression = parseJsxTagName(); + const initialExpression = parseJsxTagName(); + if (isJsxNamespacedName(initialExpression)) { + return initialExpression; + } + let expression = initialExpression; while (parseOptional(25 /* DotToken */)) { expression = finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot( /*allowIdentifierNames*/ @@ -33605,11 +33635,11 @@ ${lanes.join("\n")} } function parseClassElement() { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); if (token() === 27 /* SemicolonToken */) { nextToken(); - return finishNode(factory2.createSemicolonClassElement(), pos); + return withJSDoc(finishNode(factory2.createSemicolonClassElement(), pos), hasJSDoc); } - const hasJSDoc = hasPrecedingJSDocComment(); const modifiers = parseModifiers( /*allowDecorators*/ true, @@ -34156,7 +34186,8 @@ ${lanes.join("\n")} ParsingContext2[ParsingContext2["HeritageClauses"] = 22] = "HeritageClauses"; ParsingContext2[ParsingContext2["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; ParsingContext2[ParsingContext2["AssertEntries"] = 24] = "AssertEntries"; - ParsingContext2[ParsingContext2["Count"] = 25] = "Count"; + ParsingContext2[ParsingContext2["JSDocComment"] = 25] = "JSDocComment"; + ParsingContext2[ParsingContext2["Count"] = 26] = "Count"; })(ParsingContext || (ParsingContext = {})); let Tristate; ((Tristate2) => { @@ -34278,6 +34309,8 @@ ${lanes.join("\n")} PropertyLikeParse2[PropertyLikeParse2["CallbackParameter"] = 4] = "CallbackParameter"; })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start = 0, length2) { + const saveParsingContext = parsingContext; + parsingContext |= 1 << 25 /* JSDocComment */; const content = sourceText; const end = length2 === void 0 ? content.length : start + length2; length2 = end - start; @@ -34294,7 +34327,10 @@ ${lanes.join("\n")} let commentsPos; let comments = []; const parts = []; - return scanner2.scanRange(start + 3, length2 - 5, () => { + const result = scanner2.scanRange(start + 3, length2 - 5, doJSDocScan); + parsingContext = saveParsingContext; + return result; + function doJSDocScan() { let state = 1 /* SawAsterisk */; let margin; let indent2 = start - (content.lastIndexOf("\n", start) + 1) + 4; @@ -34390,7 +34426,7 @@ ${lanes.join("\n")} Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); const tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); return finishNode(factory2.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : trimmedComments.length ? trimmedComments : void 0, tagsArray), start, end); - }); + } function removeLeadingNewlines(comments2) { while (comments2.length && (comments2[0] === "\n" || comments2[0] === "\r")) { comments2.shift(); @@ -34749,8 +34785,8 @@ ${lanes.join("\n")} typeExpression = nestedTypeLiteral; isNameFirst = true; } - const result = target === 1 /* Property */ ? factory2.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) : factory2.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment); - return finishNode(result, start2); + const result2 = target === 1 /* Property */ ? factory2.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) : factory2.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment); + return finishNode(result2, start2); } function parseNestedTypeLiteral(typeExpression, name, target, indent2) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { @@ -34760,6 +34796,8 @@ ${lanes.join("\n")} while (child = tryParse(() => parseChildParameterOrPropertyTag(target, indent2, name))) { if (child.kind === 347 /* JSDocParameterTag */ || child.kind === 354 /* JSDocPropertyTag */) { children = append(children, child); + } else if (child.kind === 351 /* JSDocTemplateTag */) { + parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag); } } if (children) { @@ -34847,7 +34885,9 @@ ${lanes.join("\n")} const usedBrace = parseOptional(19 /* OpenBraceToken */); const pos = getNodePos(); const expression = parsePropertyAccessEntityNameExpression(); + scanner2.setInJSDocType(true); const typeArguments = tryParseTypeArguments(); + scanner2.setInJSDocType(false); const node = factory2.createExpressionWithTypeArguments(expression, typeArguments); const res = finishNode(node, pos); if (usedBrace) { @@ -34896,6 +34936,9 @@ ${lanes.join("\n")} let jsDocPropertyTags; let hasChildren = false; while (child = tryParse(() => parseChildPropertyTag(indent2))) { + if (child.kind === 351 /* JSDocTemplateTag */) { + break; + } hasChildren = true; if (child.kind === 350 /* JSDocTypeTag */) { if (childTypeTag) { @@ -34955,6 +34998,10 @@ ${lanes.join("\n")} let child; let parameters; while (child = tryParse(() => parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent2))) { + if (child.kind === 351 /* JSDocTemplateTag */) { + parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag); + break; + } parameters = append(parameters, child); } return createNodeArray(parameters || [], pos); @@ -35049,7 +35096,7 @@ ${lanes.join("\n")} const start2 = scanner2.getTokenFullStart(); nextTokenJSDoc(); const tagName = parseJSDocIdentifierName(); - skipWhitespace(); + const indentText = skipWhitespaceOrAsterisk(); let t; switch (tagName.escapedText) { case "type": @@ -35063,6 +35110,8 @@ ${lanes.join("\n")} case "param": t = 2 /* Parameter */ | 4 /* CallbackParameter */; break; + case "template": + return parseTemplateTag(start2, tagName, indent2, indentText); default: return false; } @@ -35150,9 +35199,9 @@ ${lanes.join("\n")} const end2 = scanner2.getTokenEnd(); const originalKeywordKind = token(); const text = internIdentifier(scanner2.getTokenValue()); - const result = finishNode(factoryCreateIdentifier(text, originalKeywordKind), start2, end2); + const result2 = finishNode(factoryCreateIdentifier(text, originalKeywordKind), start2, end2); nextTokenJSDoc(); - return result; + return result2; } } })(JSDocParser = Parser2.JSDocParser || (Parser2.JSDocParser = {})); @@ -36274,8 +36323,8 @@ ${lanes.join("\n")} result.push(`${tab}${tab}/* ${getLocaleSpecificMessage(Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_to_read_more_about_this_file)} */`); result.push(""); for (const entry of entries) { - const { value, description: description2 = "" } = entry; - result.push(value && `${tab}${tab}${value}${description2 && makePadding(marginLength - value.length + 2) + description2}`); + const { value, description: description3 = "" } = entry; + result.push(value && `${tab}${tab}${value}${description3 && makePadding(marginLength - value.length + 2) + description3}`); } if (fileNames.length) { result.push(`${tab}},`); @@ -39501,13 +39550,12 @@ ${lanes.join("\n")} nonRelativeNameResolutionCache.update(options2); } } - function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) { + function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, packageJsonInfoCache) { const result = createModuleOrTypeReferenceResolutionCache( currentDirectory, getCanonicalFileName, options, - /*packageJsonInfoCache*/ - void 0, + packageJsonInfoCache, getOriginalOrResolvedModuleFileName ); result.getOrCreateCacheForModuleName = (nonRelativeName, mode, redirectedReference) => result.getOrCreateCacheForNonRelativeName(nonRelativeName, mode, redirectedReference); @@ -39522,6 +39570,12 @@ ${lanes.join("\n")} getOriginalOrResolvedTypeReferenceFileName ); } + function getOptionsForLibraryResolution(options) { + return { moduleResolution: 2 /* Node10 */, traceResolution: options.traceResolution }; + } + function resolveLibrary(libraryName, resolveFrom, compilerOptions, host, cache) { + return resolveModuleName(libraryName, resolveFrom, getOptionsForLibraryResolution(compilerOptions), host, cache); + } function resolveModuleNameFromCache(moduleName, containingFile, cache, mode) { const containingDirectory = getDirectoryPath(containingFile); return cache.getFromDirectoryCache( @@ -39877,8 +39931,6 @@ ${lanes.join("\n")} const diagnosticState = { ...state, features: state.features & ~8 /* Exports */, - failedLookupLocations: [], - affectingLocations: [], reportDiagnostic: noop }; const diagnosticResult = tryResolve(extensions & (1 /* TypeScript */ | 4 /* Declaration */), diagnosticState); @@ -39918,6 +39970,12 @@ ${lanes.join("\n")} resolved2 = loadModuleFromSelfNameReference(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); } if (!resolved2) { + if (moduleName.indexOf(":") > -1) { + if (traceEnabled) { + trace(host, Diagnostics.Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); + } + return void 0; + } if (traceEnabled) { trace(host, Diagnostics.Loading_module_0_from_node_modules_folder_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); } @@ -40003,22 +40061,22 @@ ${lanes.join("\n")} function pathContainsNodeModules(path) { return stringContains(path, nodeModulesPathPart); } - function parseNodeModuleFromPath(resolved) { + function parseNodeModuleFromPath(resolved, isFolder) { const path = normalizePath(resolved); const idx = path.lastIndexOf(nodeModulesPathPart); if (idx === -1) { return void 0; } const indexAfterNodeModules = idx + nodeModulesPathPart.length; - let indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + let indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules, isFolder); if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { - indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName, isFolder); } return path.slice(0, indexAfterPackageName); } - function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex, isFolder) { const nextSeparatorIndex = path.indexOf(directorySeparator, prevSeparatorIndex + 1); - return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + return nextSeparatorIndex === -1 ? isFolder ? path.length : prevSeparatorIndex : nextSeparatorIndex; } function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); @@ -40950,7 +41008,7 @@ ${lanes.join("\n")} return withPackageId(packageInfo, fromDirectory); } const loader = (extensions2, candidate2, onlyRecordFailures, state2) => { - let pathAndExtension = loadModuleFromFile(extensions2, candidate2, onlyRecordFailures, state2) || loadNodeModuleFromDirectoryWorker( + let pathAndExtension = (rest || !(state2.features & 32 /* EsmMode */)) && loadModuleFromFile(extensions2, candidate2, onlyRecordFailures, state2) || loadNodeModuleFromDirectoryWorker( extensions2, candidate2, onlyRecordFailures, @@ -41402,7 +41460,7 @@ ${lanes.join("\n")} var inStrictMode; var inAssignmentPattern = false; var symbolCount = 0; - var Symbol46; + var Symbol47; var classifiableNames; var unreachableFlow = { flags: 1 /* Unreachable */ }; var reportedUnreachableFlow = { flags: 1 /* Unreachable */ }; @@ -41419,7 +41477,7 @@ ${lanes.join("\n")} inStrictMode = bindInStrictMode(file, opts); classifiableNames = /* @__PURE__ */ new Set(); symbolCount = 0; - Symbol46 = objectAllocator.getSymbolConstructor(); + Symbol47 = objectAllocator.getSymbolConstructor(); Debug.attachFlowNodeDebugInfo(unreachableFlow); Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { @@ -41467,7 +41525,7 @@ ${lanes.join("\n")} } function createSymbol(flags, name) { symbolCount++; - return new Symbol46(flags, name); + return new Symbol47(flags, name); } function addDeclarationToSymbol(symbol, node, symbolFlags) { symbol.flags |= symbolFlags; @@ -41516,7 +41574,7 @@ ${lanes.join("\n")} return getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText); } if (isJsxNamespacedName(name)) { - return getEscapedTextOfJsxAttributeName(name); + return getEscapedTextOfJsxNamespacedName(name); } return isPropertyNameLiteral(name) ? getEscapedTextOfIdentifierOrLiteral(name) : void 0; } @@ -44304,15 +44362,16 @@ ${lanes.join("\n")} if (getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */) { return preferredEnding === 2 /* JsExtension */ ? [2 /* JsExtension */, 1 /* Index */] : [1 /* Index */, 2 /* JsExtension */]; } + const allowImportingTsExtension = shouldAllowImportingTsExtension(compilerOptions, importingSourceFile.fileName); switch (preferredEnding) { case 2 /* JsExtension */: - return [2 /* JsExtension */, 0 /* Minimal */, 1 /* Index */]; + return allowImportingTsExtension ? [2 /* JsExtension */, 3 /* TsExtension */, 0 /* Minimal */, 1 /* Index */] : [2 /* JsExtension */, 0 /* Minimal */, 1 /* Index */]; case 3 /* TsExtension */: return [3 /* TsExtension */, 0 /* Minimal */, 2 /* JsExtension */, 1 /* Index */]; case 1 /* Index */: - return [1 /* Index */, 0 /* Minimal */, 2 /* JsExtension */]; + return allowImportingTsExtension ? [1 /* Index */, 0 /* Minimal */, 3 /* TsExtension */, 2 /* JsExtension */] : [1 /* Index */, 0 /* Minimal */, 2 /* JsExtension */]; case 0 /* Minimal */: - return [0 /* Minimal */, 1 /* Index */, 2 /* JsExtension */]; + return allowImportingTsExtension ? [0 /* Minimal */, 1 /* Index */, 3 /* TsExtension */, 2 /* JsExtension */] : [0 /* Minimal */, 1 /* Index */, 2 /* JsExtension */]; default: Debug.assertNever(preferredEnding); } @@ -44508,7 +44567,7 @@ ${lanes.join("\n")} return pathsOnly ? void 0 : relativePath; } const baseDirectory = getNormalizedAbsolutePath(getPathsBasePath(compilerOptions, host) || baseUrl, host.getCurrentDirectory()); - const relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName); + const relativeToBaseUrl = getRelativePathIfInSameVolume(moduleFileName, baseDirectory, getCanonicalFileName); if (!relativeToBaseUrl) { return pathsOnly ? void 0 : relativePath; } @@ -44716,7 +44775,7 @@ ${lanes.join("\n")} for (const { ending, value } of candidates) { if (value.length >= prefix.length + suffix.length && startsWith(value, prefix) && endsWith(value, suffix) && validateEnding({ ending, value })) { const matchedStar = value.substring(prefix.length, value.length - suffix.length); - return key.replace("*", matchedStar); + return pathIsRelative(matchedStar) ? void 0 : key.replace("*", matchedStar); } } } else if (some(candidates, (c) => c.ending !== 0 /* Minimal */ && pattern === c.value) || some(candidates, (c) => c.ending === 0 /* Minimal */ && pattern === c.value && validateEnding(c))) { @@ -44905,7 +44964,10 @@ ${lanes.join("\n")} const mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main || "index.js"; if (isString(mainFileRelative) && !(maybeBlockedByTypesVersions && matchPatternOrExact(tryParsePatterns(versionPaths.paths), mainFileRelative))) { const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (removeFileExtension(mainExportFile) === removeFileExtension(getCanonicalFileName(moduleFileToTry))) { + const canonicalModuleFileToTry = getCanonicalFileName(moduleFileToTry); + if (removeFileExtension(mainExportFile) === removeFileExtension(canonicalModuleFileToTry)) { + return { packageRootPath, moduleFileToTry }; + } else if (packageJsonContent.type !== "module" && !fileExtensionIsOneOf(canonicalModuleFileToTry, extensionsNotSupportingExtensionlessResolution) && startsWith(canonicalModuleFileToTry, mainExportFile) && getDirectoryPath(canonicalModuleFileToTry) === removeTrailingDirectorySeparator(mainExportFile) && removeFileExtension(getBaseFileName(canonicalModuleFileToTry)) === "index") { return { packageRootPath, moduleFileToTry }; } } @@ -44931,7 +44993,7 @@ ${lanes.join("\n")} } function getPathsRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { return mapDefined(rootDirs, (rootDir) => { - const relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + const relativePath = getRelativePathIfInSameVolume(path, rootDir, getCanonicalFileName); return relativePath !== void 0 && isPathRelativeToParent(relativePath) ? void 0 : relativePath; }); } @@ -44943,7 +45005,11 @@ ${lanes.join("\n")} if (fileName === noExtension) { return fileName; } - if (fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".d.cts" /* Dcts */, ".cts" /* Cts */])) { + const jsPriority = allowedEndings.indexOf(2 /* JsExtension */); + const tsPriority = allowedEndings.indexOf(3 /* TsExtension */); + if (fileExtensionIsOneOf(fileName, [".mts" /* Mts */, ".cts" /* Cts */]) && tsPriority !== -1 && tsPriority < jsPriority) { + return fileName; + } else if (fileExtensionIsOneOf(fileName, [".d.mts" /* Dmts */, ".mts" /* Mts */, ".d.cts" /* Dcts */, ".cts" /* Cts */])) { return noExtension + getJSExtensionForFile(fileName, options); } else if (!fileExtensionIsOneOf(fileName, [".d.ts" /* Dts */]) && fileExtensionIsOneOf(fileName, [".ts" /* Ts */]) && stringContains(fileName, ".d.")) { return tryGetRealFileNameForNonJsDeclarationFileName(fileName); @@ -44962,7 +45028,6 @@ ${lanes.join("\n")} case 3 /* TsExtension */: if (isDeclarationFileName(fileName)) { const extensionlessPriority = allowedEndings.findIndex((e) => e === 0 /* Minimal */ || e === 1 /* Index */); - const jsPriority = allowedEndings.indexOf(2 /* JsExtension */); return extensionlessPriority !== -1 && extensionlessPriority < jsPriority ? noExtension : noExtension + getJSExtensionForFile(fileName, options); } return fileName; @@ -45005,7 +45070,7 @@ ${lanes.join("\n")} return void 0; } } - function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { + function getRelativePathIfInSameVolume(path, directoryPath, getCanonicalFileName) { const relativePath = getRelativePathToDirectoryOrUrl( directoryPath, path, @@ -45070,18 +45135,6 @@ ${lanes.join("\n")} return moduleState === 1 /* Instantiated */ || preserveConstEnums && moduleState === 2 /* ConstEnumOnly */; } function createTypeChecker(host) { - var getPackagesMap = memoize(() => { - var map2 = /* @__PURE__ */ new Map(); - host.getSourceFiles().forEach((sf) => { - if (!sf.resolvedModules) - return; - sf.resolvedModules.forEach(({ resolvedModule }) => { - if (resolvedModule == null ? void 0 : resolvedModule.packageId) - map2.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!map2.get(resolvedModule.packageId.name)); - }); - }); - return map2; - }); var deferredDiagnosticsCallbacks = []; var addLazyDiagnostic = (arg) => { deferredDiagnosticsCallbacks.push(arg); @@ -45090,7 +45143,7 @@ ${lanes.join("\n")} var requestedExternalEmitHelperNames = /* @__PURE__ */ new Set(); var requestedExternalEmitHelpers; var externalHelpersModule; - var Symbol46 = objectAllocator.getSymbolConstructor(); + var Symbol47 = objectAllocator.getSymbolConstructor(); var Type27 = objectAllocator.getTypeConstructor(); var Signature15 = objectAllocator.getSignatureConstructor(); var typeCount = 0; @@ -45812,7 +45865,7 @@ ${lanes.join("\n")} getGlobalIterableType: getGlobalAsyncIterableType, getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType, getGlobalGeneratorType: getGlobalAsyncGeneratorType, - resolveIterationType: getAwaitedType, + resolveIterationType: (type, errorNode) => getAwaitedType(type, errorNode, Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member), mustHaveANextMethodDiagnostic: Diagnostics.An_async_iterator_must_have_a_next_method, mustBeAMethodDiagnostic: Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method, mustHaveAValueDiagnostic: Diagnostics.The_type_returned_by_the_0_method_of_an_async_iterator_must_be_a_promise_for_a_type_with_a_value_property @@ -46094,13 +46147,14 @@ ${lanes.join("\n")} return diagnostic; } function isDeprecatedSymbol(symbol) { - if (length(symbol.declarations) > 1) { - const parentSymbol = getParentOfSymbol(symbol); - if (parentSymbol && parentSymbol.flags & 64 /* Interface */) { - return some(symbol.declarations, (d) => !!(getCombinedNodeFlags(d) & 268435456 /* Deprecated */)); - } + const parentSymbol = getParentOfSymbol(symbol); + if (parentSymbol && length(symbol.declarations) > 1) { + return parentSymbol.flags & 64 /* Interface */ ? some(symbol.declarations, isDeprecatedDeclaration2) : every(symbol.declarations, isDeprecatedDeclaration2); } - return !!(getDeclarationNodeFlagsFromSymbol(symbol) & 268435456 /* Deprecated */); + return !!symbol.valueDeclaration && isDeprecatedDeclaration2(symbol.valueDeclaration) || length(symbol.declarations) && every(symbol.declarations, isDeprecatedDeclaration2); + } + function isDeprecatedDeclaration2(declaration) { + return !!(getCombinedNodeFlags(declaration) & 268435456 /* Deprecated */); } function addDeprecatedSuggestion(location, declarations, deprecatedEntity) { const diagnostic = createDiagnosticForNode(location, Diagnostics._0_is_deprecated, deprecatedEntity); @@ -46112,7 +46166,7 @@ ${lanes.join("\n")} } function createSymbol(flags, name, checkFlags) { symbolCount++; - const symbol = new Symbol46(flags | 33554432 /* Transient */, name); + const symbol = new Symbol47(flags | 33554432 /* Transient */, name); symbol.links = new SymbolLinks(); symbol.links.checkFlags = checkFlags || 0 /* None */; return symbol; @@ -46454,7 +46508,7 @@ ${lanes.join("\n")} return true; } if (isUsedInFunctionOrInstanceProperty(usage, declaration)) { - if (getEmitScriptTarget(compilerOptions) === 99 /* ESNext */ && useDefineForClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { + if (getEmitScriptTarget(compilerOptions) >= 9 /* ES2022 */ && useDefineForClassFields && getContainingClass(declaration) && (isPropertyDeclaration(declaration) || isParameterPropertyDeclaration(declaration, declaration.parent))) { return !isPropertyImmediatelyReferencedWithinDeclaration( declaration, usage, @@ -46617,6 +46671,10 @@ ${lanes.join("\n")} if (name === "const" && isConstAssertion(location)) { return void 0; } + if (isModuleDeclaration(location) && lastLocation && location.name === lastLocation) { + lastLocation = location; + location = location.parent; + } if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) { if (result = lookup(location.locals, name, meaning)) { let useResult = true; @@ -46807,6 +46865,11 @@ ${lanes.join("\n")} } } break; + case 280 /* ExportSpecifier */: + if (lastLocation && lastLocation === location.propertyName && location.parent.parent.moduleSpecifier) { + location = location.parent.parent.parent; + } + break; } if (isSelfReferenceLocation(location)) { lastSelfReferenceLocation = location; @@ -46854,7 +46917,7 @@ ${lanes.join("\n")} if (!result) { if (nameNotFoundMessage) { addLazyDiagnostic(() => { - if (!errorLocation || !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217 + if (!errorLocation || errorLocation.parent.kind !== 330 /* 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)) { let suggestion; let suggestedLib; @@ -48407,35 +48470,9 @@ ${lanes.join("\n")} } } function errorOnImplicitAnyModule(isError, errorNode, sourceFile, mode, { packageId, resolvedFileName }, moduleReference) { - var _a, _b; let errorInfo; if (!isExternalModuleNameRelative(moduleReference) && packageId) { - const node10Result = (_b = (_a = sourceFile.resolvedModules) == null ? void 0 : _a.get(moduleReference, mode)) == null ? void 0 : _b.node10Result; - errorInfo = node10Result ? chainDiagnosticMessages( - /*details*/ - void 0, - 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(packageId.name)}` : packageId.name - ) : typesPackageExists(packageId.name) ? chainDiagnosticMessages( - /*details*/ - void 0, - 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, - packageId.name, - mangleScopedPackageName(packageId.name) - ) : packageBundlesTypes(packageId.name) ? chainDiagnosticMessages( - /*details*/ - void 0, - Diagnostics.If_the_0_package_actually_exposes_this_module_try_adding_a_new_declaration_d_ts_file_containing_declare_module_1, - packageId.name, - moduleReference - ) : chainDiagnosticMessages( - /*details*/ - void 0, - 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(packageId.name) - ); + errorInfo = createModuleNotFoundChain(sourceFile, host, moduleReference, mode, packageId.name); } errorOrSuggestion(isError, errorNode, chainDiagnosticMessages( errorInfo, @@ -48444,12 +48481,6 @@ ${lanes.join("\n")} resolvedFileName )); } - function typesPackageExists(packageName) { - return getPackagesMap().has(getTypesPackageName(packageName)); - } - function packageBundlesTypes(packageName) { - return !!getPackagesMap().get(packageName); - } function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) { if (moduleSymbol == null ? void 0 : moduleSymbol.exports) { const exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias); @@ -49612,7 +49643,7 @@ ${lanes.join("\n")} } if (type.flags & 128 /* StringLiteral */) { context.approximateLength += type.value.length + 2; - return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 33554432 /* NoAsciiEscaping */)); + return factory.createLiteralTypeNode(setEmitFlags(factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */)); } if (type.flags & 256 /* NumberLiteral */) { const value = type.value; @@ -50500,7 +50531,7 @@ ${lanes.join("\n")} const typePredicate = getTypePredicateOfSignature(signature); if (typePredicate) { const assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? factory.createToken(131 /* AssertsKeyword */) : void 0; - const parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? setEmitFlags(factory.createIdentifier(typePredicate.parameterName), 33554432 /* NoAsciiEscaping */) : factory.createThisTypeNode(); + const parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? setEmitFlags(factory.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) : factory.createThisTypeNode(); const typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context); returnTypeNode = factory.createTypePredicateNode(assertsModifier, parameterName, typeNode); } else { @@ -50627,7 +50658,7 @@ ${lanes.join("\n")} const modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && canHaveModifiers(parameterDeclaration) ? map(getModifiers(parameterDeclaration), factory.cloneNode) : void 0; const isRest = parameterDeclaration && isRestParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 32768 /* RestParameter */; const dotDotDotToken = isRest ? factory.createToken(26 /* DotDotDotToken */) : void 0; - const name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 80 /* Identifier */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), 33554432 /* NoAsciiEscaping */) : parameterDeclaration.name.kind === 165 /* QualifiedName */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), 33554432 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol); + const name = parameterDeclaration ? parameterDeclaration.name ? parameterDeclaration.name.kind === 80 /* Identifier */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) : parameterDeclaration.name.kind === 165 /* QualifiedName */ ? setEmitFlags(factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) : cloneBindingName(parameterDeclaration.name) : symbolName(parameterSymbol) : symbolName(parameterSymbol); const isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */; const questionToken = isOptional ? factory.createToken(58 /* QuestionToken */) : void 0; const parameterNode = factory.createParameterDeclaration( @@ -50668,7 +50699,7 @@ ${lanes.join("\n")} if (!nodeIsSynthesized(visited)) { visited = factory.cloneNode(visited); } - return setEmitFlags(visited, 1 /* SingleLine */ | 33554432 /* NoAsciiEscaping */); + return setEmitFlags(visited, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */); } } } @@ -50993,7 +51024,7 @@ ${lanes.join("\n")} return factory.createIndexedAccessTypeNode(factory.createTypeReferenceNode(LHS, typeParameterNodes), factory.createLiteralTypeNode(factory.createStringLiteral(symbolName2))); } } - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; @@ -51079,7 +51110,7 @@ ${lanes.join("\n")} if (index === 0) { context.flags ^= 16777216 /* InInitialEntityName */; } - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; @@ -51104,7 +51135,7 @@ ${lanes.join("\n")} return factory.createStringLiteral(getSpecifierForModuleSymbol(symbol2, context)); } if (index === 0 || canUsePropertyAccess(symbolName2, languageVersion)) { - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; @@ -51121,7 +51152,7 @@ ${lanes.join("\n")} expression = factory.createNumericLiteral(+symbolName2); } if (!expression) { - const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 33554432 /* NoAsciiEscaping */); + const identifier = setEmitFlags(factory.createIdentifier(symbolName2), 16777216 /* NoAsciiEscaping */); if (typeParameterNodes) setIdentifierTypeArguments(identifier, factory.createNodeArray(typeParameterNodes)); identifier.symbol = symbol2; @@ -51274,7 +51305,7 @@ ${lanes.join("\n")} const type = getDeclaredTypeOfSymbol(sym); const name = sym.flags & 262144 /* TypeParameter */ && !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration) ? typeParameterToName(type, context) : factory.cloneNode(node); name.symbol = sym; - return { introducesError, node: setEmitFlags(setOriginalNode(name, node), 33554432 /* NoAsciiEscaping */) }; + return { introducesError, node: setEmitFlags(setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */) }; } } return { introducesError, node }; @@ -51717,7 +51748,7 @@ ${lanes.join("\n")} if (symbol.flags & 524288 /* TypeAlias */) { serializeTypeAlias(symbol, symbolName2, modifierFlags); } - if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) && symbol.escapedName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) && !(symbol.flags & 32 /* Class */) && !(symbol.flags & 8192 /* Method */) && !isConstMergedWithNSPrintableAsSignatureMerge) { + if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */ | 98304 /* Accessor */) && symbol.escapedName !== "export=" /* ExportEquals */ && !(symbol.flags & 4194304 /* Prototype */) && !(symbol.flags & 32 /* Class */) && !(symbol.flags & 8192 /* Method */) && !isConstMergedWithNSPrintableAsSignatureMerge) { if (propertyAsAlias) { const createdExport = serializeMaybeAliasAssignment(symbol); if (createdExport) { @@ -52135,7 +52166,7 @@ ${lanes.join("\n")} context.enclosingDeclaration = originalDecl || oldEnclosing; const localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); const typeParamDecls = map(localParams, (p) => typeParameterToDeclaration(p, context)); - const classType = getDeclaredTypeOfClassOrInterface(symbol); + const classType = getTypeWithThisArgument(getDeclaredTypeOfClassOrInterface(symbol)); const baseTypes = getBaseTypes(classType); const originalImplements = originalDecl && getEffectiveImplementsTypeNodes(originalDecl); const implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements) || mapDefined(getImplementsTypes(classType), serializeImplementedType); @@ -53334,7 +53365,7 @@ ${lanes.join("\n")} const elementType = checkIteratedTypeOrElementType(65 /* Destructuring */ | (declaration.dotDotDotToken ? 0 : 128 /* PossiblyOutOfBounds */), parentType, undefinedType, pattern); const index = pattern.elements.indexOf(declaration); if (declaration.dotDotDotToken) { - const baseConstraint = getBaseConstraintOrType(parentType); + const baseConstraint = mapType(parentType, (t) => t.flags & 58982400 /* InstantiableNonPrimitive */ ? getBaseConstraintOrType(t) : t); type = everyType(baseConstraint, isTupleType) ? mapType(baseConstraint, (t) => sliceTupleType(t, index)) : createArrayType(elementType); } else if (isArrayLikeType(parentType)) { const indexType = getNumberLiteralType(index); @@ -55062,6 +55093,9 @@ ${lanes.join("\n")} } return needApparentType ? getApparentType(type) : type; } + function getThisArgument(type) { + return getObjectFlags(type) & 4 /* Reference */ && length(getTypeArguments(type)) > getTypeReferenceArity(type) ? last(getTypeArguments(type)) : type; + } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { let mapper; let members; @@ -55192,7 +55226,7 @@ ${lanes.join("\n")} } return [sig.parameters]; function expandSignatureParametersWithTupleMembers(restType, restIndex) { - const elementTypes = getTypeArguments(restType); + const elementTypes = getElementTypes(restType); const associatedNames = getUniqAssociatedNamesFromTupleType(restType); const restParams = map(elementTypes, (t, i) => { const name = associatedNames && associatedNames[i] ? associatedNames[i] : getParameterNameAtPosition(sig, restIndex + i, restType); @@ -56008,7 +56042,7 @@ ${lanes.join("\n")} } function isConstTypeVariable(type) { var _a; - return !!(type && (type.flags & 262144 /* TypeParameter */ && some((_a = type.symbol) == null ? void 0 : _a.declarations, (d) => hasSyntacticModifier(d, 2048 /* Const */)) || type.flags & 1048576 /* Union */ && some(type.types, isConstTypeVariable) || type.flags & 8388608 /* IndexedAccess */ && isConstTypeVariable(type.objectType) || type.flags & 16777216 /* Conditional */ && isConstTypeVariable(getConstraintOfConditionalType(type)) || type.flags & 33554432 /* Substitution */ && isConstTypeVariable(type.baseType) || isGenericTupleType(type) && findIndex(getTypeArguments(type), (t, i) => !!(type.target.elementFlags[i] & 8 /* Variadic */) && isConstTypeVariable(t)) >= 0)); + return !!(type && (type.flags & 262144 /* TypeParameter */ && some((_a = type.symbol) == null ? void 0 : _a.declarations, (d) => hasSyntacticModifier(d, 2048 /* Const */)) || type.flags & 1048576 /* Union */ && some(type.types, isConstTypeVariable) || type.flags & 8388608 /* IndexedAccess */ && isConstTypeVariable(type.objectType) || type.flags & 16777216 /* Conditional */ && isConstTypeVariable(getConstraintOfConditionalType(type)) || type.flags & 33554432 /* Substitution */ && isConstTypeVariable(type.baseType) || isGenericTupleType(type) && findIndex(getElementTypes(type), (t, i) => !!(type.target.elementFlags[i] & 8 /* Variadic */) && isConstTypeVariable(t)) >= 0)); } function getConstraintOfIndexedAccess(type) { return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : void 0; @@ -56110,7 +56144,7 @@ ${lanes.join("\n")} return void 0; } function getBaseConstraintOfType(type) { - if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) { + if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) || isGenericTupleType(type)) { const constraint = getResolvedBaseConstraint(type); return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : void 0; } @@ -56127,7 +56161,7 @@ ${lanes.join("\n")} return type.resolvedBaseConstraint; } const stack = []; - return type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type); + return type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), getThisArgument(type)); function getImmediateBaseConstraint(t) { if (!t.immediateBaseConstraint) { if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { @@ -56217,6 +56251,13 @@ ${lanes.join("\n")} if (t.flags & 33554432 /* Substitution */) { return getBaseConstraint(getSubstitutionIntersection(t)); } + if (isGenericTupleType(t)) { + const newElements = map(getElementTypes(t), (v, i) => { + const constraint = t.target.elementFlags[i] & 8 /* Variadic */ && getBaseConstraint(v) || v; + return constraint && everyType(constraint, (c) => isArrayOrTupleType(c) && !isGenericTupleType(c)) ? constraint : v; + }); + return createTupleType(newElements, t.target.elementFlags, t.target.readonly, t.target.labeledElementDeclarations); + } return t; } } @@ -56757,7 +56798,8 @@ ${lanes.join("\n")} thisParameter = createSymbolWithType(createSymbol(1 /* FunctionScopedVariable */, "this" /* This */), getTypeFromTypeNode(thisTag.typeExpression)); } } - const classType = declaration.kind === 175 /* Constructor */ ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : void 0; + const hostDeclaration = isJSDocSignature(declaration) ? getEffectiveJSDocHost(declaration) : declaration; + const classType = hostDeclaration && isConstructorDeclaration(hostDeclaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(hostDeclaration.parent.symbol)) : void 0; const typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); if (hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { flags |= 1 /* HasRestParameter */; @@ -56983,16 +57025,16 @@ ${lanes.join("\n")} if (declaration.kind === 175 /* Constructor */) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)); } + const typeNode = getEffectiveReturnTypeNode(declaration); if (isJSDocSignature(declaration)) { const root = getJSDocRoot(declaration); - if (root && isConstructorDeclaration(root.parent)) { + if (root && isConstructorDeclaration(root.parent) && !typeNode) { return getDeclaredTypeOfClassOrInterface(getMergedSymbol(root.parent.parent.symbol)); } } if (isJSDocConstructSignature(declaration)) { return getTypeFromTypeNode(declaration.parameters[0].type); } - const typeNode = getEffectiveReturnTypeNode(declaration); if (typeNode) { return getTypeFromTypeNode(typeNode); } @@ -58270,7 +58312,7 @@ ${lanes.join("\n")} if (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type)) { addElement(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) == null ? void 0 : _a[i]); } else if (isTupleType(type)) { - const elements = getTypeArguments(type); + const elements = getElementTypes(type); if (elements.length + expandedTypes.length >= 1e4) { 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; @@ -58348,6 +58390,11 @@ ${lanes.join("\n")} function getEndElementCount(type, flags) { return type.elementFlags.length - findLastIndex(type.elementFlags, (f) => !(f & flags)) - 1; } + function getElementTypes(type) { + const typeArguments = getTypeArguments(type); + const arity = getTypeReferenceArity(type); + return typeArguments.length === arity ? typeArguments : typeArguments.slice(0, arity); + } function getTypeFromOptionalTypeNode(node) { return addOptionality( getTypeFromTypeNode(node.type), @@ -58944,7 +58991,20 @@ ${lanes.join("\n")} if (isPrivateIdentifier(name)) { return neverType; } - return isIdentifier(name) ? getStringLiteralType(unescapeLeadingUnderscores(name.escapedText)) : getRegularTypeOfLiteralType(isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name)); + if (isNumericLiteral(name)) { + return getRegularTypeOfLiteralType(checkExpression(name)); + } + if (isComputedPropertyName(name)) { + return getRegularTypeOfLiteralType(checkComputedPropertyName(name)); + } + const propertyName = getPropertyNameForPropertyNameNode(name); + if (propertyName !== void 0) { + return getStringLiteralType(unescapeLeadingUnderscores(propertyName)); + } + if (isExpression(name)) { + return getRegularTypeOfLiteralType(checkExpression(name)); + } + return neverType; } function getLiteralTypeFromProperty(prop, include, includeNonPublic) { if (includeNonPublic || !(getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { @@ -59598,7 +59658,7 @@ ${lanes.join("\n")} return isTupleTypeNode(node) && length(node.elements) > 0 && !some(node.elements, (e) => isOptionalTypeNode(e) || isRestTypeNode(e) || isNamedTupleMember(e) && !!(e.questionToken || e.dotDotDotToken)); } function isDeferredType(type, checkTuples) { - return isGenericType(type) || checkTuples && isTupleType(type) && some(getTypeArguments(type), isGenericType); + return isGenericType(type) || checkTuples && isTupleType(type) && some(getElementTypes(type), isGenericType); } function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) { let result; @@ -60533,7 +60593,7 @@ ${lanes.join("\n")} } function instantiateMappedGenericTupleType(tupleType, mappedType, typeVariable, mapper) { const elementFlags = tupleType.target.elementFlags; - const elementTypes = map(getTypeArguments(tupleType), (t, i) => { + const elementTypes = map(getElementTypes(tupleType), (t, i) => { const singleton = elementFlags[i] & 8 /* Variadic */ ? t : elementFlags[i] & 4 /* Rest */ ? createArrayType(t) : createTupleType([t], [elementFlags[i]]); return instantiateMappedType(mappedType, prependTypeMapping(typeVariable, singleton, mapper)); }); @@ -60552,7 +60612,7 @@ ${lanes.join("\n")} } function instantiateMappedTupleType(tupleType, mappedType, mapper) { const elementFlags = tupleType.target.elementFlags; - const elementTypes = map(getTypeArguments(tupleType), (_, i) => instantiateMappedTypeTemplate(mappedType, getStringLiteralType("" + i), !!(elementFlags[i] & 2 /* Optional */), mapper)); + const elementTypes = map(getElementTypes(tupleType), (_, i) => instantiateMappedTypeTemplate(mappedType, getStringLiteralType("" + i), !!(elementFlags[i] & 2 /* Optional */), mapper)); const modifiers = getMappedTypeModifiers(mappedType); const newTupleModifiers = modifiers & 4 /* IncludeOptional */ ? map(elementFlags, (f) => f & 1 /* Required */ ? 2 /* Optional */ : f) : modifiers & 8 /* ExcludeOptional */ ? map(elementFlags, (f) => f & 2 /* Optional */ ? 1 /* Required */ : f) : elementFlags; const newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers); @@ -61738,7 +61798,7 @@ ${lanes.join("\n")} return type; } function getNormalizedTupleType(type, writing) { - const elements = getTypeArguments(type); + const elements = getElementTypes(type); const normalizedElements = sameMap(elements, (t) => t.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(t, writing) : t); return elements !== normalizedElements ? createNormalizedTupleType(type.target, normalizedElements) : type; } @@ -62027,6 +62087,8 @@ ${lanes.join("\n")} return isRelatedTo(source2, target2, 3 /* Both */, reportErrors2); } function isRelatedTo(originalSource, originalTarget, recursionFlags = 3 /* Both */, reportErrors2 = false, headMessage2, intersectionState = 0 /* None */) { + if (originalSource === originalTarget) + return -1 /* True */; if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 402784252 /* Primitive */) { if (relation === comparableRelation && !(originalTarget.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(originalTarget, originalSource, relation) || isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors2 ? reportError : void 0)) { return -1 /* True */; @@ -63245,6 +63307,11 @@ ${lanes.join("\n")} } else { return 0 /* False */; } + } else if (isGenericTupleType(source2) && isTupleType(target2) && !isGenericTupleType(target2)) { + const constraint = getBaseConstraintOrType(source2); + if (constraint !== source2) { + return isRelatedTo(constraint, target2, 1 /* Source */, reportErrors2); + } } else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target2) && getObjectFlags(target2) & 8192 /* FreshLiteral */ && !isEmptyObjectType(source2)) { return 0 /* False */; } @@ -65160,7 +65227,7 @@ ${lanes.join("\n")} return type; } function isPartiallyInferableType(type) { - return !(getObjectFlags(type) & 262144 /* NonInferrableType */) || isObjectLiteralType2(type) && some(getPropertiesOfType(type), (prop) => isPartiallyInferableType(getTypeOfSymbol(prop))) || isTupleType(type) && some(getTypeArguments(type), isPartiallyInferableType); + return !(getObjectFlags(type) & 262144 /* NonInferrableType */) || isObjectLiteralType2(type) && some(getPropertiesOfType(type), (prop) => isPartiallyInferableType(getTypeOfSymbol(prop))) || isTupleType(type) && some(getElementTypes(type), isPartiallyInferableType); } function createReverseMappedType(source, target, constraint) { if (!(getIndexInfoOfType(source, stringType) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) { @@ -65170,7 +65237,7 @@ ${lanes.join("\n")} return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source)); } if (isTupleType(source)) { - const elementTypes = map(getTypeArguments(source), (t) => inferReverseMappedType(t, target, constraint)); + const elementTypes = map(getElementTypes(source), (t) => inferReverseMappedType(t, target, constraint)); const elementFlags = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? sameMap(source.target.elementFlags, (f) => f & 2 /* Optional */ ? 1 /* Required */ : f) : source.target.elementFlags; return createTupleType(elementTypes, elementFlags, source.target.readonly, source.target.labeledElementDeclarations); } @@ -66006,14 +66073,14 @@ ${lanes.join("\n")} const inference = context.inferences[index]; if (!inference.inferredType) { let inferredType; - const signature = context.signature; - if (signature) { - const inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : void 0; - if (inference.contraCandidates) { - const useCovariantType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* 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))); - inferredType = useCovariantType ? inferredCovariantType : getContravariantInference(inference); - } else if (inferredCovariantType) { - inferredType = inferredCovariantType; + let fallbackType; + if (context.signature) { + const inferredCovariantType = inference.candidates ? getCovariantInference(inference, context.signature) : void 0; + const inferredContravariantType = inference.contraCandidates ? getContravariantInference(inference) : void 0; + if (inferredCovariantType || inferredContravariantType) { + const preferCovariantType = inferredCovariantType && (!inferredContravariantType || !(inferredCovariantType.flags & 131072 /* 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)))); + inferredType = preferCovariantType ? inferredCovariantType : inferredContravariantType; + fallbackType = preferCovariantType ? inferredContravariantType : inferredCovariantType; } else if (context.flags & 1 /* NoDefault */) { inferredType = silentNeverType; } else { @@ -66030,7 +66097,7 @@ ${lanes.join("\n")} if (constraint) { const instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper); if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) { - inference.inferredType = inferredType = instantiatedConstraint; + inference.inferredType = fallbackType && context.compareTypes(fallbackType, getTypeWithThisArgument(instantiatedConstraint, fallbackType)) ? fallbackType : instantiatedConstraint; } } } @@ -68250,7 +68317,7 @@ ${lanes.join("\n")} markAliasReferenced(symbol, node); } const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); - const targetSymbol = checkDeprecatedAliasedSymbol(localOrExportSymbol, node); + const targetSymbol = resolveAliasWithDeprecationCheck(localOrExportSymbol, node); if (isDeprecatedSymbol(targetSymbol) && isUncalledFunctionReference(node, targetSymbol) && targetSymbol.declarations) { addDeprecatedSuggestion(node, targetSymbol.declarations, node.escapedText); } @@ -69343,7 +69410,7 @@ ${lanes.join("\n")} return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType2(conditional, contextFlags) : void 0; } function getContextualTypeForChildJsxExpression(node, child, contextFlags) { - const attributesType = getApparentTypeOfContextualType(node.openingElement.tagName, contextFlags); + const attributesType = getApparentTypeOfContextualType(node.openingElement.attributes, contextFlags); const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { return void 0; @@ -69419,6 +69486,7 @@ ${lanes.join("\n")} ); } function discriminateContextualTypeByJSXAttributes(node, contextualType) { + const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); return discriminateTypeByDiscriminableItems( contextualType, concatenate( @@ -69429,7 +69497,14 @@ ${lanes.join("\n")} map( filter(getPropertiesOfType(contextualType), (s) => { var _a; - return !!(s.flags & 16777216 /* Optional */) && !!((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); + if (!(s.flags & 16777216 /* Optional */) || !((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members)) { + return false; + } + const element = node.parent.parent; + if (s.escapedName === jsxChildrenPropertyName && isJsxElement(element) && getSemanticJsxChildren(element.children).length) { + return false; + } + return !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName); }), (s) => [() => undefinedType, s.escapedName] ) @@ -69671,18 +69746,10 @@ ${lanes.join("\n")} function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) { const managedSym = getJsxLibraryManagedAttributes(ns); if (managedSym) { - const declaredManagedType = getDeclaredTypeOfSymbol(managedSym); const ctorType = getStaticTypeOfReferencedJsxConstructor(context); - if (managedSym.flags & 524288 /* TypeAlias */) { - const params = getSymbolLinks(managedSym).typeParameters; - if (length(params) >= 2) { - const args = fillMissingTypeArguments([ctorType, attributesType], params, 2, isInJSFile(context)); - return getTypeAliasInstantiation(managedSym, args); - } - } - if (length(declaredManagedType.typeParameters) >= 2) { - const args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, isInJSFile(context)); - return createTypeReference(declaredManagedType, args); + const result = instantiateAliasOrInterfaceWithDefaults(managedSym, isInJSFile(context), ctorType, attributesType); + if (result) { + return result; } } return attributesType; @@ -70040,7 +70107,7 @@ ${lanes.join("\n")} } return links.immediateTarget; } - function checkObjectLiteral(node, checkMode) { + function checkObjectLiteral(node, checkMode = 0 /* Normal */) { var _a; const inDestructuringPattern = isAssignmentTarget(node); checkGrammarObjectLiteralExpression(node, inDestructuringPattern); @@ -70123,7 +70190,7 @@ ${lanes.join("\n")} prop.links.target = member; member = prop; allPropertiesTable == null ? void 0 : allPropertiesTable.set(prop.escapedName, prop); - if (contextualType && checkMode && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && (memberDecl.kind === 302 /* PropertyAssignment */ || memberDecl.kind === 173 /* MethodDeclaration */) && isContextSensitive(memberDecl)) { + if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && (memberDecl.kind === 302 /* PropertyAssignment */ || memberDecl.kind === 173 /* MethodDeclaration */) && isContextSensitive(memberDecl)) { const inferenceContext = getInferenceContext(node); Debug.assert(inferenceContext); const inferenceNode = memberDecl.kind === 302 /* PropertyAssignment */ ? memberDecl.initializer : memberDecl; @@ -70141,7 +70208,7 @@ ${lanes.join("\n")} hasComputedNumberProperty = false; hasComputedSymbolProperty = false; } - const type = getReducedType(checkExpression(memberDecl.expression)); + const type = getReducedType(checkExpression(memberDecl.expression, checkMode & 2 /* Inferential */)); if (isValidSpreadType(type)) { const mergedType = tryMergeUnionOfObjectTypeAndEmptyObject(type, inConstContext); if (allPropertiesTable) { @@ -70282,7 +70349,7 @@ ${lanes.join("\n")} function checkJsxAttribute(node, checkMode) { return node.initializer ? checkExpressionForMutableLocation(node.initializer, checkMode) : trueType; } - function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) { + function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode = 0 /* Normal */) { const attributes = openingLikeElement.attributes; const contextualType = getContextualType2(attributes, 0 /* None */); const allAttributesTable = strictNullChecks ? createSymbolTable() : void 0; @@ -70317,7 +70384,7 @@ ${lanes.join("\n")} addDeprecatedSuggestion(attributeDecl.name, prop.declarations, attributeDecl.name.escapedText); } } - if (contextualType && checkMode && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && isContextSensitive(attributeDecl)) { + if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && isContextSensitive(attributeDecl)) { const inferenceContext = getInferenceContext(attributes); Debug.assert(inferenceContext); const inferenceNode = attributeDecl.initializer.expression; @@ -70336,7 +70403,7 @@ ${lanes.join("\n")} ); attributesTable = createSymbolTable(); } - const exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode)); + const exprType = getReducedType(checkExpression(attributeDecl.expression, checkMode & 2 /* Inferential */)); if (isTypeAny(exprType)) { hasSpreadAnyType = true; } @@ -70569,6 +70636,9 @@ ${lanes.join("\n")} function getJsxLibraryManagedAttributes(jsxNamespace) { return jsxNamespace && getSymbol2(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */); } + function getJsxElementTypeSymbol(jsxNamespace) { + return jsxNamespace && getSymbol2(jsxNamespace.exports, JsxNames.ElementType, 788968 /* Type */); + } function getJsxElementPropertiesName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace); } @@ -70675,11 +70745,32 @@ ${lanes.join("\n")} } } function getJsxElementTypeTypeAt(location) { - const type = getJsxType(JsxNames.ElementType, location); - if (isErrorType(type)) + const ns = getJsxNamespaceAt(location); + if (!ns) + return void 0; + const sym = getJsxElementTypeSymbol(ns); + if (!sym) + return void 0; + const type = instantiateAliasOrInterfaceWithDefaults(sym, isInJSFile(location)); + if (!type || isErrorType(type)) return void 0; return type; } + function instantiateAliasOrInterfaceWithDefaults(managedSym, inJs, ...typeArguments) { + const declaredManagedType = getDeclaredTypeOfSymbol(managedSym); + if (managedSym.flags & 524288 /* TypeAlias */) { + const params = getSymbolLinks(managedSym).typeParameters; + if (length(params) >= typeArguments.length) { + const args = fillMissingTypeArguments(typeArguments, params, typeArguments.length, inJs); + return length(args) === 0 ? declaredManagedType : getTypeAliasInstantiation(managedSym, args); + } + } + if (length(declaredManagedType.typeParameters) >= typeArguments.length) { + const args = fillMissingTypeArguments(typeArguments, declaredManagedType.typeParameters, typeArguments.length, inJs); + return createTypeReference(declaredManagedType, args); + } + return void 0; + } function getJsxIntrinsicTagNamesAt(location) { const intrinsics = getJsxType(JsxNames.IntrinsicElements, location); return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; @@ -71230,8 +71321,9 @@ ${lanes.join("\n")} addDeprecatedSuggestion(right, [indexInfo.declaration], right.escapedText); } } else { - if (isDeprecatedSymbol(prop) && isUncalledFunctionReference(node, prop) && prop.declarations) { - addDeprecatedSuggestion(right, prop.declarations, right.escapedText); + const targetPropSymbol = resolveAliasWithDeprecationCheck(prop, right); + if (isDeprecatedSymbol(targetPropSymbol) && isUncalledFunctionReference(node, targetPropSymbol) && targetPropSymbol.declarations) { + addDeprecatedSuggestion(right, targetPropSymbol.declarations, right.escapedText); } checkPropertyNotUsedBeforeDeclaration(prop, node, right); markPropertyAsReferenced(prop, node, isSelfTypeAccess(left, parentSymbol)); @@ -71926,7 +72018,7 @@ ${lanes.join("\n")} } function getMutableArrayOrTupleType(type) { return type.flags & 1048576 /* Union */ ? mapType(type, getMutableArrayOrTupleType) : type.flags & 1 /* Any */ || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type : isTupleType(type) ? createTupleType( - getTypeArguments(type), + getElementTypes(type), type.target.elementFlags, /*readonly*/ false, @@ -72042,7 +72134,7 @@ ${lanes.join("\n")} if (getJsxNamespaceContainerForImplicitImport(node)) { return true; } - const tagType = isJsxOpeningElement(node) || isJsxSelfClosingElement(node) && !isJsxIntrinsicTagName(node.tagName) ? checkExpression(node.tagName) : void 0; + const tagType = (isJsxOpeningElement(node) || isJsxSelfClosingElement(node)) && !(isJsxIntrinsicTagName(node.tagName) || isJsxNamespacedName(node.tagName)) ? checkExpression(node.tagName) : void 0; if (!tagType) { return true; } @@ -72240,7 +72332,7 @@ ${lanes.join("\n")} const arg = args[i]; const spreadType = arg.kind === 229 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression)); if (spreadType && isTupleType(spreadType)) { - forEach(getTypeArguments(spreadType), (t, i2) => { + forEach(getElementTypes(spreadType), (t, i2) => { var _a; const flags = spreadType.target.elementFlags[i2]; const syntheticArg = createSyntheticExpression( @@ -73767,6 +73859,8 @@ ${lanes.join("\n")} } return getRegularTypeOfLiteralType(exprType); } + const links = getNodeLinks(node); + links.assertionExpressionType = exprType; checkSourceElement(type); checkNodeDeferred(node); return getTypeFromTypeNode(type); @@ -73788,9 +73882,11 @@ ${lanes.join("\n")} return { type, expression }; } function checkAssertionDeferred(node) { - const { type, expression } = getAssertionTypeAndExpression(node); + const { type } = getAssertionTypeAndExpression(node); const errNode = isParenthesizedExpression(node) ? type : node; - const exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(checkExpression(expression))); + const links = getNodeLinks(node); + Debug.assertIsDefined(links.assertionExpressionType); + const exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(links.assertionExpressionType)); const targetType = getTypeFromTypeNode(type); if (!isErrorType(targetType)) { addLazyDiagnostic(() => { @@ -74754,6 +74850,10 @@ ${lanes.join("\n")} forEachReturnStatement(func.body, (returnStatement) => { const expr = returnStatement.expression; if (expr) { + if (expr.kind === 212 /* CallExpression */ && expr.expression.kind === 80 /* Identifier */ && checkExpressionCached(expr.expression).symbol === func.symbol) { + hasReturnOfTypeNever = true; + return; + } let type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */); if (functionFlags & 2 /* Async */) { type = unwrapAwaitedType(checkAwaitedType( @@ -76234,7 +76334,7 @@ ${lanes.join("\n")} } function padTupleType(type, pattern) { const patternElements = pattern.elements; - const elementTypes = getTypeArguments(type).slice(); + const elementTypes = getElementTypes(type).slice(); const elementFlags = type.target.elementFlags.slice(); for (let i = getTypeReferenceArity(type); i < patternElements.length; i++) { const e = patternElements[i]; @@ -81507,19 +81607,17 @@ ${lanes.join("\n")} } } if (isImportSpecifier(node)) { - const targetSymbol = checkDeprecatedAliasedSymbol(symbol, node); - if (isDeprecatedAliasedSymbol(targetSymbol) && targetSymbol.declarations) { + const targetSymbol = resolveAliasWithDeprecationCheck(symbol, node); + if (isDeprecatedSymbol(targetSymbol) && targetSymbol.declarations) { addDeprecatedSuggestion(node, targetSymbol.declarations, targetSymbol.escapedName); } } } } - function isDeprecatedAliasedSymbol(symbol) { - return !!symbol.declarations && every(symbol.declarations, (d) => !!(getCombinedNodeFlags(d) & 268435456 /* Deprecated */)); - } - function checkDeprecatedAliasedSymbol(symbol, location) { - if (!(symbol.flags & 2097152 /* Alias */)) + function resolveAliasWithDeprecationCheck(symbol, location) { + if (!(symbol.flags & 2097152 /* Alias */) || isDeprecatedSymbol(symbol) || !getDeclarationOfAliasSymbol(symbol)) { return symbol; + } const targetSymbol = resolveAlias(symbol); if (targetSymbol === unknownSymbol) return targetSymbol; @@ -81529,7 +81627,7 @@ ${lanes.join("\n")} if (target === targetSymbol) break; if (target.declarations && length(target.declarations)) { - if (isDeprecatedAliasedSymbol(target)) { + if (isDeprecatedSymbol(target)) { addDeprecatedSuggestion(location, target.declarations, target.escapedName); break; } else { @@ -82622,7 +82720,7 @@ ${lanes.join("\n")} name, meaning, /*ignoreErrors*/ - false, + true, /*dontResolveAlias*/ true, getHostSignatureFromJSDoc(name) @@ -82633,7 +82731,7 @@ ${lanes.join("\n")} return resolveJSDocMemberName( name, /*ignoreErrors*/ - false, + true, getSymbolOfDeclaration(container) ); } @@ -83486,6 +83584,41 @@ ${lanes.join("\n")} } return void 0; } + function getReferencedValueDeclarations(referenceIn) { + if (!isGeneratedIdentifier(referenceIn)) { + const reference = getParseTreeNode(referenceIn, isIdentifier); + if (reference) { + const symbol = getReferencedValueSymbol(reference); + if (symbol) { + return filter(getExportSymbolOfValueSymbolIfExported(symbol).declarations, (declaration) => { + switch (declaration.kind) { + case 259 /* VariableDeclaration */: + case 168 /* Parameter */: + case 207 /* BindingElement */: + case 171 /* PropertyDeclaration */: + case 302 /* PropertyAssignment */: + case 303 /* ShorthandPropertyAssignment */: + case 305 /* EnumMember */: + case 209 /* ObjectLiteralExpression */: + case 261 /* FunctionDeclaration */: + case 217 /* FunctionExpression */: + case 218 /* ArrowFunction */: + case 262 /* ClassDeclaration */: + case 230 /* ClassExpression */: + case 265 /* EnumDeclaration */: + case 173 /* MethodDeclaration */: + case 176 /* GetAccessor */: + case 177 /* SetAccessor */: + case 266 /* ModuleDeclaration */: + return true; + } + return false; + }); + } + } + } + return void 0; + } function isLiteralConstDeclaration(node) { if (isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node)) { return isFreshLiteralType(getTypeOfSymbol(getSymbolOfDeclaration(node))); @@ -83584,6 +83717,7 @@ ${lanes.join("\n")} }, collectLinkedAliases, getReferencedValueDeclaration, + getReferencedValueDeclarations, getTypeReferenceSerializationKind, isOptionalParameter, moduleExportsSomeValue, @@ -87765,7 +87899,7 @@ ${lanes.join("\n")} case 242 /* VariableStatement */: if (hasSyntacticModifier(node, 1 /* Export */)) { for (const decl of node.declarationList.declarations) { - exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); + exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings); } } break; @@ -87827,11 +87961,11 @@ ${lanes.join("\n")} } } } - function collectExportedVariableInfo(decl, uniqueExports, exportedNames) { + function collectExportedVariableInfo(decl, uniqueExports, exportedNames, exportedBindings) { if (isBindingPattern(decl.name)) { for (const element of decl.name.elements) { if (!isOmittedExpression(element)) { - exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); + exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames, exportedBindings); } } } else if (!isGeneratedIdentifier(decl.name)) { @@ -87839,6 +87973,9 @@ ${lanes.join("\n")} if (!uniqueExports.get(text)) { uniqueExports.set(text, true); exportedNames = append(exportedNames, decl.name); + if (isLocalName(decl.name)) { + multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), decl.name); + } } } return exportedNames; @@ -88982,7 +89119,7 @@ ${lanes.join("\n")} if (promoteToIIFE) { context.startLexicalEnvironment(); } - const moveModifiers = promoteToIIFE || facts & 8 /* IsExportOfNamespace */ || facts & 2 /* HasClassOrConstructorParameterDecorators */ && legacyDecorators || facts & 1 /* HasStaticInitializedProperties */; + const moveModifiers = promoteToIIFE || facts & 8 /* IsExportOfNamespace */; let modifiers = moveModifiers ? visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike) : visitNodes2(node.modifiers, visitor, isModifierLike); if (facts & 2 /* HasClassOrConstructorParameterDecorators */) { modifiers = injectClassTypeMetadata(modifiers, node); @@ -89048,13 +89185,13 @@ ${lanes.join("\n")} } if (moveModifiers) { if (facts & 8 /* IsExportOfNamespace */) { - return demarcateMultiStatementExport( + return [ statement, createExportMemberAssignmentStatement(node) - ); + ]; } if (facts & 32 /* IsDefaultExternalExport */) { - return demarcateMultiStatementExport( + return [ statement, factory2.createExportDefault(factory2.getLocalName( node, @@ -89063,10 +89200,10 @@ ${lanes.join("\n")} /*allowSourceMaps*/ true )) - ); + ]; } if (facts & 16 /* IsNamedExternalExport */ && !promoteToIIFE) { - return demarcateMultiStatementExport( + return [ statement, factory2.createExternalModuleExport(factory2.getLocalName( node, @@ -89075,19 +89212,11 @@ ${lanes.join("\n")} /*allowSourceMaps*/ true )) - ); + ]; } } return statement; } - function demarcateMultiStatementExport(declarationStatement, exportStatement) { - addEmitFlags(declarationStatement, 8388608 /* HasEndOfDeclarationMarker */); - return [ - declarationStatement, - exportStatement, - factory2.createEndOfDeclarationMarker(declarationStatement) - ]; - } function visitClassExpression(node) { let modifiers = visitNodes2(node.modifiers, modifierElidingVisitor, isModifierLike); if (classOrConstructorParameterIsDecorated(legacyDecorators, node)) { @@ -89705,14 +89834,14 @@ ${lanes.join("\n")} } const parameterName = getNamespaceParameterName(node); const containerName = getNamespaceContainerName(node); - const exportName = hasSyntacticModifier(node, 1 /* Export */) ? factory2.getExternalModuleOrNamespaceExportName( + const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName( currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true - ) : factory2.getLocalName( + ) : factory2.getDeclarationName( node, /*allowComments*/ false, @@ -89726,7 +89855,7 @@ ${lanes.join("\n")} factory2.createObjectLiteralExpression() ) ); - if (hasNamespaceQualifiedExportName(node)) { + if (isExportOfNamespace(node)) { const localName = factory2.getLocalName( node, /*allowComments*/ @@ -89771,7 +89900,6 @@ ${lanes.join("\n")} setTextRange(enumStatement, node); addEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); - statements.push(factory2.createEndOfDeclarationMarker(node)); return statements; } function transformEnumBody(node, localName) { @@ -89844,9 +89972,6 @@ ${lanes.join("\n")} } return isInstantiatedModule(node, shouldPreserveConstEnums(compilerOptions)); } - function hasNamespaceQualifiedExportName(node) { - return isExportOfNamespace(node) || isExternalModuleExport(node) && moduleKind !== 5 /* ES2015 */ && moduleKind !== 6 /* ES2020 */ && moduleKind !== 7 /* ES2022 */ && moduleKind !== 99 /* ESNext */ && moduleKind !== 4 /* System */; - } function recordEmittedDeclarationInScope(node) { if (!currentScopeFirstDeclarationsOfName) { currentScopeFirstDeclarationsOfName = /* @__PURE__ */ new Map(); @@ -89868,20 +89993,21 @@ ${lanes.join("\n")} return node.name.escapedText; } function addVarForEnumOrModuleDeclaration(statements, node) { + const varDecl = factory2.createVariableDeclaration(factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + )); + const varFlags = currentLexicalScope.kind === 311 /* SourceFile */ ? 0 /* None */ : 1 /* Let */; const statement = factory2.createVariableStatement( visitNodes2(node.modifiers, modifierVisitor, isModifier), - factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - factory2.getLocalName( - node, - /*allowComments*/ - false, - /*allowSourceMaps*/ - true - ) - ) - ], currentLexicalScope.kind === 311 /* SourceFile */ ? 0 /* None */ : 1 /* Let */) + factory2.createVariableDeclarationList([varDecl], varFlags) ); + setOriginalNode(varDecl, node); + setSyntheticLeadingComments(varDecl, void 0); + setSyntheticTrailingComments(varDecl, void 0); setOriginalNode(statement, node); recordEmittedDeclarationInScope(node); if (isFirstEmittedDeclarationInScope(node)) { @@ -89891,15 +90017,11 @@ ${lanes.join("\n")} setSourceMapRange(statement, node); } setCommentRange(statement, node); - addEmitFlags(statement, 2048 /* NoTrailingComments */ | 8388608 /* HasEndOfDeclarationMarker */); + addEmitFlags(statement, 2048 /* NoTrailingComments */); statements.push(statement); return true; - } else { - const mergeMarker = factory2.createMergeDeclarationMarker(statement); - setEmitFlags(mergeMarker, 3072 /* NoComments */ | 8388608 /* HasEndOfDeclarationMarker */); - statements.push(mergeMarker); - return false; } + return false; } function visitModuleDeclaration(node) { if (!shouldEmitModuleDeclaration(node)) { @@ -89917,14 +90039,14 @@ ${lanes.join("\n")} } const parameterName = getNamespaceParameterName(node); const containerName = getNamespaceContainerName(node); - const exportName = hasSyntacticModifier(node, 1 /* Export */) ? factory2.getExternalModuleOrNamespaceExportName( + const exportName = isExportOfNamespace(node) ? factory2.getExternalModuleOrNamespaceExportName( currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true - ) : factory2.getLocalName( + ) : factory2.getDeclarationName( node, /*allowComments*/ false, @@ -89938,7 +90060,7 @@ ${lanes.join("\n")} factory2.createObjectLiteralExpression() ) ); - if (hasNamespaceQualifiedExportName(node)) { + if (isExportOfNamespace(node)) { const localName = factory2.getLocalName( node, /*allowComments*/ @@ -89983,7 +90105,6 @@ ${lanes.join("\n")} setTextRange(moduleStatement, node); addEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); - statements.push(factory2.createEndOfDeclarationMarker(node)); return statements; } function transformModuleBody(node, namespaceLocalName) { @@ -91577,23 +91698,12 @@ ${lanes.join("\n")} getClassLexicalEnvironment().classThis = node.emitNode.classThis; } } - const modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); + const isExport = hasSyntacticModifier(node, 1 /* Export */); + const isDefault = hasSyntacticModifier(node, 1024 /* Default */); + let modifiers = visitNodes2(node.modifiers, modifierVisitor, isModifier); const heritageClauses = visitNodes2(node.heritageClauses, heritageClauseVisitor, isHeritageClause); const { members, prologue } = transformClassMembers(node); - const classDecl = factory2.updateClassDeclaration( - node, - modifiers, - node.name, - /*typeParameters*/ - void 0, - heritageClauses, - members - ); const statements = []; - if (prologue) { - statements.push(factory2.createExpressionStatement(prologue)); - } - statements.push(classDecl); if (pendingClassReferenceAssignment) { getPendingExpressions().unshift(pendingClassReferenceAssignment); } @@ -91606,6 +91716,35 @@ ${lanes.join("\n")} addPropertyOrClassStaticBlockStatements(statements, staticProperties, factory2.getInternalName(node)); } } + if (statements.length > 0 && isExport && isDefault) { + modifiers = visitNodes2(modifiers, (node2) => isExportOrDefaultModifier(node2) ? void 0 : node2, isModifier); + statements.push(factory2.createExportAssignment( + /*modifiers*/ + void 0, + /*isExportEquals*/ + false, + factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + true + ) + )); + } + const classDecl = factory2.updateClassDeclaration( + node, + modifiers, + node.name, + /*typeParameters*/ + void 0, + heritageClauses, + members + ); + statements.unshift(classDecl); + if (prologue) { + statements.unshift(factory2.createExpressionStatement(prologue)); + } return statements; } function visitClassExpression(node, referencedName) { @@ -93055,10 +93194,6 @@ ${lanes.join("\n")} true, node ) ? transformClassDeclarationWithClassDecorators(node, node.name) : transformClassDeclarationWithoutClassDecorators(node, node.name); - if (statements.length > 1) { - statements.push(factory2.createEndOfDeclarationMarker(node)); - setEmitFlags(statements[0], getEmitFlags(statements[0]) | 8388608 /* HasEndOfDeclarationMarker */); - } return singleOrMany(statements); } function decoratorContainsPrivateIdentifierInExpression(decorator) { @@ -93131,9 +93266,12 @@ ${lanes.join("\n")} return addRange([updated], decorationStatements); } function transformClassDeclarationWithClassDecorators(node, name) { + const isExport = hasSyntacticModifier(node, 1 /* Export */); + const isDefault = hasSyntacticModifier(node, 1024 /* Default */); + const modifiers = visitNodes2(node.modifiers, (node2) => isExportOrDefaultModifier(node2) || isDecorator(node2) ? void 0 : node2, isModifierLike); const location = moveRangePastModifiers(node); const classAlias = getClassAliasIfNeeded(node); - const declName = languageVersion <= 2 /* ES2015 */ ? factory2.getInternalName( + const declName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName( node, /*allowComments*/ false, @@ -93150,9 +93288,21 @@ ${lanes.join("\n")} let members = visitNodes2(node.members, visitor, isClassElement); let decorationStatements = []; ({ members, decorationStatements } = transformDecoratorsOfClassElements(node, members)); + const assignClassAliasInStaticBlock = languageVersion >= 9 /* ES2022 */ && !!classAlias && some(members, (member) => isPropertyDeclaration(member) && hasSyntacticModifier(member, 32 /* Static */) || isClassStaticBlockDeclaration(member)); + if (assignClassAliasInStaticBlock) { + members = setTextRange(factory2.createNodeArray([ + factory2.createClassStaticBlockDeclaration( + factory2.createBlock([ + factory2.createExpressionStatement( + factory2.createAssignment(classAlias, factory2.createThis()) + ) + ]) + ), + ...members + ]), members); + } const classExpression = factory2.createClassExpression( - /*modifiers*/ - void 0, + modifiers, name && isGeneratedIdentifier(name) ? void 0 : name, /*typeParameters*/ void 0, @@ -93161,18 +93311,23 @@ ${lanes.join("\n")} ); setOriginalNode(classExpression, node); setTextRange(classExpression, location); - const statement = factory2.createVariableStatement( - /*modifiers*/ + const varDecl = factory2.createVariableDeclaration( + declName, + /*exclamationToken*/ void 0, + /*type*/ + void 0, + classAlias && !assignClassAliasInStaticBlock ? factory2.createAssignment(classAlias, classExpression) : classExpression + ); + setOriginalNode(varDecl, node); + let varModifiers; + if (isExport && !isDefault) { + varModifiers = factory2.createModifiersFromModifierFlags(1 /* Export */); + } + const statement = factory2.createVariableStatement( + varModifiers, factory2.createVariableDeclarationList([ - factory2.createVariableDeclaration( - declName, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - classAlias ? factory2.createAssignment(classAlias, classExpression) : classExpression - ) + varDecl ], 1 /* Let */) ); setOriginalNode(statement, node); @@ -93181,6 +93336,15 @@ ${lanes.join("\n")} const statements = [statement]; addRange(statements, decorationStatements); addConstructorDecorationStatement(statements, node); + if (isExport && isDefault) { + statements.push(factory2.createExportAssignment( + /*modifiers*/ + void 0, + /*isExportEquals*/ + false, + declName + )); + } return statements; } function visitClassExpression(node) { @@ -93357,13 +93521,13 @@ ${lanes.join("\n")} return void 0; } const classAlias = classAliases && classAliases[getOriginalNodeId(node)]; - const localName = languageVersion <= 2 /* ES2015 */ ? factory2.getInternalName( + const localName = languageVersion < 2 /* ES2015 */ ? factory2.getInternalName( node, /*allowComments*/ false, /*allowSourceMaps*/ true - ) : factory2.getLocalName( + ) : factory2.getDeclarationName( node, /*allowComments*/ false, @@ -93858,7 +94022,15 @@ ${lanes.join("\n")} function transformClassLike(node, className) { var _a; startLexicalEnvironment(); - const classReference = node.name ?? factory2.getGeneratedNameForNode(node); + const classReference = factory2.getLocalName( + node, + /*allowComments*/ + false, + /*allowSourceMaps*/ + false, + /*ignoreAssignedName*/ + true + ); const classInfo2 = createClassInfo(node); const classDefinitionStatements = []; let leadingBlockStatements; @@ -94174,6 +94346,7 @@ ${lanes.join("\n")} void 0, iife ); + setOriginalNode(varDecl, node); const varDecls = factory2.createVariableDeclarationList([varDecl], 1 /* Let */); const statement = factory2.createVariableStatement(modifiers, varDecls); setOriginalNode(statement, node); @@ -96510,10 +96683,7 @@ ${lanes.join("\n")} const exitNonUserCodeExpression = factory2.createAssignment(nonUserCode, factory2.createFalse()); const exitNonUserCodeStatement = factory2.createExpressionStatement(exitNonUserCodeExpression); setSourceMapRange(exitNonUserCodeStatement, node.expression); - const enterNonUserCodeExpression = factory2.createAssignment(nonUserCode, factory2.createTrue()); - const enterNonUserCodeStatement = factory2.createExpressionStatement(enterNonUserCodeExpression); - setSourceMapRange(exitNonUserCodeStatement, node.expression); - const statements = []; + const statements = [iteratorValueStatement, exitNonUserCodeStatement]; const binding = createForOfBindingStatement(factory2, node.initializer, value); statements.push(visitNode(binding, visitor, isStatement)); let bodyLocation; @@ -96526,29 +96696,14 @@ ${lanes.join("\n")} } else { statements.push(statement); } - const body = setEmitFlags( - setTextRange( - factory2.createBlock( - setTextRange(factory2.createNodeArray(statements), statementsLocation), - /*multiLine*/ - true - ), - bodyLocation + return setTextRange( + factory2.createBlock( + setTextRange(factory2.createNodeArray(statements), statementsLocation), + /*multiLine*/ + true ), - 96 /* NoSourceMap */ | 768 /* NoTokenSourceMaps */ + bodyLocation ); - return factory2.createBlock([ - iteratorValueStatement, - exitNonUserCodeStatement, - factory2.createTryStatement( - body, - /*catchClause*/ - void 0, - factory2.createBlock([ - enterNonUserCodeStatement - ]) - ) - ]); } function createDownlevelAwait(expression) { return enclosingFunctionFlags & 1 /* Generator */ ? factory2.createYieldExpression( @@ -96627,7 +96782,7 @@ ${lanes.join("\n")} factory2.createLogicalNot(done) ]), /*incrementor*/ - void 0, + factory2.createAssignment(nonUserCode, factory2.createTrue()), /*statement*/ convertForOfStatementHead(node, getValue, nonUserCode) ), @@ -98921,11 +99076,6 @@ ${lanes.join("\n")} setOriginalNode(exportStatement, statement); statements.push(exportStatement); } - const emitFlags = getEmitFlags(node); - if ((emitFlags & 8388608 /* HasEndOfDeclarationMarker */) === 0) { - statements.push(factory2.createEndOfDeclarationMarker(node)); - setEmitFlags(statement, emitFlags | 8388608 /* HasEndOfDeclarationMarker */); - } return singleOrMany(statements); } function visitClassExpression(node) { @@ -100888,7 +101038,7 @@ ${lanes.join("\n")} ); const callResult = containsYield ? factory2.createYieldExpression( factory2.createToken(42 /* AsteriskToken */), - setEmitFlags(call, 16777216 /* Iterator */) + setEmitFlags(call, 8388608 /* Iterator */) ) : call; return factory2.createExpressionStatement(callResult); } @@ -100903,7 +101053,7 @@ ${lanes.join("\n")} ); const callResult = containsYield ? factory2.createYieldExpression( factory2.createToken(42 /* AsteriskToken */), - setEmitFlags(call, 16777216 /* Iterator */) + setEmitFlags(call, 8388608 /* Iterator */) ) : call; if (isSimpleLoop) { statements.push(factory2.createExpressionStatement(callResult)); @@ -102239,7 +102389,7 @@ ${lanes.join("\n")} const resumeLabel = defineLabel(); const expression = visitNode(node.expression, visitor, isExpression); if (node.asteriskToken) { - const iterator = (getEmitFlags(node.expression) & 16777216 /* Iterator */) === 0 ? setTextRange(emitHelpers().createValuesHelper(expression), node) : expression; + const iterator = (getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0 ? setTextRange(emitHelpers().createValuesHelper(expression), node) : expression; emitYieldStar( iterator, /*location*/ @@ -103793,7 +103943,6 @@ ${lanes.join("\n")} context.enableSubstitution(303 /* ShorthandPropertyAssignment */); context.enableEmitNotification(311 /* SourceFile */); const moduleInfoMap = []; - const deferredExports = []; let currentSourceFile; let currentModuleInfo; const noSubstitution = []; @@ -104212,16 +104361,56 @@ ${lanes.join("\n")} return visitExportDeclaration(node); case 276 /* ExportAssignment */: return visitExportAssignment(node); + case 261 /* FunctionDeclaration */: + return visitFunctionDeclaration(node); + case 262 /* ClassDeclaration */: + return visitClassDeclaration(node); + default: + return topLevelNestedVisitor(node); + } + } + function topLevelNestedVisitor(node) { + switch (node.kind) { case 242 /* VariableStatement */: return visitVariableStatement(node); case 261 /* FunctionDeclaration */: return visitFunctionDeclaration(node); case 262 /* ClassDeclaration */: return visitClassDeclaration(node); - case 361 /* MergeDeclarationMarker */: - return visitMergeDeclarationMarker(node); - case 362 /* EndOfDeclarationMarker */: - return visitEndOfDeclarationMarker(node); + case 247 /* ForStatement */: + return visitForStatement( + node, + /*isTopLevel*/ + true + ); + case 248 /* ForInStatement */: + return visitForInStatement(node); + case 249 /* ForOfStatement */: + return visitForOfStatement(node); + case 245 /* DoStatement */: + return visitDoStatement(node); + case 246 /* WhileStatement */: + return visitWhileStatement(node); + case 255 /* LabeledStatement */: + return visitLabeledStatement(node); + case 253 /* WithStatement */: + return visitWithStatement(node); + case 244 /* IfStatement */: + return visitIfStatement(node); + case 254 /* SwitchStatement */: + return visitSwitchStatement(node); + case 268 /* CaseBlock */: + return visitCaseBlock(node); + case 295 /* CaseClause */: + return visitCaseClause(node); + case 296 /* DefaultClause */: + return visitDefaultClause(node); + case 257 /* TryStatement */: + return visitTryStatement(node); + case 298 /* CatchClause */: + return visitCatchClause(node); + case 240 /* Block */: + return visitBlock(node); default: return visitor(node); } @@ -104232,7 +104421,11 @@ ${lanes.join("\n")} } switch (node.kind) { case 247 /* ForStatement */: - return visitForStatement(node); + return visitForStatement( + node, + /*isTopLevel*/ + false + ); case 243 /* ExpressionStatement */: return visitExpressionStatement(node); case 216 /* ParenthesizedExpression */: @@ -104317,15 +104510,177 @@ ${lanes.join("\n")} } return visitEachChild(node, visitor, context); } - function visitForStatement(node) { + function visitForStatement(node, isTopLevel) { + if (isTopLevel && node.initializer && isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 3 /* BlockScoped */)) { + const exportStatements = appendExportsOfVariableDeclarationList( + /*statements*/ + void 0, + node.initializer, + /*isForInOrOfInitializer*/ + false + ); + if (exportStatements) { + const statements = []; + const varDeclList = visitNode(node.initializer, discardedValueVisitor, isVariableDeclarationList); + const varStatement = factory2.createVariableStatement( + /*modifiers*/ + void 0, + varDeclList + ); + statements.push(varStatement); + addRange(statements, exportStatements); + const condition = visitNode(node.condition, visitor, isExpression); + const incrementor = visitNode(node.incrementor, discardedValueVisitor, isExpression); + const body = visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context); + statements.push(factory2.updateForStatement( + node, + /*initializer*/ + void 0, + condition, + incrementor, + body + )); + return statements; + } + } return factory2.updateForStatement( node, visitNode(node.initializer, discardedValueVisitor, isForInitializer), visitNode(node.condition, visitor, isExpression), visitNode(node.incrementor, discardedValueVisitor, isExpression), - visitIterationBody(node.statement, visitor, context) + visitIterationBody(node.statement, isTopLevel ? topLevelNestedVisitor : visitor, context) ); } + function visitForInStatement(node) { + if (isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 3 /* BlockScoped */)) { + const exportStatements = appendExportsOfVariableDeclarationList( + /*statements*/ + void 0, + node.initializer, + /*isForInOrOfInitializer*/ + true + ); + if (some(exportStatements)) { + const initializer = visitNode(node.initializer, discardedValueVisitor, isForInitializer); + const expression = visitNode(node.expression, visitor, isExpression); + const body = visitIterationBody(node.statement, topLevelNestedVisitor, context); + const mergedBody = isBlock(body) ? factory2.updateBlock(body, [...exportStatements, ...body.statements]) : factory2.createBlock( + [...exportStatements, body], + /*multiLine*/ + true + ); + return factory2.updateForInStatement(node, initializer, expression, mergedBody); + } + } + return factory2.updateForInStatement( + node, + visitNode(node.initializer, discardedValueVisitor, isForInitializer), + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + } + function visitForOfStatement(node) { + if (isVariableDeclarationList(node.initializer) && !(node.initializer.flags & 3 /* BlockScoped */)) { + const exportStatements = appendExportsOfVariableDeclarationList( + /*statements*/ + void 0, + node.initializer, + /*isForInOrOfInitializer*/ + true + ); + const initializer = visitNode(node.initializer, discardedValueVisitor, isForInitializer); + const expression = visitNode(node.expression, visitor, isExpression); + let body = visitIterationBody(node.statement, topLevelNestedVisitor, context); + if (some(exportStatements)) { + body = isBlock(body) ? factory2.updateBlock(body, [...exportStatements, ...body.statements]) : factory2.createBlock( + [...exportStatements, body], + /*multiLine*/ + true + ); + } + return factory2.updateForOfStatement(node, node.awaitModifier, initializer, expression, body); + } + return factory2.updateForOfStatement( + node, + node.awaitModifier, + visitNode(node.initializer, discardedValueVisitor, isForInitializer), + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + } + function visitDoStatement(node) { + return factory2.updateDoStatement( + node, + visitIterationBody(node.statement, topLevelNestedVisitor, context), + visitNode(node.expression, visitor, isExpression) + ); + } + function visitWhileStatement(node) { + return factory2.updateWhileStatement( + node, + visitNode(node.expression, visitor, isExpression), + visitIterationBody(node.statement, topLevelNestedVisitor, context) + ); + } + function visitLabeledStatement(node) { + return factory2.updateLabeledStatement( + node, + node.label, + Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) + ); + } + function visitWithStatement(node) { + return factory2.updateWithStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) + ); + } + function visitIfStatement(node) { + return factory2.updateIfStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)), + visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) + ); + } + function visitSwitchStatement(node) { + return factory2.updateSwitchStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.caseBlock, topLevelNestedVisitor, isCaseBlock)) + ); + } + function visitCaseBlock(node) { + return factory2.updateCaseBlock( + node, + visitNodes2(node.clauses, topLevelNestedVisitor, isCaseOrDefaultClause) + ); + } + function visitCaseClause(node) { + return factory2.updateCaseClause( + node, + visitNode(node.expression, visitor, isExpression), + visitNodes2(node.statements, topLevelNestedVisitor, isStatement) + ); + } + function visitDefaultClause(node) { + return visitEachChild(node, topLevelNestedVisitor, context); + } + function visitTryStatement(node) { + return visitEachChild(node, topLevelNestedVisitor, context); + } + function visitCatchClause(node) { + return factory2.updateCatchClause( + node, + node.variableDeclaration, + Debug.checkDefined(visitNode(node.block, topLevelNestedVisitor, isBlock)) + ); + } + function visitBlock(node) { + node = visitEachChild(node, topLevelNestedVisitor, context); + return node; + } function visitExpressionStatement(node) { return factory2.updateExpressionStatement( node, @@ -104698,12 +105053,7 @@ ${lanes.join("\n")} ) ); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfImportDeclaration(statements, node); - } + statements = appendExportsOfImportDeclaration(statements, node); return singleOrMany(statements); } function createRequireCall2(importNode) { @@ -104784,12 +105134,7 @@ ${lanes.join("\n")} ); } } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfImportEqualsDeclaration(statements, node); - } + statements = appendExportsOfImportEqualsDeclaration(statements, node); return singleOrMany(statements); } function visitExportDeclaration(node) { @@ -104898,31 +105243,14 @@ ${lanes.join("\n")} if (node.isExportEquals) { return void 0; } - let statements; - const original = node.original; - if (original && hasAssociatedEndOfDeclarationMarker(original)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportStatement( - deferredExports[id], - factory2.createIdentifier("default"), - visitNode(node.expression, visitor, isExpression), - /*location*/ - node, - /*allowComments*/ - true - ); - } else { - statements = appendExportStatement( - statements, - factory2.createIdentifier("default"), - visitNode(node.expression, visitor, isExpression), - /*location*/ - node, - /*allowComments*/ - true - ); - } - return singleOrMany(statements); + return createExportStatement( + factory2.createIdentifier("default"), + visitNode(node.expression, visitor, isExpression), + /*location*/ + node, + /*allowComments*/ + true + ); } function visitFunctionDeclaration(node) { let statements; @@ -104958,12 +105286,7 @@ ${lanes.join("\n")} } else { statements = append(statements, visitEachChild(node, visitor, context)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfHoistedDeclaration(statements, node); - } + statements = appendExportsOfHoistedDeclaration(statements, node); return singleOrMany(statements); } function visitClassDeclaration(node) { @@ -104995,12 +105318,7 @@ ${lanes.join("\n")} } else { statements = append(statements, visitEachChild(node, visitor, context)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfHoistedDeclaration(statements, node); - } + statements = appendExportsOfHoistedDeclaration(statements, node); return singleOrMany(statements); } function visitVariableStatement(node) { @@ -105072,12 +105390,7 @@ ${lanes.join("\n")} } else { statements = append(statements, visitEachChild(node, visitor, context)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node); - } else { - statements = appendExportsOfVariableStatement(statements, node); - } + statements = appendExportsOfVariableStatement(statements, node); return singleOrMany(statements); } function createAllExportExpressions(name, value, location) { @@ -105122,25 +105435,6 @@ ${lanes.join("\n")} ); } } - function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 242 /* VariableStatement */) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original); - } - return node; - } - function hasAssociatedEndOfDeclarationMarker(node) { - return (getEmitFlags(node) & 8388608 /* HasEndOfDeclarationMarker */) !== 0; - } - function visitEndOfDeclarationMarker(node) { - const id = getOriginalNodeId(node); - const statements = deferredExports[id]; - if (statements) { - delete deferredExports[id]; - return append(statements, node); - } - return node; - } function appendExportsOfImportDeclaration(statements, decl) { if (currentModuleInfo.exportEquals) { return statements; @@ -105179,25 +105473,33 @@ ${lanes.join("\n")} return appendExportsOfDeclaration(statements, decl); } function appendExportsOfVariableStatement(statements, node) { + return appendExportsOfVariableDeclarationList( + statements, + node.declarationList, + /*isForInOrOfInitializer*/ + false + ); + } + function appendExportsOfVariableDeclarationList(statements, node, isForInOrOfInitializer) { if (currentModuleInfo.exportEquals) { return statements; } - for (const decl of node.declarationList.declarations) { - statements = appendExportsOfBindingElement(statements, decl); + for (const decl of node.declarations) { + statements = appendExportsOfBindingElement(statements, decl, isForInOrOfInitializer); } return statements; } - function appendExportsOfBindingElement(statements, decl) { + function appendExportsOfBindingElement(statements, decl, isForInOrOfInitializer) { if (currentModuleInfo.exportEquals) { return statements; } if (isBindingPattern(decl.name)) { for (const element of decl.name.elements) { if (!isOmittedExpression(element)) { - statements = appendExportsOfBindingElement(statements, element); + statements = appendExportsOfBindingElement(statements, element, isForInOrOfInitializer); } } - } else if (!isGeneratedIdentifier(decl.name)) { + } else if (!isGeneratedIdentifier(decl.name) && (!isVariableDeclaration(decl) || decl.initializer || isForInOrOfInitializer)) { statements = appendExportsOfDeclaration(statements, decl); } return statements; @@ -105468,7 +105770,7 @@ ${lanes.join("\n")} return node; } function substituteBinaryExpression(node) { - if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left) && !isDeclarationNameOfEnumOrNamespace(node.left)) { + if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left)) { const exportedNames = getExports(node.left); if (exportedNames) { let expression = node; @@ -105488,9 +105790,24 @@ ${lanes.join("\n")} } function getExports(name) { if (!isGeneratedIdentifier(name)) { - const valueDeclaration = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); - if (valueDeclaration) { - return currentModuleInfo && currentModuleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]; + const importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + return currentModuleInfo == null ? void 0 : currentModuleInfo.exportedBindings[getOriginalNodeId(importDeclaration)]; + } + const bindingsSet = /* @__PURE__ */ new Set(); + const declarations = resolver.getReferencedValueDeclarations(name); + if (declarations) { + for (const declaration of declarations) { + const bindings = currentModuleInfo == null ? void 0 : currentModuleInfo.exportedBindings[getOriginalNodeId(declaration)]; + if (bindings) { + for (const binding of bindings) { + bindingsSet.add(binding); + } + } + } + if (bindingsSet.size) { + return arrayFrom(bindingsSet); + } } } } @@ -105530,7 +105847,6 @@ ${lanes.join("\n")} context.enableSubstitution(235 /* MetaProperty */); context.enableEmitNotification(311 /* SourceFile */); const moduleInfoMap = []; - const deferredExports = []; const exportFunctionsMap = []; const noSubstitutionMap = []; const contextObjectMap = []; @@ -106003,13 +106319,7 @@ ${lanes.join("\n")} if (node.importClause) { hoistVariableDeclaration(getLocalNameForExternalImport(factory2, node, currentSourceFile)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfImportDeclaration(statements, node); - } - return singleOrMany(statements); + return singleOrMany(appendExportsOfImportDeclaration(statements, node)); } function visitExportDeclaration(node) { Debug.assertIsDefined(node); @@ -106019,37 +106329,19 @@ ${lanes.join("\n")} Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer."); let statements; hoistVariableDeclaration(getLocalNameForExternalImport(factory2, node, currentSourceFile)); - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfImportEqualsDeclaration(statements, node); - } - return singleOrMany(statements); + return singleOrMany(appendExportsOfImportEqualsDeclaration(statements, node)); } function visitExportAssignment(node) { if (node.isExportEquals) { return void 0; } const expression = visitNode(node.expression, visitor, isExpression); - const original = node.original; - if (original && hasAssociatedEndOfDeclarationMarker(original)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportStatement( - deferredExports[id], - factory2.createIdentifier("default"), - expression, - /*allowComments*/ - true - ); - } else { - return createExportStatement( - factory2.createIdentifier("default"), - expression, - /*allowComments*/ - true - ); - } + return createExportStatement( + factory2.createIdentifier("default"), + expression, + /*allowComments*/ + true + ); } function visitFunctionDeclaration(node) { if (hasSyntacticModifier(node, 1 /* Export */)) { @@ -106077,12 +106369,7 @@ ${lanes.join("\n")} } else { hoistedStatements = append(hoistedStatements, visitEachChild(node, visitor, context)); } - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else { - hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); - } + hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node); return void 0; } function visitClassDeclaration(node) { @@ -106111,12 +106398,7 @@ ${lanes.join("\n")} node ) ); - if (hasAssociatedEndOfDeclarationMarker(node)) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node); - } else { - statements = appendExportsOfHoistedDeclaration(statements, node); - } + statements = appendExportsOfHoistedDeclaration(statements, node); return singleOrMany(statements); } function visitVariableStatement(node) { @@ -106125,10 +106407,9 @@ ${lanes.join("\n")} } let expressions; const isExportedDeclaration = hasSyntacticModifier(node, 1 /* Export */); - const isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node); for (const variable of node.declarationList.declarations) { if (variable.initializer) { - expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration)); + expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration)); } else { hoistBindingElement(variable); } @@ -106137,17 +106418,12 @@ ${lanes.join("\n")} if (expressions) { statements = append(statements, setTextRange(factory2.createExpressionStatement(factory2.inlineExpressions(expressions)), node)); } - if (isMarkedDeclaration) { - const id = getOriginalNodeId(node); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration); - } else { - statements = appendExportsOfVariableStatement( - statements, - node, - /*exportSelf*/ - false - ); - } + statements = appendExportsOfVariableStatement( + statements, + node, + /*exportSelf*/ + false + ); return singleOrMany(statements); } function hoistBindingElement(node) { @@ -106198,31 +106474,6 @@ ${lanes.join("\n")} hoistVariableDeclaration(factory2.cloneNode(name)); return isExportedDeclaration ? createExportExpression(name, preventSubstitution(setTextRange(factory2.createAssignment(name, value), location))) : preventSubstitution(setTextRange(factory2.createAssignment(name, value), location)); } - function visitMergeDeclarationMarker(node) { - if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 242 /* VariableStatement */) { - const id = getOriginalNodeId(node); - const isExportedDeclaration = hasSyntacticModifier(node.original, 1 /* Export */); - deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration); - } - return node; - } - function hasAssociatedEndOfDeclarationMarker(node) { - return (getEmitFlags(node) & 8388608 /* HasEndOfDeclarationMarker */) !== 0; - } - function visitEndOfDeclarationMarker(node) { - const id = getOriginalNodeId(node); - const statements = deferredExports[id]; - if (statements) { - delete deferredExports[id]; - return append(statements, node); - } else { - const original = getOriginalNode(node); - if (isModuleOrEnumDeclaration(original)) { - return append(appendExportsOfDeclaration(statements, original), node); - } - } - return node; - } function appendExportsOfImportDeclaration(statements, decl) { if (moduleInfo.exportEquals) { return statements; @@ -106364,6 +106615,8 @@ ${lanes.join("\n")} return visitLabeledStatement(node); case 253 /* WithStatement */: return visitWithStatement(node); + case 244 /* IfStatement */: + return visitIfStatement(node); case 254 /* SwitchStatement */: return visitSwitchStatement(node); case 268 /* CaseBlock */: @@ -106378,10 +106631,6 @@ ${lanes.join("\n")} return visitCatchClause(node); case 240 /* Block */: return visitBlock(node); - case 361 /* MergeDeclarationMarker */: - return visitMergeDeclarationMarker(node); - case 362 /* EndOfDeclarationMarker */: - return visitEndOfDeclarationMarker(node); default: return visitor(node); } @@ -106473,6 +106722,14 @@ ${lanes.join("\n")} Debug.checkDefined(visitNode(node.statement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)) ); } + function visitIfStatement(node) { + return factory2.updateIfStatement( + node, + visitNode(node.expression, visitor, isExpression), + Debug.checkDefined(visitNode(node.thenStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock)), + visitNode(node.elseStatement, topLevelNestedVisitor, isStatement, factory2.liftToBlock) + ); + } function visitSwitchStatement(node) { return factory2.updateSwitchStatement( node, @@ -106787,7 +107044,7 @@ ${lanes.join("\n")} return node; } function substituteBinaryExpression(node) { - if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left) && !isDeclarationNameOfEnumOrNamespace(node.left)) { + if (isAssignmentOperator(node.operatorToken.kind) && isIdentifier(node.left) && !isGeneratedIdentifier(node.left) && !isLocalName(node.left)) { const exportedNames = getExports(node.left); if (exportedNames) { let expression = node; @@ -106807,22 +107064,38 @@ ${lanes.join("\n")} } function getExports(name) { let exportedNames; - if (!isGeneratedIdentifier(name)) { - const valueDeclaration = resolver.getReferencedImportDeclaration(name) || resolver.getReferencedValueDeclaration(name); - if (valueDeclaration) { - const exportContainer = resolver.getReferencedExportContainer( - name, - /*prefixLocals*/ - false - ); - if (exportContainer && exportContainer.kind === 311 /* SourceFile */) { - exportedNames = append(exportedNames, factory2.getDeclarationName(valueDeclaration)); - } - exportedNames = addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]); + const valueDeclaration = getReferencedDeclaration(name); + if (valueDeclaration) { + const exportContainer = resolver.getReferencedExportContainer( + name, + /*prefixLocals*/ + false + ); + if (exportContainer && exportContainer.kind === 311 /* SourceFile */) { + exportedNames = append(exportedNames, factory2.getDeclarationName(valueDeclaration)); } + exportedNames = addRange(exportedNames, moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]); } return exportedNames; } + function getReferencedDeclaration(name) { + if (!isGeneratedIdentifier(name)) { + const importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) + return importDeclaration; + const valueDeclaration = resolver.getReferencedValueDeclaration(name); + if (valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)])) + return valueDeclaration; + const declarations = resolver.getReferencedValueDeclarations(name); + if (declarations) { + for (const declaration of declarations) { + if (declaration !== valueDeclaration && (moduleInfo == null ? void 0 : moduleInfo.exportedBindings[getOriginalNodeId(declaration)])) + return declaration; + } + } + return valueDeclaration; + } + } function preventSubstitution(node) { if (noSubstitution === void 0) noSubstitution = []; @@ -109266,7 +109539,7 @@ ${lanes.join("\n")} } function transformNodes(resolver, host, factory2, options, nodes, transformers, allowDtsFiles) { var _a, _b; - const enabledSyntaxKindFeatures = new Array(364 /* Count */); + const enabledSyntaxKindFeatures = new Array(362 /* Count */); let lexicalEnvironmentVariableDeclarations; let lexicalEnvironmentFunctionDeclarations; let lexicalEnvironmentStatements; @@ -111029,6 +111302,8 @@ ${lanes.join("\n")} return emitJsxSpreadAttribute(node); case 293 /* JsxExpression */: return emitJsxExpression(node); + case 294 /* JsxNamespacedName */: + return emitJsxNamespacedName(node); case 295 /* CaseClause */: return emitCaseClause(node); case 296 /* DefaultClause */: @@ -111124,8 +111399,6 @@ ${lanes.join("\n")} case 353 /* JSDocSeeTag */: return emitJSDocSeeTag(node); case 358 /* NotEmittedStatement */: - case 362 /* EndOfDeclarationMarker */: - case 361 /* MergeDeclarationMarker */: return; } if (isExpression(node)) { @@ -111226,8 +111499,6 @@ ${lanes.join("\n")} return emitJsxSelfClosingElement(node); case 287 /* JsxFragment */: return emitJsxFragment(node); - case 294 /* JsxNamespacedName */: - return emitJsxNamespacedName(node); case 357 /* SyntaxList */: return Debug.fail("SyntaxList should not be printed"); case 358 /* NotEmittedStatement */: @@ -111236,10 +111507,7 @@ ${lanes.join("\n")} return emitPartiallyEmittedExpression(node); case 360 /* CommaListExpression */: return emitCommaList(node); - case 361 /* MergeDeclarationMarker */: - case 362 /* EndOfDeclarationMarker */: - return; - case 363 /* SyntheticReferenceExpression */: + case 361 /* SyntheticReferenceExpression */: return Debug.fail("SyntheticReferenceExpression should not be printed"); } } @@ -113561,7 +113829,7 @@ ${lanes.join("\n")} } } function emitEmbeddedStatement(parent2, node) { - if (isBlock(node) || getEmitFlags(parent2) & 1 /* SingleLine */) { + if (isBlock(node) || getEmitFlags(parent2) & 1 /* SingleLine */ || preserveSourceNewlines && !getLeadingLineTerminatorCount(parent2, node, 0 /* None */)) { writeSpace(); emit(node); } else { @@ -114062,6 +114330,10 @@ ${lanes.join("\n")} if (!canUseSourceFile || getSourceFileOfNode(node) !== getOriginalNode(sourceFile)) { return idText(node); } + } else if (isJsxNamespacedName(node)) { + if (!canUseSourceFile || getSourceFileOfNode(node) !== getOriginalNode(sourceFile)) { + return getTextOfJsxNamespacedName(node); + } } else { Debug.assertNode(node, isLiteralExpression); if (!canUseSourceFile) { @@ -114073,9 +114345,9 @@ ${lanes.join("\n")} function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) { if (node.kind === 11 /* StringLiteral */ && node.textSourceNode) { const textSourceNode = node.textSourceNode; - if (isIdentifier(textSourceNode) || isPrivateIdentifier(textSourceNode) || isNumericLiteral(textSourceNode)) { + if (isIdentifier(textSourceNode) || isPrivateIdentifier(textSourceNode) || isNumericLiteral(textSourceNode) || isJsxNamespacedName(textSourceNode)) { const text = isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode2(textSourceNode); - return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` : neverAsciiEscape || getEmitFlags(node) & 33554432 /* NoAsciiEscaping */ ? `"${escapeString(text)}"` : `"${escapeNonAsciiString(text)}"`; + return jsxAttributeEscape ? `"${escapeJsxAttributeString(text)}"` : neverAsciiEscape || getEmitFlags(node) & 16777216 /* NoAsciiEscaping */ ? `"${escapeString(text)}"` : `"${escapeNonAsciiString(text)}"`; } else { return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape); } @@ -115057,6 +115329,7 @@ ${lanes.join("\n")} // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant getConstantValue: notImplemented, getReferencedValueDeclaration: notImplemented, + getReferencedValueDeclarations: notImplemented, getTypeReferenceSerializationKind: notImplemented, isOptionalParameter: notImplemented, moduleExportsSomeValue: notImplemented, @@ -116109,6 +116382,25 @@ ${lanes.join("\n")} }); } } + function getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName) { + const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : currentDirectory; + return combinePaths(containingDirectory, `__lib_node_modules_lookup_${libFileName}__.ts`); + } + function getLibraryNameFromLibFileName(libFileName) { + const components = libFileName.split("."); + let path = components[1]; + let i = 2; + while (components[i] && components[i] !== "d") { + path += (i === 2 ? "/" : "-") + components[i]; + i++; + } + return "@typescript/lib-" + path; + } + function getLibFileNameFromLibReference(libReference) { + const libName = toFileNameLowerCase(libReference.fileName); + const libFileName = libMap.get(libName); + return { libName, libFileName }; + } function isReferencedFile(reason) { switch (reason == null ? void 0 : reason.kind) { case 3 /* Import */: @@ -116152,7 +116444,7 @@ ${lanes.join("\n")} } return { file, pos, end, packageId }; } - function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) { + function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences) { if (!program || (hasChangedAutomaticTypeDirectiveNames == null ? void 0 : hasChangedAutomaticTypeDirectiveNames())) return false; if (!arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) @@ -116167,6 +116459,8 @@ ${lanes.join("\n")} const currentOptions = program.getCompilerOptions(); if (!compareDataObjects(currentOptions, newOptions)) return false; + if (program.resolvedLibReferences && forEachEntry(program.resolvedLibReferences, (_value, libFileName) => hasInvalidatedLibResolutions(libFileName))) + return false; if (currentOptions.configFile && newOptions.configFile) return currentOptions.configFile.text === newOptions.configFile.text; return true; @@ -116259,6 +116553,9 @@ ${lanes.join("\n")} let fileProcessingDiagnostics; let automaticTypeDirectiveNames; let automaticTypeDirectiveResolutions; + let resolvedLibReferences; + let resolvedLibProcessing; + let packageMap; const maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0; let currentNodeModulesDepth = 0; const modulesWithElidedImports = /* @__PURE__ */ new Map(); @@ -116346,6 +116643,14 @@ ${lanes.join("\n")} createTypeReferenceResolutionLoader ); } + const hasInvalidatedLibResolutions = host.hasInvalidatedLibResolutions || returnFalse; + let actualResolveLibrary; + if (host.resolveLibrary) { + actualResolveLibrary = host.resolveLibrary.bind(host); + } else { + const libraryResolutionCache = createModuleResolutionCache(currentDirectory, getCanonicalFileName, options, moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache()); + actualResolveLibrary = (libraryName, resolveFrom, options2) => resolveLibrary(libraryName, resolveFrom, options2, host, libraryResolutionCache); + } const packageIdToSourceFile = /* @__PURE__ */ new Map(); let sourceFileToPackageName = /* @__PURE__ */ new Map(); let redirectTargetsMap = createMultiMap(); @@ -116422,7 +116727,7 @@ ${lanes.join("\n")} automaticTypeDirectiveResolutions = createModeAwareCache(); if (automaticTypeDirectiveNames.length) { (_k = tracing) == null ? void 0 : _k.push(tracing.Phase.Program, "processTypeReferences", { count: automaticTypeDirectiveNames.length }); - const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); + const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : currentDirectory; const containingFilename = combinePaths(containingDirectory, inferredTypesContainingFile); const resolutions = resolveTypeReferenceDirectiveNamesReusingOldState(automaticTypeDirectiveNames, containingFilename); for (let i = 0; i < automaticTypeDirectiveNames.length; i++) { @@ -116512,6 +116817,7 @@ ${lanes.join("\n")} ); } oldProgram = void 0; + resolvedLibProcessing = void 0; const program = { getRootFileNames: () => rootNames, getSourceFile, @@ -116553,6 +116859,10 @@ ${lanes.join("\n")} sourceFileToPackageName, redirectTargetsMap, usesUriStyleNodeCoreModules, + resolvedLibReferences, + getCurrentPackagesMap: () => packageMap, + typesPackageExists, + packageBundlesTypes, isEmittedFile, getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics2, getProjectReferences, @@ -116593,6 +116903,26 @@ ${lanes.join("\n")} measure("Program", "beforeProgram", "afterProgram"); (_p = tracing) == null ? void 0 : _p.pop(); return program; + function getPackagesMap() { + if (packageMap) + return packageMap; + packageMap = /* @__PURE__ */ new Map(); + files.forEach((sf) => { + if (!sf.resolvedModules) + return; + sf.resolvedModules.forEach(({ resolvedModule }) => { + if (resolvedModule == null ? void 0 : resolvedModule.packageId) + packageMap.set(resolvedModule.packageId.name, resolvedModule.extension === ".d.ts" /* Dts */ || !!packageMap.get(resolvedModule.packageId.name)); + }); + }); + return packageMap; + } + function typesPackageExists(packageName) { + return getPackagesMap().has(getTypesPackageName(packageName)); + } + function packageBundlesTypes(packageName) { + return !!getPackagesMap().get(packageName); + } function addResolutionDiagnostics(resolution) { var _a2; if (!((_a2 = resolution.resolutionDiagnostics) == null ? void 0 : _a2.length)) @@ -117041,6 +117371,9 @@ ${lanes.join("\n")} if (changesAffectingProgramStructure(oldOptions, options)) { return 1 /* SafeModules */; } + if (oldProgram.resolvedLibReferences && forEachEntry(oldProgram.resolvedLibReferences, (resolution, libFileName) => pathForLibFileWorker(libFileName).actual !== resolution.actual)) { + return 1 /* SafeModules */; + } if (host.hasChangedAutomaticTypeDirectiveNames) { if (host.hasChangedAutomaticTypeDirectiveNames()) return 1 /* SafeModules */; @@ -117077,6 +117410,8 @@ ${lanes.join("\n")} sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; usesUriStyleNodeCoreModules = oldProgram.usesUriStyleNodeCoreModules; + resolvedLibReferences = oldProgram.resolvedLibReferences; + packageMap = oldProgram.getCurrentPackagesMap(); return 2 /* Completely */; } function getEmitHost(writeFileCallback) { @@ -117186,7 +117521,7 @@ ${lanes.join("\n")} if (!options.lib) { return equalityComparer(file.fileName, getDefaultLibraryFileName()); } else { - return some(options.lib, (libFileName) => equalityComparer(file.fileName, pathForLibFile(libFileName))); + return some(options.lib, (libFileName) => equalityComparer(file.fileName, resolvedLibReferences.get(libFileName).actual)); } } function getTypeChecker() { @@ -117777,11 +118112,10 @@ ${lanes.join("\n")} } } function getLibFileFromReference(ref) { - const libName = toFileNameLowerCase(ref.fileName); - const libFileName = libMap.get(libName); - if (libFileName) { - return getSourceFile(pathForLibFile(libFileName)); - } + var _a2; + const { libFileName } = getLibFileNameFromLibReference(ref); + const actualFileName = libFileName && ((_a2 = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName)) == null ? void 0 : _a2.actual); + return actualFileName !== void 0 ? getSourceFile(actualFileName) : void 0; } function getSourceFileFromReference(referencingFile, ref) { return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), getSourceFile); @@ -118206,24 +118540,55 @@ ${lanes.join("\n")} } } function pathForLibFile(libFileName) { - const components = libFileName.split("."); - let path = components[1]; - let i = 2; - while (components[i] && components[i] !== "d") { - path += (i === 2 ? "/" : "-") + components[i]; - i++; + const existing = resolvedLibReferences == null ? void 0 : resolvedLibReferences.get(libFileName); + if (existing) + return existing.actual; + const result = pathForLibFileWorker(libFileName); + (resolvedLibReferences ?? (resolvedLibReferences = /* @__PURE__ */ new Map())).set(libFileName, result); + return result.actual; + } + function pathForLibFileWorker(libFileName) { + var _a2, _b2, _c2, _d2, _e2; + const existing = resolvedLibProcessing == null ? void 0 : resolvedLibProcessing.get(libFileName); + if (existing) + return existing; + if (structureIsReused !== 0 /* Not */ && oldProgram && !hasInvalidatedLibResolutions(libFileName)) { + const oldResolution = (_a2 = oldProgram.resolvedLibReferences) == null ? void 0 : _a2.get(libFileName); + if (oldResolution) { + if (oldResolution.resolution && isTraceEnabled(options, host)) { + const libraryName2 = getLibraryNameFromLibFileName(libFileName); + const resolveFrom2 = getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName); + trace( + host, + oldResolution.resolution.resolvedModule ? 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, + libraryName2, + getNormalizedAbsolutePath(resolveFrom2, currentDirectory), + (_b2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _b2.resolvedFileName, + ((_c2 = oldResolution.resolution.resolvedModule) == null ? void 0 : _c2.packageId) && packageIdToString(oldResolution.resolution.resolvedModule.packageId) + ); + } + (resolvedLibProcessing ?? (resolvedLibProcessing = /* @__PURE__ */ new Map())).set(libFileName, oldResolution); + return oldResolution; + } } - const resolveFrom = combinePaths(currentDirectory, `__lib_node_modules_lookup_${libFileName}__.ts`); - const localOverrideModuleResult = resolveModuleName("@typescript/lib-" + path, resolveFrom, { moduleResolution: 2 /* Node10 */ }, host, moduleResolutionCache); - if (localOverrideModuleResult == null ? void 0 : localOverrideModuleResult.resolvedModule) { - return localOverrideModuleResult.resolvedModule.resolvedFileName; - } - return combinePaths(defaultLibraryPath, libFileName); + const libraryName = getLibraryNameFromLibFileName(libFileName); + const resolveFrom = getInferredLibraryNameResolveFrom(options, currentDirectory, libFileName); + (_d2 = tracing) == null ? void 0 : _d2.push(tracing.Phase.Program, "resolveLibrary", { resolveFrom }); + mark("beforeResolveLibrary"); + const resolution = actualResolveLibrary(libraryName, resolveFrom, options, libFileName); + mark("afterResolveLibrary"); + measure("ResolveLibrary", "beforeResolveLibrary", "afterResolveLibrary"); + (_e2 = tracing) == null ? void 0 : _e2.pop(); + const result = { + resolution, + actual: resolution.resolvedModule ? resolution.resolvedModule.resolvedFileName : combinePaths(defaultLibraryPath, libFileName) + }; + (resolvedLibProcessing ?? (resolvedLibProcessing = /* @__PURE__ */ new Map())).set(libFileName, result); + return result; } function processLibReferenceDirectives(file) { forEach(file.libReferenceDirectives, (libReference, index) => { - const libName = toFileNameLowerCase(libReference.fileName); - const libFileName = libMap.get(libName); + const { libName, libFileName } = getLibFileNameFromLibReference(libReference); if (libFileName) { processRootFile( pathForLibFile(libFileName), @@ -118349,7 +118714,7 @@ ${lanes.join("\n")} void 0 ); } else { - const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), host.getCurrentDirectory()); + const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), currentDirectory); sourceFile = host.getSourceFile(refPath, 100 /* JSON */); addFileToFilesByName( sourceFile, @@ -120052,7 +120417,10 @@ ${lanes.join("\n")} return; const diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); if (diagnostics) { - state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : diagnostics); + state.semanticDiagnosticsPerFile.set( + sourceFilePath, + oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram) : repopulateDiagnostics(diagnostics, newProgram) + ); if (!state.semanticDiagnosticsFromOldState) { state.semanticDiagnosticsFromOldState = /* @__PURE__ */ new Set(); } @@ -120123,6 +120491,33 @@ ${lanes.join("\n")} isString(oldEmitSignature) ? [oldEmitSignature] : oldEmitSignature[0] ); } + function repopulateDiagnostics(diagnostics, newProgram) { + if (!diagnostics.length) + return diagnostics; + return sameMap(diagnostics, (diag2) => { + if (isString(diag2.messageText)) + return diag2; + const repopulatedChain = convertOrRepopulateDiagnosticMessageChain(diag2.messageText, diag2.file, newProgram, (chain) => { + var _a; + return (_a = chain.repopulateInfo) == null ? void 0 : _a.call(chain); + }); + return repopulatedChain === diag2.messageText ? diag2 : { ...diag2, messageText: repopulatedChain }; + }); + } + function convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo) { + const info = repopulateInfo(chain); + if (info) { + return { + ...createModuleNotFoundChain(sourceFile, newProgram, info.moduleReference, info.mode, info.packageName || info.moduleReference), + next: convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo) + }; + } + const next = convertOrRepopulateDiagnosticMessageChainArray(chain.next, sourceFile, newProgram, repopulateInfo); + return next === chain.next ? chain : { ...chain, next }; + } + function convertOrRepopulateDiagnosticMessageChainArray(array, sourceFile, newProgram, repopulateInfo) { + return sameMap(array, (chain) => convertOrRepopulateDiagnosticMessageChain(chain, sourceFile, newProgram, repopulateInfo)); + } function convertToDiagnostics(diagnostics, newProgram) { if (!diagnostics.length) return emptyArray; @@ -120144,9 +120539,11 @@ ${lanes.join("\n")} } function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath3) { const { file } = diagnostic; + const sourceFile = file ? newProgram.getSourceFileByPath(toPath3(file)) : void 0; return { ...diagnostic, - file: file ? newProgram.getSourceFileByPath(toPath3(file)) : void 0 + file: sourceFile, + messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertOrRepopulateDiagnosticMessageChain(diagnostic.messageText, sourceFile, newProgram, (chain) => chain.info) }; } function releaseCache(state) { @@ -120688,9 +121085,35 @@ ${lanes.join("\n")} const { file } = diagnostic; return { ...diagnostic, - file: file ? relativeToBuildInfo(file.resolvedPath) : void 0 + file: file ? relativeToBuildInfo(file.resolvedPath) : void 0, + messageText: isString(diagnostic.messageText) ? diagnostic.messageText : convertToReusableDiagnosticMessageChain(diagnostic.messageText) }; } + function convertToReusableDiagnosticMessageChain(chain) { + if (chain.repopulateInfo) { + return { + info: chain.repopulateInfo(), + next: convertToReusableDiagnosticMessageChainArray(chain.next) + }; + } + const next = convertToReusableDiagnosticMessageChainArray(chain.next); + return next === chain.next ? chain : { ...chain, next }; + } + function convertToReusableDiagnosticMessageChainArray(array) { + if (!array) + return array; + return forEach(array, (chain, index) => { + const reusable = convertToReusableDiagnosticMessageChain(chain); + if (chain === reusable) + return void 0; + const result = index > 0 ? array.slice(0, index - 1) : []; + result.push(reusable); + for (let i = index + 1; i < array.length; i++) { + result.push(convertToReusableDiagnosticMessageChain(array[i])); + } + return result; + }) || array; + } function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { let host; let newProgram; @@ -121380,6 +121803,7 @@ ${lanes.join("\n")} let failedLookupChecks; let startsWithPathChecks; let isInDirectoryChecks; + let allModuleAndTypeResolutionsAreInvalidated = false; const getCurrentDirectory = memoize(() => resolutionHost.getCurrentDirectory()); const cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); const resolvedModuleNames = /* @__PURE__ */ new Map(); @@ -121395,6 +121819,13 @@ ${lanes.join("\n")} resolutionHost.getCompilationSettings(), moduleResolutionCache.getPackageJsonInfoCache() ); + const resolvedLibraries = /* @__PURE__ */ new Map(); + const libraryResolutionCache = createModuleResolutionCache( + getCurrentDirectory(), + resolutionHost.getCanonicalFileName, + getOptionsForLibraryResolution(resolutionHost.getCompilationSettings()), + moduleResolutionCache.getPackageJsonInfoCache() + ); const directoryWatchesOfFailedLookups = /* @__PURE__ */ new Map(); const fileWatchesOfAffectingLocations = /* @__PURE__ */ new Map(); const rootDir = getRootDirectoryOfResolutionCache(rootDirForResolution, getCurrentDirectory); @@ -121411,6 +121842,7 @@ ${lanes.join("\n")} finishCachingPerDirectoryResolution, resolveModuleNameLiterals, resolveTypeReferenceDirectiveReferences, + resolveLibrary: resolveLibrary2, resolveSingleModuleNameWithoutWatching, removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile, @@ -121422,7 +121854,8 @@ ${lanes.join("\n")} isFileWithInvalidatedNonRelativeUnresolvedImports, updateTypeRootsWatch, closeTypeRootsWatch, - clear: clear2 + clear: clear2, + onChangesAffectModuleResolution }; function getResolvedModule2(resolution) { return resolution.resolvedModule; @@ -121445,13 +121878,23 @@ ${lanes.join("\n")} isInDirectoryChecks = void 0; affectingPathChecks = void 0; affectingPathChecksForFile = void 0; + allModuleAndTypeResolutionsAreInvalidated = false; moduleResolutionCache.clear(); typeReferenceDirectiveResolutionCache.clear(); moduleResolutionCache.update(resolutionHost.getCompilationSettings()); typeReferenceDirectiveResolutionCache.update(resolutionHost.getCompilationSettings()); + libraryResolutionCache.clear(); impliedFormatPackageJsons.clear(); + resolvedLibraries.clear(); hasChangedAutomaticTypeDirectiveNames = false; } + function onChangesAffectModuleResolution() { + allModuleAndTypeResolutionsAreInvalidated = true; + moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); + typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + moduleResolutionCache.update(resolutionHost.getCompilationSettings()); + typeReferenceDirectiveResolutionCache.update(resolutionHost.getCompilationSettings()); + } function startRecordingFilesWithChangedResolutions() { filesWithChangedSetOfUnresolvedImports = []; } @@ -121467,23 +121910,45 @@ ${lanes.join("\n")} const value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path); return !!value && !!value.length; } - function createHasInvalidatedResolutions(customHasInvalidatedResolutions) { + function createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidatedLibResolutions) { invalidateResolutionsOfFailedLookupLocations(); const collected = filesWithInvalidatedResolutions; filesWithInvalidatedResolutions = void 0; - return (path) => customHasInvalidatedResolutions(path) || !!(collected == null ? void 0 : collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path); + return { + hasInvalidatedResolutions: (path) => customHasInvalidatedResolutions(path) || allModuleAndTypeResolutionsAreInvalidated || !!(collected == null ? void 0 : collected.has(path)) || isFileWithInvalidatedNonRelativeUnresolvedImports(path), + hasInvalidatedLibResolutions: (libFileName) => { + var _a; + return customHasInvalidatedLibResolutions(libFileName) || !!((_a = resolvedLibraries == null ? void 0 : resolvedLibraries.get(libFileName)) == null ? void 0 : _a.isInvalidated); + } + }; } function startCachingPerDirectoryResolution() { moduleResolutionCache.clearAllExceptPackageJsonInfoCache(); typeReferenceDirectiveResolutionCache.clearAllExceptPackageJsonInfoCache(); + libraryResolutionCache.clearAllExceptPackageJsonInfoCache(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); } + function cleanupLibResolutionWatching(newProgram) { + resolvedLibraries.forEach((resolution, libFileName) => { + var _a; + if (!((_a = newProgram == null ? void 0 : newProgram.resolvedLibReferences) == null ? void 0 : _a.has(libFileName))) { + stopWatchFailedLookupLocationOfResolution( + resolution, + resolutionHost.toPath(getInferredLibraryNameResolveFrom(newProgram.getCompilerOptions(), getCurrentDirectory(), libFileName)), + getResolvedModule2 + ); + resolvedLibraries.delete(libFileName); + } + }); + } function finishCachingPerDirectoryResolution(newProgram, oldProgram) { filesWithInvalidatedNonRelativeUnresolvedImports = void 0; + allModuleAndTypeResolutionsAreInvalidated = false; nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); if (newProgram !== oldProgram) { + cleanupLibResolutionWatching(newProgram); newProgram == null ? void 0 : newProgram.getSourceFiles().forEach((newFile) => { var _a; const expected = isExternalOrCommonJsModule(newFile) ? ((_a = newFile.packageJsonLocations) == null ? void 0 : _a.length) ?? 0 : 0; @@ -121575,6 +122040,7 @@ ${lanes.join("\n")} reusedNames, loader, getResolutionWithResolvedFileName, + deferWatchingNonRelativeResolution, shouldRetryResolution, logChanges }) { @@ -121591,15 +122057,15 @@ ${lanes.join("\n")} const name = loader.nameAndMode.getName(entry); const mode = loader.nameAndMode.getMode(entry, containingSourceFile); let resolution = resolutionsInFile.get(name, mode); - if (!seenNamesInFile.has(name, mode) && unmatchedRedirects || !resolution || resolution.isInvalidated || // If the name is unresolved import that was invalidated, recalculate - hasInvalidatedNonRelativeUnresolvedImport && !isExternalModuleNameRelative(name) && shouldRetryResolution(resolution)) { + 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))) { const existingResolution = resolution; resolution = loader.resolve(name, mode); if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) { resolutionHost.onDiscoveredSymlink(); } resolutionsInFile.set(name, mode, resolution); - watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName); + watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution); if (existingResolution) { stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName); } @@ -121675,7 +122141,8 @@ ${lanes.join("\n")} typeReferenceDirectiveResolutionCache ), getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective2, - shouldRetryResolution: (resolution) => resolution.resolvedTypeReferenceDirective === void 0 + shouldRetryResolution: (resolution) => resolution.resolvedTypeReferenceDirective === void 0, + deferWatchingNonRelativeResolution: false }); } function resolveModuleNameLiterals(moduleLiterals, containingFile, redirectedReference, options, containingSourceFile, reusedNames) { @@ -121694,9 +122161,46 @@ ${lanes.join("\n")} ), getResolutionWithResolvedFileName: getResolvedModule2, shouldRetryResolution: (resolution) => !resolution.resolvedModule || !resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension), - logChanges: logChangesWhenResolvingModule + logChanges: logChangesWhenResolvingModule, + deferWatchingNonRelativeResolution: true + // Defer non relative resolution watch because we could be using ambient modules }); } + function resolveLibrary2(libraryName, resolveFrom, options, libFileName) { + var _a; + const host = ((_a = resolutionHost.getCompilerHost) == null ? void 0 : _a.call(resolutionHost)) || resolutionHost; + let resolution = resolvedLibraries == null ? void 0 : resolvedLibraries.get(libFileName); + if (!resolution || resolution.isInvalidated) { + const existingResolution = resolution; + resolution = resolveLibrary(libraryName, resolveFrom, options, host, libraryResolutionCache); + const path = resolutionHost.toPath(resolveFrom); + watchFailedLookupLocationsOfExternalModuleResolutions( + libraryName, + resolution, + path, + getResolvedModule2, + /*deferWatchingNonRelativeResolution*/ + false + ); + resolvedLibraries.set(libFileName, resolution); + if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolvedModule2); + } + } else { + if (isTraceEnabled(options, host)) { + const resolved = getResolvedModule2(resolution); + trace( + host, + (resolved == null ? void 0 : resolved.resolvedFileName) ? resolved.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, + resolveFrom, + resolved == null ? void 0 : resolved.resolvedFileName, + (resolved == null ? void 0 : resolved.packageId) && packageIdToString(resolved.packageId) + ); + } + } + return resolution; + } function resolveSingleModuleNameWithoutWatching(moduleName, containingFile) { const path = resolutionHost.toPath(containingFile); const resolutionsInFile = resolvedModuleNames.get(path); @@ -121712,7 +122216,7 @@ ${lanes.join("\n")} function isNodeModulesAtTypesDirectory(dirPath) { return endsWith(dirPath, "/node_modules/@types"); } - function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) { + function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName, deferWatchingNonRelativeResolution) { var _a; if (resolution.refCount) { resolution.refCount++; @@ -121720,7 +122224,7 @@ ${lanes.join("\n")} } else { resolution.refCount = 1; Debug.assert(!((_a = resolution.files) == null ? void 0 : _a.size)); - if (isExternalModuleNameRelative(name)) { + if (!deferWatchingNonRelativeResolution || isExternalModuleNameRelative(name)) { watchFailedLookupLocationOfResolution(resolution); } else { nonRelativeExternalModuleResolutions.add(name, resolution); @@ -121736,45 +122240,51 @@ ${lanes.join("\n")} } (resolution.files ?? (resolution.files = /* @__PURE__ */ new Set())).add(filePath); } + function watchFailedLookupLocation(failedLookupLocation, setAtRoot) { + const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + const toWatch = getDirectoryToWatchFailedLookupLocation( + failedLookupLocation, + failedLookupLocationPath, + rootDir, + rootPath, + rootPathComponents, + getCurrentDirectory + ); + if (toWatch) { + const { dir, dirPath, nonRecursive } = toWatch; + if (dirPath === rootPath) { + Debug.assert(nonRecursive); + setAtRoot = true; + } else { + setDirectoryWatcher(dir, dirPath, nonRecursive); + } + } + return setAtRoot; + } function watchFailedLookupLocationOfResolution(resolution) { Debug.assert(!!resolution.refCount); - const { failedLookupLocations, affectingLocations } = resolution; - if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length)) + const { failedLookupLocations, affectingLocations, node10Result } = resolution; + if (!(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !(affectingLocations == null ? void 0 : affectingLocations.length) && !node10Result) return; - if (failedLookupLocations == null ? void 0 : failedLookupLocations.length) + if ((failedLookupLocations == null ? void 0 : failedLookupLocations.length) || node10Result) resolutionsWithFailedLookups.add(resolution); let setAtRoot = false; if (failedLookupLocations) { for (const failedLookupLocation of failedLookupLocations) { - const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - const toWatch = getDirectoryToWatchFailedLookupLocation( - failedLookupLocation, - failedLookupLocationPath, - rootDir, - rootPath, - rootPathComponents, - getCurrentDirectory - ); - if (toWatch) { - const { dir, dirPath, nonRecursive } = toWatch; - if (dirPath === rootPath) { - Debug.assert(nonRecursive); - setAtRoot = true; - } else { - setDirectoryWatcher(dir, dirPath, nonRecursive); - } - } - } - if (setAtRoot) { - setDirectoryWatcher( - rootDir, - rootPath, - /*nonRecursive*/ - true - ); + setAtRoot = watchFailedLookupLocation(failedLookupLocation, setAtRoot); } } - watchAffectingLocationsOfResolution(resolution, !(failedLookupLocations == null ? void 0 : failedLookupLocations.length)); + if (node10Result) + setAtRoot = watchFailedLookupLocation(node10Result, setAtRoot); + if (setAtRoot) { + setDirectoryWatcher( + rootDir, + rootPath, + /*nonRecursive*/ + true + ); + } + watchAffectingLocationsOfResolution(resolution, !(failedLookupLocations == null ? void 0 : failedLookupLocations.length) && !node10Result); } function watchAffectingLocationsOfResolution(resolution, addToResolutionsWithOnlyAffectingLocations) { Debug.assert(!!resolution.refCount); @@ -121868,6 +122378,26 @@ ${lanes.join("\n")} directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive }); } } + function stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot) { + const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + const toWatch = getDirectoryToWatchFailedLookupLocation( + failedLookupLocation, + failedLookupLocationPath, + rootDir, + rootPath, + rootPathComponents, + getCurrentDirectory + ); + if (toWatch) { + const { dirPath } = toWatch; + if (dirPath === rootPath) { + removeAtRoot = true; + } else { + removeDirectoryWatcher(dirPath); + } + } + return removeAtRoot; + } function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) { Debug.checkDefined(resolution.files).delete(filePath); resolution.refCount--; @@ -121881,31 +122411,18 @@ ${lanes.join("\n")} if ((resolutions == null ? void 0 : resolutions.delete(resolution)) && !resolutions.size) resolvedFileToResolution.delete(key); } - const { failedLookupLocations, affectingLocations } = resolution; + const { failedLookupLocations, affectingLocations, node10Result } = resolution; if (resolutionsWithFailedLookups.delete(resolution)) { let removeAtRoot = false; - for (const failedLookupLocation of failedLookupLocations) { - const failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); - const toWatch = getDirectoryToWatchFailedLookupLocation( - failedLookupLocation, - failedLookupLocationPath, - rootDir, - rootPath, - rootPathComponents, - getCurrentDirectory - ); - if (toWatch) { - const { dirPath } = toWatch; - if (dirPath === rootPath) { - removeAtRoot = true; - } else { - removeDirectoryWatcher(dirPath); - } + if (failedLookupLocations) { + for (const failedLookupLocation of failedLookupLocations) { + removeAtRoot = stopWatchFailedLookupLocation(failedLookupLocation, removeAtRoot); } } - if (removeAtRoot) { + if (node10Result) + removeAtRoot = stopWatchFailedLookupLocation(node10Result, removeAtRoot); + if (removeAtRoot) removeDirectoryWatcher(rootPath); - } } else if (affectingLocations == null ? void 0 : affectingLocations.length) { resolutionsWithOnlyAffectingLocations.delete(resolution); } @@ -122000,15 +122517,37 @@ ${lanes.join("\n")} return false; } (failedLookupChecks || (failedLookupChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); - const packagePath = parseNodeModuleFromPath(fileOrDirectoryPath); + const packagePath = parseNodeModuleFromPath( + fileOrDirectoryPath, + /*isFolder*/ + true + ); if (packagePath) (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(packagePath); } } resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations(); } + function invalidatePackageJsonMap() { + const packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); + if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) { + packageJsonMap.forEach((_value, path) => isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : void 0); + } + } function invalidateResolutionsOfFailedLookupLocations() { var _a; + if (allModuleAndTypeResolutionsAreInvalidated) { + affectingPathChecksForFile = void 0; + invalidatePackageJsonMap(); + if (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks || affectingPathChecks) { + invalidateResolutions(resolvedLibraries, canInvalidateFailedLookupResolution); + } + failedLookupChecks = void 0; + startsWithPathChecks = void 0; + isInDirectoryChecks = void 0; + affectingPathChecks = void 0; + return true; + } let invalidated = false; if (affectingPathChecksForFile) { (_a = resolutionHost.getCurrentProgram()) == null ? void 0 : _a.getSourceFiles().forEach((f) => { @@ -122023,10 +122562,7 @@ ${lanes.join("\n")} return invalidated; } invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution) || invalidated; - const packageJsonMap = moduleResolutionCache.getPackageJsonInfoCache().getInternalMap(); - if (packageJsonMap && (failedLookupChecks || startsWithPathChecks || isInDirectoryChecks)) { - packageJsonMap.forEach((_value, path) => isInvalidatedFailedLookup(path) ? packageJsonMap.delete(path) : void 0); - } + invalidatePackageJsonMap(); failedLookupChecks = void 0; startsWithPathChecks = void 0; isInDirectoryChecks = void 0; @@ -122040,7 +122576,7 @@ ${lanes.join("\n")} return true; if (!failedLookupChecks && !startsWithPathChecks && !isInDirectoryChecks) return false; - return (_a = resolution.failedLookupLocations) == null ? void 0 : _a.some((location) => isInvalidatedFailedLookup(resolutionHost.toPath(location))); + return ((_a = resolution.failedLookupLocations) == null ? void 0 : _a.some((location) => isInvalidatedFailedLookup(resolutionHost.toPath(location)))) || !!resolution.node10Result && isInvalidatedFailedLookup(resolutionHost.toPath(resolution.node10Result)); } function isInvalidatedFailedLookup(locationPath) { return (failedLookupChecks == null ? void 0 : failedLookupChecks.has(locationPath)) || firstDefinedIterator((startsWithPathChecks == null ? void 0 : startsWithPathChecks.keys()) || [], (fileOrDirectoryPath) => startsWith(locationPath, fileOrDirectoryPath) ? true : void 0) || firstDefinedIterator((isInDirectoryChecks == null ? void 0 : isInDirectoryChecks.keys()) || [], (dirPath) => locationPath.length > dirPath.length && startsWith(locationPath, dirPath) && (isDiskPathRoot(dirPath) || locationPath[dirPath.length] === directorySeparator) ? true : void 0); @@ -122761,7 +123297,9 @@ ${lanes.join("\n")} 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" + NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation", + TypingInstallerLocationFile: "File location for typing installer", + TypingInstallerLocationDirectory: "Directory location for typing installer" }; } }); @@ -122920,9 +123458,11 @@ ${lanes.join("\n")} if (!compilerHost.resolveTypeReferenceDirectiveReferences && !compilerHost.resolveTypeReferenceDirectives) { compilerHost.resolveTypeReferenceDirectiveReferences = resolutionCache.resolveTypeReferenceDirectiveReferences.bind(resolutionCache); } + compilerHost.resolveLibrary = !host.resolveLibrary ? resolutionCache.resolveLibrary.bind(resolutionCache) : host.resolveLibrary.bind(host); compilerHost.getModuleResolutionCache = host.resolveModuleNameLiterals || host.resolveModuleNames ? maybeBind(host, host.getModuleResolutionCache) : () => resolutionCache.getModuleResolutionCache(); const userProvidedResolution = !!host.resolveModuleNameLiterals || !!host.resolveTypeReferenceDirectiveReferences || !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; const customHasInvalidatedResolutions = userProvidedResolution ? maybeBind(host, host.hasInvalidatedResolutions) || returnTrue : returnFalse; + const customHasInvalidLibResolutions = host.resolveLibrary ? maybeBind(host, host.hasInvalidatedLibResolutions) || returnTrue : returnFalse; builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); watchConfigFileWildCardDirectories(); @@ -122983,10 +123523,11 @@ ${lanes.join("\n")} if (hasChangedCompilerOptions) { newLine = updateNewLine(); if (program && changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { - resolutionCache.clear(); + debugger; + resolutionCache.onChangesAffectModuleResolution(); } } - const hasInvalidatedResolutions = resolutionCache.createHasInvalidatedResolutions(customHasInvalidatedResolutions); + const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = resolutionCache.createHasInvalidatedResolutions(customHasInvalidatedResolutions, customHasInvalidLibResolutions); const { originalReadFile, originalFileExists, @@ -122995,7 +123536,7 @@ ${lanes.join("\n")} originalWriteFile, readFileWithCache } = changeCompilerHostLikeToUseCache(compilerHost, toPath3); - if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, (path) => getSourceVersion(path, readFileWithCache), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, (path) => getSourceVersion(path, readFileWithCache), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { if (hasChangedConfigFileParsingErrors) { if (reportFileChangeDetectedOnCreateProgram) { reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation); @@ -123016,7 +123557,7 @@ ${lanes.join("\n")} if (reportFileChangeDetectedOnCreateProgram) { reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation); } - createNewProgram(hasInvalidatedResolutions); + createNewProgram(hasInvalidatedResolutions, hasInvalidatedLibResolutions); } reportFileChangeDetectedOnCreateProgram = false; if (host.afterProgramCreate && program !== builderProgram) { @@ -123029,7 +123570,7 @@ ${lanes.join("\n")} compilerHost.writeFile = originalWriteFile; return builderProgram; } - function createNewProgram(hasInvalidatedResolutions) { + function createNewProgram(hasInvalidatedResolutions, hasInvalidatedLibResolutions) { writeLog("CreatingProgramWith::"); writeLog(` roots: ${JSON.stringify(rootFileNames)}`); writeLog(` options: ${JSON.stringify(compilerOptions)}`); @@ -123040,6 +123581,7 @@ ${lanes.join("\n")} hasChangedConfigFileParsingErrors = false; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolutions = hasInvalidatedResolutions; + compilerHost.hasInvalidatedLibResolutions = hasInvalidatedLibResolutions; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; const oldProgram = getCurrentProgram(); builderProgram = createProgram2(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); @@ -123624,6 +124166,7 @@ ${lanes.join("\n")} compilerHost.getParsedCommandLine = (fileName) => parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); compilerHost.resolveModuleNameLiterals = maybeBind(host, host.resolveModuleNameLiterals); compilerHost.resolveTypeReferenceDirectiveReferences = maybeBind(host, host.resolveTypeReferenceDirectiveReferences); + compilerHost.resolveLibrary = maybeBind(host, host.resolveLibrary); compilerHost.resolveModuleNames = maybeBind(host, host.resolveModuleNames); compilerHost.resolveTypeReferenceDirectives = maybeBind(host, host.resolveTypeReferenceDirectives); compilerHost.getModuleResolutionCache = maybeBind(host, host.getModuleResolutionCache); @@ -123661,6 +124204,23 @@ ${lanes.join("\n")} createTypeReferenceResolutionLoader ); } + let libraryResolutionCache; + if (!compilerHost.resolveLibrary) { + libraryResolutionCache = createModuleResolutionCache( + compilerHost.getCurrentDirectory(), + compilerHost.getCanonicalFileName, + /*options*/ + void 0, + moduleResolutionCache == null ? void 0 : moduleResolutionCache.getPackageJsonInfoCache() + ); + compilerHost.resolveLibrary = (libraryName, resolveFrom, options2) => resolveLibrary( + libraryName, + resolveFrom, + options2, + host, + libraryResolutionCache + ); + } compilerHost.getBuildInfo = (fileName, configFilePath) => getBuildInfo3( state, fileName, @@ -123692,6 +124252,7 @@ ${lanes.join("\n")} compilerHost, moduleResolutionCache, typeReferenceDirectiveResolutionCache, + libraryResolutionCache, // Mutable state buildOrder: void 0, readFileWithCache: (f) => host.readFile(f), @@ -123909,7 +124470,7 @@ ${lanes.join("\n")} function disableCache(state) { if (!state.cache) return; - const { cache, host, compilerHost, extendedConfigCache, moduleResolutionCache, typeReferenceDirectiveResolutionCache } = state; + const { cache, host, compilerHost, extendedConfigCache, moduleResolutionCache, typeReferenceDirectiveResolutionCache, libraryResolutionCache } = state; host.readFile = cache.originalReadFile; host.fileExists = cache.originalFileExists; host.directoryExists = cache.originalDirectoryExists; @@ -123920,6 +124481,7 @@ ${lanes.join("\n")} extendedConfigCache.clear(); moduleResolutionCache == null ? void 0 : moduleResolutionCache.clear(); typeReferenceDirectiveResolutionCache == null ? void 0 : typeReferenceDirectiveResolutionCache.clear(); + libraryResolutionCache == null ? void 0 : libraryResolutionCache.clear(); state.cache = void 0; } function clearProjectStatus(state, resolved) { @@ -125954,7 +126516,7 @@ ${lanes.join("\n")} const d = /* @__PURE__ */ new Date(); return `${padLeft(d.getHours().toString(), 2, "0")}:${padLeft(d.getMinutes().toString(), 2, "0")}:${padLeft(d.getSeconds().toString(), 2, "0")}.${padLeft(d.getMilliseconds().toString(), 3, "0")}`; } - var ActionSet, ActionInvalidate, ActionPackageInstalled, EventTypesRegistry, EventBeginInstallTypes, EventEndInstallTypes, EventInitializationFailed, Arguments; + var ActionSet, ActionInvalidate, ActionPackageInstalled, EventTypesRegistry, EventBeginInstallTypes, EventEndInstallTypes, EventInitializationFailed, ActionWatchTypingLocations, Arguments; var init_shared = __esm({ "src/jsTyping/shared.ts"() { "use strict"; @@ -125966,6 +126528,7 @@ ${lanes.join("\n")} EventBeginInstallTypes = "event::beginInstallTypes"; EventEndInstallTypes = "event::endInstallTypes"; EventInitializationFailed = "event::initializationFailed"; + ActionWatchTypingLocations = "action::watchTypingLocations"; ((Arguments2) => { Arguments2.GlobalCacheLocation = "--globalTypingsCacheLocation"; Arguments2.LogFile = "--logFile"; @@ -125991,6 +126554,7 @@ ${lanes.join("\n")} ActionInvalidate: () => ActionInvalidate, ActionPackageInstalled: () => ActionPackageInstalled, ActionSet: () => ActionSet, + ActionWatchTypingLocations: () => ActionWatchTypingLocations, Arguments: () => Arguments, EventBeginInstallTypes: () => EventBeginInstallTypes, EventEndInstallTypes: () => EventEndInstallTypes, @@ -128317,7 +128881,12 @@ ${lanes.join("\n")} return visited; } function getSynthesizedDeepClones(nodes, includeTrivia = true) { - return nodes && factory.createNodeArray(nodes.map((n) => getSynthesizedDeepClone(n, includeTrivia)), nodes.hasTrailingComma); + if (nodes) { + const cloned = factory.createNodeArray(nodes.map((n) => getSynthesizedDeepClone(n, includeTrivia)), nodes.hasTrailingComma); + setTextRange(cloned, nodes); + return cloned; + } + return nodes; } function getSynthesizedDeepClonesWithReplacements(nodes, includeTrivia, replaceNode) { return factory.createNodeArray(nodes.map((n) => getSynthesizedDeepCloneWithReplacements(n, includeTrivia, replaceNode)), nodes.hasTrailingComma); @@ -129036,6 +129605,37 @@ ${lanes.join("\n")} } } } + function fileShouldUseJavaScriptRequire(file, program, host, preferRequire) { + var _a; + const fileName = typeof file === "string" ? file : file.fileName; + if (!hasJSFileExtension(fileName)) { + return false; + } + const compilerOptions = program.getCompilerOptions(); + const moduleKind = getEmitModuleKind(compilerOptions); + const impliedNodeFormat = typeof file === "string" ? getImpliedNodeFormatForFile(toPath(file, host.getCurrentDirectory(), hostGetCanonicalFileName(host)), (_a = program.getPackageJsonInfoCache) == null ? void 0 : _a.call(program), host, compilerOptions) : file.impliedNodeFormat; + if (impliedNodeFormat === 99 /* ESNext */) { + return false; + } + if (impliedNodeFormat === 1 /* CommonJS */) { + return true; + } + if (compilerOptions.verbatimModuleSyntax && moduleKind === 1 /* CommonJS */) { + return true; + } + if (compilerOptions.verbatimModuleSyntax && emitModuleKindIsNonNodeESM(moduleKind)) { + return false; + } + if (typeof file === "object") { + if (file.commonJsModuleIndicator) { + return true; + } + if (file.externalModuleIndicator) { + return false; + } + } + return preferRequire; + } var scanner, SemanticMeaning, tripleSlashDirectivePrefixRegex, typeKeywords, QuotePreference, displayPartWriter, lineFeed2, ANONYMOUS, syntaxMayBeASICandidate; var init_utilities4 = __esm({ "src/services/utilities.ts"() { @@ -129077,10 +129677,10 @@ ${lanes.join("\n")} 158 /* UniqueKeyword */, 159 /* UnknownKeyword */ ]; - QuotePreference = /* @__PURE__ */ ((QuotePreference5) => { - QuotePreference5[QuotePreference5["Single"] = 0] = "Single"; - QuotePreference5[QuotePreference5["Double"] = 1] = "Double"; - return QuotePreference5; + QuotePreference = /* @__PURE__ */ ((QuotePreference7) => { + QuotePreference7[QuotePreference7["Single"] = 0] = "Single"; + QuotePreference7[QuotePreference7["Double"] = 1] = "Double"; + return QuotePreference7; })(QuotePreference || {}); displayPartWriter = getDisplayPartWriter(); lineFeed2 = "\n"; @@ -133320,6 +133920,5293 @@ ${lanes.join("\n")} } }); + // src/services/refactorProvider.ts + function registerRefactor(name, refactor) { + refactors.set(name, refactor); + } + function getApplicableRefactors(context, includeInteractiveActions) { + return arrayFrom(flatMapIterator(refactors.values(), (refactor) => { + var _a; + return context.cancellationToken && context.cancellationToken.isCancellationRequested() || !((_a = refactor.kinds) == null ? void 0 : _a.some((kind) => refactorKindBeginsWith(kind, context.kind))) ? void 0 : refactor.getAvailableActions(context, includeInteractiveActions); + })); + } + function getEditsForRefactor(context, refactorName13, actionName2, interactiveRefactorArguments) { + const refactor = refactors.get(refactorName13); + return refactor && refactor.getEditsForAction(context, actionName2, interactiveRefactorArguments); + } + var refactors; + var init_refactorProvider = __esm({ + "src/services/refactorProvider.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactors = /* @__PURE__ */ new Map(); + } + }); + + // src/services/refactors/convertExport.ts + function getInfo2(context, considerPartialSpans = true) { + const { file, program } = context; + const span = getRefactorContextSpan(context); + const token = getTokenAtPosition(file, span.start); + const exportNode = !!(token.parent && getSyntacticModifierFlags(token.parent) & 1 /* Export */) && considerPartialSpans ? token.parent : getParentNodeInSpan(token, file, span); + if (!exportNode || !isSourceFile(exportNode.parent) && !(isModuleBlock(exportNode.parent) && isAmbientModule(exportNode.parent.parent))) { + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_export_statement) }; + } + const checker = program.getTypeChecker(); + const exportingModuleSymbol = getExportingModuleSymbol(exportNode.parent, checker); + const flags = getSyntacticModifierFlags(exportNode) || (isExportAssignment(exportNode) && !exportNode.isExportEquals ? 1025 /* ExportDefault */ : 0 /* None */); + const wasDefault = !!(flags & 1024 /* Default */); + if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { + return { error: getLocaleSpecificMessage(Diagnostics.This_file_already_has_a_default_export) }; + } + const noSymbolError = (id) => isIdentifier(id) && checker.getSymbolAtLocation(id) ? void 0 : { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_named_export) }; + switch (exportNode.kind) { + case 261 /* FunctionDeclaration */: + case 262 /* ClassDeclaration */: + case 263 /* InterfaceDeclaration */: + case 265 /* EnumDeclaration */: + case 264 /* TypeAliasDeclaration */: + case 266 /* ModuleDeclaration */: { + const node = exportNode; + if (!node.name) + return void 0; + return noSymbolError(node.name) || { exportNode: node, exportName: node.name, wasDefault, exportingModuleSymbol }; + } + case 242 /* VariableStatement */: { + const vs = exportNode; + if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { + return void 0; + } + const decl = first(vs.declarationList.declarations); + if (!decl.initializer) + return void 0; + Debug.assert(!wasDefault, "Can't have a default flag here"); + return noSymbolError(decl.name) || { exportNode: vs, exportName: decl.name, wasDefault, exportingModuleSymbol }; + } + case 276 /* ExportAssignment */: { + const node = exportNode; + if (node.isExportEquals) + return void 0; + return noSymbolError(node.expression) || { exportNode: node, exportName: node.expression, wasDefault, exportingModuleSymbol }; + } + default: + return void 0; + } + } + function doChange(exportingSourceFile, program, info, changes, cancellationToken) { + changeExport(exportingSourceFile, info, changes, program.getTypeChecker()); + changeImports(program, info, changes, cancellationToken); + } + function changeExport(exportingSourceFile, { wasDefault, exportNode, exportName }, changes, checker) { + if (wasDefault) { + if (isExportAssignment(exportNode) && !exportNode.isExportEquals) { + const exp = exportNode.expression; + const spec = makeExportSpecifier(exp.text, exp.text); + changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + factory.createNamedExports([spec]) + )); + } else { + changes.delete(exportingSourceFile, Debug.checkDefined(findModifier(exportNode, 90 /* DefaultKeyword */), "Should find a default keyword in modifier list")); + } + } else { + const exportKeyword = Debug.checkDefined(findModifier(exportNode, 95 /* ExportKeyword */), "Should find an export keyword in modifier list"); + switch (exportNode.kind) { + case 261 /* FunctionDeclaration */: + case 262 /* ClassDeclaration */: + case 263 /* InterfaceDeclaration */: + changes.insertNodeAfter(exportingSourceFile, exportKeyword, factory.createToken(90 /* DefaultKeyword */)); + break; + case 242 /* VariableStatement */: + const decl = first(exportNode.declarationList.declarations); + if (!ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile) && !decl.type) { + changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDefault(Debug.checkDefined(decl.initializer, "Initializer was previously known to be present"))); + break; + } + case 265 /* EnumDeclaration */: + case 264 /* TypeAliasDeclaration */: + case 266 /* ModuleDeclaration */: + changes.deleteModifier(exportingSourceFile, exportKeyword); + changes.insertNodeAfter(exportingSourceFile, exportNode, factory.createExportDefault(factory.createIdentifier(exportName.text))); + break; + default: + Debug.fail(`Unexpected exportNode kind ${exportNode.kind}`); + } + } + } + function changeImports(program, { wasDefault, exportName, exportingModuleSymbol }, changes, cancellationToken) { + const checker = program.getTypeChecker(); + const exportSymbol = Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol"); + ts_FindAllReferences_exports.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, (ref) => { + if (exportName === ref) + return; + const importingSourceFile = ref.getSourceFile(); + if (wasDefault) { + changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); + } else { + changeNamedToDefaultImport(importingSourceFile, ref, changes); + } + }); + } + function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { + const { parent: parent2 } = ref; + switch (parent2.kind) { + case 210 /* PropertyAccessExpression */: + changes.replaceNode(importingSourceFile, ref, factory.createIdentifier(exportName)); + break; + case 275 /* ImportSpecifier */: + case 280 /* ExportSpecifier */: { + const spec = parent2; + changes.replaceNode(importingSourceFile, spec, makeImportSpecifier(exportName, spec.name.text)); + break; + } + case 272 /* ImportClause */: { + const clause = parent2; + Debug.assert(clause.name === ref, "Import clause name should match provided ref"); + const spec = makeImportSpecifier(exportName, ref.text); + const { namedBindings } = clause; + if (!namedBindings) { + changes.replaceNode(importingSourceFile, ref, factory.createNamedImports([spec])); + } else if (namedBindings.kind === 273 /* NamespaceImport */) { + changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); + const quotePreference = isStringLiteral(clause.parent.moduleSpecifier) ? quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; + const newImport = makeImport( + /*defaultImport*/ + void 0, + [makeImportSpecifier(exportName, ref.text)], + clause.parent.moduleSpecifier, + quotePreference + ); + changes.insertNodeAfter(importingSourceFile, clause.parent, newImport); + } else { + changes.delete(importingSourceFile, ref); + changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec); + } + break; + } + case 204 /* ImportType */: + const importTypeNode = parent2; + changes.replaceNode(importingSourceFile, parent2, factory.createImportTypeNode(importTypeNode.argument, importTypeNode.assertions, factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); + break; + default: + Debug.failBadSyntaxKind(parent2); + } + } + function changeNamedToDefaultImport(importingSourceFile, ref, changes) { + const parent2 = ref.parent; + switch (parent2.kind) { + case 210 /* PropertyAccessExpression */: + changes.replaceNode(importingSourceFile, ref, factory.createIdentifier("default")); + break; + case 275 /* ImportSpecifier */: { + const defaultImport = factory.createIdentifier(parent2.name.text); + if (parent2.parent.elements.length === 1) { + changes.replaceNode(importingSourceFile, parent2.parent, defaultImport); + } else { + changes.delete(importingSourceFile, parent2); + changes.insertNodeBefore(importingSourceFile, parent2.parent, defaultImport); + } + break; + } + case 280 /* ExportSpecifier */: { + changes.replaceNode(importingSourceFile, parent2, makeExportSpecifier("default", parent2.name.text)); + break; + } + default: + Debug.assertNever(parent2, `Unexpected parent kind ${parent2.kind}`); + } + } + function makeImportSpecifier(propertyName, name) { + return factory.createImportSpecifier( + /*isTypeOnly*/ + false, + propertyName === name ? void 0 : factory.createIdentifier(propertyName), + factory.createIdentifier(name) + ); + } + function makeExportSpecifier(propertyName, name) { + return factory.createExportSpecifier( + /*isTypeOnly*/ + false, + propertyName === name ? void 0 : factory.createIdentifier(propertyName), + factory.createIdentifier(name) + ); + } + function getExportingModuleSymbol(parent2, checker) { + if (isSourceFile(parent2)) { + return parent2.symbol; + } + const symbol = parent2.parent.symbol; + if (symbol.valueDeclaration && isExternalModuleAugmentation(symbol.valueDeclaration)) { + return checker.getMergedSymbol(symbol); + } + return symbol; + } + var refactorName, defaultToNamedAction, namedToDefaultAction; + var init_convertExport = __esm({ + "src/services/refactors/convertExport.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName = "Convert export"; + defaultToNamedAction = { + name: "Convert default export to named export", + description: Diagnostics.Convert_default_export_to_named_export.message, + kind: "refactor.rewrite.export.named" + }; + namedToDefaultAction = { + name: "Convert named export to default export", + description: Diagnostics.Convert_named_export_to_default_export.message, + kind: "refactor.rewrite.export.default" + }; + registerRefactor(refactorName, { + kinds: [ + defaultToNamedAction.kind, + namedToDefaultAction.kind + ], + getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndDefaultExports(context) { + const info = getInfo2(context, context.triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + const action = info.wasDefault ? defaultToNamedAction : namedToDefaultAction; + return [{ name: refactorName, description: action.description, actions: [action] }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [ + { name: refactorName, description: Diagnostics.Convert_default_export_to_named_export.message, actions: [ + { ...defaultToNamedAction, notApplicableReason: info.error }, + { ...namedToDefaultAction, notApplicableReason: info.error } + ] } + ]; + } + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndDefaultExports(context, actionName2) { + Debug.assert(actionName2 === defaultToNamedAction.name || actionName2 === namedToDefaultAction.name, "Unexpected action name"); + const info = getInfo2(context); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange(context.file, context.program, info, t, context.cancellationToken)); + return { edits, renameFilename: void 0, renameLocation: void 0 }; + } + }); + } + }); + + // src/services/refactors/convertImport.ts + function getImportConversionInfo(context, considerPartialSpans = true) { + const { file } = context; + const span = getRefactorContextSpan(context); + const token = getTokenAtPosition(file, span.start); + const importDecl = considerPartialSpans ? findAncestor(token, isImportDeclaration) : getParentNodeInSpan(token, file, span); + if (!importDecl || !isImportDeclaration(importDecl)) + return { error: "Selection is not an import declaration." }; + const end = span.start + span.length; + const nextToken = findNextToken(importDecl, importDecl.parent, file); + if (nextToken && end > nextToken.getStart()) + return void 0; + const { importClause } = importDecl; + if (!importClause) { + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_import_clause) }; + } + if (!importClause.namedBindings) { + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_namespace_import_or_named_imports) }; + } + if (importClause.namedBindings.kind === 273 /* NamespaceImport */) { + return { convertTo: 0 /* Named */, import: importClause.namedBindings }; + } + const shouldUseDefault = getShouldUseDefault(context.program, importClause); + return shouldUseDefault ? { convertTo: 1 /* Default */, import: importClause.namedBindings } : { convertTo: 2 /* Namespace */, import: importClause.namedBindings }; + } + function getShouldUseDefault(program, importClause) { + return getAllowSyntheticDefaultImports(program.getCompilerOptions()) && isExportEqualsModule(importClause.parent.moduleSpecifier, program.getTypeChecker()); + } + function doChange2(sourceFile, program, changes, info) { + const checker = program.getTypeChecker(); + if (info.convertTo === 0 /* Named */) { + doChangeNamespaceToNamed(sourceFile, checker, changes, info.import, getAllowSyntheticDefaultImports(program.getCompilerOptions())); + } else { + doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, info.import, info.convertTo === 1 /* Default */); + } + } + function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { + let usedAsNamespaceOrDefault = false; + const nodesToReplace = []; + const conflictingNames = /* @__PURE__ */ new Map(); + ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, (id) => { + if (!isPropertyAccessOrQualifiedName(id.parent)) { + usedAsNamespaceOrDefault = true; + } else { + const exportName = getRightOfPropertyAccessOrQualifiedName(id.parent).text; + if (checker.resolveName( + exportName, + id, + 67108863 /* All */, + /*excludeGlobals*/ + true + )) { + conflictingNames.set(exportName, true); + } + Debug.assert(getLeftOfPropertyAccessOrQualifiedName(id.parent) === id, "Parent expression should match id"); + nodesToReplace.push(id.parent); + } + }); + const exportNameToImportName = /* @__PURE__ */ new Map(); + for (const propertyAccessOrQualifiedName of nodesToReplace) { + const exportName = getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName).text; + let importName = exportNameToImportName.get(exportName); + if (importName === void 0) { + exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? getUniqueName(exportName, sourceFile) : exportName); + } + changes.replaceNode(sourceFile, propertyAccessOrQualifiedName, factory.createIdentifier(importName)); + } + const importSpecifiers = []; + exportNameToImportName.forEach((name, propertyName) => { + importSpecifiers.push(factory.createImportSpecifier( + /*isTypeOnly*/ + false, + name === propertyName ? void 0 : factory.createIdentifier(propertyName), + factory.createIdentifier(name) + )); + }); + const importDecl = toConvert.parent.parent; + if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) { + changes.insertNodeAfter(sourceFile, importDecl, updateImport( + importDecl, + /*defaultImportName*/ + void 0, + importSpecifiers + )); + } else { + changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? factory.createIdentifier(toConvert.name.text) : void 0, importSpecifiers)); + } + } + function getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { + return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.name : propertyAccessOrQualifiedName.right; + } + function getLeftOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { + return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.expression : propertyAccessOrQualifiedName.left; + } + function doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, toConvert, shouldUseDefault = getShouldUseDefault(program, toConvert.parent)) { + const checker = program.getTypeChecker(); + const importDecl = toConvert.parent.parent; + const { moduleSpecifier } = importDecl; + const toConvertSymbols = /* @__PURE__ */ new Set(); + toConvert.elements.forEach((namedImport) => { + const symbol = checker.getSymbolAtLocation(namedImport.name); + if (symbol) { + toConvertSymbols.add(symbol); + } + }); + const preferredName = moduleSpecifier && isStringLiteral(moduleSpecifier) ? ts_codefix_exports.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 99 /* ESNext */) : "module"; + function hasNamespaceNameConflict(namedImport) { + return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(namedImport.name, checker, sourceFile, (id) => { + const symbol = checker.resolveName( + preferredName, + id, + 67108863 /* All */, + /*excludeGlobals*/ + true + ); + if (symbol) { + if (toConvertSymbols.has(symbol)) { + return isExportSpecifier(id.parent); + } + return true; + } + return false; + }); + } + const namespaceNameConflicts = toConvert.elements.some(hasNamespaceNameConflict); + const namespaceImportName = namespaceNameConflicts ? getUniqueName(preferredName, sourceFile) : preferredName; + const neededNamedImports = /* @__PURE__ */ new Set(); + for (const element of toConvert.elements) { + const propertyName = (element.propertyName || element.name).text; + ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, (id) => { + const access = factory.createPropertyAccessExpression(factory.createIdentifier(namespaceImportName), propertyName); + if (isShorthandPropertyAssignment(id.parent)) { + changes.replaceNode(sourceFile, id.parent, factory.createPropertyAssignment(id.text, access)); + } else if (isExportSpecifier(id.parent)) { + neededNamedImports.add(element); + } else { + changes.replaceNode(sourceFile, id, access); + } + }); + } + changes.replaceNode(sourceFile, toConvert, shouldUseDefault ? factory.createIdentifier(namespaceImportName) : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName))); + if (neededNamedImports.size) { + const newNamedImports = 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*/ + void 0, + newNamedImports + )); + } + } + function isExportEqualsModule(moduleSpecifier, checker) { + const externalModule = checker.resolveExternalModuleName(moduleSpecifier); + if (!externalModule) + return false; + const exportEquals = checker.resolveExternalModuleSymbol(externalModule); + return externalModule !== exportEquals; + } + function updateImport(old, defaultImportName, elements) { + return factory.createImportDeclaration( + /*modifiers*/ + void 0, + factory.createImportClause( + /*isTypeOnly*/ + false, + defaultImportName, + elements && elements.length ? factory.createNamedImports(elements) : void 0 + ), + old.moduleSpecifier, + /*assertClause*/ + void 0 + ); + } + var refactorName2, actions; + var init_convertImport = __esm({ + "src/services/refactors/convertImport.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName2 = "Convert import"; + actions = { + [0 /* Named */]: { + name: "Convert namespace import to named imports", + description: Diagnostics.Convert_namespace_import_to_named_imports.message, + kind: "refactor.rewrite.import.named" + }, + [2 /* Namespace */]: { + name: "Convert named imports to namespace import", + description: Diagnostics.Convert_named_imports_to_namespace_import.message, + kind: "refactor.rewrite.import.namespace" + }, + [1 /* Default */]: { + name: "Convert named imports to default import", + description: Diagnostics.Convert_named_imports_to_default_import.message, + kind: "refactor.rewrite.import.default" + } + }; + registerRefactor(refactorName2, { + kinds: getOwnValues(actions).map((a) => a.kind), + getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndNamespacedImports(context) { + const info = getImportConversionInfo(context, context.triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + const action = actions[info.convertTo]; + return [{ name: refactorName2, description: action.description, actions: [action] }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return getOwnValues(actions).map((action) => ({ + name: refactorName2, + description: action.description, + actions: [{ ...action, notApplicableReason: info.error }] + })); + } + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndNamespacedImports(context, actionName2) { + Debug.assert(some(getOwnValues(actions), (action) => action.name === actionName2), "Unexpected action name"); + const info = getImportConversionInfo(context); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange2(context.file, context.program, t, info)); + return { edits, renameFilename: void 0, renameLocation: void 0 }; + } + }); + } + }); + + // src/services/refactors/extractType.ts + function getRangeToExtract(context, considerEmptySpans = true) { + const { file, startPosition } = context; + const isJS = isSourceFileJS(file); + const current = getTokenAtPosition(file, startPosition); + 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))); + if (!selection || !isTypeNode(selection)) + return { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) }; + const checker = context.program.getTypeChecker(); + const enclosingNode = getEnclosingNode(selection, isJS); + if (enclosingNode === void 0) + return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }; + const typeParameters = collectTypeParameters(checker, selection, enclosingNode, file); + if (!typeParameters) + return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }; + const typeElements = flattenTypeLiteralNodeReference(checker, selection); + return { isJS, selection, enclosingNode, typeParameters, typeElements }; + } + function flattenTypeLiteralNodeReference(checker, node) { + if (!node) + return void 0; + if (isIntersectionTypeNode(node)) { + const result = []; + const seen = /* @__PURE__ */ new Map(); + for (const type of node.types) { + const flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type); + if (!flattenedTypeMembers || !flattenedTypeMembers.every((type2) => type2.name && addToSeen(seen, getNameFromPropertyName(type2.name)))) { + return void 0; + } + addRange(result, flattenedTypeMembers); + } + return result; + } else if (isParenthesizedTypeNode(node)) { + return flattenTypeLiteralNodeReference(checker, node.type); + } else if (isTypeLiteralNode(node)) { + return node.members; + } + return void 0; + } + function rangeContainsSkipTrivia(r1, node, file) { + return rangeContainsStartEnd(r1, skipTrivia(file.text, node.pos), node.end); + } + function collectTypeParameters(checker, selection, enclosingNode, file) { + const result = []; + return visitor(selection) ? void 0 : result; + function visitor(node) { + if (isTypeReferenceNode(node)) { + if (isIdentifier(node.typeName)) { + const typeName = node.typeName; + const symbol = checker.resolveName( + typeName.text, + typeName, + 262144 /* TypeParameter */, + /*excludeGlobals*/ + true + ); + for (const decl of (symbol == null ? void 0 : symbol.declarations) || emptyArray) { + if (isTypeParameterDeclaration(decl) && decl.getSourceFile() === file) { + if (decl.name.escapedText === typeName.escapedText && rangeContainsSkipTrivia(decl, selection, file)) { + return true; + } + if (rangeContainsSkipTrivia(enclosingNode, decl, file) && !rangeContainsSkipTrivia(selection, decl, file)) { + pushIfUnique(result, decl); + break; + } + } + } + } + } else if (isInferTypeNode(node)) { + const conditionalTypeNode = findAncestor(node, (n) => isConditionalTypeNode(n) && rangeContainsSkipTrivia(n.extendsType, node, file)); + if (!conditionalTypeNode || !rangeContainsSkipTrivia(selection, conditionalTypeNode, file)) { + return true; + } + } else if (isTypePredicateNode(node) || isThisTypeNode(node)) { + const functionLikeNode = findAncestor(node.parent, isFunctionLike); + if (functionLikeNode && functionLikeNode.type && rangeContainsSkipTrivia(functionLikeNode.type, node, file) && !rangeContainsSkipTrivia(selection, functionLikeNode, file)) { + return true; + } + } else if (isTypeQueryNode(node)) { + if (isIdentifier(node.exprName)) { + const symbol = checker.resolveName( + node.exprName.text, + node.exprName, + 111551 /* Value */, + /*excludeGlobals*/ + false + ); + if ((symbol == null ? void 0 : symbol.valueDeclaration) && rangeContainsSkipTrivia(enclosingNode, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) { + return true; + } + } else { + if (isThisIdentifier(node.exprName.left) && !rangeContainsSkipTrivia(selection, node.parent, file)) { + return true; + } + } + } + if (file && isTupleTypeNode(node) && getLineAndCharacterOfPosition(file, node.pos).line === getLineAndCharacterOfPosition(file, node.end).line) { + setEmitFlags(node, 1 /* SingleLine */); + } + return forEachChild(node, visitor); + } + } + function doTypeAliasChange(changes, file, name, info) { + const { enclosingNode, selection, typeParameters } = info; + const newTypeNode = factory.createTypeAliasDeclaration( + /*modifiers*/ + void 0, + name, + typeParameters.map((id) => factory.updateTypeParameterDeclaration( + id, + id.modifiers, + id.name, + id.constraint, + /*defaultType*/ + void 0 + )), + selection + ); + changes.insertNodeBefore( + file, + enclosingNode, + ignoreSourceNewlines(newTypeNode), + /*blankLineBetween*/ + true + ); + changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( + id.name, + /*typeArguments*/ + void 0 + ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace }); + } + function doInterfaceChange(changes, file, name, info) { + var _a; + const { enclosingNode, selection, typeParameters, typeElements } = info; + const newTypeNode = factory.createInterfaceDeclaration( + /*modifiers*/ + void 0, + name, + typeParameters, + /*heritageClauses*/ + void 0, + typeElements + ); + setTextRange(newTypeNode, (_a = typeElements[0]) == null ? void 0 : _a.parent); + changes.insertNodeBefore( + file, + enclosingNode, + ignoreSourceNewlines(newTypeNode), + /*blankLineBetween*/ + true + ); + changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( + id.name, + /*typeArguments*/ + void 0 + ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace }); + } + function doTypedefChange(changes, context, file, name, info) { + var _a; + const { enclosingNode, selection, typeParameters } = info; + setEmitFlags(selection, 3072 /* NoComments */ | 4096 /* NoNestedComments */); + const node = factory.createJSDocTypedefTag( + factory.createIdentifier("typedef"), + factory.createJSDocTypeExpression(selection), + factory.createIdentifier(name) + ); + const templates = []; + forEach(typeParameters, (typeParameter) => { + const constraint = getEffectiveConstraintOfTypeParameter(typeParameter); + const parameter = factory.createTypeParameterDeclaration( + /*modifiers*/ + void 0, + typeParameter.name + ); + const template = factory.createJSDocTemplateTag( + factory.createIdentifier("template"), + constraint && cast(constraint, isJSDocTypeExpression), + [parameter] + ); + templates.push(template); + }); + const jsDoc = factory.createJSDocComment( + /*comment*/ + void 0, + factory.createNodeArray(concatenate(templates, [node])) + ); + if (isJSDoc(enclosingNode)) { + const pos = enclosingNode.getStart(file); + const newLineCharacter = getNewLineOrDefaultFromHost(context.host, (_a = context.formatContext) == null ? void 0 : _a.options); + changes.insertNodeAt(file, enclosingNode.getStart(file), jsDoc, { + suffix: newLineCharacter + newLineCharacter + file.text.slice(getPrecedingNonSpaceCharacterPosition(file.text, pos - 1), pos) + }); + } else { + changes.insertNodeBefore( + file, + enclosingNode, + jsDoc, + /*blankLineBetween*/ + true + ); + } + changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( + id.name, + /*typeArguments*/ + void 0 + )))); + } + function getEnclosingNode(node, isJS) { + return findAncestor(node, isStatement) || (isJS ? findAncestor(node, isJSDoc) : void 0); + } + var refactorName3, extractToTypeAliasAction, extractToInterfaceAction, extractToTypeDefAction; + var init_extractType = __esm({ + "src/services/refactors/extractType.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName3 = "Extract type"; + extractToTypeAliasAction = { + name: "Extract to type alias", + description: getLocaleSpecificMessage(Diagnostics.Extract_to_type_alias), + kind: "refactor.extract.type" + }; + extractToInterfaceAction = { + name: "Extract to interface", + description: getLocaleSpecificMessage(Diagnostics.Extract_to_interface), + kind: "refactor.extract.interface" + }; + extractToTypeDefAction = { + name: "Extract to typedef", + description: getLocaleSpecificMessage(Diagnostics.Extract_to_typedef), + kind: "refactor.extract.typedef" + }; + registerRefactor(refactorName3, { + kinds: [ + extractToTypeAliasAction.kind, + extractToInterfaceAction.kind, + extractToTypeDefAction.kind + ], + getAvailableActions: function getRefactorActionsToExtractType(context) { + const info = getRangeToExtract(context, context.triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + return [{ + name: refactorName3, + description: getLocaleSpecificMessage(Diagnostics.Extract_type), + actions: info.isJS ? [extractToTypeDefAction] : append([extractToTypeAliasAction], info.typeElements && extractToInterfaceAction) + }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorName3, + description: getLocaleSpecificMessage(Diagnostics.Extract_type), + actions: [ + { ...extractToTypeDefAction, notApplicableReason: info.error }, + { ...extractToTypeAliasAction, notApplicableReason: info.error }, + { ...extractToInterfaceAction, notApplicableReason: info.error } + ] + }]; + } + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToExtractType(context, actionName2) { + const { file } = context; + const info = getRangeToExtract(context); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected to find a range to extract"); + const name = getUniqueName("NewType", file); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (changes) => { + switch (actionName2) { + case extractToTypeAliasAction.name: + Debug.assert(!info.isJS, "Invalid actionName/JS combo"); + return doTypeAliasChange(changes, file, name, info); + case extractToTypeDefAction.name: + Debug.assert(info.isJS, "Invalid actionName/JS combo"); + return doTypedefChange(changes, context, file, name, info); + case extractToInterfaceAction.name: + Debug.assert(!info.isJS && !!info.typeElements, "Invalid actionName/JS combo"); + return doInterfaceChange(changes, file, name, info); + default: + Debug.fail("Unexpected action name"); + } + }); + const renameFilename = file.fileName; + const renameLocation = getRenameLocation( + edits, + renameFilename, + name, + /*preferLastLocation*/ + false + ); + return { edits, renameFilename, renameLocation }; + } + }); + } + }); + + // src/services/refactors/helpers.ts + function isRefactorErrorInfo(info) { + return info.error !== void 0; + } + function refactorKindBeginsWith(known, requested) { + if (!requested) + return true; + return known.substr(0, requested.length) === requested; + } + var init_helpers = __esm({ + "src/services/refactors/helpers.ts"() { + "use strict"; + } + }); + + // src/services/refactors/moveToNewFile.ts + function doChange3(oldFile, program, toMove, changes, host, preferences, context) { + const checker = program.getTypeChecker(); + const usage = getUsageInfo(oldFile, toMove.all, checker); + const newFilename = createNewFileName(oldFile, program, context, host); + changes.createNewFile(oldFile, newFilename, getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences)); + addNewFileToTsconfig(program, changes, oldFile.fileName, newFilename, hostGetCanonicalFileName(host)); + } + function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences) { + const checker = program.getTypeChecker(); + const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective); + if (oldFile.externalModuleIndicator === void 0 && oldFile.commonJsModuleIndicator === void 0 && usage.oldImportsNeededByTargetFile.size === 0) { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return [...prologueDirectives, ...toMove.all]; + } + const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(newFilename, program, host, !!oldFile.commonJsModuleIndicator); + const quotePreference = getQuotePreference(oldFile, preferences); + const importsFromNewFile = createOldFileImportsFromTargetFile(oldFile, usage.oldFileImportsFromTargetFile, newFilename, program, host, useEsModuleSyntax, quotePreference); + if (importsFromNewFile) { + insertImports( + changes, + oldFile, + importsFromNewFile, + /*blankLineBetween*/ + true, + preferences + ); + } + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, newFilename, quotePreference); + const imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference); + const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromTargetFile, useEsModuleSyntax); + if (imports.length && body.length) { + return [ + ...prologueDirectives, + ...imports, + 4 /* NewLineTrivia */, + ...body + ]; + } + return [ + ...prologueDirectives, + ...imports, + ...body + ]; + } + function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference) { + const copiedOldImports = []; + for (const oldStatement of oldFile.statements) { + forEachImportInStatement(oldStatement, (i) => { + append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); + }); + } + let oldFileDefault; + const oldFileNamedImports = []; + const markSeenTop = nodeSeenTracker(); + newFileImportsFromOldFile.forEach((symbol) => { + if (!symbol.declarations) { + return; + } + for (const decl of symbol.declarations) { + if (!isTopLevelDeclaration(decl)) + continue; + const name = nameOfTopLevelDeclaration(decl); + if (!name) + continue; + const top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) { + addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); + } + if (hasSyntacticModifier(decl, 1024 /* Default */)) { + oldFileDefault = name; + } else { + oldFileNamedImports.push(name.text); + } + } + }); + append(copiedOldImports, makeImportOrRequire(oldFile, oldFileDefault, oldFileNamedImports, getBaseFileName(oldFile.fileName), program, host, useEsModuleSyntax, quotePreference)); + return copiedOldImports; + } + var refactorName4, description, moveToNewFileAction; + var init_moveToNewFile = __esm({ + "src/services/refactors/moveToNewFile.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName4 = "Move to a new file"; + description = getLocaleSpecificMessage(Diagnostics.Move_to_a_new_file); + moveToNewFileAction = { + name: refactorName4, + description, + kind: "refactor.move.newFile" + }; + registerRefactor(refactorName4, { + kinds: [moveToNewFileAction.kind], + getAvailableActions: function getRefactorActionsToMoveToNewFile(context) { + const statements = getStatementsToMove(context); + if (context.preferences.allowTextChangesInNewFiles && statements) { + return [{ name: refactorName4, description, actions: [moveToNewFileAction] }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorName4, + description, + actions: [{ ...moveToNewFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] + }]; + } + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToMoveToNewFile(context, actionName2) { + Debug.assert(actionName2 === refactorName4, "Wrong refactor invoked"); + const statements = Debug.checkDefined(getStatementsToMove(context)); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange3(context.file, context.program, statements, t, context.host, context.preferences, context)); + return { edits, renameFilename: void 0, renameLocation: void 0 }; + } + }); + } + }); + + // src/services/refactors/moveToFile.ts + function doChange4(context, oldFile, targetFile, program, toMove, changes, host, preferences) { + var _a; + const checker = program.getTypeChecker(); + const usage = getUsageInfo(oldFile, toMove.all, checker); + if (!host.fileExists(targetFile) || host.fileExists(targetFile) && ((_a = program.getSourceFile(targetFile)) == null ? void 0 : _a.statements.length) === 0) { + changes.createNewFile(oldFile, targetFile, getNewStatementsAndRemoveFromOldFile2(oldFile, targetFile, usage, changes, toMove, program, host, preferences)); + addNewFileToTsconfig(program, changes, oldFile.fileName, targetFile, hostGetCanonicalFileName(host)); + } else { + const targetSourceFile = Debug.checkDefined(program.getSourceFile(targetFile)); + const importAdder = ts_codefix_exports.createImportAdder(targetSourceFile, context.program, context.preferences, context.host); + getNewStatementsAndRemoveFromOldFile2(oldFile, targetSourceFile, usage, changes, toMove, program, host, preferences, importAdder); + } + } + function getNewStatementsAndRemoveFromOldFile2(oldFile, targetFile, usage, changes, toMove, program, host, preferences, importAdder) { + const checker = program.getTypeChecker(); + const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective); + if (oldFile.externalModuleIndicator === void 0 && oldFile.commonJsModuleIndicator === void 0 && usage.oldImportsNeededByTargetFile.size === 0 && usage.targetFileImportsFromOldFile.size === 0 && typeof targetFile === "string") { + deleteMovedStatements(oldFile, toMove.ranges, changes); + return [...prologueDirectives, ...toMove.all]; + } + const targetFileName = typeof targetFile === "string" ? targetFile : targetFile.fileName; + const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(targetFileName, program, host, !!oldFile.commonJsModuleIndicator); + const quotePreference = getQuotePreference(oldFile, preferences); + const importsFromTargetFile = createOldFileImportsFromTargetFile(oldFile, usage.oldFileImportsFromTargetFile, targetFileName, program, host, useEsModuleSyntax, quotePreference); + if (importsFromTargetFile) { + insertImports( + changes, + oldFile, + importsFromTargetFile, + /*blankLineBetween*/ + true, + preferences + ); + } + deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); + deleteMovedStatements(oldFile, toMove.ranges, changes); + updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, targetFileName, quotePreference); + const imports = getTargetFileImportsAndAddExportInOldFile(oldFile, targetFileName, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference, importAdder); + const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromTargetFile, useEsModuleSyntax); + if (typeof targetFile !== "string") { + if (targetFile.statements.length > 0) { + changes.insertNodesAfter(targetFile, targetFile.statements[targetFile.statements.length - 1], body); + } + if (imports.length > 0) { + insertImports( + changes, + targetFile, + imports, + /*blankLineBetween*/ + true, + preferences + ); + } + } + if (importAdder) { + importAdder.writeFixes(changes); + } + if (imports.length && body.length) { + return [ + ...prologueDirectives, + ...imports, + 4 /* NewLineTrivia */, + ...body + ]; + } + return [ + ...prologueDirectives, + ...imports, + ...body + ]; + } + function getTargetFileImportsAndAddExportInOldFile(oldFile, targetFile, importsToCopy, targetFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference, importAdder) { + const copiedOldImports = []; + if (importAdder) { + importsToCopy.forEach((isValidTypeOnlyUseSite, symbol) => { + try { + importAdder.addImportFromExportedSymbol(skipAlias(symbol, checker), isValidTypeOnlyUseSite); + } catch { + for (const oldStatement of oldFile.statements) { + forEachImportInStatement(oldStatement, (i) => { + append(copiedOldImports, filterImport(i, factory.createStringLiteral(moduleSpecifierFromImport(i).text), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); + }); + } + } + }); + } else { + const targetSourceFile = program.getSourceFile(targetFile); + for (const oldStatement of oldFile.statements) { + forEachImportInStatement(oldStatement, (i) => { + var _a, _b; + const moduleSpecifier = moduleSpecifierFromImport(i); + const resolved = (_a = oldFile.resolvedModules) == null ? void 0 : _a.get(moduleSpecifier.text, getModeForUsageLocation(oldFile, moduleSpecifier)); + const fileName = (_b = resolved == null ? void 0 : resolved.resolvedModule) == null ? void 0 : _b.resolvedFileName; + if (fileName && targetSourceFile) { + const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), targetSourceFile, targetSourceFile.path, fileName, createModuleSpecifierResolutionHost(program, host)); + append(copiedOldImports, filterImport(i, makeStringLiteral(newModuleSpecifier, quotePreference), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); + } else { + append(copiedOldImports, filterImport(i, factory.createStringLiteral(moduleSpecifierFromImport(i).text), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); + } + }); + } + } + const targetFileSourceFile = program.getSourceFile(targetFile); + let oldFileDefault; + const oldFileNamedImports = []; + const markSeenTop = nodeSeenTracker(); + targetFileImportsFromOldFile.forEach((symbol) => { + if (!symbol.declarations) { + return; + } + for (const decl of symbol.declarations) { + if (!isTopLevelDeclaration(decl)) + continue; + const name = nameOfTopLevelDeclaration(decl); + if (!name) + continue; + const top = getTopLevelDeclarationStatement(decl); + if (markSeenTop(top)) { + addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); + } + if (importAdder && checker.isUnknownSymbol(symbol)) { + importAdder.addImportFromExportedSymbol(skipAlias(symbol, checker)); + } else { + if (hasSyntacticModifier(decl, 1024 /* Default */)) { + oldFileDefault = name; + } else { + oldFileNamedImports.push(name.text); + } + } + } + }); + 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)); + } + function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { + const cfg = program.getCompilerOptions().configFile; + if (!cfg) + return; + const newFileAbsolutePath = normalizePath(combinePaths(oldFileName, "..", newFileNameWithExtension)); + 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) => 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); + } + } + function deleteMovedStatements(sourceFile, moved, changes) { + for (const { first: first2, afterLast } of moved) { + changes.deleteNodeRangeExcludingEnd(sourceFile, first2, afterLast); + } + } + function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { + for (const statement of oldFile.statements) { + if (contains(toMove, statement)) + continue; + forEachImportInStatement(statement, (i) => deleteUnusedImports(oldFile, i, changes, (name) => toDelete.has(checker.getSymbolAtLocation(name)))); + } + } + function updateImportsInOtherFiles(changes, program, host, oldFile, movedSymbols, targetFileName, quotePreference) { + const checker = program.getTypeChecker(); + for (const sourceFile of program.getSourceFiles()) { + if (sourceFile === oldFile) + continue; + for (const statement of sourceFile.statements) { + forEachImportInStatement(statement, (importNode) => { + if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) + return; + const shouldMove = (name) => { + const symbol = isBindingElement(name.parent) ? getPropertySymbolFromBindingElement(checker, name.parent) : skipAlias(checker.getSymbolAtLocation(name), checker); + return !!symbol && movedSymbols.has(symbol); + }; + deleteUnusedImports(sourceFile, importNode, changes, shouldMove); + const pathToTargetFileWithExtension = resolvePath(getDirectoryPath(oldFile.path), targetFileName); + const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToTargetFileWithExtension, createModuleSpecifierResolutionHost(program, host)); + const newImportDeclaration = filterImport(importNode, makeStringLiteral(newModuleSpecifier, quotePreference), shouldMove); + if (newImportDeclaration) + changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); + const ns = getNamespaceLikeImport(importNode); + if (ns) + updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, ns, importNode, quotePreference); + }); + } + } + } + function getNamespaceLikeImport(node) { + switch (node.kind) { + case 271 /* ImportDeclaration */: + return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 273 /* NamespaceImport */ ? node.importClause.namedBindings.name : void 0; + case 270 /* ImportEqualsDeclaration */: + return node.name; + case 259 /* VariableDeclaration */: + return tryCast(node.name, isIdentifier); + default: + return Debug.assertNever(node, `Unexpected node kind ${node.kind}`); + } + } + function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, oldImportId, oldImportNode, quotePreference) { + const preferredNewNamespaceName = ts_codefix_exports.moduleSpecifierToValidIdentifier(newModuleSpecifier, 99 /* ESNext */); + let needUniqueName = false; + const toChange = []; + ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, (ref) => { + if (!isPropertyAccessExpression(ref.parent)) + return; + needUniqueName = needUniqueName || !!checker.resolveName( + preferredNewNamespaceName, + ref, + 67108863 /* All */, + /*excludeGlobals*/ + true + ); + if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) { + toChange.push(ref); + } + }); + if (toChange.length) { + const newNamespaceName = needUniqueName ? getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; + for (const ref of toChange) { + changes.replaceNode(sourceFile, ref, factory.createIdentifier(newNamespaceName)); + } + changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, preferredNewNamespaceName, newModuleSpecifier, quotePreference)); + } + } + function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier, quotePreference) { + const newNamespaceId = factory.createIdentifier(newNamespaceName); + const newModuleString = makeStringLiteral(newModuleSpecifier, quotePreference); + switch (node.kind) { + case 271 /* ImportDeclaration */: + return factory.createImportDeclaration( + /*modifiers*/ + void 0, + factory.createImportClause( + /*isTypeOnly*/ + false, + /*name*/ + void 0, + factory.createNamespaceImport(newNamespaceId) + ), + newModuleString, + /*assertClause*/ + void 0 + ); + case 270 /* ImportEqualsDeclaration */: + return factory.createImportEqualsDeclaration( + /*modifiers*/ + void 0, + /*isTypeOnly*/ + false, + newNamespaceId, + factory.createExternalModuleReference(newModuleString) + ); + case 259 /* VariableDeclaration */: + return factory.createVariableDeclaration( + newNamespaceId, + /*exclamationToken*/ + void 0, + /*type*/ + void 0, + createRequireCall(newModuleString) + ); + default: + return Debug.assertNever(node, `Unexpected node kind ${node.kind}`); + } + } + function createRequireCall(moduleSpecifier) { + return factory.createCallExpression( + factory.createIdentifier("require"), + /*typeArguments*/ + void 0, + [moduleSpecifier] + ); + } + function moduleSpecifierFromImport(i) { + return i.kind === 271 /* ImportDeclaration */ ? i.moduleSpecifier : i.kind === 270 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]; + } + function forEachImportInStatement(statement, cb) { + if (isImportDeclaration(statement)) { + if (isStringLiteral(statement.moduleSpecifier)) + cb(statement); + } else if (isImportEqualsDeclaration(statement)) { + if (isExternalModuleReference(statement.moduleReference) && isStringLiteralLike(statement.moduleReference.expression)) { + cb(statement); + } + } else if (isVariableStatement(statement)) { + for (const decl of statement.declarationList.declarations) { + if (decl.initializer && isRequireCall( + decl.initializer, + /*requireStringLiteralLikeArgument*/ + true + )) { + cb(decl); + } + } + } + } + function createOldFileImportsFromTargetFile(sourceFile, targetFileNeedExport, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference) { + let defaultImport; + const imports = []; + targetFileNeedExport.forEach((symbol) => { + if (symbol.escapedName === "default" /* Default */) { + defaultImport = factory.createIdentifier(symbolNameNoDefault(symbol)); + } else { + imports.push(symbol.name); + } + }); + return makeImportOrRequire(sourceFile, defaultImport, imports, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference); + } + function makeImportOrRequire(sourceFile, defaultImport, imports, targetFileNameWithExtension, program, host, useEs6Imports, quotePreference) { + const pathToTargetFile = resolvePath(getDirectoryPath(sourceFile.path), targetFileNameWithExtension); + const pathToTargetFileWithCorrectExtension = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToTargetFile, createModuleSpecifierResolutionHost(program, host)); + if (useEs6Imports) { + const specifiers = imports.map((i) => factory.createImportSpecifier( + /*isTypeOnly*/ + false, + /*propertyName*/ + void 0, + factory.createIdentifier(i) + )); + return makeImportIfNecessary(defaultImport, specifiers, pathToTargetFileWithCorrectExtension, quotePreference); + } else { + Debug.assert(!defaultImport, "No default import should exist"); + const bindingElements = imports.map((i) => factory.createBindingElement( + /*dotDotDotToken*/ + void 0, + /*propertyName*/ + void 0, + i + )); + return bindingElements.length ? makeVariableStatement( + factory.createObjectBindingPattern(bindingElements), + /*type*/ + void 0, + createRequireCall(makeStringLiteral(pathToTargetFileWithCorrectExtension, quotePreference)) + ) : void 0; + } + } + function makeVariableStatement(name, type, initializer, flags = 2 /* Const */) { + return factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList([factory.createVariableDeclaration( + name, + /*exclamationToken*/ + void 0, + type, + initializer + )], flags) + ); + } + function addExports(sourceFile, toMove, needExport, useEs6Exports) { + return flatMap(toMove, (statement) => { + if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, (d) => { + var _a; + return needExport.has(Debug.checkDefined((_a = tryCast(d, canHaveSymbol)) == null ? void 0 : _a.symbol)); + })) { + const exports = addExport(getSynthesizedDeepClone(statement), useEs6Exports); + if (exports) + return exports; + } + return getSynthesizedDeepClone(statement); + }); + } + function isExported(sourceFile, decl, useEs6Exports, name) { + var _a; + if (useEs6Exports) { + return !isExpressionStatement(decl) && hasSyntacticModifier(decl, 1 /* Export */) || !!(name && sourceFile.symbol && ((_a = sourceFile.symbol.exports) == null ? void 0 : _a.has(name.escapedText))); + } + return !!sourceFile.symbol && !!sourceFile.symbol.exports && getNamesToExportInCommonJS(decl).some((name2) => sourceFile.symbol.exports.has(escapeLeadingUnderscores(name2))); + } + function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { + switch (importDecl.kind) { + case 271 /* ImportDeclaration */: + deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); + break; + case 270 /* ImportEqualsDeclaration */: + if (isUnused(importDecl.name)) { + changes.delete(sourceFile, importDecl); + } + break; + case 259 /* VariableDeclaration */: + deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); + break; + default: + Debug.assertNever(importDecl, `Unexpected import decl kind ${importDecl.kind}`); + } + } + function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { + if (!importDecl.importClause) + return; + const { name, namedBindings } = importDecl.importClause; + const defaultUnused = !name || isUnused(name); + const namedBindingsUnused = !namedBindings || (namedBindings.kind === 273 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every((e) => isUnused(e.name))); + if (defaultUnused && namedBindingsUnused) { + changes.delete(sourceFile, importDecl); + } else { + if (name && defaultUnused) { + changes.delete(sourceFile, name); + } + if (namedBindings) { + if (namedBindingsUnused) { + changes.replaceNode( + sourceFile, + importDecl.importClause, + factory.updateImportClause( + importDecl.importClause, + importDecl.importClause.isTypeOnly, + name, + /*namedBindings*/ + void 0 + ) + ); + } else if (namedBindings.kind === 274 /* NamedImports */) { + for (const element of namedBindings.elements) { + if (isUnused(element.name)) + changes.delete(sourceFile, element); + } + } + } + } + } + function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { + const { name } = varDecl; + switch (name.kind) { + case 80 /* 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 + ); + } else { + changes.delete(sourceFile, name); + } + } + break; + case 206 /* ArrayBindingPattern */: + break; + case 205 /* 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 + ); + } else { + for (const element of name.elements) { + if (isIdentifier(element.name) && isUnused(element.name)) { + changes.delete(sourceFile, element.name); + } + } + } + break; + } + } + function isTopLevelDeclarationStatement(node) { + Debug.assert(isSourceFile(node.parent), "Node parent should be a SourceFile"); + return isNonVariableTopLevelDeclaration(node) || isVariableStatement(node); + } + function addExport(decl, useEs6Exports) { + return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); + } + function addEs6Export(d) { + const modifiers = canHaveModifiers(d) ? concatenate([factory.createModifier(95 /* ExportKeyword */)], getModifiers(d)) : void 0; + switch (d.kind) { + case 261 /* FunctionDeclaration */: + return factory.updateFunctionDeclaration(d, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); + case 262 /* ClassDeclaration */: + const decorators = canHaveDecorators(d) ? getDecorators(d) : void 0; + return factory.updateClassDeclaration(d, concatenate(decorators, modifiers), d.name, d.typeParameters, d.heritageClauses, d.members); + case 242 /* VariableStatement */: + return factory.updateVariableStatement(d, modifiers, d.declarationList); + case 266 /* ModuleDeclaration */: + return factory.updateModuleDeclaration(d, modifiers, d.name, d.body); + case 265 /* EnumDeclaration */: + return factory.updateEnumDeclaration(d, modifiers, d.name, d.members); + case 264 /* TypeAliasDeclaration */: + return factory.updateTypeAliasDeclaration(d, modifiers, d.name, d.typeParameters, d.type); + case 263 /* InterfaceDeclaration */: + return factory.updateInterfaceDeclaration(d, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); + case 270 /* ImportEqualsDeclaration */: + return factory.updateImportEqualsDeclaration(d, modifiers, d.isTypeOnly, d.name, d.moduleReference); + case 243 /* ExpressionStatement */: + return Debug.fail(); + default: + return Debug.assertNever(d, `Unexpected declaration kind ${d.kind}`); + } + } + function addCommonjsExport(decl) { + return [decl, ...getNamesToExportInCommonJS(decl).map(createExportAssignment)]; + } + function createExportAssignment(name) { + return factory.createExpressionStatement( + factory.createBinaryExpression( + factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(name)), + 64 /* EqualsToken */, + factory.createIdentifier(name) + ) + ); + } + function getNamesToExportInCommonJS(decl) { + switch (decl.kind) { + case 261 /* FunctionDeclaration */: + case 262 /* ClassDeclaration */: + return [decl.name.text]; + case 242 /* VariableStatement */: + return mapDefined(decl.declarationList.declarations, (d) => isIdentifier(d.name) ? d.name.text : void 0); + case 266 /* ModuleDeclaration */: + case 265 /* EnumDeclaration */: + case 264 /* TypeAliasDeclaration */: + case 263 /* InterfaceDeclaration */: + case 270 /* ImportEqualsDeclaration */: + return emptyArray; + case 243 /* ExpressionStatement */: + return Debug.fail("Can't export an ExpressionStatement"); + default: + return Debug.assertNever(decl, `Unexpected decl kind ${decl.kind}`); + } + } + function filterImport(i, moduleSpecifier, keep) { + switch (i.kind) { + case 271 /* ImportDeclaration */: { + const clause = i.importClause; + if (!clause) + return void 0; + const defaultImport = clause.name && keep(clause.name) ? clause.name : void 0; + const namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); + return defaultImport || namedBindings ? factory.createImportDeclaration( + /*modifiers*/ + void 0, + factory.createImportClause(clause.isTypeOnly, defaultImport, namedBindings), + getSynthesizedDeepClone(moduleSpecifier), + /*assertClause*/ + void 0 + ) : void 0; + } + case 270 /* ImportEqualsDeclaration */: + return keep(i.name) ? i : void 0; + case 259 /* VariableDeclaration */: { + const name = filterBindingName(i.name, keep); + return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : void 0; + } + default: + return Debug.assertNever(i, `Unexpected import kind ${i.kind}`); + } + } + function filterNamedBindings(namedBindings, keep) { + if (namedBindings.kind === 273 /* NamespaceImport */) { + return keep(namedBindings.name) ? namedBindings : void 0; + } else { + const newElements = namedBindings.elements.filter((e) => keep(e.name)); + return newElements.length ? factory.createNamedImports(newElements) : void 0; + } + } + function filterBindingName(name, keep) { + switch (name.kind) { + case 80 /* Identifier */: + return keep(name) ? name : void 0; + case 206 /* ArrayBindingPattern */: + return name; + case 205 /* ObjectBindingPattern */: { + const newElements = name.elements.filter((prop) => prop.propertyName || !isIdentifier(prop.name) || keep(prop.name)); + return newElements.length ? factory.createObjectBindingPattern(newElements) : void 0; + } + } + } + function nameOfTopLevelDeclaration(d) { + return isExpressionStatement(d) ? tryCast(d.expression.left.name, isIdentifier) : tryCast(d.name, isIdentifier); + } + function getTopLevelDeclarationStatement(d) { + switch (d.kind) { + case 259 /* VariableDeclaration */: + return d.parent.parent; + case 207 /* BindingElement */: + return getTopLevelDeclarationStatement( + cast(d.parent.parent, (p) => isVariableDeclaration(p) || isBindingElement(p)) + ); + default: + return d; + } + } + function addExportToChanges(sourceFile, decl, name, changes, useEs6Exports) { + if (isExported(sourceFile, decl, useEs6Exports, name)) + return; + if (useEs6Exports) { + if (!isExpressionStatement(decl)) + changes.insertExportModifier(sourceFile, decl); + } else { + const names = getNamesToExportInCommonJS(decl); + if (names.length !== 0) + changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); + } + } + function createNewFileName(oldFile, program, context, host) { + const checker = program.getTypeChecker(); + const toMove = getStatementsToMove(context); + let usage; + if (toMove) { + usage = getUsageInfo(oldFile, toMove.all, checker); + 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, + currentDirectory, + host + ) + ) + extension; + return newFileName; + } + return ""; + } + function getRangeToMove(context) { + const { file } = context; + const range = createTextRangeFromSpan(getRefactorContextSpan(context)); + const { statements } = file; + const startNodeIndex = findIndex(statements, (s) => s.end > range.pos); + if (startNodeIndex === -1) + return void 0; + const startStatement = statements[startNodeIndex]; + if (isNamedDeclaration(startStatement) && startStatement.name && rangeContainsRange(startStatement.name, range)) { + return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; + } + if (range.pos > startStatement.getStart(file)) + return void 0; + const afterEndNodeIndex = findIndex(statements, (s) => s.end > range.end, startNodeIndex); + if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) + return void 0; + return { + toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), + afterLast: afterEndNodeIndex === -1 ? void 0 : statements[afterEndNodeIndex] + }; + } + function getStatementsToMove(context) { + const rangeToMove = getRangeToMove(context); + if (rangeToMove === void 0) + return void 0; + const all = []; + const ranges = []; + const { toMove, afterLast } = rangeToMove; + getRangesWhere(toMove, isAllowedStatementToMove, (start, afterEndIndex) => { + for (let i = start; i < afterEndIndex; i++) + all.push(toMove[i]); + ranges.push({ first: toMove[start], afterLast }); + }); + return all.length === 0 ? void 0 : { all, ranges }; + } + function isAllowedStatementToMove(statement) { + return !isPureImport(statement) && !isPrologueDirective(statement); + } + function isPureImport(node) { + switch (node.kind) { + case 271 /* ImportDeclaration */: + return true; + case 270 /* ImportEqualsDeclaration */: + return !hasSyntacticModifier(node, 1 /* Export */); + case 242 /* VariableStatement */: + return node.declarationList.declarations.every((d) => !!d.initializer && isRequireCall( + d.initializer, + /*requireStringLiteralLikeArgument*/ + true + )); + default: + return false; + } + } + function getUsageInfo(oldFile, toMove, checker) { + const movedSymbols = /* @__PURE__ */ new Set(); + const oldImportsNeededByTargetFile = /* @__PURE__ */ new Map(); + const targetFileImportsFromOldFile = /* @__PURE__ */ new Set(); + const containsJsx = find(toMove, (statement) => !!(statement.transformFlags & 2 /* ContainsJsx */)); + const jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx); + if (jsxNamespaceSymbol) { + oldImportsNeededByTargetFile.set(jsxNamespaceSymbol, false); + } + for (const statement of toMove) { + forEachTopLevelDeclaration(statement, (decl) => { + movedSymbols.add(Debug.checkDefined(isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here")); + }); + } + for (const statement of toMove) { + forEachReference(statement, checker, (symbol, isValidTypeOnlyUseSite) => { + if (!symbol.declarations) + return; + for (const decl of symbol.declarations) { + if (isInImport(decl)) { + const prevIsTypeOnly = oldImportsNeededByTargetFile.get(symbol); + oldImportsNeededByTargetFile.set(symbol, prevIsTypeOnly === void 0 ? isValidTypeOnlyUseSite : prevIsTypeOnly && isValidTypeOnlyUseSite); + } else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) { + targetFileImportsFromOldFile.add(symbol); + } + } + }); + } + const unusedImportsFromOldFile = new Set(oldImportsNeededByTargetFile.keys()); + const oldFileImportsFromTargetFile = /* @__PURE__ */ new Set(); + for (const statement of oldFile.statements) { + if (contains(toMove, statement)) + continue; + if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) { + unusedImportsFromOldFile.delete(jsxNamespaceSymbol); + } + forEachReference(statement, checker, (symbol) => { + if (movedSymbols.has(symbol)) + oldFileImportsFromTargetFile.add(symbol); + unusedImportsFromOldFile.delete(symbol); + }); + } + return { movedSymbols, targetFileImportsFromOldFile, oldFileImportsFromTargetFile, oldImportsNeededByTargetFile, unusedImportsFromOldFile }; + function getJsxNamespaceSymbol(containsJsx2) { + if (containsJsx2 === void 0) { + return void 0; + } + const jsxNamespace = checker.getJsxNamespace(containsJsx2); + const jsxNamespaceSymbol2 = checker.resolveName( + jsxNamespace, + containsJsx2, + 1920 /* Namespace */, + /*excludeGlobals*/ + true + ); + return !!jsxNamespaceSymbol2 && some(jsxNamespaceSymbol2.declarations, isInImport) ? jsxNamespaceSymbol2 : void 0; + } + } + function makeUniqueFilename(proposedFilename, extension, inDirectory, host) { + let newFilename = proposedFilename; + for (let i = 1; ; i++) { + const name = combinePaths(inDirectory, newFilename + extension); + if (!host.fileExists(name)) + return newFilename; + newFilename = `${proposedFilename}.${i}`; + } + } + function inferNewFileName(importsFromNewFile, movedSymbols) { + return forEachKey(importsFromNewFile, symbolNameNoDefault) || forEachKey(movedSymbols, symbolNameNoDefault) || "newFile"; + } + function forEachReference(node, checker, onReference) { + node.forEachChild(function cb(node2) { + if (isIdentifier(node2) && !isDeclarationName(node2)) { + const sym = checker.getSymbolAtLocation(node2); + if (sym) + onReference(sym, isValidTypeOnlyAliasUseSite(node2)); + } else { + node2.forEachChild(cb); + } + }); + } + function forEachTopLevelDeclaration(statement, cb) { + switch (statement.kind) { + case 261 /* FunctionDeclaration */: + case 262 /* ClassDeclaration */: + case 266 /* ModuleDeclaration */: + case 265 /* EnumDeclaration */: + case 264 /* TypeAliasDeclaration */: + case 263 /* InterfaceDeclaration */: + case 270 /* ImportEqualsDeclaration */: + return cb(statement); + case 242 /* VariableStatement */: + return firstDefined(statement.declarationList.declarations, (decl) => forEachTopLevelDeclarationInBindingName(decl.name, cb)); + case 243 /* ExpressionStatement */: { + const { expression } = statement; + return isBinaryExpression(expression) && getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : void 0; + } + } + } + function isInImport(decl) { + switch (decl.kind) { + case 270 /* ImportEqualsDeclaration */: + case 275 /* ImportSpecifier */: + case 272 /* ImportClause */: + case 273 /* NamespaceImport */: + return true; + case 259 /* VariableDeclaration */: + return isVariableDeclarationInImport(decl); + case 207 /* BindingElement */: + return isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); + default: + return false; + } + } + function isVariableDeclarationInImport(decl) { + return isSourceFile(decl.parent.parent.parent) && !!decl.initializer && isRequireCall( + decl.initializer, + /*requireStringLiteralLikeArgument*/ + true + ); + } + function isTopLevelDeclaration(node) { + return isNonVariableTopLevelDeclaration(node) && isSourceFile(node.parent) || isVariableDeclaration(node) && isSourceFile(node.parent.parent.parent); + } + function sourceFileOfTopLevelDeclaration(node) { + return isVariableDeclaration(node) ? node.parent.parent.parent : node.parent; + } + function forEachTopLevelDeclarationInBindingName(name, cb) { + switch (name.kind) { + case 80 /* Identifier */: + return cb(cast(name.parent, (x) => isVariableDeclaration(x) || isBindingElement(x))); + case 206 /* ArrayBindingPattern */: + case 205 /* ObjectBindingPattern */: + return firstDefined(name.elements, (em) => isOmittedExpression(em) ? void 0 : forEachTopLevelDeclarationInBindingName(em.name, cb)); + default: + return Debug.assertNever(name, `Unexpected name kind ${name.kind}`); + } + } + function isNonVariableTopLevelDeclaration(node) { + switch (node.kind) { + case 261 /* FunctionDeclaration */: + case 262 /* ClassDeclaration */: + case 266 /* ModuleDeclaration */: + case 265 /* EnumDeclaration */: + case 264 /* TypeAliasDeclaration */: + case 263 /* InterfaceDeclaration */: + case 270 /* ImportEqualsDeclaration */: + return true; + default: + return false; + } + } + var refactorNameForMoveToFile, description2, moveToFileAction; + var init_moveToFile = __esm({ + "src/services/refactors/moveToFile.ts"() { + "use strict"; + init_moduleSpecifiers(); + init_ts4(); + init_refactorProvider(); + refactorNameForMoveToFile = "Move to file"; + description2 = getLocaleSpecificMessage(Diagnostics.Move_to_file); + moveToFileAction = { + name: "Move to file", + description: description2, + kind: "refactor.move.file" + }; + registerRefactor(refactorNameForMoveToFile, { + kinds: [moveToFileAction.kind], + getAvailableActions: function getRefactorActionsToMoveToFile(context, interactiveRefactorArguments) { + const statements = getStatementsToMove(context); + if (!interactiveRefactorArguments) { + return emptyArray; + } + if (context.preferences.allowTextChangesInNewFiles && statements) { + return [{ name: refactorNameForMoveToFile, description: description2, actions: [moveToFileAction] }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorNameForMoveToFile, + description: description2, + actions: [{ ...moveToFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] + }]; + } + return emptyArray; + }, + getEditsForAction: function getRefactorEditsToMoveToFile(context, actionName2, interactiveRefactorArguments) { + Debug.assert(actionName2 === refactorNameForMoveToFile, "Wrong refactor invoked"); + const statements = Debug.checkDefined(getStatementsToMove(context)); + Debug.assert(interactiveRefactorArguments, "No interactive refactor arguments available"); + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange4(context, context.file, interactiveRefactorArguments.targetFile, context.program, statements, t, context.host, context.preferences)); + return { edits, renameFilename: void 0, renameLocation: void 0 }; + } + }); + } + }); + + // src/services/refactors/convertOverloadListToSingleSignature.ts + function getRefactorActionsToConvertOverloadsToOneSignature(context) { + const { file, startPosition, program } = context; + const info = getConvertableOverloadListAtPosition(file, startPosition, program); + if (!info) + return emptyArray; + return [{ + name: refactorName5, + description: refactorDescription, + actions: [functionOverloadAction] + }]; + } + function getRefactorEditsToConvertOverloadsToOneSignature(context) { + const { file, startPosition, program } = context; + const signatureDecls = getConvertableOverloadListAtPosition(file, startPosition, program); + if (!signatureDecls) + return void 0; + const checker = program.getTypeChecker(); + const lastDeclaration = signatureDecls[signatureDecls.length - 1]; + let updated = lastDeclaration; + switch (lastDeclaration.kind) { + case 172 /* MethodSignature */: { + updated = factory.updateMethodSignature( + lastDeclaration, + lastDeclaration.modifiers, + lastDeclaration.name, + lastDeclaration.questionToken, + lastDeclaration.typeParameters, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.type + ); + break; + } + case 173 /* MethodDeclaration */: { + updated = factory.updateMethodDeclaration( + lastDeclaration, + lastDeclaration.modifiers, + lastDeclaration.asteriskToken, + lastDeclaration.name, + lastDeclaration.questionToken, + lastDeclaration.typeParameters, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.type, + lastDeclaration.body + ); + break; + } + case 178 /* CallSignature */: { + updated = factory.updateCallSignature( + lastDeclaration, + lastDeclaration.typeParameters, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.type + ); + break; + } + case 175 /* Constructor */: { + updated = factory.updateConstructorDeclaration( + lastDeclaration, + lastDeclaration.modifiers, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.body + ); + break; + } + case 179 /* ConstructSignature */: { + updated = factory.updateConstructSignature( + lastDeclaration, + lastDeclaration.typeParameters, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.type + ); + break; + } + case 261 /* FunctionDeclaration */: { + updated = factory.updateFunctionDeclaration( + lastDeclaration, + lastDeclaration.modifiers, + lastDeclaration.asteriskToken, + lastDeclaration.name, + lastDeclaration.typeParameters, + getNewParametersForCombinedSignature(signatureDecls), + lastDeclaration.type, + lastDeclaration.body + ); + break; + } + default: + return Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring"); + } + if (updated === lastDeclaration) { + return; + } + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => { + t.replaceNodeRange(file, signatureDecls[0], signatureDecls[signatureDecls.length - 1], updated); + }); + return { renameFilename: void 0, renameLocation: void 0, edits }; + function getNewParametersForCombinedSignature(signatureDeclarations) { + const lastSig = signatureDeclarations[signatureDeclarations.length - 1]; + if (isFunctionLikeDeclaration(lastSig) && lastSig.body) { + signatureDeclarations = signatureDeclarations.slice(0, signatureDeclarations.length - 1); + } + return factory.createNodeArray([ + factory.createParameterDeclaration( + /*modifiers*/ + void 0, + factory.createToken(26 /* DotDotDotToken */), + "args", + /*questionToken*/ + void 0, + factory.createUnionTypeNode(map(signatureDeclarations, convertSignatureParametersToTuple)) + ) + ]); + } + function convertSignatureParametersToTuple(decl) { + const members = map(decl.parameters, convertParameterToNamedTupleMember); + return setEmitFlags(factory.createTupleTypeNode(members), some(members, (m) => !!length(getSyntheticLeadingComments(m))) ? 0 /* None */ : 1 /* SingleLine */); + } + function convertParameterToNamedTupleMember(p) { + Debug.assert(isIdentifier(p.name)); + const result = setTextRange(factory.createNamedTupleMember( + p.dotDotDotToken, + p.name, + p.questionToken, + p.type || factory.createKeywordTypeNode(133 /* AnyKeyword */) + ), p); + const parameterDocComment = p.symbol && p.symbol.getDocumentationComment(checker); + if (parameterDocComment) { + const newComment = displayPartsToString(parameterDocComment); + if (newComment.length) { + setSyntheticLeadingComments(result, [{ + text: `* +${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} + `, + kind: 3 /* MultiLineCommentTrivia */, + pos: -1, + end: -1, + hasTrailingNewLine: true, + hasLeadingNewline: true + }]); + } + } + return result; + } + } + function isConvertableSignatureDeclaration(d) { + switch (d.kind) { + case 172 /* MethodSignature */: + case 173 /* MethodDeclaration */: + case 178 /* CallSignature */: + case 175 /* Constructor */: + case 179 /* ConstructSignature */: + case 261 /* FunctionDeclaration */: + return true; + } + return false; + } + function getConvertableOverloadListAtPosition(file, startPosition, program) { + const node = getTokenAtPosition(file, startPosition); + const containingDecl = findAncestor(node, isConvertableSignatureDeclaration); + if (!containingDecl) { + return; + } + if (isFunctionLikeDeclaration(containingDecl) && containingDecl.body && rangeContainsPosition(containingDecl.body, startPosition)) { + return; + } + const checker = program.getTypeChecker(); + const signatureSymbol = containingDecl.symbol; + if (!signatureSymbol) { + return; + } + const decls = signatureSymbol.declarations; + if (length(decls) <= 1) { + return; + } + if (!every(decls, (d) => getSourceFileOfNode(d) === file)) { + return; + } + if (!isConvertableSignatureDeclaration(decls[0])) { + return; + } + const kindOne = decls[0].kind; + if (!every(decls, (d) => d.kind === kindOne)) { + return; + } + const signatureDecls = decls; + if (some(signatureDecls, (d) => !!d.typeParameters || some(d.parameters, (p) => !!p.modifiers || !isIdentifier(p.name)))) { + return; + } + const signatures = mapDefined(signatureDecls, (d) => checker.getSignatureFromDeclaration(d)); + if (length(signatures) !== length(decls)) { + return; + } + const returnOne = checker.getReturnTypeOfSignature(signatures[0]); + if (!every(signatures, (s) => checker.getReturnTypeOfSignature(s) === returnOne)) { + return; + } + return signatureDecls; + } + var refactorName5, refactorDescription, functionOverloadAction; + var init_convertOverloadListToSingleSignature = __esm({ + "src/services/refactors/convertOverloadListToSingleSignature.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName5 = "Convert overload list to single signature"; + refactorDescription = Diagnostics.Convert_overload_list_to_single_signature.message; + functionOverloadAction = { + name: refactorName5, + description: refactorDescription, + kind: "refactor.rewrite.function.overloadList" + }; + registerRefactor(refactorName5, { + kinds: [functionOverloadAction.kind], + getEditsForAction: getRefactorEditsToConvertOverloadsToOneSignature, + getAvailableActions: getRefactorActionsToConvertOverloadsToOneSignature + }); + } + }); + + // src/services/refactors/addOrRemoveBracesToArrowFunction.ts + function getRefactorActionsToRemoveFunctionBraces(context) { + const { file, startPosition, triggerReason } = context; + const info = getConvertibleArrowFunctionAtPosition(file, startPosition, triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + return [{ + name: refactorName6, + description: refactorDescription2, + actions: [ + info.addBraces ? addBracesAction : removeBracesAction + ] + }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorName6, + description: refactorDescription2, + actions: [ + { ...addBracesAction, notApplicableReason: info.error }, + { ...removeBracesAction, notApplicableReason: info.error } + ] + }]; + } + return emptyArray; + } + function getRefactorEditsToRemoveFunctionBraces(context, actionName2) { + const { file, startPosition } = context; + const info = getConvertibleArrowFunctionAtPosition(file, startPosition); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const { expression, returnStatement, func } = info; + let body; + if (actionName2 === addBracesAction.name) { + const returnStatement2 = factory.createReturnStatement(expression); + body = factory.createBlock( + [returnStatement2], + /*multiLine*/ + true + ); + copyLeadingComments( + expression, + returnStatement2, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + true + ); + } else if (actionName2 === removeBracesAction.name && returnStatement) { + const actualExpression = expression || factory.createVoidZero(); + body = needsParentheses(actualExpression) ? factory.createParenthesizedExpression(actualExpression) : actualExpression; + copyTrailingAsLeadingComments( + returnStatement, + body, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + copyLeadingComments( + returnStatement, + body, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + copyTrailingComments( + returnStatement, + body, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + } else { + Debug.fail("invalid action"); + } + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => { + t.replaceNode(file, func.body, body); + }); + return { renameFilename: void 0, renameLocation: void 0, edits }; + } + function getConvertibleArrowFunctionAtPosition(file, startPosition, considerFunctionBodies = true, kind) { + const node = getTokenAtPosition(file, startPosition); + const func = getContainingFunction(node); + if (!func) { + return { + error: getLocaleSpecificMessage(Diagnostics.Could_not_find_a_containing_arrow_function) + }; + } + if (!isArrowFunction(func)) { + return { + error: getLocaleSpecificMessage(Diagnostics.Containing_function_is_not_an_arrow_function) + }; + } + if (!rangeContainsRange(func, node) || rangeContainsRange(func.body, node) && !considerFunctionBodies) { + return void 0; + } + if (refactorKindBeginsWith(addBracesAction.kind, kind) && isExpression(func.body)) { + return { func, addBraces: true, expression: func.body }; + } else if (refactorKindBeginsWith(removeBracesAction.kind, kind) && isBlock(func.body) && func.body.statements.length === 1) { + const firstStatement = first(func.body.statements); + if (isReturnStatement(firstStatement)) { + return { func, addBraces: false, expression: firstStatement.expression, returnStatement: firstStatement }; + } + } + return void 0; + } + var refactorName6, refactorDescription2, addBracesAction, removeBracesAction; + var init_addOrRemoveBracesToArrowFunction = __esm({ + "src/services/refactors/addOrRemoveBracesToArrowFunction.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName6 = "Add or remove braces in an arrow function"; + refactorDescription2 = Diagnostics.Add_or_remove_braces_in_an_arrow_function.message; + addBracesAction = { + name: "Add braces to arrow function", + description: Diagnostics.Add_braces_to_arrow_function.message, + kind: "refactor.rewrite.arrow.braces.add" + }; + removeBracesAction = { + name: "Remove braces from arrow function", + description: Diagnostics.Remove_braces_from_arrow_function.message, + kind: "refactor.rewrite.arrow.braces.remove" + }; + registerRefactor(refactorName6, { + kinds: [removeBracesAction.kind], + getEditsForAction: getRefactorEditsToRemoveFunctionBraces, + getAvailableActions: getRefactorActionsToRemoveFunctionBraces + }); + } + }); + + // src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts + var ts_refactor_addOrRemoveBracesToArrowFunction_exports = {}; + var init_ts_refactor_addOrRemoveBracesToArrowFunction = __esm({ + "src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts"() { + "use strict"; + init_convertOverloadListToSingleSignature(); + init_addOrRemoveBracesToArrowFunction(); + } + }); + + // src/services/refactors/convertArrowFunctionOrFunctionExpression.ts + function getRefactorActionsToConvertFunctionExpressions(context) { + const { file, startPosition, program, kind } = context; + const info = getFunctionInfo(file, startPosition, program); + if (!info) + return emptyArray; + const { selectedVariableDeclaration, func } = info; + const possibleActions = []; + const errors = []; + if (refactorKindBeginsWith(toNamedFunctionAction.kind, kind)) { + const error = selectedVariableDeclaration || isArrowFunction(func) && isVariableDeclaration(func.parent) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_named_function); + if (error) { + errors.push({ ...toNamedFunctionAction, notApplicableReason: error }); + } else { + possibleActions.push(toNamedFunctionAction); + } + } + if (refactorKindBeginsWith(toAnonymousFunctionAction.kind, kind)) { + const error = !selectedVariableDeclaration && isArrowFunction(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_anonymous_function); + if (error) { + errors.push({ ...toAnonymousFunctionAction, notApplicableReason: error }); + } else { + possibleActions.push(toAnonymousFunctionAction); + } + } + if (refactorKindBeginsWith(toArrowFunctionAction.kind, kind)) { + const error = isFunctionExpression(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_arrow_function); + if (error) { + errors.push({ ...toArrowFunctionAction, notApplicableReason: error }); + } else { + possibleActions.push(toArrowFunctionAction); + } + } + return [{ + name: refactorName7, + description: refactorDescription3, + actions: possibleActions.length === 0 && context.preferences.provideRefactorNotApplicableReason ? errors : possibleActions + }]; + } + function getRefactorEditsToConvertFunctionExpressions(context, actionName2) { + const { file, startPosition, program } = context; + const info = getFunctionInfo(file, startPosition, program); + if (!info) + return void 0; + const { func } = info; + const edits = []; + switch (actionName2) { + case toAnonymousFunctionAction.name: + edits.push(...getEditInfoForConvertToAnonymousFunction(context, func)); + break; + case toNamedFunctionAction.name: + const variableInfo = getVariableInfo(func); + if (!variableInfo) + return void 0; + edits.push(...getEditInfoForConvertToNamedFunction(context, func, variableInfo)); + break; + case toArrowFunctionAction.name: + if (!isFunctionExpression(func)) + return void 0; + edits.push(...getEditInfoForConvertToArrowFunction(context, func)); + break; + default: + return Debug.fail("invalid action"); + } + return { renameFilename: void 0, renameLocation: void 0, edits }; + } + function containingThis(node) { + let containsThis = false; + node.forEachChild(function checkThis(child) { + if (isThis(child)) { + containsThis = true; + return; + } + if (!isClassLike(child) && !isFunctionDeclaration(child) && !isFunctionExpression(child)) { + forEachChild(child, checkThis); + } + }); + return containsThis; + } + function getFunctionInfo(file, startPosition, program) { + const token = getTokenAtPosition(file, startPosition); + const typeChecker = program.getTypeChecker(); + const func = tryGetFunctionFromVariableDeclaration(file, typeChecker, token.parent); + if (func && !containingThis(func.body) && !typeChecker.containsArgumentsReference(func)) { + return { selectedVariableDeclaration: true, func }; + } + const maybeFunc = getContainingFunction(token); + if (maybeFunc && (isFunctionExpression(maybeFunc) || isArrowFunction(maybeFunc)) && !rangeContainsRange(maybeFunc.body, token) && !containingThis(maybeFunc.body) && !typeChecker.containsArgumentsReference(maybeFunc)) { + if (isFunctionExpression(maybeFunc) && isFunctionReferencedInFile(file, typeChecker, maybeFunc)) + return void 0; + return { selectedVariableDeclaration: false, func: maybeFunc }; + } + return void 0; + } + function isSingleVariableDeclaration(parent2) { + return isVariableDeclaration(parent2) || isVariableDeclarationList(parent2) && parent2.declarations.length === 1; + } + function tryGetFunctionFromVariableDeclaration(sourceFile, typeChecker, parent2) { + if (!isSingleVariableDeclaration(parent2)) { + return void 0; + } + const variableDeclaration = isVariableDeclaration(parent2) ? parent2 : first(parent2.declarations); + const initializer = variableDeclaration.initializer; + if (initializer && (isArrowFunction(initializer) || isFunctionExpression(initializer) && !isFunctionReferencedInFile(sourceFile, typeChecker, initializer))) { + return initializer; + } + return void 0; + } + function convertToBlock(body) { + if (isExpression(body)) { + const returnStatement = factory.createReturnStatement(body); + const file = body.getSourceFile(); + setTextRange(returnStatement, body); + suppressLeadingAndTrailingTrivia(returnStatement); + copyTrailingAsLeadingComments( + body, + returnStatement, + file, + /*commentKind*/ + void 0, + /*hasTrailingNewLine*/ + true + ); + return factory.createBlock( + [returnStatement], + /*multiLine*/ + true + ); + } else { + return body; + } + } + function getVariableInfo(func) { + const variableDeclaration = func.parent; + if (!isVariableDeclaration(variableDeclaration) || !isVariableDeclarationInVariableStatement(variableDeclaration)) + return void 0; + const variableDeclarationList = variableDeclaration.parent; + const statement = variableDeclarationList.parent; + if (!isVariableDeclarationList(variableDeclarationList) || !isVariableStatement(statement) || !isIdentifier(variableDeclaration.name)) + return void 0; + return { variableDeclaration, variableDeclarationList, statement, name: variableDeclaration.name }; + } + function getEditInfoForConvertToAnonymousFunction(context, func) { + const { file } = context; + const body = convertToBlock(func.body); + const newNode = factory.createFunctionExpression( + func.modifiers, + func.asteriskToken, + /*name*/ + void 0, + func.typeParameters, + func.parameters, + func.type, + body + ); + return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode)); + } + function getEditInfoForConvertToNamedFunction(context, func, variableInfo) { + const { file } = context; + const body = convertToBlock(func.body); + const { variableDeclaration, variableDeclarationList, statement, name } = variableInfo; + suppressLeadingTrivia(statement); + const modifiersFlags = getCombinedModifierFlags(variableDeclaration) & 1 /* Export */ | getEffectiveModifierFlags(func); + const modifiers = factory.createModifiersFromModifierFlags(modifiersFlags); + const newNode = factory.createFunctionDeclaration(length(modifiers) ? modifiers : void 0, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); + if (variableDeclarationList.declarations.length === 1) { + return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, statement, newNode)); + } else { + return ts_textChanges_exports.ChangeTracker.with(context, (t) => { + t.delete(file, variableDeclaration); + t.insertNodeAfter(file, statement, newNode); + }); + } + } + function getEditInfoForConvertToArrowFunction(context, func) { + const { file } = context; + const statements = func.body.statements; + const head = statements[0]; + let body; + if (canBeConvertedToExpression(func.body, head)) { + body = head.expression; + suppressLeadingAndTrailingTrivia(body); + copyComments(head, body); + } else { + body = func.body; + } + const newNode = factory.createArrowFunction(func.modifiers, func.typeParameters, func.parameters, func.type, factory.createToken(39 /* EqualsGreaterThanToken */), body); + return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode)); + } + function canBeConvertedToExpression(body, head) { + return body.statements.length === 1 && (isReturnStatement(head) && !!head.expression); + } + function isFunctionReferencedInFile(sourceFile, typeChecker, node) { + return !!node.name && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(node.name, typeChecker, sourceFile); + } + var refactorName7, refactorDescription3, toAnonymousFunctionAction, toNamedFunctionAction, toArrowFunctionAction; + var init_convertArrowFunctionOrFunctionExpression = __esm({ + "src/services/refactors/convertArrowFunctionOrFunctionExpression.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName7 = "Convert arrow function or function expression"; + refactorDescription3 = getLocaleSpecificMessage(Diagnostics.Convert_arrow_function_or_function_expression); + toAnonymousFunctionAction = { + name: "Convert to anonymous function", + description: getLocaleSpecificMessage(Diagnostics.Convert_to_anonymous_function), + kind: "refactor.rewrite.function.anonymous" + }; + toNamedFunctionAction = { + name: "Convert to named function", + description: getLocaleSpecificMessage(Diagnostics.Convert_to_named_function), + kind: "refactor.rewrite.function.named" + }; + toArrowFunctionAction = { + name: "Convert to arrow function", + description: getLocaleSpecificMessage(Diagnostics.Convert_to_arrow_function), + kind: "refactor.rewrite.function.arrow" + }; + registerRefactor(refactorName7, { + kinds: [ + toAnonymousFunctionAction.kind, + toNamedFunctionAction.kind, + toArrowFunctionAction.kind + ], + getEditsForAction: getRefactorEditsToConvertFunctionExpressions, + getAvailableActions: getRefactorActionsToConvertFunctionExpressions + }); + } + }); + + // src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts + var ts_refactor_convertArrowFunctionOrFunctionExpression_exports = {}; + var init_ts_refactor_convertArrowFunctionOrFunctionExpression = __esm({ + "src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts"() { + "use strict"; + init_convertArrowFunctionOrFunctionExpression(); + } + }); + + // src/services/refactors/convertParamsToDestructuredObject.ts + function getRefactorActionsToConvertParametersToDestructuredObject(context) { + const { file, startPosition } = context; + const isJSFile = isSourceFileJS(file); + if (isJSFile) + return emptyArray; + const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker()); + if (!functionDeclaration) + return emptyArray; + return [{ + name: refactorName8, + description: refactorDescription4, + actions: [toDestructuredAction] + }]; + } + function getRefactorEditsToConvertParametersToDestructuredObject(context, actionName2) { + Debug.assert(actionName2 === refactorName8, "Unexpected action name"); + const { file, startPosition, program, cancellationToken, host } = context; + const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); + if (!functionDeclaration || !cancellationToken) + return void 0; + const groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken); + if (groupedReferences.valid) { + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange5(file, program, host, t, functionDeclaration, groupedReferences)); + return { renameFilename: void 0, renameLocation: void 0, edits }; + } + return { edits: [] }; + } + function doChange5(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { + const signature = groupedReferences.signature; + const newFunctionDeclarationParams = map(createNewParameters(functionDeclaration, program, host), (param) => getSynthesizedDeepClone(param)); + if (signature) { + const newSignatureParams = map(createNewParameters(signature, program, host), (param) => getSynthesizedDeepClone(param)); + replaceParameters(signature, newSignatureParams); + } + replaceParameters(functionDeclaration, newFunctionDeclarationParams); + const functionCalls = sortAndDeduplicate( + groupedReferences.functionCalls, + /*comparer*/ + (a, b) => compareValues(a.pos, b.pos) + ); + for (const call of functionCalls) { + if (call.arguments && call.arguments.length) { + const newArgument = getSynthesizedDeepClone( + createNewArgument(functionDeclaration, call.arguments), + /*includeTrivia*/ + true + ); + changes.replaceNodeRange( + getSourceFileOfNode(call), + first(call.arguments), + last(call.arguments), + newArgument, + { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include } + ); + } + } + function replaceParameters(declarationOrSignature, parameterDeclarations) { + changes.replaceNodeRangeWithNodes( + sourceFile, + first(declarationOrSignature.parameters), + last(declarationOrSignature.parameters), + parameterDeclarations, + { + joiner: ", ", + // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter + indentation: 0, + leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include + } + ); + } + } + function getGroupedReferences(functionDeclaration, program, cancellationToken) { + const functionNames = getFunctionNames(functionDeclaration); + const classNames = isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : []; + const names = deduplicate([...functionNames, ...classNames], equateValues); + const checker = program.getTypeChecker(); + const references = flatMap( + names, + /*mapfn*/ + (name) => ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken) + ); + const groupedReferences = groupReferences(references); + if (!every( + groupedReferences.declarations, + /*callback*/ + (decl) => contains(names, decl) + )) { + groupedReferences.valid = false; + } + return groupedReferences; + function groupReferences(referenceEntries) { + const classReferences = { accessExpressions: [], typeUsages: [] }; + const groupedReferences2 = { functionCalls: [], declarations: [], classReferences, valid: true }; + const functionSymbols = map(functionNames, getSymbolTargetAtLocation); + const classSymbols = map(classNames, getSymbolTargetAtLocation); + const isConstructor = isConstructorDeclaration(functionDeclaration); + const contextualSymbols = map(functionNames, (name) => getSymbolForContextualType(name, checker)); + for (const entry of referenceEntries) { + if (entry.kind === ts_FindAllReferences_exports.EntryKind.Span) { + groupedReferences2.valid = false; + continue; + } + if (contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) { + if (isValidMethodSignature(entry.node.parent)) { + groupedReferences2.signature = entry.node.parent; + continue; + } + const call = entryToFunctionCall(entry); + if (call) { + groupedReferences2.functionCalls.push(call); + continue; + } + } + const contextualSymbol = getSymbolForContextualType(entry.node, checker); + if (contextualSymbol && contains(contextualSymbols, contextualSymbol)) { + const decl = entryToDeclaration(entry); + if (decl) { + groupedReferences2.declarations.push(decl); + continue; + } + } + if (contains(functionSymbols, getSymbolTargetAtLocation(entry.node)) || isNewExpressionTarget(entry.node)) { + const importOrExportReference = entryToImportOrExport(entry); + if (importOrExportReference) { + continue; + } + const decl = entryToDeclaration(entry); + if (decl) { + groupedReferences2.declarations.push(decl); + continue; + } + const call = entryToFunctionCall(entry); + if (call) { + groupedReferences2.functionCalls.push(call); + continue; + } + } + if (isConstructor && contains(classSymbols, getSymbolTargetAtLocation(entry.node))) { + const importOrExportReference = entryToImportOrExport(entry); + if (importOrExportReference) { + continue; + } + const decl = entryToDeclaration(entry); + if (decl) { + groupedReferences2.declarations.push(decl); + continue; + } + const accessExpression = entryToAccessExpression(entry); + if (accessExpression) { + classReferences.accessExpressions.push(accessExpression); + continue; + } + if (isClassDeclaration(functionDeclaration.parent)) { + const type = entryToType(entry); + if (type) { + classReferences.typeUsages.push(type); + continue; + } + } + } + groupedReferences2.valid = false; + } + return groupedReferences2; + } + function getSymbolTargetAtLocation(node) { + const symbol = checker.getSymbolAtLocation(node); + return symbol && getSymbolTarget(symbol, checker); + } + } + function getSymbolForContextualType(node, checker) { + const element = getContainingObjectLiteralElement(node); + if (element) { + const contextualType = checker.getContextualTypeForObjectLiteralElement(element); + const symbol = contextualType == null ? void 0 : contextualType.getSymbol(); + if (symbol && !(getCheckFlags(symbol) & 6 /* Synthetic */)) { + return symbol; + } + } + } + function entryToImportOrExport(entry) { + const node = entry.node; + if (isImportSpecifier(node.parent) || isImportClause(node.parent) || isImportEqualsDeclaration(node.parent) || isNamespaceImport(node.parent)) { + return node; + } + if (isExportSpecifier(node.parent) || isExportAssignment(node.parent)) { + return node; + } + return void 0; + } + function entryToDeclaration(entry) { + if (isDeclaration(entry.node.parent)) { + return entry.node; + } + return void 0; + } + function entryToFunctionCall(entry) { + if (entry.node.parent) { + const functionReference = entry.node; + const parent2 = functionReference.parent; + switch (parent2.kind) { + case 212 /* CallExpression */: + case 213 /* NewExpression */: + const callOrNewExpression = tryCast(parent2, isCallOrNewExpression); + if (callOrNewExpression && callOrNewExpression.expression === functionReference) { + return callOrNewExpression; + } + break; + case 210 /* PropertyAccessExpression */: + const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); + if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { + const callOrNewExpression2 = tryCast(propertyAccessExpression.parent, isCallOrNewExpression); + if (callOrNewExpression2 && callOrNewExpression2.expression === propertyAccessExpression) { + return callOrNewExpression2; + } + } + break; + case 211 /* ElementAccessExpression */: + const elementAccessExpression = tryCast(parent2, isElementAccessExpression); + if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { + const callOrNewExpression2 = tryCast(elementAccessExpression.parent, isCallOrNewExpression); + if (callOrNewExpression2 && callOrNewExpression2.expression === elementAccessExpression) { + return callOrNewExpression2; + } + } + break; + } + } + return void 0; + } + function entryToAccessExpression(entry) { + if (entry.node.parent) { + const reference = entry.node; + const parent2 = reference.parent; + switch (parent2.kind) { + case 210 /* PropertyAccessExpression */: + const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); + if (propertyAccessExpression && propertyAccessExpression.expression === reference) { + return propertyAccessExpression; + } + break; + case 211 /* ElementAccessExpression */: + const elementAccessExpression = tryCast(parent2, isElementAccessExpression); + if (elementAccessExpression && elementAccessExpression.expression === reference) { + return elementAccessExpression; + } + break; + } + } + return void 0; + } + function entryToType(entry) { + const reference = entry.node; + if (getMeaningFromLocation(reference) === 2 /* Type */ || isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) { + return reference; + } + return void 0; + } + function getFunctionDeclarationAtPosition(file, startPosition, checker) { + const node = getTouchingToken(file, startPosition); + const functionDeclaration = getContainingFunctionDeclaration(node); + if (isTopLevelJSDoc(node)) + return void 0; + if (functionDeclaration && isValidFunctionDeclaration(functionDeclaration, checker) && rangeContainsRange(functionDeclaration, node) && !(functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node))) + return functionDeclaration; + return void 0; + } + function isTopLevelJSDoc(node) { + const containingJSDoc = findAncestor(node, isJSDocNode); + if (containingJSDoc) { + const containingNonJSDoc = findAncestor(containingJSDoc, (n) => !isJSDocNode(n)); + return !!containingNonJSDoc && isFunctionLikeDeclaration(containingNonJSDoc); + } + return false; + } + function isValidMethodSignature(node) { + return isMethodSignature(node) && (isInterfaceDeclaration(node.parent) || isTypeLiteralNode(node.parent)); + } + function isValidFunctionDeclaration(functionDeclaration, checker) { + var _a; + if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) + return false; + switch (functionDeclaration.kind) { + case 261 /* FunctionDeclaration */: + return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); + case 173 /* MethodDeclaration */: + if (isObjectLiteralExpression(functionDeclaration.parent)) { + const contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); + return ((_a = contextualSymbol == null ? void 0 : contextualSymbol.declarations) == null ? void 0 : _a.length) === 1 && isSingleImplementation(functionDeclaration, checker); + } + return isSingleImplementation(functionDeclaration, checker); + case 175 /* Constructor */: + if (isClassDeclaration(functionDeclaration.parent)) { + return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker); + } else { + return isValidVariableDeclaration(functionDeclaration.parent.parent) && isSingleImplementation(functionDeclaration, checker); + } + case 217 /* FunctionExpression */: + case 218 /* ArrowFunction */: + return isValidVariableDeclaration(functionDeclaration.parent); + } + return false; + } + function isSingleImplementation(functionDeclaration, checker) { + return !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); + } + function hasNameOrDefault(functionOrClassDeclaration) { + if (!functionOrClassDeclaration.name) { + const defaultKeyword = findModifier(functionOrClassDeclaration, 90 /* DefaultKeyword */); + return !!defaultKeyword; + } + return true; + } + function isValidParameterNodeArray(parameters, checker) { + return getRefactorableParametersLength(parameters) >= minimumParameterLength && every( + parameters, + /*callback*/ + (paramDecl) => isValidParameterDeclaration(paramDecl, checker) + ); + } + function isValidParameterDeclaration(parameterDeclaration, checker) { + if (isRestParameter(parameterDeclaration)) { + const type = checker.getTypeAtLocation(parameterDeclaration); + if (!checker.isArrayType(type) && !checker.isTupleType(type)) + return false; + } + return !parameterDeclaration.modifiers && isIdentifier(parameterDeclaration.name); + } + function isValidVariableDeclaration(node) { + return isVariableDeclaration(node) && isVarConst(node) && isIdentifier(node.name) && !node.type; + } + function hasThisParameter(parameters) { + return parameters.length > 0 && isThis(parameters[0].name); + } + function getRefactorableParametersLength(parameters) { + if (hasThisParameter(parameters)) { + return parameters.length - 1; + } + return parameters.length; + } + function getRefactorableParameters(parameters) { + if (hasThisParameter(parameters)) { + parameters = factory.createNodeArray(parameters.slice(1), parameters.hasTrailingComma); + } + return parameters; + } + function createPropertyOrShorthandAssignment(name, initializer) { + if (isIdentifier(initializer) && getTextOfIdentifierOrLiteral(initializer) === name) { + return factory.createShorthandPropertyAssignment(name); + } + return factory.createPropertyAssignment(name, initializer); + } + function createNewArgument(functionDeclaration, functionArguments) { + const parameters = getRefactorableParameters(functionDeclaration.parameters); + const hasRestParameter2 = isRestParameter(last(parameters)); + const nonRestArguments = hasRestParameter2 ? functionArguments.slice(0, parameters.length - 1) : functionArguments; + const properties = map(nonRestArguments, (arg, i) => { + const parameterName = getParameterName(parameters[i]); + const property = createPropertyOrShorthandAssignment(parameterName, arg); + suppressLeadingAndTrailingTrivia(property.name); + if (isPropertyAssignment(property)) + suppressLeadingAndTrailingTrivia(property.initializer); + copyComments(arg, property); + return property; + }); + if (hasRestParameter2 && functionArguments.length >= parameters.length) { + const restArguments = functionArguments.slice(parameters.length - 1); + const restProperty = factory.createPropertyAssignment(getParameterName(last(parameters)), factory.createArrayLiteralExpression(restArguments)); + properties.push(restProperty); + } + const objectLiteral = factory.createObjectLiteralExpression( + properties, + /*multiLine*/ + false + ); + return objectLiteral; + } + function createNewParameters(functionDeclaration, program, host) { + const checker = program.getTypeChecker(); + const refactorableParameters = getRefactorableParameters(functionDeclaration.parameters); + const bindingElements = map(refactorableParameters, createBindingElementFromParameterDeclaration); + const objectParameterName = factory.createObjectBindingPattern(bindingElements); + const objectParameterType = createParameterTypeNode(refactorableParameters); + let objectInitializer; + if (every(refactorableParameters, isOptionalParameter)) { + objectInitializer = factory.createObjectLiteralExpression(); + } + const objectParameter = factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + objectParameterName, + /*questionToken*/ + void 0, + objectParameterType, + objectInitializer + ); + if (hasThisParameter(functionDeclaration.parameters)) { + const thisParameter = functionDeclaration.parameters[0]; + const newThisParameter = factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + thisParameter.name, + /*questionToken*/ + void 0, + thisParameter.type + ); + suppressLeadingAndTrailingTrivia(newThisParameter.name); + copyComments(thisParameter.name, newThisParameter.name); + if (thisParameter.type) { + suppressLeadingAndTrailingTrivia(newThisParameter.type); + copyComments(thisParameter.type, newThisParameter.type); + } + return factory.createNodeArray([newThisParameter, objectParameter]); + } + return factory.createNodeArray([objectParameter]); + function createBindingElementFromParameterDeclaration(parameterDeclaration) { + const element = factory.createBindingElement( + /*dotDotDotToken*/ + void 0, + /*propertyName*/ + void 0, + getParameterName(parameterDeclaration), + isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? factory.createArrayLiteralExpression() : parameterDeclaration.initializer + ); + suppressLeadingAndTrailingTrivia(element); + if (parameterDeclaration.initializer && element.initializer) { + copyComments(parameterDeclaration.initializer, element.initializer); + } + return element; + } + function createParameterTypeNode(parameters) { + const members = map(parameters, createPropertySignatureFromParameterDeclaration); + const typeNode = addEmitFlags(factory.createTypeLiteralNode(members), 1 /* SingleLine */); + return typeNode; + } + function createPropertySignatureFromParameterDeclaration(parameterDeclaration) { + let parameterType = parameterDeclaration.type; + if (!parameterType && (parameterDeclaration.initializer || isRestParameter(parameterDeclaration))) { + parameterType = getTypeNode3(parameterDeclaration); + } + const propertySignature = factory.createPropertySignature( + /*modifiers*/ + void 0, + getParameterName(parameterDeclaration), + isOptionalParameter(parameterDeclaration) ? factory.createToken(58 /* QuestionToken */) : parameterDeclaration.questionToken, + parameterType + ); + suppressLeadingAndTrailingTrivia(propertySignature); + copyComments(parameterDeclaration.name, propertySignature.name); + if (parameterDeclaration.type && propertySignature.type) { + copyComments(parameterDeclaration.type, propertySignature.type); + } + return propertySignature; + } + function getTypeNode3(node) { + const type = checker.getTypeAtLocation(node); + return getTypeNodeIfAccessible(type, node, program, host); + } + function isOptionalParameter(parameterDeclaration) { + if (isRestParameter(parameterDeclaration)) { + const type = checker.getTypeAtLocation(parameterDeclaration); + return !checker.isTupleType(type); + } + return checker.isOptionalParameter(parameterDeclaration); + } + } + function getParameterName(paramDeclaration) { + return getTextOfIdentifierOrLiteral(paramDeclaration.name); + } + function getClassNames(constructorDeclaration) { + switch (constructorDeclaration.parent.kind) { + case 262 /* ClassDeclaration */: + const classDeclaration = constructorDeclaration.parent; + if (classDeclaration.name) + return [classDeclaration.name]; + const defaultModifier = Debug.checkDefined( + findModifier(classDeclaration, 90 /* DefaultKeyword */), + "Nameless class declaration should be a default export" + ); + return [defaultModifier]; + case 230 /* ClassExpression */: + const classExpression = constructorDeclaration.parent; + const variableDeclaration = constructorDeclaration.parent.parent; + const className = classExpression.name; + if (className) + return [className, variableDeclaration.name]; + return [variableDeclaration.name]; + } + } + function getFunctionNames(functionDeclaration) { + switch (functionDeclaration.kind) { + case 261 /* FunctionDeclaration */: + if (functionDeclaration.name) + return [functionDeclaration.name]; + const defaultModifier = Debug.checkDefined( + findModifier(functionDeclaration, 90 /* DefaultKeyword */), + "Nameless function declaration should be a default export" + ); + return [defaultModifier]; + case 173 /* MethodDeclaration */: + return [functionDeclaration.name]; + case 175 /* Constructor */: + const ctrKeyword = Debug.checkDefined( + findChildOfKind(functionDeclaration, 137 /* ConstructorKeyword */, functionDeclaration.getSourceFile()), + "Constructor declaration should have constructor keyword" + ); + if (functionDeclaration.parent.kind === 230 /* ClassExpression */) { + const variableDeclaration = functionDeclaration.parent.parent; + return [variableDeclaration.name, ctrKeyword]; + } + return [ctrKeyword]; + case 218 /* ArrowFunction */: + return [functionDeclaration.parent.name]; + case 217 /* FunctionExpression */: + if (functionDeclaration.name) + return [functionDeclaration.name, functionDeclaration.parent.name]; + return [functionDeclaration.parent.name]; + default: + return Debug.assertNever(functionDeclaration, `Unexpected function declaration kind ${functionDeclaration.kind}`); + } + } + var refactorName8, minimumParameterLength, refactorDescription4, toDestructuredAction; + var init_convertParamsToDestructuredObject = __esm({ + "src/services/refactors/convertParamsToDestructuredObject.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName8 = "Convert parameters to destructured object"; + minimumParameterLength = 1; + refactorDescription4 = getLocaleSpecificMessage(Diagnostics.Convert_parameters_to_destructured_object); + toDestructuredAction = { + name: refactorName8, + description: refactorDescription4, + kind: "refactor.rewrite.parameters.toDestructured" + }; + registerRefactor(refactorName8, { + kinds: [toDestructuredAction.kind], + getEditsForAction: getRefactorEditsToConvertParametersToDestructuredObject, + getAvailableActions: getRefactorActionsToConvertParametersToDestructuredObject + }); + } + }); + + // src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts + var ts_refactor_convertParamsToDestructuredObject_exports = {}; + var init_ts_refactor_convertParamsToDestructuredObject = __esm({ + "src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts"() { + "use strict"; + init_convertParamsToDestructuredObject(); + } + }); + + // src/services/refactors/convertStringOrTemplateLiteral.ts + function getRefactorActionsToConvertToTemplateString(context) { + const { file, startPosition } = context; + const node = getNodeOrParentOfParentheses(file, startPosition); + const maybeBinary = getParentBinaryExpression(node); + const refactorInfo = { name: refactorName9, description: refactorDescription5, actions: [] }; + if (isBinaryExpression(maybeBinary) && treeToArray(maybeBinary).isValidConcatenation) { + refactorInfo.actions.push(convertStringAction); + return [refactorInfo]; + } else if (context.preferences.provideRefactorNotApplicableReason) { + refactorInfo.actions.push({ + ...convertStringAction, + notApplicableReason: getLocaleSpecificMessage(Diagnostics.Can_only_convert_string_concatenation) + }); + return [refactorInfo]; + } + return emptyArray; + } + function getNodeOrParentOfParentheses(file, startPosition) { + const node = getTokenAtPosition(file, startPosition); + const nestedBinary = getParentBinaryExpression(node); + const isNonStringBinary = !treeToArray(nestedBinary).isValidConcatenation; + if (isNonStringBinary && isParenthesizedExpression(nestedBinary.parent) && isBinaryExpression(nestedBinary.parent.parent)) { + return nestedBinary.parent.parent; + } + return node; + } + function getRefactorEditsToConvertToTemplateString(context, actionName2) { + const { file, startPosition } = context; + const node = getNodeOrParentOfParentheses(file, startPosition); + switch (actionName2) { + case refactorDescription5: + return { edits: getEditsForToTemplateLiteral(context, node) }; + default: + return Debug.fail("invalid action"); + } + } + function getEditsForToTemplateLiteral(context, node) { + const maybeBinary = getParentBinaryExpression(node); + const file = context.file; + const templateLiteral = nodesToTemplate(treeToArray(maybeBinary), file); + const trailingCommentRanges = getTrailingCommentRanges(file.text, maybeBinary.end); + if (trailingCommentRanges) { + const lastComment = trailingCommentRanges[trailingCommentRanges.length - 1]; + const trailingRange = { pos: trailingCommentRanges[0].pos, end: lastComment.end }; + return ts_textChanges_exports.ChangeTracker.with(context, (t) => { + t.deleteRange(file, trailingRange); + t.replaceNode(file, maybeBinary, templateLiteral); + }); + } else { + return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, maybeBinary, templateLiteral)); + } + } + function isNotEqualsOperator(node) { + return node.operatorToken.kind !== 64 /* EqualsToken */; + } + function getParentBinaryExpression(expr) { + const container = findAncestor(expr.parent, (n) => { + switch (n.kind) { + case 210 /* PropertyAccessExpression */: + case 211 /* ElementAccessExpression */: + return false; + case 227 /* TemplateExpression */: + case 225 /* BinaryExpression */: + return !(isBinaryExpression(n.parent) && isNotEqualsOperator(n.parent)); + default: + return "quit"; + } + }); + return container || expr; + } + function treeToArray(current) { + const loop = (current2) => { + if (!isBinaryExpression(current2)) { + return { + nodes: [current2], + operators: [], + validOperators: true, + hasString: isStringLiteral(current2) || isNoSubstitutionTemplateLiteral(current2) + }; + } + const { nodes: nodes2, operators: operators2, hasString: leftHasString, validOperators: leftOperatorValid } = loop(current2.left); + if (!(leftHasString || isStringLiteral(current2.right) || isTemplateExpression(current2.right))) { + return { nodes: [current2], operators: [], hasString: false, validOperators: true }; + } + const currentOperatorValid = current2.operatorToken.kind === 40 /* PlusToken */; + const validOperators2 = leftOperatorValid && currentOperatorValid; + nodes2.push(current2.right); + operators2.push(current2.operatorToken); + return { nodes: nodes2, operators: operators2, hasString: true, validOperators: validOperators2 }; + }; + const { nodes, operators, validOperators, hasString } = loop(current); + return { nodes, operators, isValidConcatenation: validOperators && hasString }; + } + function escapeRawStringForTemplate(s) { + return s.replace(/\\.|[$`]/g, (m) => m[0] === "\\" ? m : "\\" + m); + } + function getRawTextOfTemplate(node) { + const rightShaving = isTemplateHead(node) || isTemplateMiddle(node) ? -2 : -1; + return getTextOfNode(node).slice(1, rightShaving); + } + function concatConsecutiveString(index, nodes) { + const indexes = []; + let text = "", rawText = ""; + while (index < nodes.length) { + const node = nodes[index]; + if (isStringLiteralLike(node)) { + text += node.text; + rawText += escapeRawStringForTemplate(getTextOfNode(node).slice(1, -1)); + indexes.push(index); + index++; + } else if (isTemplateExpression(node)) { + text += node.head.text; + rawText += getRawTextOfTemplate(node.head); + break; + } else { + break; + } + } + return [index, text, rawText, indexes]; + } + function nodesToTemplate({ nodes, operators }, file) { + const copyOperatorComments = copyTrailingOperatorComments(operators, file); + const copyCommentFromStringLiterals = copyCommentFromMultiNode(nodes, file, copyOperatorComments); + const [begin, headText, rawHeadText, headIndexes] = concatConsecutiveString(0, nodes); + if (begin === nodes.length) { + const noSubstitutionTemplateLiteral = factory.createNoSubstitutionTemplateLiteral(headText, rawHeadText); + copyCommentFromStringLiterals(headIndexes, noSubstitutionTemplateLiteral); + return noSubstitutionTemplateLiteral; + } + const templateSpans = []; + const templateHead = factory.createTemplateHead(headText, rawHeadText); + copyCommentFromStringLiterals(headIndexes, templateHead); + for (let i = begin; i < nodes.length; i++) { + const currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); + copyOperatorComments(i, currentNode); + const [newIndex, subsequentText, rawSubsequentText, stringIndexes] = concatConsecutiveString(i + 1, nodes); + i = newIndex - 1; + const isLast = i === nodes.length - 1; + if (isTemplateExpression(currentNode)) { + const spans = map(currentNode.templateSpans, (span, index) => { + copyExpressionComments(span); + 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)); + }); + templateSpans.push(...spans); + } else { + const templatePart = isLast ? factory.createTemplateTail(subsequentText, rawSubsequentText) : factory.createTemplateMiddle(subsequentText, rawSubsequentText); + copyCommentFromStringLiterals(stringIndexes, templatePart); + templateSpans.push(factory.createTemplateSpan(currentNode, templatePart)); + } + } + return factory.createTemplateExpression(templateHead, templateSpans); + } + function copyExpressionComments(node) { + const file = node.getSourceFile(); + copyTrailingComments( + node, + node.expression, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + copyTrailingAsLeadingComments( + node.expression, + node.expression, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + } + function getExpressionFromParenthesesOrExpression(node) { + if (isParenthesizedExpression(node)) { + copyExpressionComments(node); + node = node.expression; + } + return node; + } + var refactorName9, refactorDescription5, convertStringAction, copyTrailingOperatorComments, copyCommentFromMultiNode; + var init_convertStringOrTemplateLiteral = __esm({ + "src/services/refactors/convertStringOrTemplateLiteral.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName9 = "Convert to template string"; + refactorDescription5 = getLocaleSpecificMessage(Diagnostics.Convert_to_template_string); + convertStringAction = { + name: refactorName9, + description: refactorDescription5, + kind: "refactor.rewrite.string" + }; + registerRefactor(refactorName9, { + kinds: [convertStringAction.kind], + getEditsForAction: getRefactorEditsToConvertToTemplateString, + getAvailableActions: getRefactorActionsToConvertToTemplateString + }); + copyTrailingOperatorComments = (operators, file) => (index, targetNode) => { + if (index < operators.length) { + copyTrailingComments( + operators[index], + targetNode, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + } + }; + copyCommentFromMultiNode = (nodes, file, copyOperatorComments) => (indexes, targetNode) => { + while (indexes.length > 0) { + const index = indexes.shift(); + copyTrailingComments( + nodes[index], + targetNode, + file, + 3 /* MultiLineCommentTrivia */, + /*hasTrailingNewLine*/ + false + ); + copyOperatorComments(index, targetNode); + } + }; + } + }); + + // src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts + var ts_refactor_convertStringOrTemplateLiteral_exports = {}; + var init_ts_refactor_convertStringOrTemplateLiteral = __esm({ + "src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts"() { + "use strict"; + init_convertStringOrTemplateLiteral(); + } + }); + + // src/services/refactors/convertToOptionalChainExpression.ts + function getRefactorActionsToConvertToOptionalChain(context) { + const info = getInfo3(context, context.triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + return [{ + name: refactorName10, + description: convertToOptionalChainExpressionMessage, + actions: [toOptionalChainAction] + }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorName10, + description: convertToOptionalChainExpressionMessage, + actions: [{ ...toOptionalChainAction, notApplicableReason: info.error }] + }]; + } + return emptyArray; + } + function getRefactorEditsToConvertToOptionalChain(context, actionName2) { + const info = getInfo3(context); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const edits = ts_textChanges_exports.ChangeTracker.with( + context, + (t) => doChange6(context.file, context.program.getTypeChecker(), t, info, actionName2) + ); + return { edits, renameFilename: void 0, renameLocation: void 0 }; + } + function isValidExpression(node) { + return isBinaryExpression(node) || isConditionalExpression(node); + } + function isValidStatement(node) { + return isExpressionStatement(node) || isReturnStatement(node) || isVariableStatement(node); + } + function isValidExpressionOrStatement(node) { + return isValidExpression(node) || isValidStatement(node); + } + function getInfo3(context, considerEmptySpans = true) { + const { file, program } = context; + const span = getRefactorContextSpan(context); + const forEmptySpan = span.length === 0; + if (forEmptySpan && !considerEmptySpans) + return void 0; + const startToken = getTokenAtPosition(file, span.start); + const endToken = findTokenOnLeftOfPosition(file, span.start + span.length); + const adjustedSpan = createTextSpanFromBounds(startToken.pos, endToken && endToken.end >= startToken.pos ? endToken.getEnd() : startToken.getEnd()); + const parent2 = forEmptySpan ? getValidParentNodeOfEmptySpan(startToken) : getValidParentNodeContainingSpan(startToken, adjustedSpan); + const expression = parent2 && isValidExpressionOrStatement(parent2) ? getExpression(parent2) : void 0; + if (!expression) + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; + const checker = program.getTypeChecker(); + return isConditionalExpression(expression) ? getConditionalInfo(expression, checker) : getBinaryInfo(expression); + } + function getConditionalInfo(expression, checker) { + const condition = expression.condition; + const finalExpression = getFinalExpressionInChain(expression.whenTrue); + if (!finalExpression || checker.isNullableType(checker.getTypeAtLocation(finalExpression))) { + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; + } + if ((isPropertyAccessExpression(condition) || isIdentifier(condition)) && getMatchingStart(condition, finalExpression.expression)) { + return { finalExpression, occurrences: [condition], expression }; + } else if (isBinaryExpression(condition)) { + const occurrences = getOccurrencesInExpression(finalExpression.expression, condition); + return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) }; + } + } + function getBinaryInfo(expression) { + if (expression.operatorToken.kind !== 56 /* AmpersandAmpersandToken */) { + return { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_logical_AND_access_chains) }; + } + const finalExpression = getFinalExpressionInChain(expression.right); + if (!finalExpression) + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; + const occurrences = getOccurrencesInExpression(finalExpression.expression, expression.left); + return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) }; + } + function getOccurrencesInExpression(matchTo, expression) { + const occurrences = []; + while (isBinaryExpression(expression) && expression.operatorToken.kind === 56 /* AmpersandAmpersandToken */) { + const match = getMatchingStart(skipParentheses(matchTo), skipParentheses(expression.right)); + if (!match) { + break; + } + occurrences.push(match); + matchTo = match; + expression = expression.left; + } + const finalMatch = getMatchingStart(matchTo, expression); + if (finalMatch) { + occurrences.push(finalMatch); + } + return occurrences.length > 0 ? occurrences : void 0; + } + function getMatchingStart(chain, subchain) { + if (!isIdentifier(subchain) && !isPropertyAccessExpression(subchain) && !isElementAccessExpression(subchain)) { + return void 0; + } + return chainStartsWith(chain, subchain) ? subchain : void 0; + } + function chainStartsWith(chain, subchain) { + while (isCallExpression(chain) || isPropertyAccessExpression(chain) || isElementAccessExpression(chain)) { + if (getTextOfChainNode(chain) === getTextOfChainNode(subchain)) + break; + chain = chain.expression; + } + while (isPropertyAccessExpression(chain) && isPropertyAccessExpression(subchain) || isElementAccessExpression(chain) && isElementAccessExpression(subchain)) { + if (getTextOfChainNode(chain) !== getTextOfChainNode(subchain)) + return false; + chain = chain.expression; + subchain = subchain.expression; + } + return isIdentifier(chain) && isIdentifier(subchain) && chain.getText() === subchain.getText(); + } + function getTextOfChainNode(node) { + if (isIdentifier(node) || isStringOrNumericLiteralLike(node)) { + return node.getText(); + } + if (isPropertyAccessExpression(node)) { + return getTextOfChainNode(node.name); + } + if (isElementAccessExpression(node)) { + return getTextOfChainNode(node.argumentExpression); + } + return void 0; + } + function getValidParentNodeContainingSpan(node, span) { + while (node.parent) { + if (isValidExpressionOrStatement(node) && span.length !== 0 && node.end >= span.start + span.length) { + return node; + } + node = node.parent; + } + return void 0; + } + function getValidParentNodeOfEmptySpan(node) { + while (node.parent) { + if (isValidExpressionOrStatement(node) && !isValidExpressionOrStatement(node.parent)) { + return node; + } + node = node.parent; + } + return void 0; + } + function getExpression(node) { + if (isValidExpression(node)) { + return node; + } + if (isVariableStatement(node)) { + const variable = getSingleVariableOfVariableStatement(node); + const initializer = variable == null ? void 0 : variable.initializer; + return initializer && isValidExpression(initializer) ? initializer : void 0; + } + return node.expression && isValidExpression(node.expression) ? node.expression : void 0; + } + function getFinalExpressionInChain(node) { + node = skipParentheses(node); + if (isBinaryExpression(node)) { + return getFinalExpressionInChain(node.left); + } else if ((isPropertyAccessExpression(node) || isElementAccessExpression(node) || isCallExpression(node)) && !isOptionalChain(node)) { + return node; + } + return void 0; + } + function convertOccurrences(checker, toConvert, occurrences) { + if (isPropertyAccessExpression(toConvert) || isElementAccessExpression(toConvert) || isCallExpression(toConvert)) { + const chain = convertOccurrences(checker, toConvert.expression, occurrences); + const lastOccurrence = occurrences.length > 0 ? occurrences[occurrences.length - 1] : void 0; + const isOccurrence = (lastOccurrence == null ? void 0 : lastOccurrence.getText()) === toConvert.expression.getText(); + if (isOccurrence) + occurrences.pop(); + if (isCallExpression(toConvert)) { + return isOccurrence ? factory.createCallChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.typeArguments, toConvert.arguments) : factory.createCallChain(chain, toConvert.questionDotToken, toConvert.typeArguments, toConvert.arguments); + } else if (isPropertyAccessExpression(toConvert)) { + return isOccurrence ? factory.createPropertyAccessChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.name) : factory.createPropertyAccessChain(chain, toConvert.questionDotToken, toConvert.name); + } else if (isElementAccessExpression(toConvert)) { + return isOccurrence ? factory.createElementAccessChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.argumentExpression) : factory.createElementAccessChain(chain, toConvert.questionDotToken, toConvert.argumentExpression); + } + } + return toConvert; + } + function doChange6(sourceFile, checker, changes, info, _actionName) { + const { finalExpression, occurrences, expression } = info; + const firstOccurrence = occurrences[occurrences.length - 1]; + const convertedChain = convertOccurrences(checker, finalExpression, occurrences); + if (convertedChain && (isPropertyAccessExpression(convertedChain) || isElementAccessExpression(convertedChain) || isCallExpression(convertedChain))) { + if (isBinaryExpression(expression)) { + changes.replaceNodeRange(sourceFile, firstOccurrence, finalExpression, convertedChain); + } else if (isConditionalExpression(expression)) { + changes.replaceNode( + sourceFile, + expression, + factory.createBinaryExpression(convertedChain, factory.createToken(61 /* QuestionQuestionToken */), expression.whenFalse) + ); + } + } + } + var refactorName10, convertToOptionalChainExpressionMessage, toOptionalChainAction; + var init_convertToOptionalChainExpression = __esm({ + "src/services/refactors/convertToOptionalChainExpression.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName10 = "Convert to optional chain expression"; + convertToOptionalChainExpressionMessage = getLocaleSpecificMessage(Diagnostics.Convert_to_optional_chain_expression); + toOptionalChainAction = { + name: refactorName10, + description: convertToOptionalChainExpressionMessage, + kind: "refactor.rewrite.expression.optionalChain" + }; + registerRefactor(refactorName10, { + kinds: [toOptionalChainAction.kind], + getEditsForAction: getRefactorEditsToConvertToOptionalChain, + getAvailableActions: getRefactorActionsToConvertToOptionalChain + }); + } + }); + + // src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts + var ts_refactor_convertToOptionalChainExpression_exports = {}; + var init_ts_refactor_convertToOptionalChainExpression = __esm({ + "src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts"() { + "use strict"; + init_convertToOptionalChainExpression(); + } + }); + + // src/services/refactors/extractSymbol.ts + function getRefactorActionsToExtractSymbol(context) { + const requestedRefactor = context.kind; + const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context), context.triggerReason === "invoked"); + const targetRange = rangeToExtract.targetRange; + if (targetRange === void 0) { + if (!rangeToExtract.errors || rangeToExtract.errors.length === 0 || !context.preferences.provideRefactorNotApplicableReason) { + return emptyArray; + } + const errors = []; + if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { + errors.push({ + name: refactorName11, + description: extractFunctionAction.description, + actions: [{ ...extractFunctionAction, notApplicableReason: getStringError(rangeToExtract.errors) }] + }); + } + if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { + errors.push({ + name: refactorName11, + description: extractConstantAction.description, + actions: [{ ...extractConstantAction, notApplicableReason: getStringError(rangeToExtract.errors) }] + }); + } + return errors; + } + const extractions = getPossibleExtractions(targetRange, context); + if (extractions === void 0) { + return emptyArray; + } + const functionActions = []; + const usedFunctionNames = /* @__PURE__ */ new Map(); + let innermostErrorFunctionAction; + const constantActions = []; + const usedConstantNames = /* @__PURE__ */ new Map(); + let innermostErrorConstantAction; + let i = 0; + for (const { functionExtraction, constantExtraction } of extractions) { + if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { + const description3 = functionExtraction.description; + if (functionExtraction.errors.length === 0) { + if (!usedFunctionNames.has(description3)) { + usedFunctionNames.set(description3, true); + functionActions.push({ + description: description3, + name: `function_scope_${i}`, + kind: extractFunctionAction.kind + }); + } + } else if (!innermostErrorFunctionAction) { + innermostErrorFunctionAction = { + description: description3, + name: `function_scope_${i}`, + notApplicableReason: getStringError(functionExtraction.errors), + kind: extractFunctionAction.kind + }; + } + } + if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { + const description3 = constantExtraction.description; + if (constantExtraction.errors.length === 0) { + if (!usedConstantNames.has(description3)) { + usedConstantNames.set(description3, true); + constantActions.push({ + description: description3, + name: `constant_scope_${i}`, + kind: extractConstantAction.kind + }); + } + } else if (!innermostErrorConstantAction) { + innermostErrorConstantAction = { + description: description3, + name: `constant_scope_${i}`, + notApplicableReason: getStringError(constantExtraction.errors), + kind: extractConstantAction.kind + }; + } + } + i++; + } + const infos = []; + if (functionActions.length) { + infos.push({ + name: refactorName11, + description: getLocaleSpecificMessage(Diagnostics.Extract_function), + actions: functionActions + }); + } else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorFunctionAction) { + infos.push({ + name: refactorName11, + description: getLocaleSpecificMessage(Diagnostics.Extract_function), + actions: [innermostErrorFunctionAction] + }); + } + if (constantActions.length) { + infos.push({ + name: refactorName11, + description: getLocaleSpecificMessage(Diagnostics.Extract_constant), + actions: constantActions + }); + } else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorConstantAction) { + infos.push({ + name: refactorName11, + description: getLocaleSpecificMessage(Diagnostics.Extract_constant), + actions: [innermostErrorConstantAction] + }); + } + return infos.length ? infos : emptyArray; + function getStringError(errors) { + let error = errors[0].messageText; + if (typeof error !== "string") { + error = error.messageText; + } + return error; + } + } + function getRefactorEditsToExtractSymbol(context, actionName2) { + const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context)); + const targetRange = rangeToExtract.targetRange; + const parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName2); + if (parsedFunctionIndexMatch) { + const index = +parsedFunctionIndexMatch[1]; + Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index"); + return getFunctionExtractionAtIndex(targetRange, context, index); + } + const parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName2); + if (parsedConstantIndexMatch) { + const index = +parsedConstantIndexMatch[1]; + Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index"); + return getConstantExtractionAtIndex(targetRange, context, index); + } + Debug.fail("Unrecognized action name"); + } + function getRangeToExtract2(sourceFile, span, invoked = true) { + const { length: length2 } = span; + if (length2 === 0 && !invoked) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractEmpty)] }; + } + const cursorRequest = length2 === 0 && invoked; + const startToken = findFirstNonJsxWhitespaceToken(sourceFile, span.start); + const endToken = findTokenOnLeftOfPosition(sourceFile, textSpanEnd(span)); + const adjustedSpan = startToken && endToken && invoked ? getAdjustedSpanFromNodes(startToken, endToken, sourceFile) : span; + const start = cursorRequest ? getExtractableParent(startToken) : getParentNodeInSpan(startToken, sourceFile, adjustedSpan); + const end = cursorRequest ? start : getParentNodeInSpan(endToken, sourceFile, adjustedSpan); + let rangeFacts = 0 /* None */; + let thisNode; + if (!start || !end) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + } + if (start.flags & 8388608 /* JSDoc */) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractJSDoc)] }; + } + if (start.parent !== end.parent) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + } + if (start !== end) { + if (!isBlockLike(start.parent)) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + } + const statements = []; + for (const statement of start.parent.statements) { + if (statement === start || statements.length) { + const errors2 = checkNode(statement); + if (errors2) { + return { errors: errors2 }; + } + statements.push(statement); + } + if (statement === end) { + break; + } + } + if (!statements.length) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + } + return { targetRange: { range: statements, facts: rangeFacts, thisNode } }; + } + if (isReturnStatement(start) && !start.expression) { + return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; + } + const node = refineNode(start); + const errors = checkRootNode(node) || checkNode(node); + if (errors) { + return { errors }; + } + return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, thisNode } }; + function refineNode(node2) { + if (isReturnStatement(node2)) { + if (node2.expression) { + return node2.expression; + } + } else if (isVariableStatement(node2) || isVariableDeclarationList(node2)) { + const declarations = isVariableStatement(node2) ? node2.declarationList.declarations : node2.declarations; + let numInitializers = 0; + let lastInitializer; + for (const declaration of declarations) { + if (declaration.initializer) { + numInitializers++; + lastInitializer = declaration.initializer; + } + } + if (numInitializers === 1) { + return lastInitializer; + } + } else if (isVariableDeclaration(node2)) { + if (node2.initializer) { + return node2.initializer; + } + } + return node2; + } + function checkRootNode(node2) { + if (isIdentifier(isExpressionStatement(node2) ? node2.expression : node2)) { + return [createDiagnosticForNode(node2, Messages.cannotExtractIdentifier)]; + } + return void 0; + } + function checkForStaticContext(nodeToCheck, containingClass) { + let current = nodeToCheck; + while (current !== containingClass) { + if (current.kind === 171 /* PropertyDeclaration */) { + if (isStatic(current)) { + rangeFacts |= 32 /* InStaticRegion */; + } + break; + } else if (current.kind === 168 /* Parameter */) { + const ctorOrMethod = getContainingFunction(current); + if (ctorOrMethod.kind === 175 /* Constructor */) { + rangeFacts |= 32 /* InStaticRegion */; + } + break; + } else if (current.kind === 173 /* MethodDeclaration */) { + if (isStatic(current)) { + rangeFacts |= 32 /* InStaticRegion */; + } + } + current = current.parent; + } + } + function checkNode(nodeToCheck) { + let PermittedJumps; + ((PermittedJumps2) => { + PermittedJumps2[PermittedJumps2["None"] = 0] = "None"; + PermittedJumps2[PermittedJumps2["Break"] = 1] = "Break"; + PermittedJumps2[PermittedJumps2["Continue"] = 2] = "Continue"; + PermittedJumps2[PermittedJumps2["Return"] = 4] = "Return"; + })(PermittedJumps || (PermittedJumps = {})); + Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (1)"); + Debug.assert(!positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (2)"); + if (!isStatement(nodeToCheck) && !(isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck)) && !isStringLiteralJsxAttribute(nodeToCheck)) { + return [createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)]; + } + if (nodeToCheck.flags & 16777216 /* Ambient */) { + return [createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)]; + } + const containingClass = getContainingClass(nodeToCheck); + if (containingClass) { + checkForStaticContext(nodeToCheck, containingClass); + } + let errors2; + let permittedJumps = 4 /* Return */; + let seenLabels; + visit(nodeToCheck); + if (rangeFacts & 8 /* UsesThis */) { + const container = getThisContainer( + nodeToCheck, + /*includeArrowFunctions*/ + false, + /*includeClassComputedPropertyName*/ + false + ); + if (container.kind === 261 /* FunctionDeclaration */ || container.kind === 173 /* MethodDeclaration */ && container.parent.kind === 209 /* ObjectLiteralExpression */ || container.kind === 217 /* FunctionExpression */) { + rangeFacts |= 16 /* UsesThisInFunction */; + } + } + return errors2; + function visit(node2) { + if (errors2) { + return true; + } + if (isDeclaration(node2)) { + const declaringNode = node2.kind === 259 /* VariableDeclaration */ ? node2.parent.parent : node2; + if (hasSyntacticModifier(declaringNode, 1 /* Export */)) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity)); + return true; + } + } + switch (node2.kind) { + case 271 /* ImportDeclaration */: + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractImport)); + return true; + case 276 /* ExportAssignment */: + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity)); + return true; + case 108 /* SuperKeyword */: + if (node2.parent.kind === 212 /* CallExpression */) { + const containingClass2 = getContainingClass(node2); + if (containingClass2 === void 0 || containingClass2.pos < span.start || containingClass2.end >= span.start + span.length) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractSuper)); + return true; + } + } else { + rangeFacts |= 8 /* UsesThis */; + thisNode = node2; + } + break; + case 218 /* ArrowFunction */: + forEachChild(node2, function check(n) { + if (isThis(n)) { + rangeFacts |= 8 /* UsesThis */; + thisNode = node2; + } else if (isClassLike(n) || isFunctionLike(n) && !isArrowFunction(n)) { + return false; + } else { + forEachChild(n, check); + } + }); + case 262 /* ClassDeclaration */: + case 261 /* FunctionDeclaration */: + if (isSourceFile(node2.parent) && node2.parent.externalModuleIndicator === void 0) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.functionWillNotBeVisibleInTheNewScope)); + } + case 230 /* ClassExpression */: + case 217 /* FunctionExpression */: + case 173 /* MethodDeclaration */: + case 175 /* Constructor */: + case 176 /* GetAccessor */: + case 177 /* SetAccessor */: + return false; + } + const savedPermittedJumps = permittedJumps; + switch (node2.kind) { + case 244 /* IfStatement */: + permittedJumps &= ~4 /* Return */; + break; + case 257 /* TryStatement */: + permittedJumps = 0 /* None */; + break; + case 240 /* Block */: + if (node2.parent && node2.parent.kind === 257 /* TryStatement */ && node2.parent.finallyBlock === node2) { + permittedJumps = 4 /* Return */; + } + break; + case 296 /* DefaultClause */: + case 295 /* CaseClause */: + permittedJumps |= 1 /* Break */; + break; + default: + if (isIterationStatement( + node2, + /*lookInLabeledStatements*/ + false + )) { + permittedJumps |= 1 /* Break */ | 2 /* Continue */; + } + break; + } + switch (node2.kind) { + case 196 /* ThisType */: + case 110 /* ThisKeyword */: + rangeFacts |= 8 /* UsesThis */; + thisNode = node2; + break; + case 255 /* LabeledStatement */: { + const label = node2.label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + forEachChild(node2, visit); + seenLabels.pop(); + break; + } + case 251 /* BreakStatement */: + case 250 /* ContinueStatement */: { + const label = node2.label; + if (label) { + if (!contains(seenLabels, label.escapedText)) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); + } + } else { + if (!(permittedJumps & (node2.kind === 251 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); + } + } + break; + } + case 222 /* AwaitExpression */: + rangeFacts |= 4 /* IsAsyncFunction */; + break; + case 228 /* YieldExpression */: + rangeFacts |= 2 /* IsGenerator */; + break; + case 252 /* ReturnStatement */: + if (permittedJumps & 4 /* Return */) { + rangeFacts |= 1 /* HasReturn */; + } else { + (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalReturnStatement)); + } + break; + default: + forEachChild(node2, visit); + break; + } + permittedJumps = savedPermittedJumps; + } + } + } + function getAdjustedSpanFromNodes(startNode2, endNode2, sourceFile) { + const start = startNode2.getStart(sourceFile); + let end = endNode2.getEnd(); + if (sourceFile.text.charCodeAt(end) === 59 /* semicolon */) { + end++; + } + return { start, length: end - start }; + } + function getStatementOrExpressionRange(node) { + if (isStatement(node)) { + return [node]; + } + if (isExpressionNode(node)) { + return isExpressionStatement(node.parent) ? [node.parent] : node; + } + if (isStringLiteralJsxAttribute(node)) { + return node; + } + return void 0; + } + function isScope(node) { + return isArrowFunction(node) ? isFunctionBody(node.body) : isFunctionLikeDeclaration(node) || isSourceFile(node) || isModuleBlock(node) || isClassLike(node); + } + function collectEnclosingScopes(range) { + let current = isReadonlyArray(range.range) ? first(range.range) : range.range; + if (range.facts & 8 /* UsesThis */ && !(range.facts & 16 /* UsesThisInFunction */)) { + const containingClass = getContainingClass(current); + if (containingClass) { + const containingFunction = findAncestor(current, isFunctionLikeDeclaration); + return containingFunction ? [containingFunction, containingClass] : [containingClass]; + } + } + const scopes = []; + while (true) { + current = current.parent; + if (current.kind === 168 /* Parameter */) { + current = findAncestor(current, (parent2) => isFunctionLikeDeclaration(parent2)).parent; + } + if (isScope(current)) { + scopes.push(current); + if (current.kind === 311 /* SourceFile */) { + return scopes; + } + } + } + } + function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { + const { scopes, readsAndWrites: { target, usagesPerScope, functionErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); + Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + context.cancellationToken.throwIfCancellationRequested(); + return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); + } + function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { + const { scopes, readsAndWrites: { target, usagesPerScope, constantErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); + Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); + Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); + context.cancellationToken.throwIfCancellationRequested(); + const expression = isExpression(target) ? target : target.statements[0].expression; + return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context); + } + function getPossibleExtractions(targetRange, context) { + const { scopes, readsAndWrites: { functionErrorsPerScope, constantErrorsPerScope } } = getPossibleExtractionsWorker(targetRange, context); + const extractions = scopes.map((scope, i) => { + const functionDescriptionPart = getDescriptionForFunctionInScope(scope); + const constantDescriptionPart = getDescriptionForConstantInScope(scope); + const scopeDescription = isFunctionLikeDeclaration(scope) ? getDescriptionForFunctionLikeDeclaration(scope) : isClassLike(scope) ? getDescriptionForClassLikeDeclaration(scope) : getDescriptionForModuleLikeDeclaration(scope); + let functionDescription; + let constantDescription; + if (scopeDescription === 1 /* Global */) { + functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]); + constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]); + } else if (scopeDescription === 0 /* Module */) { + functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]); + constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]); + } else { + functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]); + constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]); + } + if (i === 0 && !isClassLike(scope)) { + constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]); + } + return { + functionExtraction: { + description: functionDescription, + errors: functionErrorsPerScope[i] + }, + constantExtraction: { + description: constantDescription, + errors: constantErrorsPerScope[i] + } + }; + }); + return extractions; + } + function getPossibleExtractionsWorker(targetRange, context) { + const { file: sourceFile } = context; + const scopes = collectEnclosingScopes(targetRange); + const enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); + const readsAndWrites = collectReadsAndWrites( + targetRange, + scopes, + enclosingTextRange, + sourceFile, + context.program.getTypeChecker(), + context.cancellationToken + ); + return { scopes, readsAndWrites }; + } + function getDescriptionForFunctionInScope(scope) { + return isFunctionLikeDeclaration(scope) ? "inner function" : isClassLike(scope) ? "method" : "function"; + } + function getDescriptionForConstantInScope(scope) { + return isClassLike(scope) ? "readonly field" : "constant"; + } + function getDescriptionForFunctionLikeDeclaration(scope) { + switch (scope.kind) { + case 175 /* Constructor */: + return "constructor"; + case 217 /* FunctionExpression */: + case 261 /* FunctionDeclaration */: + return scope.name ? `function '${scope.name.text}'` : ANONYMOUS; + case 218 /* ArrowFunction */: + return "arrow function"; + case 173 /* MethodDeclaration */: + return `method '${scope.name.getText()}'`; + case 176 /* GetAccessor */: + return `'get ${scope.name.getText()}'`; + case 177 /* SetAccessor */: + return `'set ${scope.name.getText()}'`; + default: + Debug.assertNever(scope, `Unexpected scope kind ${scope.kind}`); + } + } + function getDescriptionForClassLikeDeclaration(scope) { + return scope.kind === 262 /* ClassDeclaration */ ? scope.name ? `class '${scope.name.text}'` : "anonymous class declaration" : scope.name ? `class expression '${scope.name.text}'` : "anonymous class expression"; + } + function getDescriptionForModuleLikeDeclaration(scope) { + return scope.kind === 267 /* ModuleBlock */ ? `namespace '${scope.parent.name.getText()}'` : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; + } + function extractFunctionInScope(node, scope, { usages: usagesInScope, typeParameterUsages, substitutions }, exposedVariableDeclarations, range, context) { + const checker = context.program.getTypeChecker(); + const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); + const importAdder = ts_codefix_exports.createImportAdder(context.file, context.program, context.preferences, context.host); + const file = scope.getSourceFile(); + const functionNameText = getUniqueName(isClassLike(scope) ? "newMethod" : "newFunction", file); + const isJS = isInJSFile(scope); + const functionName = factory.createIdentifier(functionNameText); + let returnType; + const parameters = []; + const callArguments = []; + let writes; + usagesInScope.forEach((usage, name) => { + let typeNode; + if (!isJS) { + let type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); + type = checker.getBaseTypeOfLiteralType(type); + typeNode = ts_codefix_exports.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */); + } + const paramDecl = factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + /*name*/ + name, + /*questionToken*/ + void 0, + typeNode + ); + parameters.push(paramDecl); + if (usage.usage === 2 /* Write */) { + (writes || (writes = [])).push(usage); + } + callArguments.push(factory.createIdentifier(name)); + }); + const typeParametersAndDeclarations = arrayFrom(typeParameterUsages.values(), (type) => ({ type, declaration: getFirstDeclarationBeforePosition(type, context.startPosition) })); + const sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); + const typeParameters = sortedTypeParametersAndDeclarations.length === 0 ? void 0 : mapDefined(sortedTypeParametersAndDeclarations, ({ declaration }) => declaration); + const callTypeArguments = typeParameters !== void 0 ? typeParameters.map((decl) => factory.createTypeReferenceNode( + decl.name, + /*typeArguments*/ + void 0 + )) : void 0; + if (isExpression(node) && !isJS) { + const contextualType = checker.getContextualType(node); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); + } + const { body, returnValueProperty } = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & 1 /* HasReturn */)); + suppressLeadingAndTrailingTrivia(body); + let newFunction; + const callThis = !!(range.facts & 16 /* UsesThisInFunction */); + if (isClassLike(scope)) { + const modifiers = isJS ? [] : [factory.createModifier(123 /* PrivateKeyword */)]; + if (range.facts & 32 /* InStaticRegion */) { + modifiers.push(factory.createModifier(126 /* StaticKeyword */)); + } + if (range.facts & 4 /* IsAsyncFunction */) { + modifiers.push(factory.createModifier(134 /* AsyncKeyword */)); + } + newFunction = factory.createMethodDeclaration( + modifiers.length ? modifiers : void 0, + range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0, + functionName, + /*questionToken*/ + void 0, + typeParameters, + parameters, + returnType, + body + ); + } else { + if (callThis) { + parameters.unshift( + factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + /*name*/ + "this", + /*questionToken*/ + void 0, + checker.typeToTypeNode( + checker.getTypeAtLocation(range.thisNode), + scope, + 1 /* NoTruncation */ + ), + /*initializer*/ + void 0 + ) + ); + } + newFunction = factory.createFunctionDeclaration( + range.facts & 4 /* IsAsyncFunction */ ? [factory.createToken(134 /* AsyncKeyword */)] : void 0, + range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0, + functionName, + typeParameters, + parameters, + returnType, + body + ); + } + const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); + const minInsertionPos = (isReadonlyArray(range.range) ? last(range.range) : range.range).end; + const nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); + if (nodeToInsertBefore) { + changeTracker.insertNodeBefore( + context.file, + nodeToInsertBefore, + newFunction, + /*blankLineBetween*/ + true + ); + } else { + changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); + } + importAdder.writeFixes(changeTracker); + const newNodes = []; + const called = getCalledExpression(scope, range, functionNameText); + if (callThis) { + callArguments.unshift(factory.createIdentifier("this")); + } + let call = factory.createCallExpression( + callThis ? factory.createPropertyAccessExpression( + called, + "call" + ) : called, + callTypeArguments, + // Note that no attempt is made to take advantage of type argument inference + callArguments + ); + if (range.facts & 2 /* IsGenerator */) { + call = factory.createYieldExpression(factory.createToken(42 /* AsteriskToken */), call); + } + if (range.facts & 4 /* IsAsyncFunction */) { + call = factory.createAwaitExpression(call); + } + if (isInJSXContent(node)) { + call = factory.createJsxExpression( + /*dotDotDotToken*/ + void 0, + call + ); + } + if (exposedVariableDeclarations.length && !writes) { + Debug.assert(!returnValueProperty, "Expected no returnValueProperty"); + Debug.assert(!(range.facts & 1 /* HasReturn */), "Expected RangeFacts.HasReturn flag to be unset"); + if (exposedVariableDeclarations.length === 1) { + const variableDeclaration = exposedVariableDeclarations[0]; + newNodes.push(factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + getSynthesizedDeepClone(variableDeclaration.name), + /*exclamationToken*/ + void 0, + /*type*/ + getSynthesizedDeepClone(variableDeclaration.type), + /*initializer*/ + call + )], + variableDeclaration.parent.flags + ) + )); + } else { + const bindingElements = []; + const typeElements = []; + let commonNodeFlags = exposedVariableDeclarations[0].parent.flags; + let sawExplicitType = false; + for (const variableDeclaration of exposedVariableDeclarations) { + bindingElements.push(factory.createBindingElement( + /*dotDotDotToken*/ + void 0, + /*propertyName*/ + void 0, + /*name*/ + getSynthesizedDeepClone(variableDeclaration.name) + )); + const variableType = checker.typeToTypeNode( + checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), + scope, + 1 /* NoTruncation */ + ); + typeElements.push(factory.createPropertySignature( + /*modifiers*/ + void 0, + /*name*/ + variableDeclaration.symbol.name, + /*questionToken*/ + void 0, + /*type*/ + variableType + )); + sawExplicitType = sawExplicitType || variableDeclaration.type !== void 0; + commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; + } + const typeLiteral = sawExplicitType ? factory.createTypeLiteralNode(typeElements) : void 0; + if (typeLiteral) { + setEmitFlags(typeLiteral, 1 /* SingleLine */); + } + newNodes.push(factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + factory.createObjectBindingPattern(bindingElements), + /*exclamationToken*/ + void 0, + /*type*/ + typeLiteral, + /*initializer*/ + call + )], + commonNodeFlags + ) + )); + } + } else if (exposedVariableDeclarations.length || writes) { + if (exposedVariableDeclarations.length) { + for (const variableDeclaration of exposedVariableDeclarations) { + let flags = variableDeclaration.parent.flags; + if (flags & 2 /* Const */) { + flags = flags & ~2 /* Const */ | 1 /* Let */; + } + newNodes.push(factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + variableDeclaration.symbol.name, + /*exclamationToken*/ + void 0, + getTypeDeepCloneUnionUndefined(variableDeclaration.type) + )], + flags + ) + )); + } + } + if (returnValueProperty) { + newNodes.push(factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList( + [factory.createVariableDeclaration( + returnValueProperty, + /*exclamationToken*/ + void 0, + getTypeDeepCloneUnionUndefined(returnType) + )], + 1 /* Let */ + ) + )); + } + const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (returnValueProperty) { + assignments.unshift(factory.createShorthandPropertyAssignment(returnValueProperty)); + } + if (assignments.length === 1) { + Debug.assert(!returnValueProperty, "Shouldn't have returnValueProperty here"); + newNodes.push(factory.createExpressionStatement(factory.createAssignment(assignments[0].name, call))); + if (range.facts & 1 /* HasReturn */) { + newNodes.push(factory.createReturnStatement()); + } + } else { + newNodes.push(factory.createExpressionStatement(factory.createAssignment(factory.createObjectLiteralExpression(assignments), call))); + if (returnValueProperty) { + newNodes.push(factory.createReturnStatement(factory.createIdentifier(returnValueProperty))); + } + } + } else { + if (range.facts & 1 /* HasReturn */) { + newNodes.push(factory.createReturnStatement(call)); + } else if (isReadonlyArray(range.range)) { + newNodes.push(factory.createExpressionStatement(call)); + } else { + newNodes.push(call); + } + } + if (isReadonlyArray(range.range)) { + changeTracker.replaceNodeRangeWithNodes(context.file, first(range.range), last(range.range), newNodes); + } else { + changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes); + } + const edits = changeTracker.getChanges(); + const renameRange = isReadonlyArray(range.range) ? first(range.range) : range.range; + const renameFilename = renameRange.getSourceFile().fileName; + const renameLocation = getRenameLocation( + edits, + renameFilename, + functionNameText, + /*preferLastLocation*/ + false + ); + return { renameFilename, renameLocation, edits }; + function getTypeDeepCloneUnionUndefined(typeNode) { + if (typeNode === void 0) { + return void 0; + } + const clone2 = getSynthesizedDeepClone(typeNode); + let withoutParens = clone2; + while (isParenthesizedTypeNode(withoutParens)) { + withoutParens = withoutParens.type; + } + return isUnionTypeNode(withoutParens) && find(withoutParens.types, (t) => t.kind === 157 /* UndefinedKeyword */) ? clone2 : factory.createUnionTypeNode([clone2, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); + } + } + function extractConstantInScope(node, scope, { substitutions }, rangeFacts, context) { + const checker = context.program.getTypeChecker(); + const file = scope.getSourceFile(); + const localNameText = isPropertyAccessExpression(node) && !isClassLike(scope) && !checker.resolveName( + node.name.text, + node, + 111551 /* Value */, + /*excludeGlobals*/ + false + ) && !isPrivateIdentifier(node.name) && !identifierToKeywordKind(node.name) ? node.name.text : getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file); + const isJS = isInJSFile(scope); + let variableType = isJS || !checker.isContextSensitive(node) ? void 0 : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); + let initializer = transformConstantInitializer(skipParentheses(node), substitutions); + ({ variableType, initializer } = transformFunctionInitializerAndType(variableType, initializer)); + suppressLeadingAndTrailingTrivia(initializer); + const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); + if (isClassLike(scope)) { + Debug.assert(!isJS, "Cannot extract to a JS class"); + const modifiers = []; + modifiers.push(factory.createModifier(123 /* PrivateKeyword */)); + if (rangeFacts & 32 /* InStaticRegion */) { + modifiers.push(factory.createModifier(126 /* StaticKeyword */)); + } + modifiers.push(factory.createModifier(148 /* ReadonlyKeyword */)); + const newVariable = factory.createPropertyDeclaration( + modifiers, + localNameText, + /*questionOrExclamationToken*/ + void 0, + variableType, + initializer + ); + let localReference = factory.createPropertyAccessExpression( + rangeFacts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.getText()) : factory.createThis(), + factory.createIdentifier(localNameText) + ); + if (isInJSXContent(node)) { + localReference = factory.createJsxExpression( + /*dotDotDotToken*/ + void 0, + localReference + ); + } + const maxInsertionPos = node.pos; + const nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); + changeTracker.insertNodeBefore( + context.file, + nodeToInsertBefore, + newVariable, + /*blankLineBetween*/ + true + ); + changeTracker.replaceNode(context.file, node, localReference); + } else { + const newVariableDeclaration = factory.createVariableDeclaration( + localNameText, + /*exclamationToken*/ + void 0, + variableType, + initializer + ); + const oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); + if (oldVariableDeclaration) { + changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); + const localReference = factory.createIdentifier(localNameText); + changeTracker.replaceNode(context.file, node, localReference); + } else if (node.parent.kind === 243 /* ExpressionStatement */ && scope === findAncestor(node, isScope)) { + const newVariableStatement = factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */) + ); + changeTracker.replaceNode(context.file, node.parent, newVariableStatement); + } else { + const newVariableStatement = factory.createVariableStatement( + /*modifiers*/ + void 0, + factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */) + ); + const nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); + if (nodeToInsertBefore.pos === 0) { + changeTracker.insertNodeAtTopOfFile( + context.file, + newVariableStatement, + /*blankLineBetween*/ + false + ); + } else { + changeTracker.insertNodeBefore( + context.file, + nodeToInsertBefore, + newVariableStatement, + /*blankLineBetween*/ + false + ); + } + if (node.parent.kind === 243 /* ExpressionStatement */) { + changeTracker.delete(context.file, node.parent); + } else { + let localReference = factory.createIdentifier(localNameText); + if (isInJSXContent(node)) { + localReference = factory.createJsxExpression( + /*dotDotDotToken*/ + void 0, + localReference + ); + } + changeTracker.replaceNode(context.file, node, localReference); + } + } + } + const edits = changeTracker.getChanges(); + const renameFilename = node.getSourceFile().fileName; + const renameLocation = getRenameLocation( + edits, + renameFilename, + localNameText, + /*preferLastLocation*/ + true + ); + return { renameFilename, renameLocation, edits }; + function transformFunctionInitializerAndType(variableType2, initializer2) { + if (variableType2 === void 0) + return { variableType: variableType2, initializer: initializer2 }; + if (!isFunctionExpression(initializer2) && !isArrowFunction(initializer2) || !!initializer2.typeParameters) + return { variableType: variableType2, initializer: initializer2 }; + const functionType = checker.getTypeAtLocation(node); + const functionSignature = singleOrUndefined(checker.getSignaturesOfType(functionType, 0 /* Call */)); + if (!functionSignature) + return { variableType: variableType2, initializer: initializer2 }; + if (!!functionSignature.getTypeParameters()) + return { variableType: variableType2, initializer: initializer2 }; + const parameters = []; + let hasAny = false; + for (const p of initializer2.parameters) { + if (p.type) { + parameters.push(p); + } else { + 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, 1 /* NoTruncation */), + p.initializer + )); + } + } + if (hasAny) + return { variableType: variableType2, initializer: initializer2 }; + variableType2 = void 0; + if (isArrowFunction(initializer2)) { + initializer2 = factory.updateArrowFunction( + initializer2, + canHaveModifiers(node) ? getModifiers(node) : void 0, + initializer2.typeParameters, + parameters, + initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), + initializer2.equalsGreaterThanToken, + initializer2.body + ); + } else { + if (functionSignature && !!functionSignature.thisParameter) { + const firstParameter = firstOrUndefined(parameters); + if (!firstParameter || isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this") { + const thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node); + parameters.splice(0, 0, factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "this", + /*questionToken*/ + void 0, + checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */) + )); + } + } + initializer2 = factory.updateFunctionExpression( + initializer2, + canHaveModifiers(node) ? getModifiers(node) : void 0, + initializer2.asteriskToken, + initializer2.name, + initializer2.typeParameters, + parameters, + initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), + initializer2.body + ); + } + return { variableType: variableType2, initializer: initializer2 }; + } + } + function getContainingVariableDeclarationIfInList(node, scope) { + let prevNode; + while (node !== void 0 && node !== scope) { + if (isVariableDeclaration(node) && node.initializer === prevNode && isVariableDeclarationList(node.parent) && node.parent.declarations.length > 1) { + return node; + } + prevNode = node; + node = node.parent; + } + } + function getFirstDeclarationBeforePosition(type, position) { + let firstDeclaration; + const symbol = type.symbol; + if (symbol && symbol.declarations) { + for (const declaration of symbol.declarations) { + if ((firstDeclaration === void 0 || declaration.pos < firstDeclaration.pos) && declaration.pos < position) { + firstDeclaration = declaration; + } + } + } + return firstDeclaration; + } + function compareTypesByDeclarationOrder({ type: type1, declaration: declaration1 }, { type: type2, declaration: declaration2 }) { + return compareProperties(declaration1, declaration2, "pos", compareValues) || compareStringsCaseSensitive( + type1.symbol ? type1.symbol.getName() : "", + type2.symbol ? type2.symbol.getName() : "" + ) || compareValues(type1.id, type2.id); + } + function getCalledExpression(scope, range, functionNameText) { + const functionReference = factory.createIdentifier(functionNameText); + if (isClassLike(scope)) { + const lhs = range.facts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.text) : factory.createThis(); + return factory.createPropertyAccessExpression(lhs, functionReference); + } else { + return functionReference; + } + } + function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn2) { + const hasWritesOrVariableDeclarations = writes !== void 0 || exposedVariableDeclarations.length > 0; + if (isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { + return { body: factory.createBlock( + body.statements, + /*multiLine*/ + true + ), returnValueProperty: void 0 }; + } + let returnValueProperty; + let ignoreReturns = false; + const statements = factory.createNodeArray(isBlock(body) ? body.statements.slice(0) : [isStatement(body) ? body : factory.createReturnStatement(skipParentheses(body))]); + if (hasWritesOrVariableDeclarations || substitutions.size) { + const rewrittenStatements = visitNodes2(statements, visitor, isStatement).slice(); + if (hasWritesOrVariableDeclarations && !hasReturn2 && isStatement(body)) { + const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (assignments.length === 1) { + rewrittenStatements.push(factory.createReturnStatement(assignments[0].name)); + } else { + rewrittenStatements.push(factory.createReturnStatement(factory.createObjectLiteralExpression(assignments))); + } + } + return { body: factory.createBlock( + rewrittenStatements, + /*multiLine*/ + true + ), returnValueProperty }; + } else { + return { body: factory.createBlock( + statements, + /*multiLine*/ + true + ), returnValueProperty: void 0 }; + } + function visitor(node) { + if (!ignoreReturns && isReturnStatement(node) && hasWritesOrVariableDeclarations) { + const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); + if (node.expression) { + if (!returnValueProperty) { + returnValueProperty = "__return"; + } + assignments.unshift(factory.createPropertyAssignment(returnValueProperty, visitNode(node.expression, visitor, isExpression))); + } + if (assignments.length === 1) { + return factory.createReturnStatement(assignments[0].name); + } else { + return factory.createReturnStatement(factory.createObjectLiteralExpression(assignments)); + } + } else { + const oldIgnoreReturns = ignoreReturns; + ignoreReturns = ignoreReturns || isFunctionLikeDeclaration(node) || isClassLike(node); + const substitution = substitutions.get(getNodeId(node).toString()); + const result = substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext); + ignoreReturns = oldIgnoreReturns; + return result; + } + } + } + function transformConstantInitializer(initializer, substitutions) { + return substitutions.size ? visitor(initializer) : initializer; + function visitor(node) { + const substitution = substitutions.get(getNodeId(node).toString()); + return substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext); + } + } + function getStatementsOrClassElements(scope) { + if (isFunctionLikeDeclaration(scope)) { + const body = scope.body; + if (isBlock(body)) { + return body.statements; + } + } else if (isModuleBlock(scope) || isSourceFile(scope)) { + return scope.statements; + } else if (isClassLike(scope)) { + return scope.members; + } else { + assertType(scope); + } + return emptyArray; + } + function getNodeToInsertFunctionBefore(minPos, scope) { + return find(getStatementsOrClassElements(scope), (child) => child.pos >= minPos && isFunctionLikeDeclaration(child) && !isConstructorDeclaration(child)); + } + function getNodeToInsertPropertyBefore(maxPos, scope) { + const members = scope.members; + Debug.assert(members.length > 0, "Found no members"); + let prevMember; + let allProperties = true; + for (const member of members) { + if (member.pos > maxPos) { + return prevMember || members[0]; + } + if (allProperties && !isPropertyDeclaration(member)) { + if (prevMember !== void 0) { + return member; + } + allProperties = false; + } + prevMember = member; + } + if (prevMember === void 0) + return Debug.fail(); + return prevMember; + } + function getNodeToInsertConstantBefore(node, scope) { + Debug.assert(!isClassLike(scope)); + let prevScope; + for (let curr = node; curr !== scope; curr = curr.parent) { + if (isScope(curr)) { + prevScope = curr; + } + } + for (let curr = (prevScope || node).parent; ; curr = curr.parent) { + if (isBlockLike(curr)) { + let prevStatement; + for (const statement of curr.statements) { + if (statement.pos > node.pos) { + break; + } + prevStatement = statement; + } + if (!prevStatement && isCaseClause(curr)) { + Debug.assert(isSwitchStatement(curr.parent.parent), "Grandparent isn't a switch statement"); + return curr.parent.parent; + } + return Debug.checkDefined(prevStatement, "prevStatement failed to get set"); + } + Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); + } + } + function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { + const variableAssignments = map(exposedVariableDeclarations, (v) => factory.createShorthandPropertyAssignment(v.symbol.name)); + const writeAssignments = map(writes, (w) => factory.createShorthandPropertyAssignment(w.symbol.name)); + return variableAssignments === void 0 ? writeAssignments : writeAssignments === void 0 ? variableAssignments : variableAssignments.concat(writeAssignments); + } + function isReadonlyArray(v) { + return isArray(v); + } + function getEnclosingTextRange(targetRange, sourceFile) { + return isReadonlyArray(targetRange.range) ? { pos: first(targetRange.range).getStart(sourceFile), end: last(targetRange.range).getEnd() } : targetRange.range; + } + function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { + const allTypeParameterUsages = /* @__PURE__ */ new Map(); + const usagesPerScope = []; + const substitutionsPerScope = []; + const functionErrorsPerScope = []; + const constantErrorsPerScope = []; + const visibleDeclarationsInExtractedRange = []; + const exposedVariableSymbolSet = /* @__PURE__ */ new Map(); + const exposedVariableDeclarations = []; + let firstExposedNonVariableDeclaration; + const expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && isExpressionStatement(targetRange.range[0]) ? targetRange.range[0].expression : void 0; + let expressionDiagnostic; + if (expression === void 0) { + const statements = targetRange.range; + const start = first(statements).getStart(); + const end = last(statements).end; + expressionDiagnostic = createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); + } else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) { + expressionDiagnostic = createDiagnosticForNode(expression, Messages.uselessConstantType); + } + for (const scope of scopes) { + usagesPerScope.push({ usages: /* @__PURE__ */ new Map(), typeParameterUsages: /* @__PURE__ */ new Map(), substitutions: /* @__PURE__ */ new Map() }); + substitutionsPerScope.push(/* @__PURE__ */ new Map()); + functionErrorsPerScope.push([]); + const constantErrors = []; + if (expressionDiagnostic) { + constantErrors.push(expressionDiagnostic); + } + if (isClassLike(scope) && isInJSFile(scope)) { + constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); + } + if (isArrowFunction(scope) && !isBlock(scope.body)) { + constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction)); + } + constantErrorsPerScope.push(constantErrors); + } + const seenUsages = /* @__PURE__ */ new Map(); + const target = isReadonlyArray(targetRange.range) ? factory.createBlock(targetRange.range) : targetRange.range; + const unmodifiedNode = isReadonlyArray(targetRange.range) ? first(targetRange.range) : targetRange.range; + const inGenericContext = isInGenericContext(unmodifiedNode); + collectUsages(target); + if (inGenericContext && !isReadonlyArray(targetRange.range) && !isJsxAttribute(targetRange.range)) { + const contextualType = checker.getContextualType(targetRange.range); + recordTypeParameterUsages(contextualType); + } + if (allTypeParameterUsages.size > 0) { + const seenTypeParameterUsages = /* @__PURE__ */ new Map(); + let i = 0; + for (let curr = unmodifiedNode; curr !== void 0 && i < scopes.length; curr = curr.parent) { + if (curr === scopes[i]) { + seenTypeParameterUsages.forEach((typeParameter, id) => { + usagesPerScope[i].typeParameterUsages.set(id, typeParameter); + }); + i++; + } + if (isDeclarationWithTypeParameters(curr)) { + for (const typeParameterDecl of getEffectiveTypeParameterDeclarations(curr)) { + const typeParameter = checker.getTypeAtLocation(typeParameterDecl); + if (allTypeParameterUsages.has(typeParameter.id.toString())) { + seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter); + } + } + } + } + Debug.assert(i === scopes.length, "Should have iterated all scopes"); + } + if (visibleDeclarationsInExtractedRange.length) { + const containingLexicalScopeOfExtraction = isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : getEnclosingBlockScopeContainer(scopes[0]); + forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); + } + for (let i = 0; i < scopes.length; i++) { + const scopeUsages = usagesPerScope[i]; + if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { + const errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; + constantErrorsPerScope[i].push(createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); + } + if (targetRange.facts & 16 /* UsesThisInFunction */ && isClassLike(scopes[i])) { + functionErrorsPerScope[i].push(createDiagnosticForNode(targetRange.thisNode, Messages.cannotExtractFunctionsContainingThisToMethod)); + } + let hasWrite = false; + let readonlyClassPropertyWrite; + usagesPerScope[i].usages.forEach((value) => { + if (value.usage === 2 /* Write */) { + hasWrite = true; + if (value.symbol.flags & 106500 /* ClassMember */ && value.symbol.valueDeclaration && hasEffectiveModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) { + readonlyClassPropertyWrite = value.symbol.valueDeclaration; + } + } + }); + Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0, "No variable declarations expected if something was extracted"); + if (hasWrite && !isReadonlyArray(targetRange.range)) { + const diag2 = createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression); + functionErrorsPerScope[i].push(diag2); + constantErrorsPerScope[i].push(diag2); + } else if (readonlyClassPropertyWrite && i > 0) { + const diag2 = createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor); + functionErrorsPerScope[i].push(diag2); + constantErrorsPerScope[i].push(diag2); + } else if (firstExposedNonVariableDeclaration) { + const diag2 = createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity); + functionErrorsPerScope[i].push(diag2); + constantErrorsPerScope[i].push(diag2); + } + } + return { target, usagesPerScope, functionErrorsPerScope, constantErrorsPerScope, exposedVariableDeclarations }; + function isInGenericContext(node) { + return !!findAncestor(node, (n) => isDeclarationWithTypeParameters(n) && getEffectiveTypeParameterDeclarations(n).length !== 0); + } + function recordTypeParameterUsages(type) { + const symbolWalker = checker.getSymbolWalker(() => (cancellationToken.throwIfCancellationRequested(), true)); + const { visitedTypes } = symbolWalker.walkType(type); + for (const visitedType of visitedTypes) { + if (visitedType.isTypeParameter()) { + allTypeParameterUsages.set(visitedType.id.toString(), visitedType); + } + } + } + function collectUsages(node, valueUsage = 1 /* Read */) { + if (inGenericContext) { + const type = checker.getTypeAtLocation(node); + recordTypeParameterUsages(type); + } + if (isDeclaration(node) && node.symbol) { + visibleDeclarationsInExtractedRange.push(node); + } + if (isAssignmentExpression(node)) { + collectUsages(node.left, 2 /* Write */); + collectUsages(node.right); + } else if (isUnaryExpressionWithWrite(node)) { + collectUsages(node.operand, 2 /* Write */); + } else if (isPropertyAccessExpression(node) || isElementAccessExpression(node)) { + forEachChild(node, collectUsages); + } else if (isIdentifier(node)) { + if (!node.parent) { + return; + } + if (isQualifiedName(node.parent) && node !== node.parent.left) { + return; + } + if (isPropertyAccessExpression(node.parent) && node !== node.parent.expression) { + return; + } + recordUsage( + node, + valueUsage, + /*isTypeNode*/ + isPartOfTypeNode(node) + ); + } else { + forEachChild(node, collectUsages); + } + } + function recordUsage(n, usage, isTypeNode2) { + const symbolId = recordUsagebySymbol(n, usage, isTypeNode2); + if (symbolId) { + for (let i = 0; i < scopes.length; i++) { + const substitution = substitutionsPerScope[i].get(symbolId); + if (substitution) { + usagesPerScope[i].substitutions.set(getNodeId(n).toString(), substitution); + } + } + } + } + function recordUsagebySymbol(identifier, usage, isTypeName) { + const symbol = getSymbolReferencedByIdentifier(identifier); + if (!symbol) { + return void 0; + } + const symbolId = getSymbolId(symbol).toString(); + const lastUsage = seenUsages.get(symbolId); + if (lastUsage && lastUsage >= usage) { + return symbolId; + } + seenUsages.set(symbolId, usage); + if (lastUsage) { + for (const perScope of usagesPerScope) { + const prevEntry = perScope.usages.get(identifier.text); + if (prevEntry) { + perScope.usages.set(identifier.text, { usage, symbol, node: identifier }); + } + } + return symbolId; + } + const decls = symbol.getDeclarations(); + const declInFile = decls && find(decls, (d) => d.getSourceFile() === sourceFile); + if (!declInFile) { + return void 0; + } + if (rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) { + return void 0; + } + if (targetRange.facts & 2 /* IsGenerator */ && usage === 2 /* Write */) { + const diag2 = createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators); + for (const errors of functionErrorsPerScope) { + errors.push(diag2); + } + for (const errors of constantErrorsPerScope) { + errors.push(diag2); + } + } + for (let i = 0; i < scopes.length; i++) { + const scope = scopes[i]; + const resolvedSymbol = checker.resolveName( + symbol.name, + scope, + symbol.flags, + /*excludeGlobals*/ + false + ); + if (resolvedSymbol === symbol) { + continue; + } + if (!substitutionsPerScope[i].has(symbolId)) { + const substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName); + if (substitution) { + substitutionsPerScope[i].set(symbolId, substitution); + } else if (isTypeName) { + if (!(symbol.flags & 262144 /* TypeParameter */)) { + const diag2 = createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope); + functionErrorsPerScope[i].push(diag2); + constantErrorsPerScope[i].push(diag2); + } + } else { + usagesPerScope[i].usages.set(identifier.text, { usage, symbol, node: identifier }); + } + } + } + return symbolId; + } + function checkForUsedDeclarations(node) { + if (node === targetRange.range || isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0) { + return; + } + const sym = isIdentifier(node) ? getSymbolReferencedByIdentifier(node) : checker.getSymbolAtLocation(node); + if (sym) { + const decl = find(visibleDeclarationsInExtractedRange, (d) => d.symbol === sym); + if (decl) { + if (isVariableDeclaration(decl)) { + const idString = decl.symbol.id.toString(); + if (!exposedVariableSymbolSet.has(idString)) { + exposedVariableDeclarations.push(decl); + exposedVariableSymbolSet.set(idString, true); + } + } else { + firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; + } + } + } + forEachChild(node, checkForUsedDeclarations); + } + function getSymbolReferencedByIdentifier(identifier) { + return identifier.parent && isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier ? checker.getShorthandAssignmentValueSymbol(identifier.parent) : checker.getSymbolAtLocation(identifier); + } + function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode2) { + if (!symbol) { + return void 0; + } + const decls = symbol.getDeclarations(); + if (decls && decls.some((d) => d.parent === scopeDecl)) { + return factory.createIdentifier(symbol.name); + } + const prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode2); + if (prefix === void 0) { + return void 0; + } + return isTypeNode2 ? factory.createQualifiedName(prefix, factory.createIdentifier(symbol.name)) : factory.createPropertyAccessExpression(prefix, symbol.name); + } + } + function getExtractableParent(node) { + return findAncestor(node, (node2) => node2.parent && isExtractableExpression(node2) && !isBinaryExpression(node2.parent)); + } + function isExtractableExpression(node) { + const { parent: parent2 } = node; + switch (parent2.kind) { + case 305 /* EnumMember */: + return false; + } + switch (node.kind) { + case 11 /* StringLiteral */: + return parent2.kind !== 271 /* ImportDeclaration */ && parent2.kind !== 275 /* ImportSpecifier */; + case 229 /* SpreadElement */: + case 205 /* ObjectBindingPattern */: + case 207 /* BindingElement */: + return false; + case 80 /* Identifier */: + return parent2.kind !== 207 /* BindingElement */ && parent2.kind !== 275 /* ImportSpecifier */ && parent2.kind !== 280 /* ExportSpecifier */; + } + return true; + } + function isBlockLike(node) { + switch (node.kind) { + case 240 /* Block */: + case 311 /* SourceFile */: + case 267 /* ModuleBlock */: + case 295 /* CaseClause */: + return true; + default: + return false; + } + } + function isInJSXContent(node) { + return isStringLiteralJsxAttribute(node) || (isJsxElement(node) || isJsxSelfClosingElement(node) || isJsxFragment(node)) && (isJsxElement(node.parent) || isJsxFragment(node.parent)); + } + function isStringLiteralJsxAttribute(node) { + return isStringLiteral(node) && node.parent && isJsxAttribute(node.parent); + } + var refactorName11, extractConstantAction, extractFunctionAction, Messages, RangeFacts; + var init_extractSymbol = __esm({ + "src/services/refactors/extractSymbol.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName11 = "Extract Symbol"; + extractConstantAction = { + name: "Extract Constant", + description: getLocaleSpecificMessage(Diagnostics.Extract_constant), + kind: "refactor.extract.constant" + }; + extractFunctionAction = { + name: "Extract Function", + description: getLocaleSpecificMessage(Diagnostics.Extract_function), + kind: "refactor.extract.function" + }; + registerRefactor(refactorName11, { + kinds: [ + extractConstantAction.kind, + extractFunctionAction.kind + ], + getEditsForAction: getRefactorEditsToExtractSymbol, + getAvailableActions: getRefactorActionsToExtractSymbol + }); + ((Messages2) => { + function createMessage(message) { + return { message, code: 0, category: 3 /* Message */, key: message }; + } + Messages2.cannotExtractRange = createMessage("Cannot extract range."); + Messages2.cannotExtractImport = createMessage("Cannot extract import statement."); + Messages2.cannotExtractSuper = createMessage("Cannot extract super call."); + Messages2.cannotExtractJSDoc = createMessage("Cannot extract JSDoc."); + Messages2.cannotExtractEmpty = createMessage("Cannot extract empty range."); + Messages2.expressionExpected = createMessage("expression expected."); + Messages2.uselessConstantType = createMessage("No reason to extract constant of type."); + Messages2.statementOrExpressionExpected = createMessage("Statement or expression expected."); + Messages2.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); + Messages2.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); + Messages2.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); + Messages2.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); + Messages2.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); + Messages2.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); + Messages2.cannotExtractIdentifier = createMessage("Select more than a single identifier."); + Messages2.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); + Messages2.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); + Messages2.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); + Messages2.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); + Messages2.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); + Messages2.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); + Messages2.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); + Messages2.cannotExtractFunctionsContainingThisToMethod = createMessage("Cannot extract functions containing this to method"); + })(Messages || (Messages = {})); + RangeFacts = /* @__PURE__ */ ((RangeFacts2) => { + RangeFacts2[RangeFacts2["None"] = 0] = "None"; + RangeFacts2[RangeFacts2["HasReturn"] = 1] = "HasReturn"; + RangeFacts2[RangeFacts2["IsGenerator"] = 2] = "IsGenerator"; + RangeFacts2[RangeFacts2["IsAsyncFunction"] = 4] = "IsAsyncFunction"; + RangeFacts2[RangeFacts2["UsesThis"] = 8] = "UsesThis"; + RangeFacts2[RangeFacts2["UsesThisInFunction"] = 16] = "UsesThisInFunction"; + RangeFacts2[RangeFacts2["InStaticRegion"] = 32] = "InStaticRegion"; + return RangeFacts2; + })(RangeFacts || {}); + } + }); + + // src/services/_namespaces/ts.refactor.extractSymbol.ts + var ts_refactor_extractSymbol_exports = {}; + __export(ts_refactor_extractSymbol_exports, { + Messages: () => Messages, + RangeFacts: () => RangeFacts, + getRangeToExtract: () => getRangeToExtract2, + getRefactorActionsToExtractSymbol: () => getRefactorActionsToExtractSymbol, + getRefactorEditsToExtractSymbol: () => getRefactorEditsToExtractSymbol + }); + var init_ts_refactor_extractSymbol = __esm({ + "src/services/_namespaces/ts.refactor.extractSymbol.ts"() { + "use strict"; + init_extractSymbol(); + } + }); + + // src/services/refactors/generateGetAccessorAndSetAccessor.ts + var actionName, actionDescription, generateGetSetAction; + var init_generateGetAccessorAndSetAccessor = __esm({ + "src/services/refactors/generateGetAccessorAndSetAccessor.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + actionName = "Generate 'get' and 'set' accessors"; + actionDescription = Diagnostics.Generate_get_and_set_accessors.message; + generateGetSetAction = { + name: actionName, + description: actionDescription, + kind: "refactor.rewrite.property.generateAccessors" + }; + registerRefactor(actionName, { + kinds: [generateGetSetAction.kind], + getEditsForAction: function getRefactorActionsToGenerateGetAndSetAccessors(context, actionName2) { + if (!context.endPosition) + return void 0; + const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition); + Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); + const edits = ts_codefix_exports.generateAccessorFromProperty(context.file, context.program, context.startPosition, context.endPosition, context, actionName2); + if (!edits) + return void 0; + const renameFilename = context.file.fileName; + const nameNeedRename = info.renameAccessor ? info.accessorName : info.fieldName; + const renameLocationOffset = isIdentifier(nameNeedRename) ? 0 : -1; + const renameLocation = renameLocationOffset + getRenameLocation( + edits, + renameFilename, + nameNeedRename.text, + /*preferLastLocation*/ + isParameter(info.declaration) + ); + return { renameFilename, renameLocation, edits }; + }, + getAvailableActions(context) { + if (!context.endPosition) + return emptyArray; + const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition, context.triggerReason === "invoked"); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + return [{ + name: actionName, + description: actionDescription, + actions: [generateGetSetAction] + }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: actionName, + description: actionDescription, + actions: [{ ...generateGetSetAction, notApplicableReason: info.error }] + }]; + } + return emptyArray; + } + }); + } + }); + + // src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts + var ts_refactor_generateGetAccessorAndSetAccessor_exports = {}; + var init_ts_refactor_generateGetAccessorAndSetAccessor = __esm({ + "src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts"() { + "use strict"; + init_generateGetAccessorAndSetAccessor(); + } + }); + + // src/services/refactors/inferFunctionReturnType.ts + function getRefactorEditsToInferReturnType(context) { + const info = getInfo4(context); + if (info && !isRefactorErrorInfo(info)) { + const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange7(context.file, t, info.declaration, info.returnTypeNode)); + return { renameFilename: void 0, renameLocation: void 0, edits }; + } + return void 0; + } + function getRefactorActionsToInferReturnType(context) { + const info = getInfo4(context); + if (!info) + return emptyArray; + if (!isRefactorErrorInfo(info)) { + return [{ + name: refactorName12, + description: refactorDescription6, + actions: [inferReturnTypeAction] + }]; + } + if (context.preferences.provideRefactorNotApplicableReason) { + return [{ + name: refactorName12, + description: refactorDescription6, + actions: [{ ...inferReturnTypeAction, notApplicableReason: info.error }] + }]; + } + return emptyArray; + } + function doChange7(sourceFile, changes, declaration, typeNode) { + const closeParen = findChildOfKind(declaration, 22 /* CloseParenToken */, sourceFile); + const needParens = isArrowFunction(declaration) && closeParen === void 0; + const endNode2 = needParens ? first(declaration.parameters) : closeParen; + if (endNode2) { + if (needParens) { + changes.insertNodeBefore(sourceFile, endNode2, factory.createToken(21 /* OpenParenToken */)); + changes.insertNodeAfter(sourceFile, endNode2, factory.createToken(22 /* CloseParenToken */)); + } + changes.insertNodeAt(sourceFile, endNode2.end, typeNode, { prefix: ": " }); + } + } + function getInfo4(context) { + if (isInJSFile(context.file) || !refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind)) + return; + const token = getTokenAtPosition(context.file, context.startPosition); + const declaration = findAncestor(token, (n) => isBlock(n) || n.parent && isArrowFunction(n.parent) && (n.kind === 39 /* EqualsGreaterThanToken */ || n.parent.body === n) ? "quit" : isConvertibleDeclaration(n)); + if (!declaration || !declaration.body || declaration.type) { + return { error: getLocaleSpecificMessage(Diagnostics.Return_type_must_be_inferred_from_a_function) }; + } + const typeChecker = context.program.getTypeChecker(); + const returnType = tryGetReturnType(typeChecker, declaration); + if (!returnType) { + return { error: getLocaleSpecificMessage(Diagnostics.Could_not_determine_function_return_type) }; + } + const returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */); + if (returnTypeNode) { + return { declaration, returnTypeNode }; + } + } + function isConvertibleDeclaration(node) { + switch (node.kind) { + case 261 /* FunctionDeclaration */: + case 217 /* FunctionExpression */: + case 218 /* ArrowFunction */: + case 173 /* MethodDeclaration */: + return true; + default: + return false; + } + } + function tryGetReturnType(typeChecker, node) { + if (typeChecker.isImplementationOfOverload(node)) { + const signatures = typeChecker.getTypeAtLocation(node).getCallSignatures(); + if (signatures.length > 1) { + return typeChecker.getUnionType(mapDefined(signatures, (s) => s.getReturnType())); + } + } + const signature = typeChecker.getSignatureFromDeclaration(node); + if (signature) { + return typeChecker.getReturnTypeOfSignature(signature); + } + } + var refactorName12, refactorDescription6, inferReturnTypeAction; + var init_inferFunctionReturnType = __esm({ + "src/services/refactors/inferFunctionReturnType.ts"() { + "use strict"; + init_ts4(); + init_ts_refactor(); + refactorName12 = "Infer function return type"; + refactorDescription6 = Diagnostics.Infer_function_return_type.message; + inferReturnTypeAction = { + name: refactorName12, + description: refactorDescription6, + kind: "refactor.rewrite.function.returnType" + }; + registerRefactor(refactorName12, { + kinds: [inferReturnTypeAction.kind], + getEditsForAction: getRefactorEditsToInferReturnType, + getAvailableActions: getRefactorActionsToInferReturnType + }); + } + }); + + // src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts + var ts_refactor_inferFunctionReturnType_exports = {}; + var init_ts_refactor_inferFunctionReturnType = __esm({ + "src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts"() { + "use strict"; + init_inferFunctionReturnType(); + } + }); + + // src/services/_namespaces/ts.refactor.ts + var ts_refactor_exports = {}; + __export(ts_refactor_exports, { + addExportToChanges: () => addExportToChanges, + addExports: () => addExports, + addNewFileToTsconfig: () => addNewFileToTsconfig, + addOrRemoveBracesToArrowFunction: () => ts_refactor_addOrRemoveBracesToArrowFunction_exports, + convertArrowFunctionOrFunctionExpression: () => ts_refactor_convertArrowFunctionOrFunctionExpression_exports, + convertParamsToDestructuredObject: () => ts_refactor_convertParamsToDestructuredObject_exports, + convertStringOrTemplateLiteral: () => ts_refactor_convertStringOrTemplateLiteral_exports, + convertToOptionalChainExpression: () => ts_refactor_convertToOptionalChainExpression_exports, + createNewFileName: () => createNewFileName, + createOldFileImportsFromTargetFile: () => createOldFileImportsFromTargetFile, + deleteMovedStatements: () => deleteMovedStatements, + deleteUnusedImports: () => deleteUnusedImports, + deleteUnusedOldImports: () => deleteUnusedOldImports, + doChangeNamedToNamespaceOrDefault: () => doChangeNamedToNamespaceOrDefault, + extractSymbol: () => ts_refactor_extractSymbol_exports, + filterImport: () => filterImport, + forEachImportInStatement: () => forEachImportInStatement, + generateGetAccessorAndSetAccessor: () => ts_refactor_generateGetAccessorAndSetAccessor_exports, + getApplicableRefactors: () => getApplicableRefactors, + getEditsForRefactor: () => getEditsForRefactor, + getStatementsToMove: () => getStatementsToMove, + getTopLevelDeclarationStatement: () => getTopLevelDeclarationStatement, + getUsageInfo: () => getUsageInfo, + inferFunctionReturnType: () => ts_refactor_inferFunctionReturnType_exports, + isRefactorErrorInfo: () => isRefactorErrorInfo, + isTopLevelDeclaration: () => isTopLevelDeclaration, + makeImportOrRequire: () => makeImportOrRequire, + moduleSpecifierFromImport: () => moduleSpecifierFromImport, + nameOfTopLevelDeclaration: () => nameOfTopLevelDeclaration, + refactorKindBeginsWith: () => refactorKindBeginsWith, + registerRefactor: () => registerRefactor, + updateImportsInOtherFiles: () => updateImportsInOtherFiles + }); + var init_ts_refactor = __esm({ + "src/services/_namespaces/ts.refactor.ts"() { + "use strict"; + init_refactorProvider(); + init_convertExport(); + init_convertImport(); + init_extractType(); + init_helpers(); + init_moveToNewFile(); + init_moveToFile(); + init_ts_refactor_addOrRemoveBracesToArrowFunction(); + init_ts_refactor_convertArrowFunctionOrFunctionExpression(); + init_ts_refactor_convertParamsToDestructuredObject(); + init_ts_refactor_convertStringOrTemplateLiteral(); + init_ts_refactor_convertToOptionalChainExpression(); + init_ts_refactor_extractSymbol(); + init_ts_refactor_generateGetAccessorAndSetAccessor(); + init_ts_refactor_inferFunctionReturnType(); + } + }); + // src/services/classifier2020.ts function getSemanticClassifications2(program, cancellationToken, sourceFile, span) { const classifications = getEncodedSemanticClassifications2(program, cancellationToken, sourceFile, span); @@ -133849,6 +139736,7 @@ ${lanes.join("\n")} const rootFileNames = host.getScriptFileNames().slice(); const newSettings = host.getCompilationSettings() || getDefaultCompilerOptions2(); const hasInvalidatedResolutions = host.hasInvalidatedResolutions || returnFalse; + const hasInvalidatedLibResolutions = maybeBind(host, host.hasInvalidatedLibResolutions) || returnFalse; const hasChangedAutomaticTypeDirectiveNames = maybeBind(host, host.hasChangedAutomaticTypeDirectiveNames); const projectReferences = (_b = host.getProjectReferences) == null ? void 0 : _b.call(host); let parsedCommandLines; @@ -133879,6 +139767,7 @@ ${lanes.join("\n")} onReleaseOldSourceFile, onReleaseParsedCommandLine, hasInvalidatedResolutions, + hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, trace: maybeBind(host, host.trace), resolveModuleNames: maybeBind(host, host.resolveModuleNames), @@ -133887,6 +139776,7 @@ ${lanes.join("\n")} resolveTypeReferenceDirectives: maybeBind(host, host.resolveTypeReferenceDirectives), resolveModuleNameLiterals: maybeBind(host, host.resolveModuleNameLiterals), resolveTypeReferenceDirectiveReferences: maybeBind(host, host.resolveTypeReferenceDirectiveReferences), + resolveLibrary: maybeBind(host, host.resolveLibrary), useSourceOfProjectReferenceRedirect: maybeBind(host, host.useSourceOfProjectReferenceRedirect), getParsedCommandLine }; @@ -133908,7 +139798,7 @@ ${lanes.join("\n")} onUnRecoverableConfigFileDiagnostic: noop }; const documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings); - if (isProgramUptoDate(program, rootFileNames, newSettings, (_path, fileName) => host.getScriptVersion(fileName), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { + if (isProgramUptoDate(program, rootFileNames, newSettings, (_path, fileName) => host.getScriptVersion(fileName), (fileName) => compilerHost.fileExists(fileName), hasInvalidatedResolutions, hasInvalidatedLibResolutions, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) { return; } const options = { @@ -134212,7 +140102,7 @@ ${lanes.join("\n")} const sourceFile = getValidSourceFile(fileName); return DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } - function findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) { + function findRenameLocations(fileName, position, findInStrings, findInComments, preferences) { synchronizeHostData(); const sourceFile = getValidSourceFile(fileName); const node = getAdjustedRenameLocation(getTouchingPropertyName(sourceFile, position)); @@ -134229,11 +140119,13 @@ ${lanes.join("\n")} }; }); } else { + const quotePreference = getQuotePreference(sourceFile, preferences ?? emptyOptions); + const providePrefixAndSuffixTextForRename = typeof preferences === "boolean" ? preferences : preferences == null ? void 0 : preferences.providePrefixAndSuffixTextForRename; return getReferencesWorker( node, position, { findInStrings, findInComments, providePrefixAndSuffixTextForRename, use: ts_FindAllReferences_exports.FindReferencesUse.Rename }, - (entry, originalNode, checker) => ts_FindAllReferences_exports.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false) + (entry, originalNode, checker) => ts_FindAllReferences_exports.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false, quotePreference) ); } } @@ -134478,6 +140370,7 @@ ${lanes.join("\n")} const token = findPrecedingToken(position, sourceFile); if (!token || token.parent.kind === 311 /* SourceFile */) return void 0; + const jsxTagWordPattern = "[a-zA-Z0-9:\\-\\._$]*"; if (isJsxFragment(token.parent.parent)) { const openFragment = token.parent.parent.openingFragment; const closeFragment = token.parent.parent.closingFragment; @@ -134487,7 +140380,10 @@ ${lanes.join("\n")} const closePos = closeFragment.getStart(sourceFile) + 2; if (position !== openPos && position !== closePos) return void 0; - return { ranges: [{ start: openPos, length: 0 }, { start: closePos, length: 0 }] }; + return { + ranges: [{ start: openPos, length: 0 }, { start: closePos, length: 0 }], + wordPattern: jsxTagWordPattern + }; } else { const tag = findAncestor( token.parent, @@ -134513,7 +140409,8 @@ ${lanes.join("\n")} if (openingTagText !== closeTag.tagName.getText(sourceFile)) return void 0; return { - ranges: [{ start: openTagStart, length: openTagEnd - openTagStart }, { start: closeTagStart, length: closeTagEnd - closeTagStart }] + ranges: [{ start: openTagStart, length: openTagEnd - openTagStart }, { start: closeTagStart, length: closeTagEnd - closeTagStart }], + wordPattern: jsxTagWordPattern }; } } @@ -134815,15 +140712,24 @@ ${lanes.join("\n")} function getSmartSelectionRange2(fileName, position) { return ts_SmartSelectionRange_exports.getSmartSelectionRange(position, syntaxTreeCache.getCurrentSourceFile(fileName)); } - function getApplicableRefactors2(fileName, positionOrRange, preferences = emptyOptions, triggerReason, kind) { + function getApplicableRefactors2(fileName, positionOrRange, preferences = emptyOptions, triggerReason, kind, includeInteractiveActions) { synchronizeHostData(); const file = getValidSourceFile(fileName); - return ts_refactor_exports.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences, emptyOptions, triggerReason, kind)); + return ts_refactor_exports.getApplicableRefactors(getRefactorContext(file, positionOrRange, preferences, emptyOptions, triggerReason, kind), includeInteractiveActions); } - function getEditsForRefactor2(fileName, formatOptions, positionOrRange, refactorName13, actionName2, preferences = emptyOptions) { + function getMoveToRefactoringFileSuggestions(fileName, positionOrRange, preferences = emptyOptions) { + synchronizeHostData(); + const sourceFile = getValidSourceFile(fileName); + const allFiles = Debug.checkDefined(program.getSourceFiles()); + const extension = extensionFromPath(fileName); + const files = mapDefined(allFiles, (file) => !(program == null ? void 0 : program.isSourceFileFromExternalLibrary(sourceFile)) && !(sourceFile === getValidSourceFile(file.fileName) || extension === ".ts" /* Ts */ && extensionFromPath(file.fileName) === ".d.ts" /* Dts */ || extension === ".d.ts" /* Dts */ && startsWith(getBaseFileName(file.fileName), "lib.") && extensionFromPath(file.fileName) === ".d.ts" /* Dts */) && extension === extensionFromPath(file.fileName) ? file.fileName : void 0); + const newFileName = createNewFileName(sourceFile, program, getRefactorContext(sourceFile, positionOrRange, preferences, emptyOptions), host); + return { newFileName, files }; + } + function getEditsForRefactor2(fileName, formatOptions, positionOrRange, refactorName13, actionName2, preferences = emptyOptions, interactiveRefactorArguments) { synchronizeHostData(); const file = getValidSourceFile(fileName); - return ts_refactor_exports.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName13, actionName2); + return ts_refactor_exports.getEditsForRefactor(getRefactorContext(file, positionOrRange, preferences, formatOptions), refactorName13, actionName2, interactiveRefactorArguments); } function toLineColumnOffset(fileName, position) { if (position === 0) { @@ -134910,6 +140816,7 @@ ${lanes.join("\n")} updateIsDefinitionOfReferencedSymbols, getApplicableRefactors: getApplicableRefactors2, getEditsForRefactor: getEditsForRefactor2, + getMoveToRefactoringFileSuggestions, toLineColumnOffset, getSourceMapper: () => sourceMapper, clearSourceMapperCache: () => sourceMapper.clearCache(), @@ -135041,6 +140948,7 @@ ${lanes.join("\n")} init_ts4(); init_ts_NavigateTo(); init_ts_NavigationBar(); + init_ts_refactor(); init_classifier(); init_classifier2020(); servicesVersion = "0.8"; @@ -136232,10 +142140,10 @@ ${lanes.join("\n")} () => this.languageService.getSmartSelectionRange(fileName, position) ); } - findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) { + findRenameLocations(fileName, position, findInStrings, findInComments, preferences) { return this.forwardJSONCall( - `findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments}, ${providePrefixAndSuffixTextForRename})`, - () => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) + `findRenameLocations('${fileName}', ${position}, ${findInStrings}, ${findInComments})`, + () => this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, preferences) ); } /// GET BRACE MATCHING @@ -137672,10 +143580,10 @@ ${lanes.join("\n")} }); // src/services/codeFixProvider.ts - function createCodeFixActionWithoutFixAll(fixName8, changes, description2) { + function createCodeFixActionWithoutFixAll(fixName8, changes, description3) { return createCodeFixActionWorker( fixName8, - diagnosticToString(description2), + diagnosticToString(description3), changes, /*fixId*/ void 0, @@ -137683,14 +143591,14 @@ ${lanes.join("\n")} void 0 ); } - function createCodeFixAction(fixName8, changes, description2, fixId52, fixAllDescription, command) { - return createCodeFixActionWorker(fixName8, diagnosticToString(description2), changes, fixId52, diagnosticToString(fixAllDescription), command); + function createCodeFixAction(fixName8, changes, description3, fixId52, fixAllDescription, command) { + return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId52, diagnosticToString(fixAllDescription), command); } - function createCodeFixActionMaybeFixAll(fixName8, changes, description2, fixId52, fixAllDescription, command) { - return createCodeFixActionWorker(fixName8, diagnosticToString(description2), changes, fixId52, fixAllDescription && diagnosticToString(fixAllDescription), command); + function createCodeFixActionMaybeFixAll(fixName8, changes, description3, fixId52, fixAllDescription, command) { + return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId52, fixAllDescription && diagnosticToString(fixAllDescription), command); } - function createCodeFixActionWorker(fixName8, description2, changes, fixId52, fixAllDescription, command) { - return { fixName: fixName8, description: description2, changes, fixId: fixId52, fixAllDescription, commands: command ? [command] : void 0 }; + function createCodeFixActionWorker(fixName8, description3, changes, fixId52, fixAllDescription, command) { + return { fixName: fixName8, description: description3, changes, fixId: fixId52, fixAllDescription, commands: command ? [command] : void 0 }; } function registerCodeFix(reg) { for (const error of reg.errorCodes) { @@ -138471,7 +144379,7 @@ ${lanes.join("\n")} function hasUsableJSDoc(decl) { return isFunctionLikeDeclaration(decl) ? decl.parameters.some(hasUsableJSDoc) || !decl.type && !!getJSDocReturnType(decl) : !decl.type && !!getJSDocType(decl); } - function doChange(changes, sourceFile, decl) { + function doChange8(changes, sourceFile, decl) { if (isFunctionLikeDeclaration(decl) && (getJSDocReturnType(decl) || decl.parameters.some((p) => !!getJSDocType(p)))) { if (!decl.typeParameters) { const typeParameters = getJSDocTypeParameterDeclarations(decl); @@ -138625,21 +144533,21 @@ ${lanes.join("\n")} const decl = getDeclaration(context.sourceFile, context.span.start); if (!decl) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange(t, context.sourceFile, decl)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange8(t, context.sourceFile, decl)); return [createCodeFixAction(fixId8, changes, Diagnostics.Annotate_with_type_from_JSDoc, fixId8, Diagnostics.Annotate_everything_with_types_from_JSDoc)]; }, fixIds: [fixId8], getAllCodeActions: (context) => codeFixAll(context, errorCodes9, (changes, diag2) => { const decl = getDeclaration(diag2.file, diag2.start); if (decl) - doChange(changes, diag2.file, decl); + doChange8(changes, diag2.file, decl); }) }); } }); // src/services/codefixes/convertFunctionToEs6Class.ts - function doChange2(changes, sourceFile, position, checker, preferences, compilerOptions) { + function doChange9(changes, sourceFile, position, checker, preferences, compilerOptions) { const ctorSymbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, position)); if (!ctorSymbol || !ctorSymbol.valueDeclaration || !(ctorSymbol.flags & (16 /* Function */ | 3 /* Variable */))) { return void 0; @@ -138929,11 +144837,11 @@ ${lanes.join("\n")} registerCodeFix({ errorCodes: errorCodes10, getCodeActions(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange2(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange9(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())); return [createCodeFixAction(fixId9, changes, Diagnostics.Convert_function_to_an_ES2015_class, fixId9, Diagnostics.Convert_all_constructor_functions_to_classes)]; }, fixIds: [fixId9], - getAllCodeActions: (context) => codeFixAll(context, errorCodes10, (changes, err) => doChange2(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())) + getAllCodeActions: (context) => codeFixAll(context, errorCodes10, (changes, err) => doChange9(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())) }); } }); @@ -139984,7 +145892,7 @@ ${lanes.join("\n")} function convertSingleImport(name, moduleSpecifier, checker, identifiers, target, quotePreference) { switch (name.kind) { case 205 /* ObjectBindingPattern */: { - const importSpecifiers = mapAllOrFail(name.elements, (e) => e.dotDotDotToken || e.initializer || e.propertyName && !isIdentifier(e.propertyName) || !isIdentifier(e.name) ? void 0 : makeImportSpecifier(e.propertyName && e.propertyName.text, e.name.text)); + const importSpecifiers = mapAllOrFail(name.elements, (e) => e.dotDotDotToken || e.initializer || e.propertyName && !isIdentifier(e.propertyName) || !isIdentifier(e.name) ? void 0 : makeImportSpecifier2(e.propertyName && e.propertyName.text, e.name.text)); if (importSpecifiers) { return convertedImports([makeImport( /*defaultImport*/ @@ -140122,12 +146030,12 @@ ${lanes.join("\n")} ) : makeImport( /*defaultImport*/ void 0, - [makeImportSpecifier(propertyName, localName)], + [makeImportSpecifier2(propertyName, localName)], moduleSpecifier, quotePreference ); } - function makeImportSpecifier(propertyName, name) { + function makeImportSpecifier2(propertyName, name) { return factory.createImportSpecifier( /*isTypeOnly*/ false, @@ -140196,7 +146104,7 @@ ${lanes.join("\n")} Debug.assert(!!qualifiedName, "Expected position to be owned by a qualified name."); return isIdentifier(qualifiedName.left) ? qualifiedName : void 0; } - function doChange3(changeTracker, sourceFile, qualifiedName) { + function doChange10(changeTracker, sourceFile, qualifiedName) { const rightText = qualifiedName.right.text; const replacement = factory.createIndexedAccessTypeNode( factory.createTypeReferenceNode( @@ -140222,7 +146130,7 @@ ${lanes.join("\n")} const qualifiedName = getQualifiedName(context.sourceFile, context.span.start); if (!qualifiedName) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange3(t, context.sourceFile, qualifiedName)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange10(t, context.sourceFile, qualifiedName)); const newText = `${qualifiedName.left.text}["${qualifiedName.right.text}"]`; return [createCodeFixAction(fixId11, changes, [Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId11, Diagnostics.Rewrite_all_as_indexed_access_types)]; }, @@ -140230,7 +146138,7 @@ ${lanes.join("\n")} getAllCodeActions: (context) => codeFixAll(context, errorCodes12, (changes, diag2) => { const q = getQualifiedName(diag2.file, diag2.start); if (q) { - doChange3(changes, diag2.file, q); + doChange10(changes, diag2.file, q); } }) }); @@ -140327,7 +146235,7 @@ ${lanes.join("\n")} const { parent: parent2 } = getTokenAtPosition(sourceFile, pos); return isImportSpecifier(parent2) || isImportDeclaration(parent2) && parent2.importClause ? parent2 : void 0; } - function doChange4(changes, sourceFile, declaration) { + function doChange11(changes, sourceFile, declaration) { if (isImportSpecifier(declaration)) { changes.replaceNode(sourceFile, declaration, factory.updateImportSpecifier( declaration, @@ -140431,7 +146339,7 @@ ${lanes.join("\n")} getCodeActions: function getCodeActionsToConvertToTypeOnlyImport(context) { const declaration = getDeclaration2(context.sourceFile, context.span.start); if (declaration) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange4(t, context.sourceFile, declaration)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange11(t, context.sourceFile, declaration)); return [createCodeFixAction(fixId13, changes, Diagnostics.Convert_to_type_only_import, fixId13, Diagnostics.Convert_all_imports_not_used_as_a_value_to_type_only_imports)]; } return void 0; @@ -140441,7 +146349,7 @@ ${lanes.join("\n")} return codeFixAll(context, errorCodes14, (changes, diag2) => { const declaration = getDeclaration2(diag2.file, diag2.start); if (declaration) { - doChange4(changes, diag2.file, declaration); + doChange11(changes, diag2.file, declaration); } }); } @@ -140450,7 +146358,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/convertTypedefToType.ts - function doChange5(changes, node, sourceFile) { + function doChange12(changes, node, sourceFile) { if (isJSDocTypedefTag(node)) { fixSingleTypeDef(changes, node, sourceFile); } @@ -140574,7 +146482,7 @@ ${lanes.join("\n")} ); if (!node) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange5(t, node, context.sourceFile)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange12(t, node, context.sourceFile)); if (changes.length > 0) { return [ createCodeFixAction( @@ -140590,14 +146498,14 @@ ${lanes.join("\n")} getAllCodeActions: (context) => codeFixAll(context, errorCodes15, (changes, diag2) => { const node = getTokenAtPosition(diag2.file, diag2.start); if (node) - doChange5(changes, node, diag2.file); + doChange12(changes, node, diag2.file); }) }); } }); // src/services/codefixes/convertLiteralTypeToMappedType.ts - function getInfo2(sourceFile, pos) { + function getInfo5(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); if (isIdentifier(token)) { const propertySignature = cast(token.parent.parent, isPropertySignature); @@ -140611,7 +146519,7 @@ ${lanes.join("\n")} } return void 0; } - function doChange6(changes, sourceFile, { container, typeNode, constraint, name }) { + function doChange13(changes, sourceFile, { container, typeNode, constraint, name }) { changes.replaceNode(sourceFile, container, factory.createMappedTypeNode( /*readonlyToken*/ void 0, @@ -140642,19 +146550,19 @@ ${lanes.join("\n")} errorCodes: errorCodes16, getCodeActions: function getCodeActionsToConvertLiteralTypeToMappedType(context) { const { sourceFile, span } = context; - const info = getInfo2(sourceFile, span.start); + const info = getInfo5(sourceFile, span.start); if (!info) { return void 0; } const { name, constraint } = info; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange6(t, sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange13(t, sourceFile, info)); return [createCodeFixAction(fixId15, changes, [Diagnostics.Convert_0_to_1_in_0, constraint, name], fixId15, Diagnostics.Convert_all_type_literals_to_mapped_type)]; }, fixIds: [fixId15], getAllCodeActions: (context) => codeFixAll(context, errorCodes16, (changes, diag2) => { - const info = getInfo2(diag2.file, diag2.start); + const info = getInfo5(diag2.file, diag2.start); if (info) { - doChange6(changes, diag2.file, info); + doChange13(changes, diag2.file, info); } }) }); @@ -141011,8 +146919,8 @@ ${lanes.join("\n")} const packageJsonImportFilter = createPackageJsonImportFilter(sourceFile, preferences, host); return getBestFix(getImportFixes(exportInfos, position, isValidTypeOnlyUseSite, useRequire, program, sourceFile, host, preferences).fixes, sourceFile, program, packageJsonImportFilter, host); } - function codeFixActionToCodeAction({ description: description2, changes, commands }) { - return { description: description2, changes, commands }; + function codeFixActionToCodeAction({ description: description3, changes, commands }) { + return { description: description3, changes, commands }; } function getAllExportInfoForSymbol(importingFile, symbol, symbolName2, moduleSymbol, preferCapitalized, program, host, preferences, cancellationToken) { const getChecker = createGetChecker(program, host); @@ -141987,7 +147895,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixAddMissingConstraint.ts - function getInfo3(program, sourceFile, span) { + function getInfo6(program, sourceFile, span) { const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3) => diag3.start === span.start && diag3.length === span.length); if (diag2 === void 0 || diag2.relatedInformation === void 0) return; @@ -142077,7 +147985,7 @@ ${lanes.join("\n")} errorCodes: errorCodes19, getCodeActions(context) { const { sourceFile, span, program, preferences, host } = context; - const info = getInfo3(program, sourceFile, span); + const info = getInfo6(program, sourceFile, span); if (info === void 0) return; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingConstraint(t, program, preferences, host, sourceFile, info)); @@ -142089,7 +147997,7 @@ ${lanes.join("\n")} const seen = /* @__PURE__ */ new Map(); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { eachDiagnostic(context, errorCodes19, (diag2) => { - const info = getInfo3(program, diag2.file, createTextSpan(diag2.start, diag2.length)); + const info = getInfo6(program, diag2.file, createTextSpan(diag2.start, diag2.length)); if (info) { if (addToSeen(seen, getNodeId(info.declaration))) { return addMissingConstraint(changes, program, preferences, host, diag2.file, info); @@ -142269,7 +148177,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts - function doChange7(changes, sourceFile, node, preferences) { + function doChange14(changes, sourceFile, node, preferences) { const quotePreference = getQuotePreference(sourceFile, preferences); const argumentsExpression = factory.createStringLiteral(node.name.text, quotePreference === 0 /* Single */); changes.replaceNode( @@ -142297,16 +148205,16 @@ ${lanes.join("\n")} getCodeActions(context) { const { sourceFile, span, preferences } = context; const property = getPropertyAccessExpression(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange7(t, context.sourceFile, property, preferences)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange14(t, context.sourceFile, property, preferences)); return [createCodeFixAction(fixId18, changes, [Diagnostics.Use_element_access_for_0, property.name.text], fixId18, Diagnostics.Use_element_access_for_all_undeclared_properties)]; }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes21, (changes, diag2) => doChange7(changes, diag2.file, getPropertyAccessExpression(diag2.file, diag2.start), context.preferences)) + getAllCodeActions: (context) => codeFixAll(context, errorCodes21, (changes, diag2) => doChange14(changes, diag2.file, getPropertyAccessExpression(diag2.file, diag2.start), context.preferences)) }); } }); // src/services/codefixes/fixImplicitThis.ts - function doChange8(changes, sourceFile, pos, checker) { + function doChange15(changes, sourceFile, pos, checker) { const token = getTokenAtPosition(sourceFile, pos); if (!isThis(token)) return void 0; @@ -142361,20 +148269,20 @@ ${lanes.join("\n")} const { sourceFile, program, span } = context; let diagnostic; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => { - diagnostic = doChange8(t, sourceFile, span.start, program.getTypeChecker()); + diagnostic = doChange15(t, sourceFile, span.start, program.getTypeChecker()); }); return diagnostic ? [createCodeFixAction(fixId19, changes, diagnostic, fixId19, Diagnostics.Fix_all_implicit_this_errors)] : emptyArray; }, fixIds: [fixId19], getAllCodeActions: (context) => codeFixAll(context, errorCodes22, (changes, diag2) => { - doChange8(changes, diag2.file, diag2.start, context.program.getTypeChecker()); + doChange15(changes, diag2.file, diag2.start, context.program.getTypeChecker()); }) }); } }); // src/services/codefixes/fixImportNonExportedMember.ts - function getInfo4(sourceFile, pos, program) { + function getInfo7(sourceFile, pos, program) { var _a; const token = getTokenAtPosition(sourceFile, pos); if (isIdentifier(token)) { @@ -142410,7 +148318,7 @@ ${lanes.join("\n")} } return void 0; } - function doChange9(changes, program, { exportName, node, moduleSourceFile }) { + function doChange16(changes, program, { exportName, node, moduleSourceFile }) { const exportDeclaration = tryGetExportDeclaration(moduleSourceFile, exportName.isTypeOnly); if (exportDeclaration) { updateExport(changes, program, moduleSourceFile, exportDeclaration, [exportName]); @@ -142507,10 +148415,10 @@ ${lanes.join("\n")} fixIds: [fixId20], getCodeActions(context) { const { sourceFile, span, program } = context; - const info = getInfo4(sourceFile, span.start, program); + const info = getInfo7(sourceFile, span.start, program); if (info === void 0) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange9(t, program, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange16(t, program, info)); return [createCodeFixAction(fixId20, changes, [Diagnostics.Export_0_from_module_1, info.exportName.node.text, info.moduleSpecifier], fixId20, Diagnostics.Export_all_referenced_locals)]; }, getAllCodeActions(context) { @@ -142518,7 +148426,7 @@ ${lanes.join("\n")} return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { const exports = /* @__PURE__ */ new Map(); eachDiagnostic(context, errorCodes23, (diag2) => { - const info = getInfo4(diag2.file, diag2.start, program); + const info = getInfo7(diag2.file, diag2.start, program); if (info === void 0) return void 0; const { exportName, node, moduleSourceFile } = info; @@ -142562,7 +148470,7 @@ ${lanes.join("\n")} const token = getTokenAtPosition(sourceFile, pos); return findAncestor(token, (t) => t.kind === 201 /* NamedTupleMember */); } - function doChange10(changes, sourceFile, namedTupleMember) { + function doChange17(changes, sourceFile, namedTupleMember) { if (!namedTupleMember) { return; } @@ -142605,7 +148513,7 @@ ${lanes.join("\n")} getCodeActions: function getCodeActionsToFixIncorrectNamedTupleSyntax(context) { const { sourceFile, span } = context; const namedTupleMember = getNamedTupleMember(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange10(t, sourceFile, namedTupleMember)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange17(t, sourceFile, namedTupleMember)); return [createCodeFixAction(fixId21, changes, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels, fixId21, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels)]; }, fixIds: [fixId21] @@ -142614,7 +148522,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixSpelling.ts - function getInfo5(sourceFile, pos, context, errorCode) { + function getInfo8(sourceFile, pos, context, errorCode) { const node = getTokenAtPosition(sourceFile, pos); const parent2 = node.parent; if ((errorCode === Diagnostics.No_overload_matches_this_call.code || errorCode === Diagnostics.Type_0_is_not_assignable_to_type_1.code) && !isJsxAttribute(parent2)) @@ -142663,7 +148571,7 @@ ${lanes.join("\n")} } return suggestedSymbol === void 0 ? void 0 : { node, suggestedSymbol }; } - function doChange11(changes, sourceFile, node, suggestedSymbol, target) { + function doChange18(changes, sourceFile, node, suggestedSymbol, target) { const suggestion = symbolName(suggestedSymbol); if (!isIdentifierText(suggestion, target) && isPropertyAccessExpression(node.parent)) { const valDecl = suggestedSymbol.valueDeclaration; @@ -142724,20 +148632,20 @@ ${lanes.join("\n")} errorCodes: errorCodes25, getCodeActions(context) { const { sourceFile, errorCode } = context; - const info = getInfo5(sourceFile, context.span.start, context, errorCode); + const info = getInfo8(sourceFile, context.span.start, context, errorCode); if (!info) return void 0; const { node, suggestedSymbol } = info; const target = getEmitScriptTarget(context.host.getCompilationSettings()); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange11(t, sourceFile, node, suggestedSymbol, target)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange18(t, sourceFile, node, suggestedSymbol, target)); return [createCodeFixAction("spelling", changes, [Diagnostics.Change_spelling_to_0, symbolName(suggestedSymbol)], fixId22, Diagnostics.Fix_all_detected_spelling_errors)]; }, fixIds: [fixId22], getAllCodeActions: (context) => codeFixAll(context, errorCodes25, (changes, diag2) => { - const info = getInfo5(diag2.file, diag2.start, context, diag2.code); + const info = getInfo8(diag2.file, diag2.start, context, diag2.code); const target = getEmitScriptTarget(context.host.getCompilationSettings()); if (info) - doChange11(changes, context.sourceFile, info.node, info.suggestedSymbol, target); + doChange18(changes, context.sourceFile, info.node, info.suggestedSymbol, target); }) }); } @@ -142837,7 +148745,7 @@ ${lanes.join("\n")} } return checker.isTypeAssignableTo(exprType, type); } - function getInfo6(checker, sourceFile, position, errorCode) { + function getInfo9(checker, sourceFile, position, errorCode) { const node = getTokenAtPosition(sourceFile, position); if (!node.parent) return void 0; @@ -142959,7 +148867,7 @@ ${lanes.join("\n")} fixIds: [fixIdAddReturnStatement, fixRemoveBracesFromArrowFunctionBody, fixIdWrapTheBlockWithParen], getCodeActions: function getCodeActionsToCorrectReturnValue(context) { const { program, sourceFile, span: { start }, errorCode } = context; - const info = getInfo6(program.getTypeChecker(), sourceFile, start, errorCode); + const info = getInfo9(program.getTypeChecker(), sourceFile, start, errorCode); if (!info) return void 0; if (info.kind === 0 /* MissingReturnStatement */) { @@ -142972,7 +148880,7 @@ ${lanes.join("\n")} } }, getAllCodeActions: (context) => codeFixAll(context, errorCodes26, (changes, diag2) => { - const info = getInfo6(context.program.getTypeChecker(), diag2.file, diag2.start, diag2.code); + const info = getInfo9(context.program.getTypeChecker(), diag2.file, diag2.start, diag2.code); if (!info) return void 0; switch (context.fixId) { @@ -143006,7 +148914,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixAddMissingMember.ts - function getInfo7(sourceFile, tokenPos, errorCode, checker, program) { + function getInfo10(sourceFile, tokenPos, errorCode, checker, program) { var _a; const token = getTokenAtPosition(sourceFile, tokenPos); const parent2 = token.parent; @@ -143561,7 +149469,7 @@ ${lanes.join("\n")} errorCodes: errorCodes27, getCodeActions(context) { const typeChecker = context.program.getTypeChecker(); - const info = getInfo7(context.sourceFile, context.span.start, context.errorCode, typeChecker, context.program); + const info = getInfo10(context.sourceFile, context.span.start, context.errorCode, typeChecker, context.program); if (!info) { return void 0; } @@ -143591,7 +149499,7 @@ ${lanes.join("\n")} const typeDeclToMembers = /* @__PURE__ */ new Map(); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { eachDiagnostic(context, errorCodes27, (diag2) => { - const info = getInfo7(diag2.file, diag2.start, diag2.code, checker, context.program); + const info = getInfo10(diag2.file, diag2.start, diag2.code, checker, context.program); if (!info || !addToSeen(seen, getNodeId(info.parentDeclaration) + "#" + info.token.text)) { return; } @@ -143796,7 +149704,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts - function doChange12(changes, sourceFile, constructor, superCall) { + function doChange19(changes, sourceFile, constructor, superCall) { changes.insertNodeAtConstructorStart(sourceFile, constructor, superCall); changes.delete(sourceFile, superCall); } @@ -143827,7 +149735,7 @@ ${lanes.join("\n")} if (!nodes) return void 0; const { constructor, superCall } = nodes; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange12(t, sourceFile, constructor, superCall)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange19(t, sourceFile, constructor, superCall)); return [createCodeFixAction(fixId26, changes, Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId26, Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)]; }, fixIds: [fixId26], @@ -143840,7 +149748,7 @@ ${lanes.join("\n")} return; const { constructor, superCall } = nodes; if (addToSeen(seenClasses, getNodeId(constructor.parent))) { - doChange12(changes, sourceFile, constructor, superCall); + doChange19(changes, sourceFile, constructor, superCall); } }); } @@ -143854,7 +149762,7 @@ ${lanes.join("\n")} Debug.assert(isConstructorDeclaration(token.parent), "token should be at the constructor declaration"); return token.parent; } - function doChange13(changes, sourceFile, ctr) { + function doChange20(changes, sourceFile, ctr) { const superCall = factory.createExpressionStatement(factory.createCallExpression( factory.createSuper(), /*typeArguments*/ @@ -143877,17 +149785,17 @@ ${lanes.join("\n")} getCodeActions(context) { const { sourceFile, span } = context; const ctr = getNode(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange13(t, sourceFile, ctr)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange20(t, sourceFile, ctr)); return [createCodeFixAction(fixId27, changes, Diagnostics.Add_missing_super_call, fixId27, Diagnostics.Add_all_missing_super_calls)]; }, fixIds: [fixId27], - getAllCodeActions: (context) => codeFixAll(context, errorCodes32, (changes, diag2) => doChange13(changes, context.sourceFile, getNode(diag2.file, diag2.start))) + getAllCodeActions: (context) => codeFixAll(context, errorCodes32, (changes, diag2) => doChange20(changes, context.sourceFile, getNode(diag2.file, diag2.start))) }); } }); // src/services/codefixes/fixEnableJsxFlag.ts - function doChange14(changeTracker, configFile) { + function doChange21(changeTracker, configFile) { setJsonCompilerOptionValue(changeTracker, configFile, "jsx", factory.createStringLiteral("react")); } var fixID, errorCodes33; @@ -143907,7 +149815,7 @@ ${lanes.join("\n")} } const changes = ts_textChanges_exports.ChangeTracker.with( context, - (changeTracker) => doChange14(changeTracker, configFile) + (changeTracker) => doChange21(changeTracker, configFile) ); return [ createCodeFixActionWithoutFixAll(fixID, changes, Diagnostics.Enable_the_jsx_flag_in_your_configuration_file) @@ -143919,14 +149827,14 @@ ${lanes.join("\n")} if (configFile === void 0) { return void 0; } - doChange14(changes, configFile); + doChange21(changes, configFile); }) }); } }); // src/services/codefixes/fixNaNEquality.ts - function getInfo8(program, sourceFile, span) { + function getInfo11(program, sourceFile, span) { const diag2 = find(program.getSemanticDiagnostics(sourceFile), (diag3) => diag3.start === span.start && diag3.length === span.length); if (diag2 === void 0 || diag2.relatedInformation === void 0) return; @@ -143941,7 +149849,7 @@ ${lanes.join("\n")} } return void 0; } - function doChange15(changes, sourceFile, arg, expression) { + function doChange22(changes, sourceFile, arg, expression) { const callExpression = factory.createCallExpression( factory.createPropertyAccessExpression(factory.createIdentifier("Number"), factory.createIdentifier("isNaN")), /*typeArguments*/ @@ -143973,19 +149881,19 @@ ${lanes.join("\n")} errorCodes: errorCodes34, getCodeActions(context) { const { sourceFile, span, program } = context; - const info = getInfo8(program, sourceFile, span); + const info = getInfo11(program, sourceFile, span); if (info === void 0) return; const { suggestion, expression, arg } = info; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange15(t, sourceFile, arg, expression)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange22(t, sourceFile, arg, expression)); return [createCodeFixAction(fixId28, changes, [Diagnostics.Use_0, suggestion], fixId28, Diagnostics.Use_Number_isNaN_in_all_conditions)]; }, fixIds: [fixId28], getAllCodeActions: (context) => { return codeFixAll(context, errorCodes34, (changes, diag2) => { - const info = getInfo8(context.program, diag2.file, createTextSpan(diag2.start, diag2.length)); + const info = getInfo11(context.program, diag2.file, createTextSpan(diag2.start, diag2.length)); if (info) { - doChange15(changes, diag2.file, info.arg, info.expression); + doChange22(changes, diag2.file, info.arg, info.expression); } }); } @@ -144041,7 +149949,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixPropertyAssignment.ts - function doChange16(changes, sourceFile, node) { + function doChange23(changes, sourceFile, node) { changes.replaceNode(sourceFile, node, factory.createPropertyAssignment(node.name, node.objectAssignmentInitializer)); } function getProperty2(sourceFile, pos) { @@ -144063,10 +149971,10 @@ ${lanes.join("\n")} getCodeActions(context) { const { sourceFile, span } = context; const property = getProperty2(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange16(t, context.sourceFile, property)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange23(t, context.sourceFile, property)); return [createCodeFixAction(fixId29, changes, [Diagnostics.Change_0_to_1, "=", ":"], fixId29, [Diagnostics.Switch_each_misused_0_to_1, "=", ":"])]; }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes35, (changes, diag2) => doChange16(changes, diag2.file, getProperty2(diag2.file, diag2.start))) + getAllCodeActions: (context) => codeFixAll(context, errorCodes35, (changes, diag2) => doChange23(changes, diag2.file, getProperty2(diag2.file, diag2.start))) }); } }); @@ -144122,13 +150030,13 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixForgottenThisPropertyAccess.ts - function getInfo9(sourceFile, pos, diagCode) { + function getInfo12(sourceFile, pos, diagCode) { const node = getTokenAtPosition(sourceFile, pos); if (isIdentifier(node) || isPrivateIdentifier(node)) { return { node, className: diagCode === didYouMeanStaticMemberCode ? getContainingClass(node).name.text : void 0 }; } } - function doChange17(changes, sourceFile, { node, className }) { + function doChange24(changes, sourceFile, { node, className }) { suppressLeadingAndTrailingTrivia(node); changes.replaceNode(sourceFile, node, factory.createPropertyAccessExpression(className ? factory.createIdentifier(className) : factory.createThis(), node)); } @@ -144149,18 +150057,18 @@ ${lanes.join("\n")} errorCodes: errorCodes37, getCodeActions(context) { const { sourceFile } = context; - const info = getInfo9(sourceFile, context.span.start, context.errorCode); + const info = getInfo12(sourceFile, context.span.start, context.errorCode); if (!info) { return void 0; } - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange17(t, sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange24(t, sourceFile, info)); return [createCodeFixAction(fixId31, changes, [Diagnostics.Add_0_to_unresolved_variable, info.className || "this"], fixId31, Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name)]; }, fixIds: [fixId31], getAllCodeActions: (context) => codeFixAll(context, errorCodes37, (changes, diag2) => { - const info = getInfo9(diag2.file, diag2.start, diag2.code); + const info = getInfo12(diag2.file, diag2.start, diag2.code); if (info) - doChange17(changes, context.sourceFile, info); + doChange24(changes, context.sourceFile, info); }) }); } @@ -144170,7 +150078,7 @@ ${lanes.join("\n")} function isValidCharacter(character) { return hasProperty(htmlEntity, character); } - function doChange18(changes, preferences, sourceFile, start, useHtmlEntity) { + function doChange25(changes, preferences, sourceFile, start, useHtmlEntity) { const character = sourceFile.getText()[start]; if (!isValidCharacter(character)) { return; @@ -144195,7 +150103,7 @@ ${lanes.join("\n")} fixIds: [fixIdExpression, fixIdHtmlEntity], getCodeActions(context) { const { sourceFile, preferences, span } = context; - const changeToExpression = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange18( + const changeToExpression = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange25( t, preferences, sourceFile, @@ -144203,7 +150111,7 @@ ${lanes.join("\n")} /*useHtmlEntity*/ false )); - const changeToHtmlEntity = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange18( + const changeToHtmlEntity = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange25( t, preferences, sourceFile, @@ -144217,7 +150125,7 @@ ${lanes.join("\n")} ]; }, getAllCodeActions(context) { - return codeFixAll(context, errorCodes38, (changes, diagnostic) => doChange18(changes, context.preferences, diagnostic.file, diagnostic.start, context.fixId === fixIdHtmlEntity)); + return codeFixAll(context, errorCodes38, (changes, diagnostic) => doChange25(changes, context.preferences, diagnostic.file, diagnostic.start, context.fixId === fixIdHtmlEntity)); } }); htmlEntity = { @@ -144264,7 +150172,7 @@ ${lanes.join("\n")} const changes = ts_textChanges_exports.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]); } - function getInfo10(sourceFile, pos) { + function getInfo13(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); if (token.parent && isJSDocParameterTag(token.parent) && isIdentifier(token.parent.name)) { const jsDocParameterTag = token.parent; @@ -144293,7 +150201,7 @@ ${lanes.join("\n")} getCodeActions: function getCodeActionsToFixUnmatchedParameter(context) { const { sourceFile, span } = context; const actions2 = []; - const info = getInfo10(sourceFile, span.start); + const info = getInfo13(sourceFile, span.start); if (info) { append(actions2, getDeleteAction(context, info)); append(actions2, getRenameAction(context, info)); @@ -144305,7 +150213,7 @@ ${lanes.join("\n")} const tagsToSignature = /* @__PURE__ */ new Map(); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { eachDiagnostic(context, errorCodes39, ({ file, start }) => { - const info = getInfo10(file, start); + const info = getInfo13(file, start); if (info) { tagsToSignature.set(info.signature, append(tagsToSignature.get(info.signature), info.jsDocParameterTag)); } @@ -144728,7 +150636,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixUnreachableCode.ts - function doChange19(changes, sourceFile, start, length2, errorCode) { + function doChange26(changes, sourceFile, start, length2, errorCode) { const token = getTokenAtPosition(sourceFile, start); const statement = findAncestor(token, isStatement); if (statement.getStart(sourceFile) !== token.getStart(sourceFile)) { @@ -144790,17 +150698,17 @@ ${lanes.join("\n")} const syntacticDiagnostics = context.program.getSyntacticDiagnostics(context.sourceFile, context.cancellationToken); if (syntacticDiagnostics.length) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange19(t, context.sourceFile, context.span.start, context.span.length, context.errorCode)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange26(t, context.sourceFile, context.span.start, context.span.length, context.errorCode)); return [createCodeFixAction(fixId33, changes, Diagnostics.Remove_unreachable_code, fixId33, Diagnostics.Remove_all_unreachable_code)]; }, fixIds: [fixId33], - getAllCodeActions: (context) => codeFixAll(context, errorCodes42, (changes, diag2) => doChange19(changes, diag2.file, diag2.start, diag2.length, diag2.code)) + getAllCodeActions: (context) => codeFixAll(context, errorCodes42, (changes, diag2) => doChange26(changes, diag2.file, diag2.start, diag2.length, diag2.code)) }); } }); // src/services/codefixes/fixUnusedLabel.ts - function doChange20(changes, sourceFile, start) { + function doChange27(changes, sourceFile, start) { const token = getTokenAtPosition(sourceFile, start); const labeledStatement = cast(token.parent, isLabeledStatement); const pos = token.getStart(sourceFile); @@ -144824,17 +150732,17 @@ ${lanes.join("\n")} registerCodeFix({ errorCodes: errorCodes43, getCodeActions(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange20(t, context.sourceFile, context.span.start)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange27(t, context.sourceFile, context.span.start)); return [createCodeFixAction(fixId34, changes, Diagnostics.Remove_unused_label, fixId34, Diagnostics.Remove_all_unused_labels)]; }, fixIds: [fixId34], - getAllCodeActions: (context) => codeFixAll(context, errorCodes43, (changes, diag2) => doChange20(changes, diag2.file, diag2.start)) + getAllCodeActions: (context) => codeFixAll(context, errorCodes43, (changes, diag2) => doChange27(changes, diag2.file, diag2.start)) }); } }); // src/services/codefixes/fixJSDocTypes.ts - function doChange21(changes, sourceFile, oldTypeNode, newType, checker) { + function doChange28(changes, sourceFile, oldTypeNode, newType, checker) { changes.replaceNode(sourceFile, oldTypeNode, checker.typeToTypeNode( newType, /*enclosingDeclaration*/ @@ -144843,7 +150751,7 @@ ${lanes.join("\n")} void 0 )); } - function getInfo11(sourceFile, pos, checker) { + function getInfo14(sourceFile, pos, checker) { const decl = findAncestor(getTokenAtPosition(sourceFile, pos), isTypeContainer); const typeNode = decl && decl.type; return typeNode && { typeNode, type: getType(checker, typeNode) }; @@ -144901,7 +150809,7 @@ ${lanes.join("\n")} getCodeActions(context) { const { sourceFile } = context; const checker = context.program.getTypeChecker(); - const info = getInfo11(sourceFile, context.span.start, checker); + const info = getInfo14(sourceFile, context.span.start, checker); if (!info) return void 0; const { typeNode, type } = info; @@ -144912,7 +150820,7 @@ ${lanes.join("\n")} } return actions2; function fix(type2, fixId52, fixAllDescription) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange21(t, sourceFile, typeNode, type2, checker)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange28(t, sourceFile, typeNode, type2, checker)); return createCodeFixAction("jdocTypes", changes, [Diagnostics.Change_0_to_1, original, checker.typeToString(type2)], fixId52, fixAllDescription); } }, @@ -144921,12 +150829,12 @@ ${lanes.join("\n")} const { fixId: fixId52, program, sourceFile } = context; const checker = program.getTypeChecker(); return codeFixAll(context, errorCodes44, (changes, err) => { - const info = getInfo11(err.file, err.start, checker); + const info = getInfo14(err.file, err.start, checker); if (!info) return; const { typeNode, type } = info; const fixedType = typeNode.kind === 320 /* JSDocNullableType */ && fixId52 === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; - doChange21(changes, sourceFile, typeNode, fixedType, checker); + doChange28(changes, sourceFile, typeNode, fixedType, checker); }); } }); @@ -144934,7 +150842,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixMissingCallParentheses.ts - function doChange22(changes, sourceFile, name) { + function doChange29(changes, sourceFile, name) { changes.replaceNodeWithText(sourceFile, name, `${name.text}()`); } function getCallName(sourceFile, start) { @@ -144969,13 +150877,13 @@ ${lanes.join("\n")} const callName = getCallName(sourceFile, span.start); if (!callName) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange22(t, context.sourceFile, callName)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange29(t, context.sourceFile, callName)); return [createCodeFixAction(fixId35, changes, Diagnostics.Add_missing_call_parentheses, fixId35, Diagnostics.Add_all_missing_call_parentheses)]; }, getAllCodeActions: (context) => codeFixAll(context, errorCodes45, (changes, diag2) => { const callName = getCallName(diag2.file, diag2.start); if (callName) - doChange22(changes, diag2.file, callName); + doChange29(changes, diag2.file, callName); }) }); } @@ -145017,7 +150925,7 @@ ${lanes.join("\n")} returnType: getReturnType(containingFunction) }; } - function doChange23(changes, sourceFile, { insertBefore, returnType }) { + function doChange30(changes, sourceFile, { insertBefore, returnType }) { if (returnType) { const entityName = getEntityNameFromTypeNode(returnType); if (!entityName || entityName.kind !== 80 /* Identifier */ || entityName.text !== "Promise") { @@ -145045,7 +150953,7 @@ ${lanes.join("\n")} const nodes = getNodes3(sourceFile, span.start); if (!nodes) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange23(t, sourceFile, nodes)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange30(t, sourceFile, nodes)); return [createCodeFixAction(fixId36, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId36, Diagnostics.Add_all_missing_async_modifiers)]; }, fixIds: [fixId36], @@ -145055,7 +150963,7 @@ ${lanes.join("\n")} const nodes = getNodes3(diag2.file, diag2.start); if (!nodes || !addToSeen(seen, getNodeId(nodes.insertBefore))) return; - doChange23(changes, context.sourceFile, nodes); + doChange30(changes, context.sourceFile, nodes); }); } }); @@ -145063,7 +150971,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixPropertyOverrideAccessor.ts - function doChange24(file, start, length2, code, context) { + function doChange31(file, start, length2, code, context) { let startPosition; let endPosition; if (code === Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property.code) { @@ -145104,14 +151012,14 @@ ${lanes.join("\n")} registerCodeFix({ errorCodes: errorCodes47, getCodeActions(context) { - const edits = doChange24(context.sourceFile, context.span.start, context.span.length, context.errorCode, context); + const edits = doChange31(context.sourceFile, context.span.start, context.span.length, context.errorCode, context); if (edits) { return [createCodeFixAction(fixId37, edits, Diagnostics.Generate_get_and_set_accessors, fixId37, Diagnostics.Generate_get_and_set_accessors_for_all_overriding_properties)]; } }, fixIds: [fixId37], getAllCodeActions: (context) => codeFixAll(context, errorCodes47, (changes, diag2) => { - const edits = doChange24(diag2.file, diag2.start, diag2.length, diag2.code, context); + const edits = doChange31(diag2.file, diag2.start, diag2.length, diag2.code, context); if (edits) { for (const edit of edits) { changes.pushRaw(context.sourceFile, edit); @@ -145158,7 +151066,7 @@ ${lanes.join("\n")} } return errorCode; } - function doChange25(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, preferences) { + function doChange32(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, preferences) { if (!isParameterPropertyModifier(token.kind) && token.kind !== 80 /* Identifier */ && token.kind !== 26 /* DotDotDotToken */ && token.kind !== 110 /* ThisKeyword */) { return void 0; } @@ -146102,7 +152010,7 @@ ${lanes.join("\n")} const token = getTokenAtPosition(sourceFile, start); let declaration; const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => { - declaration = doChange25( + declaration = doChange32( changes2, sourceFile, token, @@ -146123,7 +152031,7 @@ ${lanes.join("\n")} const { sourceFile, program, cancellationToken, host, preferences } = context; const markSeen = nodeSeenTracker(); return codeFixAll(context, errorCodes48, (changes, err) => { - doChange25(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences); + doChange32(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences); }); } }); @@ -146131,7 +152039,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixReturnTypeInAsyncFunction.ts - function getInfo12(sourceFile, checker, pos) { + function getInfo15(sourceFile, checker, pos) { if (isInJSFile(sourceFile)) { return void 0; } @@ -146154,7 +152062,7 @@ ${lanes.join("\n")} return { returnTypeNode, returnType, promisedTypeNode, promisedType }; } } - function doChange26(changes, sourceFile, returnTypeNode, promisedTypeNode) { + function doChange33(changes, sourceFile, returnTypeNode, promisedTypeNode) { changes.replaceNode(sourceFile, returnTypeNode, factory.createTypeReferenceNode("Promise", [promisedTypeNode])); } var fixId39, errorCodes49; @@ -146173,12 +152081,12 @@ ${lanes.join("\n")} getCodeActions: function getCodeActionsToFixReturnTypeInAsyncFunction(context) { const { sourceFile, program, span } = context; const checker = program.getTypeChecker(); - const info = getInfo12(sourceFile, program.getTypeChecker(), span.start); + const info = getInfo15(sourceFile, program.getTypeChecker(), span.start); if (!info) { return void 0; } const { returnTypeNode, returnType, promisedTypeNode, promisedType } = info; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange26(t, sourceFile, returnTypeNode, promisedTypeNode)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange33(t, sourceFile, returnTypeNode, promisedTypeNode)); return [createCodeFixAction( fixId39, changes, @@ -146192,9 +152100,9 @@ ${lanes.join("\n")} )]; }, getAllCodeActions: (context) => codeFixAll(context, errorCodes49, (changes, diag2) => { - const info = getInfo12(diag2.file, context.program.getTypeChecker(), diag2.start); + const info = getInfo15(diag2.file, context.program.getTypeChecker(), diag2.start); if (info) { - doChange26(changes, diag2.file, info.returnTypeNode, info.promisedTypeNode); + doChange33(changes, diag2.file, info.returnTypeNode, info.promisedTypeNode); } }) }); @@ -146887,7 +152795,7 @@ ${lanes.join("\n")} return token; } var PreserveOptionalFlags; - var init_helpers = __esm({ + var init_helpers2 = __esm({ "src/services/codefixes/helpers.ts"() { "use strict"; init_ts4(); @@ -147238,7 +153146,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixStrictClassInitialization.ts - function getInfo13(sourceFile, pos) { + function getInfo16(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); if (isIdentifier(token) && isPropertyDeclaration(token.parent)) { const type = getEffectiveTypeAnnotationNode(token.parent); @@ -147356,7 +153264,7 @@ ${lanes.join("\n")} registerCodeFix({ errorCodes: errorCodes51, getCodeActions: function getCodeActionsForStrictClassInitializationErrors(context) { - const info = getInfo13(context.sourceFile, context.span.start); + const info = getInfo16(context.sourceFile, context.span.start); if (!info) return; const result = []; @@ -147368,7 +153276,7 @@ ${lanes.join("\n")} fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], getAllCodeActions: (context) => { return codeFixAll(context, errorCodes51, (changes, diag2) => { - const info = getInfo13(diag2.file, diag2.start); + const info = getInfo16(diag2.file, diag2.start); if (!info) return; switch (context.fixId) { @@ -147395,7 +153303,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/requireInTs.ts - function doChange27(changes, sourceFile, info) { + function doChange34(changes, sourceFile, info) { const { allowSyntheticDefaults, defaultImportName, namedImports, statement, required } = info; changes.replaceNode(sourceFile, statement, defaultImportName && !allowSyntheticDefaults ? factory.createImportEqualsDeclaration( /*modifiers*/ @@ -147418,7 +153326,7 @@ ${lanes.join("\n")} void 0 )); } - function getInfo14(sourceFile, program, pos) { + function getInfo17(sourceFile, program, pos) { const { parent: parent2 } = getTokenAtPosition(sourceFile, pos); if (!isRequireCall( parent2, @@ -147468,18 +153376,18 @@ ${lanes.join("\n")} registerCodeFix({ errorCodes: errorCodes52, getCodeActions(context) { - const info = getInfo14(context.sourceFile, context.program, context.span.start); + const info = getInfo17(context.sourceFile, context.program, context.span.start); if (!info) { return void 0; } - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange27(t, context.sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange34(t, context.sourceFile, info)); return [createCodeFixAction(fixId41, changes, Diagnostics.Convert_require_to_import, fixId41, Diagnostics.Convert_all_require_to_import)]; }, fixIds: [fixId41], getAllCodeActions: (context) => codeFixAll(context, errorCodes52, (changes, diag2) => { - const info = getInfo14(diag2.file, context.program, diag2.start); + const info = getInfo17(diag2.file, context.program, diag2.start); if (info) { - doChange27(changes, context.sourceFile, info); + doChange34(changes, context.sourceFile, info); } }) }); @@ -147487,7 +153395,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/useDefaultImport.ts - function getInfo15(sourceFile, pos) { + function getInfo18(sourceFile, pos) { const name = getTokenAtPosition(sourceFile, pos); if (!isIdentifier(name)) return void 0; @@ -147499,7 +153407,7 @@ ${lanes.join("\n")} return { importNode, name, moduleSpecifier: importNode.moduleSpecifier }; } } - function doChange28(changes, sourceFile, info, preferences) { + function doChange35(changes, sourceFile, info, preferences) { changes.replaceNode(sourceFile, info.importNode, makeImport( info.name, /*namedImports*/ @@ -147520,17 +153428,17 @@ ${lanes.join("\n")} errorCodes: errorCodes53, getCodeActions(context) { const { sourceFile, span: { start } } = context; - const info = getInfo15(sourceFile, start); + const info = getInfo18(sourceFile, start); if (!info) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange28(t, sourceFile, info, context.preferences)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange35(t, sourceFile, info, context.preferences)); return [createCodeFixAction(fixId42, changes, Diagnostics.Convert_to_default_import, fixId42, Diagnostics.Convert_all_to_default_imports)]; }, fixIds: [fixId42], getAllCodeActions: (context) => codeFixAll(context, errorCodes53, (changes, diag2) => { - const info = getInfo15(diag2.file, diag2.start); + const info = getInfo18(diag2.file, diag2.start); if (info) - doChange28(changes, diag2.file, info, context.preferences); + doChange35(changes, diag2.file, info, context.preferences); }) }); } @@ -147578,7 +153486,7 @@ ${lanes.join("\n")} Debug.assert(token.parent.kind === 204 /* ImportType */, "Token parent should be an ImportType"); return token.parent; } - function doChange29(changes, sourceFile, importType) { + function doChange36(changes, sourceFile, importType) { const newTypeNode = factory.updateImportTypeNode( importType, importType.argument, @@ -147604,11 +153512,11 @@ ${lanes.join("\n")} getCodeActions: function getCodeActionsToAddMissingTypeof(context) { const { sourceFile, span } = context; const importType = getImportTypeNode(sourceFile, span.start); - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange29(t, sourceFile, importType)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange36(t, sourceFile, importType)); return [createCodeFixAction(fixId44, changes, Diagnostics.Add_missing_typeof, fixId44, Diagnostics.Add_missing_typeof)]; }, fixIds: [fixId44], - getAllCodeActions: (context) => codeFixAll(context, errorCodes55, (changes, diag2) => doChange29(changes, context.sourceFile, getImportTypeNode(diag2.file, diag2.start))) + getAllCodeActions: (context) => codeFixAll(context, errorCodes55, (changes, diag2) => doChange36(changes, context.sourceFile, getImportTypeNode(diag2.file, diag2.start))) }); } }); @@ -147627,7 +153535,7 @@ ${lanes.join("\n")} return void 0; return binaryExpr; } - function doChange30(changeTracker, sf, node) { + function doChange37(changeTracker, sf, node) { const jsx = flattenInvalidBinaryExpr(node); if (jsx) changeTracker.replaceNode(sf, node, factory.createJsxFragment(factory.createJsxOpeningFragment(), jsx, factory.createJsxJsxClosingFragment())); @@ -147665,7 +153573,7 @@ ${lanes.join("\n")} const node = findNodeToFix(sourceFile, span.start); if (!node) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange30(t, sourceFile, node)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange37(t, sourceFile, node)); return [createCodeFixAction(fixID2, changes, Diagnostics.Wrap_in_JSX_fragment, fixID2, Diagnostics.Wrap_all_unparented_JSX_in_JSX_fragment)]; }, fixIds: [fixID2], @@ -147673,14 +153581,14 @@ ${lanes.join("\n")} const node = findNodeToFix(context.sourceFile, diag2.start); if (!node) return void 0; - doChange30(changes, context.sourceFile, node); + doChange37(changes, context.sourceFile, node); }) }); } }); // src/services/codefixes/convertToMappedObjectType.ts - function getInfo16(sourceFile, pos) { + function getInfo19(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); const indexSignature = tryCast(token.parent.parent, isIndexSignatureDeclaration); if (!indexSignature) @@ -147693,7 +153601,7 @@ ${lanes.join("\n")} function createTypeAliasFromInterface(declaration, type) { return factory.createTypeAliasDeclaration(declaration.modifiers, declaration.name, declaration.typeParameters, type); } - function doChange31(changes, sourceFile, { indexSignature, container }) { + function doChange38(changes, sourceFile, { indexSignature, container }) { const members = isInterfaceDeclaration(container) ? container.members : container.type.members; const otherMembers = members.filter((member) => !isIndexSignatureDeclaration(member)); const parameter = first(indexSignature.parameters); @@ -147732,18 +153640,18 @@ ${lanes.join("\n")} errorCodes: errorCodes57, getCodeActions: function getCodeActionsToConvertToMappedTypeObject(context) { const { sourceFile, span } = context; - const info = getInfo16(sourceFile, span.start); + const info = getInfo19(sourceFile, span.start); if (!info) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange31(t, sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange38(t, sourceFile, info)); const name = idText(info.container.name); return [createCodeFixAction(fixId45, changes, [Diagnostics.Convert_0_to_mapped_object_type, name], fixId45, [Diagnostics.Convert_0_to_mapped_object_type, name])]; }, fixIds: [fixId45], getAllCodeActions: (context) => codeFixAll(context, errorCodes57, (changes, diag2) => { - const info = getInfo16(diag2.file, diag2.start); + const info = getInfo19(diag2.file, diag2.start); if (info) - doChange31(changes, diag2.file, info); + doChange38(changes, diag2.file, info); }) }); } @@ -147890,7 +153798,7 @@ ${lanes.join("\n")} }); // src/services/codefixes/convertConstToLet.ts - function getInfo17(sourceFile, pos, program) { + function getInfo20(sourceFile, pos, program) { var _a; const checker = program.getTypeChecker(); const symbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, pos)); @@ -147904,7 +153812,7 @@ ${lanes.join("\n")} return; return { symbol, token: constToken }; } - function doChange32(changes, sourceFile, token) { + function doChange39(changes, sourceFile, token) { changes.replaceNode(sourceFile, token, factory.createToken(121 /* LetKeyword */)); } var fixId49, errorCodes61; @@ -147919,10 +153827,10 @@ ${lanes.join("\n")} errorCodes: errorCodes61, getCodeActions: function getCodeActionsToConvertConstToLet(context) { const { sourceFile, span, program } = context; - const info = getInfo17(sourceFile, span.start, program); + const info = getInfo20(sourceFile, span.start, program); if (info === void 0) return; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange32(t, sourceFile, info.token)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange39(t, sourceFile, info.token)); return [createCodeFixActionMaybeFixAll(fixId49, changes, Diagnostics.Convert_const_to_let, fixId49, Diagnostics.Convert_all_const_to_let)]; }, getAllCodeActions: (context) => { @@ -147930,10 +153838,10 @@ ${lanes.join("\n")} const seen = /* @__PURE__ */ new Map(); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { eachDiagnostic(context, errorCodes61, (diag2) => { - const info = getInfo17(diag2.file, diag2.start, program); + const info = getInfo20(diag2.file, diag2.start, program); if (info) { if (addToSeen(seen, getSymbolId(info.symbol))) { - return doChange32(changes, diag2.file, info.token); + return doChange39(changes, diag2.file, info.token); } } return void 0; @@ -147946,11 +153854,11 @@ ${lanes.join("\n")} }); // src/services/codefixes/fixExpectedComma.ts - function getInfo18(sourceFile, pos, _) { + function getInfo21(sourceFile, pos, _) { const node = getTokenAtPosition(sourceFile, pos); return node.kind === 27 /* SemicolonToken */ && node.parent && (isObjectLiteralExpression(node.parent) || isArrayLiteralExpression(node.parent)) ? { node } : void 0; } - function doChange33(changes, sourceFile, { node }) { + function doChange40(changes, sourceFile, { node }) { const newNode = factory.createToken(28 /* CommaToken */); changes.replaceNode(sourceFile, node, newNode); } @@ -147967,10 +153875,10 @@ ${lanes.join("\n")} errorCodes: errorCodes62, getCodeActions(context) { const { sourceFile } = context; - const info = getInfo18(sourceFile, context.span.start, context.errorCode); + const info = getInfo21(sourceFile, context.span.start, context.errorCode); if (!info) return void 0; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange33(t, sourceFile, info)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange40(t, sourceFile, info)); return [createCodeFixAction( fixId50, changes, @@ -147981,9 +153889,9 @@ ${lanes.join("\n")} }, fixIds: [fixId50], getAllCodeActions: (context) => codeFixAll(context, errorCodes62, (changes, diag2) => { - const info = getInfo18(diag2.file, diag2.start, diag2.code); + const info = getInfo21(diag2.file, diag2.start, diag2.code); if (info) - doChange33(changes, context.sourceFile, info); + doChange40(changes, context.sourceFile, info); }) }); } @@ -148168,7 +154076,7 @@ ${lanes.join("\n")} init_inferFromUsage(); init_fixReturnTypeInAsyncFunction(); init_disableJsDiagnostics(); - init_helpers(); + init_helpers2(); init_generateAccessors(); init_fixInvalidImportSyntax(); init_fixStrictClassInitialization(); @@ -148676,11 +154584,11 @@ ${lanes.join("\n")} } } const dotDotDot = !isObject && dotDotDotToken ? "..." : ""; - const description2 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : ""; - return `@param {${dotDotDot}${type}} ${paramName} ${description2}`; + const description3 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : ""; + return `@param {${dotDotDot}${type}} ${paramName} ${description3}`; } else { - const description2 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : ""; - return `@param ${paramName} ${description2}`; + const description3 = isSnippet ? `\${${tabstopCounter.tabstop++}}` : ""; + return `@param ${paramName} ${description3}`; } } function getJSDocParamNameWithInitializer(paramName, initializer) { @@ -150005,7 +155913,7 @@ ${lanes.join("\n")} ) : isEqualityOperatorKind(previousToken.kind) && isBinaryExpression(parent2) && isEqualityOperatorKind(parent2.operatorToken.kind) ? ( // completion at `x ===/**/` should be for the right side checker.getTypeAtLocation(parent2.left) - ) : checker.getContextualType(previousToken); + ) : checker.getContextualType(previousToken, 4 /* Completions */) || checker.getContextualType(previousToken); } } function getFirstSymbolInChain(symbol, enclosingDeclaration, checker) { @@ -151180,7 +157088,7 @@ ${lanes.join("\n")} return true; } } - return isDeclarationName(contextToken2) && !isShorthandPropertyAssignment(contextToken2.parent) && !isJsxAttribute(contextToken2.parent) && !((isClassLike(contextToken2.parent) || isInterfaceDeclaration(contextToken2.parent)) && (contextToken2 !== previousToken || position > previousToken.end)); + return isDeclarationName(contextToken2) && !isShorthandPropertyAssignment(contextToken2.parent) && !isJsxAttribute(contextToken2.parent) && !((isClassLike(contextToken2.parent) || isInterfaceDeclaration(contextToken2.parent) || isTypeParameterDeclaration(contextToken2.parent)) && (contextToken2 !== previousToken || position > previousToken.end)); } function isPreviousPropertyDeclarationTerminated(contextToken2, position2) { return contextToken2.kind !== 64 /* EqualsToken */ && (contextToken2.kind === 27 /* SemicolonToken */ || !positionsAreOnSameLine(contextToken2.end, position2, sourceFile)); @@ -153617,8 +159525,8 @@ ${lanes.join("\n")} const { displayParts, symbolKind } = ts_SymbolDisplay_exports.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning); return { displayParts, kind: symbolKind }; } - function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText) { - return { ...entryToDocumentSpan(entry), ...providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker) }; + function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText, quotePreference) { + return { ...entryToDocumentSpan(entry), ...providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker, quotePreference) }; } function toReferencedSymbolEntry(entry, symbol) { const referenceEntry = toReferenceEntry(entry); @@ -153654,7 +159562,7 @@ ${lanes.join("\n")} }; } } - function getPrefixAndSuffixText(entry, originalNode, checker) { + function getPrefixAndSuffixText(entry, originalNode, checker, quotePreference) { if (entry.kind !== 0 /* Span */ && isIdentifier(originalNode)) { const { node, kind } = entry; const parent2 = node.parent; @@ -153685,6 +159593,10 @@ ${lanes.join("\n")} return originalNode === entry.node || checker.getSymbolAtLocation(originalNode) === checker.getSymbolAtLocation(entry.node) ? { prefixText: name + " as " } : { suffixText: " as " + name }; } } + if (entry.kind !== 0 /* Span */ && isNumericLiteral(entry.node) && isAccessExpression(entry.node.parent)) { + const quote2 = getQuoteFromPreference(quotePreference); + return { prefixText: quote2, suffixText: quote2 }; + } return emptyOptions; } function toImplementationLocation(entry, checker) { @@ -157534,5113 +163446,6 @@ ${lanes.join("\n")} } }); - // src/services/refactorProvider.ts - function registerRefactor(name, refactor) { - refactors.set(name, refactor); - } - function getApplicableRefactors(context) { - return arrayFrom(flatMapIterator(refactors.values(), (refactor) => { - var _a; - return context.cancellationToken && context.cancellationToken.isCancellationRequested() || !((_a = refactor.kinds) == null ? void 0 : _a.some((kind) => refactorKindBeginsWith(kind, context.kind))) ? void 0 : refactor.getAvailableActions(context); - })); - } - function getEditsForRefactor(context, refactorName13, actionName2) { - const refactor = refactors.get(refactorName13); - return refactor && refactor.getEditsForAction(context, actionName2); - } - var refactors; - var init_refactorProvider = __esm({ - "src/services/refactorProvider.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactors = /* @__PURE__ */ new Map(); - } - }); - - // src/services/refactors/convertExport.ts - function getInfo19(context, considerPartialSpans = true) { - const { file, program } = context; - const span = getRefactorContextSpan(context); - const token = getTokenAtPosition(file, span.start); - const exportNode = !!(token.parent && getSyntacticModifierFlags(token.parent) & 1 /* Export */) && considerPartialSpans ? token.parent : getParentNodeInSpan(token, file, span); - if (!exportNode || !isSourceFile(exportNode.parent) && !(isModuleBlock(exportNode.parent) && isAmbientModule(exportNode.parent.parent))) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_export_statement) }; - } - const checker = program.getTypeChecker(); - const exportingModuleSymbol = getExportingModuleSymbol(exportNode.parent, checker); - const flags = getSyntacticModifierFlags(exportNode) || (isExportAssignment(exportNode) && !exportNode.isExportEquals ? 1025 /* ExportDefault */ : 0 /* None */); - const wasDefault = !!(flags & 1024 /* Default */); - if (!(flags & 1 /* Export */) || !wasDefault && exportingModuleSymbol.exports.has("default" /* Default */)) { - return { error: getLocaleSpecificMessage(Diagnostics.This_file_already_has_a_default_export) }; - } - const noSymbolError = (id) => isIdentifier(id) && checker.getSymbolAtLocation(id) ? void 0 : { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_named_export) }; - switch (exportNode.kind) { - case 261 /* FunctionDeclaration */: - case 262 /* ClassDeclaration */: - case 263 /* InterfaceDeclaration */: - case 265 /* EnumDeclaration */: - case 264 /* TypeAliasDeclaration */: - case 266 /* ModuleDeclaration */: { - const node = exportNode; - if (!node.name) - return void 0; - return noSymbolError(node.name) || { exportNode: node, exportName: node.name, wasDefault, exportingModuleSymbol }; - } - case 242 /* VariableStatement */: { - const vs = exportNode; - if (!(vs.declarationList.flags & 2 /* Const */) || vs.declarationList.declarations.length !== 1) { - return void 0; - } - const decl = first(vs.declarationList.declarations); - if (!decl.initializer) - return void 0; - Debug.assert(!wasDefault, "Can't have a default flag here"); - return noSymbolError(decl.name) || { exportNode: vs, exportName: decl.name, wasDefault, exportingModuleSymbol }; - } - case 276 /* ExportAssignment */: { - const node = exportNode; - if (node.isExportEquals) - return void 0; - return noSymbolError(node.expression) || { exportNode: node, exportName: node.expression, wasDefault, exportingModuleSymbol }; - } - default: - return void 0; - } - } - function doChange34(exportingSourceFile, program, info, changes, cancellationToken) { - changeExport(exportingSourceFile, info, changes, program.getTypeChecker()); - changeImports(program, info, changes, cancellationToken); - } - function changeExport(exportingSourceFile, { wasDefault, exportNode, exportName }, changes, checker) { - if (wasDefault) { - if (isExportAssignment(exportNode) && !exportNode.isExportEquals) { - const exp = exportNode.expression; - const spec = makeExportSpecifier(exp.text, exp.text); - changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - factory.createNamedExports([spec]) - )); - } else { - changes.delete(exportingSourceFile, Debug.checkDefined(findModifier(exportNode, 90 /* DefaultKeyword */), "Should find a default keyword in modifier list")); - } - } else { - const exportKeyword = Debug.checkDefined(findModifier(exportNode, 95 /* ExportKeyword */), "Should find an export keyword in modifier list"); - switch (exportNode.kind) { - case 261 /* FunctionDeclaration */: - case 262 /* ClassDeclaration */: - case 263 /* InterfaceDeclaration */: - changes.insertNodeAfter(exportingSourceFile, exportKeyword, factory.createToken(90 /* DefaultKeyword */)); - break; - case 242 /* VariableStatement */: - const decl = first(exportNode.declarationList.declarations); - if (!ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(exportName, checker, exportingSourceFile) && !decl.type) { - changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDefault(Debug.checkDefined(decl.initializer, "Initializer was previously known to be present"))); - break; - } - case 265 /* EnumDeclaration */: - case 264 /* TypeAliasDeclaration */: - case 266 /* ModuleDeclaration */: - changes.deleteModifier(exportingSourceFile, exportKeyword); - changes.insertNodeAfter(exportingSourceFile, exportNode, factory.createExportDefault(factory.createIdentifier(exportName.text))); - break; - default: - Debug.fail(`Unexpected exportNode kind ${exportNode.kind}`); - } - } - } - function changeImports(program, { wasDefault, exportName, exportingModuleSymbol }, changes, cancellationToken) { - const checker = program.getTypeChecker(); - const exportSymbol = Debug.checkDefined(checker.getSymbolAtLocation(exportName), "Export name should resolve to a symbol"); - ts_FindAllReferences_exports.Core.eachExportReference(program.getSourceFiles(), checker, cancellationToken, exportSymbol, exportingModuleSymbol, exportName.text, wasDefault, (ref) => { - if (exportName === ref) - return; - const importingSourceFile = ref.getSourceFile(); - if (wasDefault) { - changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName.text); - } else { - changeNamedToDefaultImport(importingSourceFile, ref, changes); - } - }); - } - function changeDefaultToNamedImport(importingSourceFile, ref, changes, exportName) { - const { parent: parent2 } = ref; - switch (parent2.kind) { - case 210 /* PropertyAccessExpression */: - changes.replaceNode(importingSourceFile, ref, factory.createIdentifier(exportName)); - break; - case 275 /* ImportSpecifier */: - case 280 /* ExportSpecifier */: { - const spec = parent2; - changes.replaceNode(importingSourceFile, spec, makeImportSpecifier2(exportName, spec.name.text)); - break; - } - case 272 /* ImportClause */: { - const clause = parent2; - Debug.assert(clause.name === ref, "Import clause name should match provided ref"); - const spec = makeImportSpecifier2(exportName, ref.text); - const { namedBindings } = clause; - if (!namedBindings) { - changes.replaceNode(importingSourceFile, ref, factory.createNamedImports([spec])); - } else if (namedBindings.kind === 273 /* NamespaceImport */) { - changes.deleteRange(importingSourceFile, { pos: ref.getStart(importingSourceFile), end: namedBindings.getStart(importingSourceFile) }); - const quotePreference = isStringLiteral(clause.parent.moduleSpecifier) ? quotePreferenceFromString(clause.parent.moduleSpecifier, importingSourceFile) : 1 /* Double */; - const newImport = makeImport( - /*defaultImport*/ - void 0, - [makeImportSpecifier2(exportName, ref.text)], - clause.parent.moduleSpecifier, - quotePreference - ); - changes.insertNodeAfter(importingSourceFile, clause.parent, newImport); - } else { - changes.delete(importingSourceFile, ref); - changes.insertNodeAtEndOfList(importingSourceFile, namedBindings.elements, spec); - } - break; - } - case 204 /* ImportType */: - const importTypeNode = parent2; - changes.replaceNode(importingSourceFile, parent2, factory.createImportTypeNode(importTypeNode.argument, importTypeNode.assertions, factory.createIdentifier(exportName), importTypeNode.typeArguments, importTypeNode.isTypeOf)); - break; - default: - Debug.failBadSyntaxKind(parent2); - } - } - function changeNamedToDefaultImport(importingSourceFile, ref, changes) { - const parent2 = ref.parent; - switch (parent2.kind) { - case 210 /* PropertyAccessExpression */: - changes.replaceNode(importingSourceFile, ref, factory.createIdentifier("default")); - break; - case 275 /* ImportSpecifier */: { - const defaultImport = factory.createIdentifier(parent2.name.text); - if (parent2.parent.elements.length === 1) { - changes.replaceNode(importingSourceFile, parent2.parent, defaultImport); - } else { - changes.delete(importingSourceFile, parent2); - changes.insertNodeBefore(importingSourceFile, parent2.parent, defaultImport); - } - break; - } - case 280 /* ExportSpecifier */: { - changes.replaceNode(importingSourceFile, parent2, makeExportSpecifier("default", parent2.name.text)); - break; - } - default: - Debug.assertNever(parent2, `Unexpected parent kind ${parent2.kind}`); - } - } - function makeImportSpecifier2(propertyName, name) { - return factory.createImportSpecifier( - /*isTypeOnly*/ - false, - propertyName === name ? void 0 : factory.createIdentifier(propertyName), - factory.createIdentifier(name) - ); - } - function makeExportSpecifier(propertyName, name) { - return factory.createExportSpecifier( - /*isTypeOnly*/ - false, - propertyName === name ? void 0 : factory.createIdentifier(propertyName), - factory.createIdentifier(name) - ); - } - function getExportingModuleSymbol(parent2, checker) { - if (isSourceFile(parent2)) { - return parent2.symbol; - } - const symbol = parent2.parent.symbol; - if (symbol.valueDeclaration && isExternalModuleAugmentation(symbol.valueDeclaration)) { - return checker.getMergedSymbol(symbol); - } - return symbol; - } - var refactorName, defaultToNamedAction, namedToDefaultAction; - var init_convertExport = __esm({ - "src/services/refactors/convertExport.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName = "Convert export"; - defaultToNamedAction = { - name: "Convert default export to named export", - description: Diagnostics.Convert_default_export_to_named_export.message, - kind: "refactor.rewrite.export.named" - }; - namedToDefaultAction = { - name: "Convert named export to default export", - description: Diagnostics.Convert_named_export_to_default_export.message, - kind: "refactor.rewrite.export.default" - }; - registerRefactor(refactorName, { - kinds: [ - defaultToNamedAction.kind, - namedToDefaultAction.kind - ], - getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndDefaultExports(context) { - const info = getInfo19(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - const action = info.wasDefault ? defaultToNamedAction : namedToDefaultAction; - return [{ name: refactorName, description: action.description, actions: [action] }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [ - { name: refactorName, description: Diagnostics.Convert_default_export_to_named_export.message, actions: [ - { ...defaultToNamedAction, notApplicableReason: info.error }, - { ...namedToDefaultAction, notApplicableReason: info.error } - ] } - ]; - } - return emptyArray; - }, - getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndDefaultExports(context, actionName2) { - Debug.assert(actionName2 === defaultToNamedAction.name || actionName2 === namedToDefaultAction.name, "Unexpected action name"); - const info = getInfo19(context); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange34(context.file, context.program, info, t, context.cancellationToken)); - return { edits, renameFilename: void 0, renameLocation: void 0 }; - } - }); - } - }); - - // src/services/refactors/convertImport.ts - function getImportConversionInfo(context, considerPartialSpans = true) { - const { file } = context; - const span = getRefactorContextSpan(context); - const token = getTokenAtPosition(file, span.start); - const importDecl = considerPartialSpans ? findAncestor(token, isImportDeclaration) : getParentNodeInSpan(token, file, span); - if (!importDecl || !isImportDeclaration(importDecl)) - return { error: "Selection is not an import declaration." }; - const end = span.start + span.length; - const nextToken = findNextToken(importDecl, importDecl.parent, file); - if (nextToken && end > nextToken.getStart()) - return void 0; - const { importClause } = importDecl; - if (!importClause) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_import_clause) }; - } - if (!importClause.namedBindings) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_namespace_import_or_named_imports) }; - } - if (importClause.namedBindings.kind === 273 /* NamespaceImport */) { - return { convertTo: 0 /* Named */, import: importClause.namedBindings }; - } - const shouldUseDefault = getShouldUseDefault(context.program, importClause); - return shouldUseDefault ? { convertTo: 1 /* Default */, import: importClause.namedBindings } : { convertTo: 2 /* Namespace */, import: importClause.namedBindings }; - } - function getShouldUseDefault(program, importClause) { - return getAllowSyntheticDefaultImports(program.getCompilerOptions()) && isExportEqualsModule(importClause.parent.moduleSpecifier, program.getTypeChecker()); - } - function doChange35(sourceFile, program, changes, info) { - const checker = program.getTypeChecker(); - if (info.convertTo === 0 /* Named */) { - doChangeNamespaceToNamed(sourceFile, checker, changes, info.import, getAllowSyntheticDefaultImports(program.getCompilerOptions())); - } else { - doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, info.import, info.convertTo === 1 /* Default */); - } - } - function doChangeNamespaceToNamed(sourceFile, checker, changes, toConvert, allowSyntheticDefaultImports) { - let usedAsNamespaceOrDefault = false; - const nodesToReplace = []; - const conflictingNames = /* @__PURE__ */ new Map(); - ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(toConvert.name, checker, sourceFile, (id) => { - if (!isPropertyAccessOrQualifiedName(id.parent)) { - usedAsNamespaceOrDefault = true; - } else { - const exportName = getRightOfPropertyAccessOrQualifiedName(id.parent).text; - if (checker.resolveName( - exportName, - id, - 67108863 /* All */, - /*excludeGlobals*/ - true - )) { - conflictingNames.set(exportName, true); - } - Debug.assert(getLeftOfPropertyAccessOrQualifiedName(id.parent) === id, "Parent expression should match id"); - nodesToReplace.push(id.parent); - } - }); - const exportNameToImportName = /* @__PURE__ */ new Map(); - for (const propertyAccessOrQualifiedName of nodesToReplace) { - const exportName = getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName).text; - let importName = exportNameToImportName.get(exportName); - if (importName === void 0) { - exportNameToImportName.set(exportName, importName = conflictingNames.has(exportName) ? getUniqueName(exportName, sourceFile) : exportName); - } - changes.replaceNode(sourceFile, propertyAccessOrQualifiedName, factory.createIdentifier(importName)); - } - const importSpecifiers = []; - exportNameToImportName.forEach((name, propertyName) => { - importSpecifiers.push(factory.createImportSpecifier( - /*isTypeOnly*/ - false, - name === propertyName ? void 0 : factory.createIdentifier(propertyName), - factory.createIdentifier(name) - )); - }); - const importDecl = toConvert.parent.parent; - if (usedAsNamespaceOrDefault && !allowSyntheticDefaultImports) { - changes.insertNodeAfter(sourceFile, importDecl, updateImport( - importDecl, - /*defaultImportName*/ - void 0, - importSpecifiers - )); - } else { - changes.replaceNode(sourceFile, importDecl, updateImport(importDecl, usedAsNamespaceOrDefault ? factory.createIdentifier(toConvert.name.text) : void 0, importSpecifiers)); - } - } - function getRightOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { - return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.name : propertyAccessOrQualifiedName.right; - } - function getLeftOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName) { - return isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.expression : propertyAccessOrQualifiedName.left; - } - function doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, toConvert, shouldUseDefault = getShouldUseDefault(program, toConvert.parent)) { - const checker = program.getTypeChecker(); - const importDecl = toConvert.parent.parent; - const { moduleSpecifier } = importDecl; - const toConvertSymbols = /* @__PURE__ */ new Set(); - toConvert.elements.forEach((namedImport) => { - const symbol = checker.getSymbolAtLocation(namedImport.name); - if (symbol) { - toConvertSymbols.add(symbol); - } - }); - const preferredName = moduleSpecifier && isStringLiteral(moduleSpecifier) ? ts_codefix_exports.moduleSpecifierToValidIdentifier(moduleSpecifier.text, 99 /* ESNext */) : "module"; - function hasNamespaceNameConflict(namedImport) { - return !!ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(namedImport.name, checker, sourceFile, (id) => { - const symbol = checker.resolveName( - preferredName, - id, - 67108863 /* All */, - /*excludeGlobals*/ - true - ); - if (symbol) { - if (toConvertSymbols.has(symbol)) { - return isExportSpecifier(id.parent); - } - return true; - } - return false; - }); - } - const namespaceNameConflicts = toConvert.elements.some(hasNamespaceNameConflict); - const namespaceImportName = namespaceNameConflicts ? getUniqueName(preferredName, sourceFile) : preferredName; - const neededNamedImports = /* @__PURE__ */ new Set(); - for (const element of toConvert.elements) { - const propertyName = (element.propertyName || element.name).text; - ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, (id) => { - const access = factory.createPropertyAccessExpression(factory.createIdentifier(namespaceImportName), propertyName); - if (isShorthandPropertyAssignment(id.parent)) { - changes.replaceNode(sourceFile, id.parent, factory.createPropertyAssignment(id.text, access)); - } else if (isExportSpecifier(id.parent)) { - neededNamedImports.add(element); - } else { - changes.replaceNode(sourceFile, id, access); - } - }); - } - changes.replaceNode(sourceFile, toConvert, shouldUseDefault ? factory.createIdentifier(namespaceImportName) : factory.createNamespaceImport(factory.createIdentifier(namespaceImportName))); - if (neededNamedImports.size) { - const newNamedImports = 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*/ - void 0, - newNamedImports - )); - } - } - function isExportEqualsModule(moduleSpecifier, checker) { - const externalModule = checker.resolveExternalModuleName(moduleSpecifier); - if (!externalModule) - return false; - const exportEquals = checker.resolveExternalModuleSymbol(externalModule); - return externalModule !== exportEquals; - } - function updateImport(old, defaultImportName, elements) { - return factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - /*isTypeOnly*/ - false, - defaultImportName, - elements && elements.length ? factory.createNamedImports(elements) : void 0 - ), - old.moduleSpecifier, - /*assertClause*/ - void 0 - ); - } - var refactorName2, actions; - var init_convertImport = __esm({ - "src/services/refactors/convertImport.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName2 = "Convert import"; - actions = { - [0 /* Named */]: { - name: "Convert namespace import to named imports", - description: Diagnostics.Convert_namespace_import_to_named_imports.message, - kind: "refactor.rewrite.import.named" - }, - [2 /* Namespace */]: { - name: "Convert named imports to namespace import", - description: Diagnostics.Convert_named_imports_to_namespace_import.message, - kind: "refactor.rewrite.import.namespace" - }, - [1 /* Default */]: { - name: "Convert named imports to default import", - description: Diagnostics.Convert_named_imports_to_default_import.message, - kind: "refactor.rewrite.import.default" - } - }; - registerRefactor(refactorName2, { - kinds: getOwnValues(actions).map((a) => a.kind), - getAvailableActions: function getRefactorActionsToConvertBetweenNamedAndNamespacedImports(context) { - const info = getImportConversionInfo(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - const action = actions[info.convertTo]; - return [{ name: refactorName2, description: action.description, actions: [action] }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return getOwnValues(actions).map((action) => ({ - name: refactorName2, - description: action.description, - actions: [{ ...action, notApplicableReason: info.error }] - })); - } - return emptyArray; - }, - getEditsForAction: function getRefactorEditsToConvertBetweenNamedAndNamespacedImports(context, actionName2) { - Debug.assert(some(getOwnValues(actions), (action) => action.name === actionName2), "Unexpected action name"); - const info = getImportConversionInfo(context); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange35(context.file, context.program, t, info)); - return { edits, renameFilename: void 0, renameLocation: void 0 }; - } - }); - } - }); - - // src/services/refactors/extractType.ts - function getRangeToExtract(context, considerEmptySpans = true) { - const { file, startPosition } = context; - const isJS = isSourceFileJS(file); - const current = getTokenAtPosition(file, startPosition); - 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))); - if (!selection || !isTypeNode(selection)) - return { error: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_type_node) }; - const checker = context.program.getTypeChecker(); - const enclosingNode = getEnclosingNode(selection, isJS); - if (enclosingNode === void 0) - return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }; - const typeParameters = collectTypeParameters(checker, selection, enclosingNode, file); - if (!typeParameters) - return { error: getLocaleSpecificMessage(Diagnostics.No_type_could_be_extracted_from_this_type_node) }; - const typeElements = flattenTypeLiteralNodeReference(checker, selection); - return { isJS, selection, enclosingNode, typeParameters, typeElements }; - } - function flattenTypeLiteralNodeReference(checker, node) { - if (!node) - return void 0; - if (isIntersectionTypeNode(node)) { - const result = []; - const seen = /* @__PURE__ */ new Map(); - for (const type of node.types) { - const flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type); - if (!flattenedTypeMembers || !flattenedTypeMembers.every((type2) => type2.name && addToSeen(seen, getNameFromPropertyName(type2.name)))) { - return void 0; - } - addRange(result, flattenedTypeMembers); - } - return result; - } else if (isParenthesizedTypeNode(node)) { - return flattenTypeLiteralNodeReference(checker, node.type); - } else if (isTypeLiteralNode(node)) { - return node.members; - } - return void 0; - } - function rangeContainsSkipTrivia(r1, node, file) { - return rangeContainsStartEnd(r1, skipTrivia(file.text, node.pos), node.end); - } - function collectTypeParameters(checker, selection, enclosingNode, file) { - const result = []; - return visitor(selection) ? void 0 : result; - function visitor(node) { - if (isTypeReferenceNode(node)) { - if (isIdentifier(node.typeName)) { - const typeName = node.typeName; - const symbol = checker.resolveName( - typeName.text, - typeName, - 262144 /* TypeParameter */, - /*excludeGlobals*/ - true - ); - for (const decl of (symbol == null ? void 0 : symbol.declarations) || emptyArray) { - if (isTypeParameterDeclaration(decl) && decl.getSourceFile() === file) { - if (decl.name.escapedText === typeName.escapedText && rangeContainsSkipTrivia(decl, selection, file)) { - return true; - } - if (rangeContainsSkipTrivia(enclosingNode, decl, file) && !rangeContainsSkipTrivia(selection, decl, file)) { - pushIfUnique(result, decl); - break; - } - } - } - } - } else if (isInferTypeNode(node)) { - const conditionalTypeNode = findAncestor(node, (n) => isConditionalTypeNode(n) && rangeContainsSkipTrivia(n.extendsType, node, file)); - if (!conditionalTypeNode || !rangeContainsSkipTrivia(selection, conditionalTypeNode, file)) { - return true; - } - } else if (isTypePredicateNode(node) || isThisTypeNode(node)) { - const functionLikeNode = findAncestor(node.parent, isFunctionLike); - if (functionLikeNode && functionLikeNode.type && rangeContainsSkipTrivia(functionLikeNode.type, node, file) && !rangeContainsSkipTrivia(selection, functionLikeNode, file)) { - return true; - } - } else if (isTypeQueryNode(node)) { - if (isIdentifier(node.exprName)) { - const symbol = checker.resolveName( - node.exprName.text, - node.exprName, - 111551 /* Value */, - /*excludeGlobals*/ - false - ); - if ((symbol == null ? void 0 : symbol.valueDeclaration) && rangeContainsSkipTrivia(enclosingNode, symbol.valueDeclaration, file) && !rangeContainsSkipTrivia(selection, symbol.valueDeclaration, file)) { - return true; - } - } else { - if (isThisIdentifier(node.exprName.left) && !rangeContainsSkipTrivia(selection, node.parent, file)) { - return true; - } - } - } - if (file && isTupleTypeNode(node) && getLineAndCharacterOfPosition(file, node.pos).line === getLineAndCharacterOfPosition(file, node.end).line) { - setEmitFlags(node, 1 /* SingleLine */); - } - return forEachChild(node, visitor); - } - } - function doTypeAliasChange(changes, file, name, info) { - const { enclosingNode, selection, typeParameters } = info; - const newTypeNode = factory.createTypeAliasDeclaration( - /*modifiers*/ - void 0, - name, - typeParameters.map((id) => factory.updateTypeParameterDeclaration( - id, - id.modifiers, - id.name, - id.constraint, - /*defaultType*/ - void 0 - )), - selection - ); - changes.insertNodeBefore( - file, - enclosingNode, - ignoreSourceNewlines(newTypeNode), - /*blankLineBetween*/ - true - ); - changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( - id.name, - /*typeArguments*/ - void 0 - ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace }); - } - function doInterfaceChange(changes, file, name, info) { - var _a; - const { enclosingNode, selection, typeParameters, typeElements } = info; - const newTypeNode = factory.createInterfaceDeclaration( - /*modifiers*/ - void 0, - name, - typeParameters, - /*heritageClauses*/ - void 0, - typeElements - ); - setTextRange(newTypeNode, (_a = typeElements[0]) == null ? void 0 : _a.parent); - changes.insertNodeBefore( - file, - enclosingNode, - ignoreSourceNewlines(newTypeNode), - /*blankLineBetween*/ - true - ); - changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( - id.name, - /*typeArguments*/ - void 0 - ))), { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.Exclude, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.ExcludeWhitespace }); - } - function doTypedefChange(changes, context, file, name, info) { - var _a; - const { enclosingNode, selection, typeParameters } = info; - setEmitFlags(selection, 3072 /* NoComments */ | 4096 /* NoNestedComments */); - const node = factory.createJSDocTypedefTag( - factory.createIdentifier("typedef"), - factory.createJSDocTypeExpression(selection), - factory.createIdentifier(name) - ); - const templates = []; - forEach(typeParameters, (typeParameter) => { - const constraint = getEffectiveConstraintOfTypeParameter(typeParameter); - const parameter = factory.createTypeParameterDeclaration( - /*modifiers*/ - void 0, - typeParameter.name - ); - const template = factory.createJSDocTemplateTag( - factory.createIdentifier("template"), - constraint && cast(constraint, isJSDocTypeExpression), - [parameter] - ); - templates.push(template); - }); - const jsDoc = factory.createJSDocComment( - /*comment*/ - void 0, - factory.createNodeArray(concatenate(templates, [node])) - ); - if (isJSDoc(enclosingNode)) { - const pos = enclosingNode.getStart(file); - const newLineCharacter = getNewLineOrDefaultFromHost(context.host, (_a = context.formatContext) == null ? void 0 : _a.options); - changes.insertNodeAt(file, enclosingNode.getStart(file), jsDoc, { - suffix: newLineCharacter + newLineCharacter + file.text.slice(getPrecedingNonSpaceCharacterPosition(file.text, pos - 1), pos) - }); - } else { - changes.insertNodeBefore( - file, - enclosingNode, - jsDoc, - /*blankLineBetween*/ - true - ); - } - changes.replaceNode(file, selection, factory.createTypeReferenceNode(name, typeParameters.map((id) => factory.createTypeReferenceNode( - id.name, - /*typeArguments*/ - void 0 - )))); - } - function getEnclosingNode(node, isJS) { - return findAncestor(node, isStatement) || (isJS ? findAncestor(node, isJSDoc) : void 0); - } - var refactorName3, extractToTypeAliasAction, extractToInterfaceAction, extractToTypeDefAction; - var init_extractType = __esm({ - "src/services/refactors/extractType.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName3 = "Extract type"; - extractToTypeAliasAction = { - name: "Extract to type alias", - description: getLocaleSpecificMessage(Diagnostics.Extract_to_type_alias), - kind: "refactor.extract.type" - }; - extractToInterfaceAction = { - name: "Extract to interface", - description: getLocaleSpecificMessage(Diagnostics.Extract_to_interface), - kind: "refactor.extract.interface" - }; - extractToTypeDefAction = { - name: "Extract to typedef", - description: getLocaleSpecificMessage(Diagnostics.Extract_to_typedef), - kind: "refactor.extract.typedef" - }; - registerRefactor(refactorName3, { - kinds: [ - extractToTypeAliasAction.kind, - extractToInterfaceAction.kind, - extractToTypeDefAction.kind - ], - getAvailableActions: function getRefactorActionsToExtractType(context) { - const info = getRangeToExtract(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - return [{ - name: refactorName3, - description: getLocaleSpecificMessage(Diagnostics.Extract_type), - actions: info.isJS ? [extractToTypeDefAction] : append([extractToTypeAliasAction], info.typeElements && extractToInterfaceAction) - }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorName3, - description: getLocaleSpecificMessage(Diagnostics.Extract_type), - actions: [ - { ...extractToTypeDefAction, notApplicableReason: info.error }, - { ...extractToTypeAliasAction, notApplicableReason: info.error }, - { ...extractToInterfaceAction, notApplicableReason: info.error } - ] - }]; - } - return emptyArray; - }, - getEditsForAction: function getRefactorEditsToExtractType(context, actionName2) { - const { file } = context; - const info = getRangeToExtract(context); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected to find a range to extract"); - const name = getUniqueName("NewType", file); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (changes) => { - switch (actionName2) { - case extractToTypeAliasAction.name: - Debug.assert(!info.isJS, "Invalid actionName/JS combo"); - return doTypeAliasChange(changes, file, name, info); - case extractToTypeDefAction.name: - Debug.assert(info.isJS, "Invalid actionName/JS combo"); - return doTypedefChange(changes, context, file, name, info); - case extractToInterfaceAction.name: - Debug.assert(!info.isJS && !!info.typeElements, "Invalid actionName/JS combo"); - return doInterfaceChange(changes, file, name, info); - default: - Debug.fail("Unexpected action name"); - } - }); - const renameFilename = file.fileName; - const renameLocation = getRenameLocation( - edits, - renameFilename, - name, - /*preferLastLocation*/ - false - ); - return { edits, renameFilename, renameLocation }; - } - }); - } - }); - - // src/services/refactors/helpers.ts - function isRefactorErrorInfo(info) { - return info.error !== void 0; - } - function refactorKindBeginsWith(known, requested) { - if (!requested) - return true; - return known.substr(0, requested.length) === requested; - } - var init_helpers2 = __esm({ - "src/services/refactors/helpers.ts"() { - "use strict"; - } - }); - - // src/services/refactors/moveToNewFile.ts - function getRangeToMove(context) { - const { file } = context; - const range = createTextRangeFromSpan(getRefactorContextSpan(context)); - const { statements } = file; - const startNodeIndex = findIndex(statements, (s) => s.end > range.pos); - if (startNodeIndex === -1) - return void 0; - const startStatement = statements[startNodeIndex]; - if (isNamedDeclaration(startStatement) && startStatement.name && rangeContainsRange(startStatement.name, range)) { - return { toMove: [statements[startNodeIndex]], afterLast: statements[startNodeIndex + 1] }; - } - if (range.pos > startStatement.getStart(file)) - return void 0; - const afterEndNodeIndex = findIndex(statements, (s) => s.end > range.end, startNodeIndex); - if (afterEndNodeIndex !== -1 && (afterEndNodeIndex === 0 || statements[afterEndNodeIndex].getStart(file) < range.end)) - return void 0; - return { - toMove: statements.slice(startNodeIndex, afterEndNodeIndex === -1 ? statements.length : afterEndNodeIndex), - afterLast: afterEndNodeIndex === -1 ? void 0 : statements[afterEndNodeIndex] - }; - } - function doChange36(oldFile, program, toMove, changes, host, preferences) { - const checker = program.getTypeChecker(); - const usage = getUsageInfo(oldFile, toMove.all, checker); - 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.oldFileImportsFromNewFile, usage.movedSymbols), - extension, - currentDirectory, - host - ) - ) + extension; - changes.createNewFile(oldFile, newFilename, getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences)); - addNewFileToTsconfig(program, changes, oldFile.fileName, newFilename, hostGetCanonicalFileName(host)); - } - function getStatementsToMove(context) { - const rangeToMove = getRangeToMove(context); - if (rangeToMove === void 0) - return void 0; - const all = []; - const ranges = []; - const { toMove, afterLast } = rangeToMove; - getRangesWhere(toMove, isAllowedStatementToMove, (start, afterEndIndex) => { - for (let i = start; i < afterEndIndex; i++) - all.push(toMove[i]); - ranges.push({ first: toMove[start], afterLast }); - }); - return all.length === 0 ? void 0 : { all, ranges }; - } - function isAllowedStatementToMove(statement) { - return !isPureImport(statement) && !isPrologueDirective(statement); - } - function isPureImport(node) { - switch (node.kind) { - case 271 /* ImportDeclaration */: - return true; - case 270 /* ImportEqualsDeclaration */: - return !hasSyntacticModifier(node, 1 /* Export */); - case 242 /* VariableStatement */: - return node.declarationList.declarations.every((d) => !!d.initializer && isRequireCall( - d.initializer, - /*requireStringLiteralLikeArgument*/ - true - )); - default: - return false; - } - } - function addNewFileToTsconfig(program, changes, oldFileName, newFileNameWithExtension, getCanonicalFileName) { - const cfg = program.getCompilerOptions().configFile; - if (!cfg) - return; - const newFileAbsolutePath = normalizePath(combinePaths(oldFileName, "..", newFileNameWithExtension)); - 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) => 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); - } - } - function getNewStatementsAndRemoveFromOldFile(oldFile, usage, changes, toMove, program, host, newFilename, preferences) { - const checker = program.getTypeChecker(); - const prologueDirectives = takeWhile(oldFile.statements, isPrologueDirective); - if (oldFile.externalModuleIndicator === void 0 && oldFile.commonJsModuleIndicator === void 0 && usage.oldImportsNeededByNewFile.size() === 0) { - deleteMovedStatements(oldFile, toMove.ranges, changes); - return [...prologueDirectives, ...toMove.all]; - } - const useEsModuleSyntax = !!oldFile.externalModuleIndicator; - const quotePreference = getQuotePreference(oldFile, preferences); - const importsFromNewFile = createOldFileImportsFromNewFile(oldFile, usage.oldFileImportsFromNewFile, newFilename, program, host, useEsModuleSyntax, quotePreference); - if (importsFromNewFile) { - insertImports( - changes, - oldFile, - importsFromNewFile, - /*blankLineBetween*/ - true, - preferences - ); - } - deleteUnusedOldImports(oldFile, toMove.all, changes, usage.unusedImportsFromOldFile, checker); - deleteMovedStatements(oldFile, toMove.ranges, changes); - updateImportsInOtherFiles(changes, program, host, oldFile, usage.movedSymbols, newFilename, quotePreference); - const imports = getNewFileImportsAndAddExportInOldFile(oldFile, usage.oldImportsNeededByNewFile, usage.newFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference); - const body = addExports(oldFile, toMove.all, usage.oldFileImportsFromNewFile, useEsModuleSyntax); - if (imports.length && body.length) { - return [ - ...prologueDirectives, - ...imports, - 4 /* NewLineTrivia */, - ...body - ]; - } - return [ - ...prologueDirectives, - ...imports, - ...body - ]; - } - function deleteMovedStatements(sourceFile, moved, changes) { - for (const { first: first2, afterLast } of moved) { - changes.deleteNodeRangeExcludingEnd(sourceFile, first2, afterLast); - } - } - function deleteUnusedOldImports(oldFile, toMove, changes, toDelete, checker) { - for (const statement of oldFile.statements) { - if (contains(toMove, statement)) - continue; - forEachImportInStatement(statement, (i) => deleteUnusedImports(oldFile, i, changes, (name) => toDelete.has(checker.getSymbolAtLocation(name)))); - } - } - function updateImportsInOtherFiles(changes, program, host, oldFile, movedSymbols, newFilename, quotePreference) { - const checker = program.getTypeChecker(); - for (const sourceFile of program.getSourceFiles()) { - if (sourceFile === oldFile) - continue; - for (const statement of sourceFile.statements) { - forEachImportInStatement(statement, (importNode) => { - if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) - return; - const shouldMove = (name) => { - const symbol = isBindingElement(name.parent) ? getPropertySymbolFromBindingElement(checker, name.parent) : skipAlias(checker.getSymbolAtLocation(name), checker); - return !!symbol && movedSymbols.has(symbol); - }; - deleteUnusedImports(sourceFile, importNode, changes, shouldMove); - const pathToNewFileWithExtension = resolvePath(getDirectoryPath(oldFile.path), newFilename); - const newModuleSpecifier = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToNewFileWithExtension, createModuleSpecifierResolutionHost(program, host)); - const newImportDeclaration = filterImport(importNode, makeStringLiteral(newModuleSpecifier, quotePreference), shouldMove); - if (newImportDeclaration) - changes.insertNodeAfter(sourceFile, statement, newImportDeclaration); - const ns = getNamespaceLikeImport(importNode); - if (ns) - updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, ns, importNode, quotePreference); - }); - } - } - } - function getNamespaceLikeImport(node) { - switch (node.kind) { - case 271 /* ImportDeclaration */: - return node.importClause && node.importClause.namedBindings && node.importClause.namedBindings.kind === 273 /* NamespaceImport */ ? node.importClause.namedBindings.name : void 0; - case 270 /* ImportEqualsDeclaration */: - return node.name; - case 259 /* VariableDeclaration */: - return tryCast(node.name, isIdentifier); - default: - return Debug.assertNever(node, `Unexpected node kind ${node.kind}`); - } - } - function updateNamespaceLikeImport(changes, sourceFile, checker, movedSymbols, newModuleSpecifier, oldImportId, oldImportNode, quotePreference) { - const preferredNewNamespaceName = ts_codefix_exports.moduleSpecifierToValidIdentifier(newModuleSpecifier, 99 /* ESNext */); - let needUniqueName = false; - const toChange = []; - ts_FindAllReferences_exports.Core.eachSymbolReferenceInFile(oldImportId, checker, sourceFile, (ref) => { - if (!isPropertyAccessExpression(ref.parent)) - return; - needUniqueName = needUniqueName || !!checker.resolveName( - preferredNewNamespaceName, - ref, - 67108863 /* All */, - /*excludeGlobals*/ - true - ); - if (movedSymbols.has(checker.getSymbolAtLocation(ref.parent.name))) { - toChange.push(ref); - } - }); - if (toChange.length) { - const newNamespaceName = needUniqueName ? getUniqueName(preferredNewNamespaceName, sourceFile) : preferredNewNamespaceName; - for (const ref of toChange) { - changes.replaceNode(sourceFile, ref, factory.createIdentifier(newNamespaceName)); - } - changes.insertNodeAfter(sourceFile, oldImportNode, updateNamespaceLikeImportNode(oldImportNode, preferredNewNamespaceName, newModuleSpecifier, quotePreference)); - } - } - function updateNamespaceLikeImportNode(node, newNamespaceName, newModuleSpecifier, quotePreference) { - const newNamespaceId = factory.createIdentifier(newNamespaceName); - const newModuleString = makeStringLiteral(newModuleSpecifier, quotePreference); - switch (node.kind) { - case 271 /* ImportDeclaration */: - return factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause( - /*isTypeOnly*/ - false, - /*name*/ - void 0, - factory.createNamespaceImport(newNamespaceId) - ), - newModuleString, - /*assertClause*/ - void 0 - ); - case 270 /* ImportEqualsDeclaration */: - return factory.createImportEqualsDeclaration( - /*modifiers*/ - void 0, - /*isTypeOnly*/ - false, - newNamespaceId, - factory.createExternalModuleReference(newModuleString) - ); - case 259 /* VariableDeclaration */: - return factory.createVariableDeclaration( - newNamespaceId, - /*exclamationToken*/ - void 0, - /*type*/ - void 0, - createRequireCall(newModuleString) - ); - default: - return Debug.assertNever(node, `Unexpected node kind ${node.kind}`); - } - } - function moduleSpecifierFromImport(i) { - return i.kind === 271 /* ImportDeclaration */ ? i.moduleSpecifier : i.kind === 270 /* ImportEqualsDeclaration */ ? i.moduleReference.expression : i.initializer.arguments[0]; - } - function forEachImportInStatement(statement, cb) { - if (isImportDeclaration(statement)) { - if (isStringLiteral(statement.moduleSpecifier)) - cb(statement); - } else if (isImportEqualsDeclaration(statement)) { - if (isExternalModuleReference(statement.moduleReference) && isStringLiteralLike(statement.moduleReference.expression)) { - cb(statement); - } - } else if (isVariableStatement(statement)) { - for (const decl of statement.declarationList.declarations) { - if (decl.initializer && isRequireCall( - decl.initializer, - /*requireStringLiteralLikeArgument*/ - true - )) { - cb(decl); - } - } - } - } - function createOldFileImportsFromNewFile(sourceFile, newFileNeedExport, newFileNameWithExtension, program, host, useEs6Imports, quotePreference) { - let defaultImport; - const imports = []; - newFileNeedExport.forEach((symbol) => { - if (symbol.escapedName === "default" /* Default */) { - defaultImport = factory.createIdentifier(symbolNameNoDefault(symbol)); - } else { - imports.push(symbol.name); - } - }); - return makeImportOrRequire(sourceFile, defaultImport, imports, newFileNameWithExtension, program, host, useEs6Imports, quotePreference); - } - function makeImportOrRequire(sourceFile, defaultImport, imports, newFileNameWithExtension, program, host, useEs6Imports, quotePreference) { - const pathToNewFile = resolvePath(getDirectoryPath(sourceFile.path), newFileNameWithExtension); - const pathToNewFileWithCorrectExtension = getModuleSpecifier(program.getCompilerOptions(), sourceFile, sourceFile.path, pathToNewFile, createModuleSpecifierResolutionHost(program, host)); - if (useEs6Imports) { - const specifiers = imports.map((i) => factory.createImportSpecifier( - /*isTypeOnly*/ - false, - /*propertyName*/ - void 0, - factory.createIdentifier(i) - )); - return makeImportIfNecessary(defaultImport, specifiers, pathToNewFileWithCorrectExtension, quotePreference); - } else { - Debug.assert(!defaultImport, "No default import should exist"); - const bindingElements = imports.map((i) => factory.createBindingElement( - /*dotDotDotToken*/ - void 0, - /*propertyName*/ - void 0, - i - )); - return bindingElements.length ? makeVariableStatement( - factory.createObjectBindingPattern(bindingElements), - /*type*/ - void 0, - createRequireCall(makeStringLiteral(pathToNewFileWithCorrectExtension, quotePreference)) - ) : void 0; - } - } - function makeVariableStatement(name, type, initializer, flags = 2 /* Const */) { - return factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([factory.createVariableDeclaration( - name, - /*exclamationToken*/ - void 0, - type, - initializer - )], flags) - ); - } - function createRequireCall(moduleSpecifier) { - return factory.createCallExpression( - factory.createIdentifier("require"), - /*typeArguments*/ - void 0, - [moduleSpecifier] - ); - } - function addExports(sourceFile, toMove, needExport, useEs6Exports) { - return flatMap(toMove, (statement) => { - if (isTopLevelDeclarationStatement(statement) && !isExported(sourceFile, statement, useEs6Exports) && forEachTopLevelDeclaration(statement, (d) => { - var _a; - return needExport.has(Debug.checkDefined((_a = tryCast(d, canHaveSymbol)) == null ? void 0 : _a.symbol)); - })) { - const exports = addExport(statement, useEs6Exports); - if (exports) - return exports; - } - return statement; - }); - } - function deleteUnusedImports(sourceFile, importDecl, changes, isUnused) { - switch (importDecl.kind) { - case 271 /* ImportDeclaration */: - deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused); - break; - case 270 /* ImportEqualsDeclaration */: - if (isUnused(importDecl.name)) { - changes.delete(sourceFile, importDecl); - } - break; - case 259 /* VariableDeclaration */: - deleteUnusedImportsInVariableDeclaration(sourceFile, importDecl, changes, isUnused); - break; - default: - Debug.assertNever(importDecl, `Unexpected import decl kind ${importDecl.kind}`); - } - } - function deleteUnusedImportsInDeclaration(sourceFile, importDecl, changes, isUnused) { - if (!importDecl.importClause) - return; - const { name, namedBindings } = importDecl.importClause; - const defaultUnused = !name || isUnused(name); - const namedBindingsUnused = !namedBindings || (namedBindings.kind === 273 /* NamespaceImport */ ? isUnused(namedBindings.name) : namedBindings.elements.length !== 0 && namedBindings.elements.every((e) => isUnused(e.name))); - if (defaultUnused && namedBindingsUnused) { - changes.delete(sourceFile, importDecl); - } else { - if (name && defaultUnused) { - changes.delete(sourceFile, name); - } - if (namedBindings) { - if (namedBindingsUnused) { - changes.replaceNode( - sourceFile, - importDecl.importClause, - factory.updateImportClause( - importDecl.importClause, - importDecl.importClause.isTypeOnly, - name, - /*namedBindings*/ - void 0 - ) - ); - } else if (namedBindings.kind === 274 /* NamedImports */) { - for (const element of namedBindings.elements) { - if (isUnused(element.name)) - changes.delete(sourceFile, element); - } - } - } - } - } - function deleteUnusedImportsInVariableDeclaration(sourceFile, varDecl, changes, isUnused) { - const { name } = varDecl; - switch (name.kind) { - case 80 /* 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 - ); - } else { - changes.delete(sourceFile, name); - } - } - break; - case 206 /* ArrayBindingPattern */: - break; - case 205 /* 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 - ); - } else { - for (const element of name.elements) { - if (isIdentifier(element.name) && isUnused(element.name)) { - changes.delete(sourceFile, element.name); - } - } - } - break; - } - } - function getNewFileImportsAndAddExportInOldFile(oldFile, importsToCopy, newFileImportsFromOldFile, changes, checker, program, host, useEsModuleSyntax, quotePreference) { - const copiedOldImports = []; - for (const oldStatement of oldFile.statements) { - forEachImportInStatement(oldStatement, (i) => { - append(copiedOldImports, filterImport(i, moduleSpecifierFromImport(i), (name) => importsToCopy.has(checker.getSymbolAtLocation(name)))); - }); - } - let oldFileDefault; - const oldFileNamedImports = []; - const markSeenTop = nodeSeenTracker(); - newFileImportsFromOldFile.forEach((symbol) => { - if (!symbol.declarations) { - return; - } - for (const decl of symbol.declarations) { - if (!isTopLevelDeclaration(decl)) - continue; - const name = nameOfTopLevelDeclaration(decl); - if (!name) - continue; - const top = getTopLevelDeclarationStatement(decl); - if (markSeenTop(top)) { - addExportToChanges(oldFile, top, name, changes, useEsModuleSyntax); - } - if (hasSyntacticModifier(decl, 1024 /* Default */)) { - oldFileDefault = name; - } else { - oldFileNamedImports.push(name.text); - } - } - }); - append(copiedOldImports, makeImportOrRequire(oldFile, oldFileDefault, oldFileNamedImports, getBaseFileName(oldFile.fileName), program, host, useEsModuleSyntax, quotePreference)); - return copiedOldImports; - } - function makeUniqueFilename(proposedFilename, extension, inDirectory, host) { - let newFilename = proposedFilename; - for (let i = 1; ; i++) { - const name = combinePaths(inDirectory, newFilename + extension); - if (!host.fileExists(name)) - return newFilename; - newFilename = `${proposedFilename}.${i}`; - } - } - function inferNewFilename(importsFromNewFile, movedSymbols) { - return importsFromNewFile.forEachEntry(symbolNameNoDefault) || movedSymbols.forEachEntry(symbolNameNoDefault) || "newFile"; - } - function getUsageInfo(oldFile, toMove, checker) { - const movedSymbols = new SymbolSet(); - const oldImportsNeededByNewFile = new SymbolSet(); - const newFileImportsFromOldFile = new SymbolSet(); - const containsJsx = find(toMove, (statement) => !!(statement.transformFlags & 2 /* ContainsJsx */)); - const jsxNamespaceSymbol = getJsxNamespaceSymbol(containsJsx); - if (jsxNamespaceSymbol) { - oldImportsNeededByNewFile.add(jsxNamespaceSymbol); - } - for (const statement of toMove) { - forEachTopLevelDeclaration(statement, (decl) => { - movedSymbols.add(Debug.checkDefined(isExpressionStatement(decl) ? checker.getSymbolAtLocation(decl.expression.left) : decl.symbol, "Need a symbol here")); - }); - } - for (const statement of toMove) { - forEachReference(statement, checker, (symbol) => { - if (!symbol.declarations) - return; - for (const decl of symbol.declarations) { - if (isInImport(decl)) { - oldImportsNeededByNewFile.add(symbol); - } else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) { - newFileImportsFromOldFile.add(symbol); - } - } - }); - } - const unusedImportsFromOldFile = oldImportsNeededByNewFile.clone(); - const oldFileImportsFromNewFile = new SymbolSet(); - for (const statement of oldFile.statements) { - if (contains(toMove, statement)) - continue; - if (jsxNamespaceSymbol && !!(statement.transformFlags & 2 /* ContainsJsx */)) { - unusedImportsFromOldFile.delete(jsxNamespaceSymbol); - } - forEachReference(statement, checker, (symbol) => { - if (movedSymbols.has(symbol)) - oldFileImportsFromNewFile.add(symbol); - unusedImportsFromOldFile.delete(symbol); - }); - } - return { movedSymbols, newFileImportsFromOldFile, oldFileImportsFromNewFile, oldImportsNeededByNewFile, unusedImportsFromOldFile }; - function getJsxNamespaceSymbol(containsJsx2) { - if (containsJsx2 === void 0) { - return void 0; - } - const jsxNamespace = checker.getJsxNamespace(containsJsx2); - const jsxNamespaceSymbol2 = checker.resolveName( - jsxNamespace, - containsJsx2, - 1920 /* Namespace */, - /*excludeGlobals*/ - true - ); - return !!jsxNamespaceSymbol2 && some(jsxNamespaceSymbol2.declarations, isInImport) ? jsxNamespaceSymbol2 : void 0; - } - } - function isInImport(decl) { - switch (decl.kind) { - case 270 /* ImportEqualsDeclaration */: - case 275 /* ImportSpecifier */: - case 272 /* ImportClause */: - case 273 /* NamespaceImport */: - return true; - case 259 /* VariableDeclaration */: - return isVariableDeclarationInImport(decl); - case 207 /* BindingElement */: - return isVariableDeclaration(decl.parent.parent) && isVariableDeclarationInImport(decl.parent.parent); - default: - return false; - } - } - function isVariableDeclarationInImport(decl) { - return isSourceFile(decl.parent.parent.parent) && !!decl.initializer && isRequireCall( - decl.initializer, - /*requireStringLiteralLikeArgument*/ - true - ); - } - function filterImport(i, moduleSpecifier, keep) { - switch (i.kind) { - case 271 /* ImportDeclaration */: { - const clause = i.importClause; - if (!clause) - return void 0; - const defaultImport = clause.name && keep(clause.name) ? clause.name : void 0; - const namedBindings = clause.namedBindings && filterNamedBindings(clause.namedBindings, keep); - return defaultImport || namedBindings ? factory.createImportDeclaration( - /*modifiers*/ - void 0, - factory.createImportClause(clause.isTypeOnly, defaultImport, namedBindings), - moduleSpecifier, - /*assertClause*/ - void 0 - ) : void 0; - } - case 270 /* ImportEqualsDeclaration */: - return keep(i.name) ? i : void 0; - case 259 /* VariableDeclaration */: { - const name = filterBindingName(i.name, keep); - return name ? makeVariableStatement(name, i.type, createRequireCall(moduleSpecifier), i.parent.flags) : void 0; - } - default: - return Debug.assertNever(i, `Unexpected import kind ${i.kind}`); - } - } - function filterNamedBindings(namedBindings, keep) { - if (namedBindings.kind === 273 /* NamespaceImport */) { - return keep(namedBindings.name) ? namedBindings : void 0; - } else { - const newElements = namedBindings.elements.filter((e) => keep(e.name)); - return newElements.length ? factory.createNamedImports(newElements) : void 0; - } - } - function filterBindingName(name, keep) { - switch (name.kind) { - case 80 /* Identifier */: - return keep(name) ? name : void 0; - case 206 /* ArrayBindingPattern */: - return name; - case 205 /* ObjectBindingPattern */: { - const newElements = name.elements.filter((prop) => prop.propertyName || !isIdentifier(prop.name) || keep(prop.name)); - return newElements.length ? factory.createObjectBindingPattern(newElements) : void 0; - } - } - } - function forEachReference(node, checker, onReference) { - node.forEachChild(function cb(node2) { - if (isIdentifier(node2) && !isDeclarationName(node2)) { - const sym = checker.getSymbolAtLocation(node2); - if (sym) - onReference(sym); - } else { - node2.forEachChild(cb); - } - }); - } - function isTopLevelDeclaration(node) { - return isNonVariableTopLevelDeclaration(node) && isSourceFile(node.parent) || isVariableDeclaration(node) && isSourceFile(node.parent.parent.parent); - } - function sourceFileOfTopLevelDeclaration(node) { - return isVariableDeclaration(node) ? node.parent.parent.parent : node.parent; - } - function isTopLevelDeclarationStatement(node) { - Debug.assert(isSourceFile(node.parent), "Node parent should be a SourceFile"); - return isNonVariableTopLevelDeclaration(node) || isVariableStatement(node); - } - function isNonVariableTopLevelDeclaration(node) { - switch (node.kind) { - case 261 /* FunctionDeclaration */: - case 262 /* ClassDeclaration */: - case 266 /* ModuleDeclaration */: - case 265 /* EnumDeclaration */: - case 264 /* TypeAliasDeclaration */: - case 263 /* InterfaceDeclaration */: - case 270 /* ImportEqualsDeclaration */: - return true; - default: - return false; - } - } - function forEachTopLevelDeclaration(statement, cb) { - switch (statement.kind) { - case 261 /* FunctionDeclaration */: - case 262 /* ClassDeclaration */: - case 266 /* ModuleDeclaration */: - case 265 /* EnumDeclaration */: - case 264 /* TypeAliasDeclaration */: - case 263 /* InterfaceDeclaration */: - case 270 /* ImportEqualsDeclaration */: - return cb(statement); - case 242 /* VariableStatement */: - return firstDefined(statement.declarationList.declarations, (decl) => forEachTopLevelDeclarationInBindingName(decl.name, cb)); - case 243 /* ExpressionStatement */: { - const { expression } = statement; - return isBinaryExpression(expression) && getAssignmentDeclarationKind(expression) === 1 /* ExportsProperty */ ? cb(statement) : void 0; - } - } - } - function forEachTopLevelDeclarationInBindingName(name, cb) { - switch (name.kind) { - case 80 /* Identifier */: - return cb(cast(name.parent, (x) => isVariableDeclaration(x) || isBindingElement(x))); - case 206 /* ArrayBindingPattern */: - case 205 /* ObjectBindingPattern */: - return firstDefined(name.elements, (em) => isOmittedExpression(em) ? void 0 : forEachTopLevelDeclarationInBindingName(em.name, cb)); - default: - return Debug.assertNever(name, `Unexpected name kind ${name.kind}`); - } - } - function nameOfTopLevelDeclaration(d) { - return isExpressionStatement(d) ? tryCast(d.expression.left.name, isIdentifier) : tryCast(d.name, isIdentifier); - } - function getTopLevelDeclarationStatement(d) { - switch (d.kind) { - case 259 /* VariableDeclaration */: - return d.parent.parent; - case 207 /* BindingElement */: - return getTopLevelDeclarationStatement( - cast(d.parent.parent, (p) => isVariableDeclaration(p) || isBindingElement(p)) - ); - default: - return d; - } - } - function addExportToChanges(sourceFile, decl, name, changes, useEs6Exports) { - if (isExported(sourceFile, decl, useEs6Exports, name)) - return; - if (useEs6Exports) { - if (!isExpressionStatement(decl)) - changes.insertExportModifier(sourceFile, decl); - } else { - const names = getNamesToExportInCommonJS(decl); - if (names.length !== 0) - changes.insertNodesAfter(sourceFile, decl, names.map(createExportAssignment)); - } - } - function isExported(sourceFile, decl, useEs6Exports, name) { - var _a; - if (useEs6Exports) { - return !isExpressionStatement(decl) && hasSyntacticModifier(decl, 1 /* Export */) || !!(name && ((_a = sourceFile.symbol.exports) == null ? void 0 : _a.has(name.escapedText))); - } - return !!sourceFile.symbol && !!sourceFile.symbol.exports && getNamesToExportInCommonJS(decl).some((name2) => sourceFile.symbol.exports.has(escapeLeadingUnderscores(name2))); - } - function addExport(decl, useEs6Exports) { - return useEs6Exports ? [addEs6Export(decl)] : addCommonjsExport(decl); - } - function addEs6Export(d) { - const modifiers = canHaveModifiers(d) ? concatenate([factory.createModifier(95 /* ExportKeyword */)], getModifiers(d)) : void 0; - switch (d.kind) { - case 261 /* FunctionDeclaration */: - return factory.updateFunctionDeclaration(d, modifiers, d.asteriskToken, d.name, d.typeParameters, d.parameters, d.type, d.body); - case 262 /* ClassDeclaration */: - const decorators = canHaveDecorators(d) ? getDecorators(d) : void 0; - return factory.updateClassDeclaration(d, concatenate(decorators, modifiers), d.name, d.typeParameters, d.heritageClauses, d.members); - case 242 /* VariableStatement */: - return factory.updateVariableStatement(d, modifiers, d.declarationList); - case 266 /* ModuleDeclaration */: - return factory.updateModuleDeclaration(d, modifiers, d.name, d.body); - case 265 /* EnumDeclaration */: - return factory.updateEnumDeclaration(d, modifiers, d.name, d.members); - case 264 /* TypeAliasDeclaration */: - return factory.updateTypeAliasDeclaration(d, modifiers, d.name, d.typeParameters, d.type); - case 263 /* InterfaceDeclaration */: - return factory.updateInterfaceDeclaration(d, modifiers, d.name, d.typeParameters, d.heritageClauses, d.members); - case 270 /* ImportEqualsDeclaration */: - return factory.updateImportEqualsDeclaration(d, modifiers, d.isTypeOnly, d.name, d.moduleReference); - case 243 /* ExpressionStatement */: - return Debug.fail(); - default: - return Debug.assertNever(d, `Unexpected declaration kind ${d.kind}`); - } - } - function addCommonjsExport(decl) { - return [decl, ...getNamesToExportInCommonJS(decl).map(createExportAssignment)]; - } - function getNamesToExportInCommonJS(decl) { - switch (decl.kind) { - case 261 /* FunctionDeclaration */: - case 262 /* ClassDeclaration */: - return [decl.name.text]; - case 242 /* VariableStatement */: - return mapDefined(decl.declarationList.declarations, (d) => isIdentifier(d.name) ? d.name.text : void 0); - case 266 /* ModuleDeclaration */: - case 265 /* EnumDeclaration */: - case 264 /* TypeAliasDeclaration */: - case 263 /* InterfaceDeclaration */: - case 270 /* ImportEqualsDeclaration */: - return emptyArray; - case 243 /* ExpressionStatement */: - return Debug.fail("Can't export an ExpressionStatement"); - default: - return Debug.assertNever(decl, `Unexpected decl kind ${decl.kind}`); - } - } - function createExportAssignment(name) { - return factory.createExpressionStatement( - factory.createBinaryExpression( - factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(name)), - 64 /* EqualsToken */, - factory.createIdentifier(name) - ) - ); - } - var refactorName4, description, moveToNewFileAction, SymbolSet; - var init_moveToNewFile = __esm({ - "src/services/refactors/moveToNewFile.ts"() { - "use strict"; - init_moduleSpecifiers(); - init_ts4(); - init_ts_refactor(); - refactorName4 = "Move to a new file"; - description = getLocaleSpecificMessage(Diagnostics.Move_to_a_new_file); - moveToNewFileAction = { - name: refactorName4, - description, - kind: "refactor.move.newFile" - }; - registerRefactor(refactorName4, { - kinds: [moveToNewFileAction.kind], - getAvailableActions: function getRefactorActionsToMoveToNewFile(context) { - const statements = getStatementsToMove(context); - if (context.preferences.allowTextChangesInNewFiles && statements) { - return [{ name: refactorName4, description, actions: [moveToNewFileAction] }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorName4, - description, - actions: [{ ...moveToNewFileAction, notApplicableReason: getLocaleSpecificMessage(Diagnostics.Selection_is_not_a_valid_statement_or_statements) }] - }]; - } - return emptyArray; - }, - getEditsForAction: function getRefactorEditsToMoveToNewFile(context, actionName2) { - Debug.assert(actionName2 === refactorName4, "Wrong refactor invoked"); - const statements = Debug.checkDefined(getStatementsToMove(context)); - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange36(context.file, context.program, statements, t, context.host, context.preferences)); - return { edits, renameFilename: void 0, renameLocation: void 0 }; - } - }); - SymbolSet = class { - constructor() { - this.map = /* @__PURE__ */ new Map(); - } - add(symbol) { - this.map.set(String(getSymbolId(symbol)), symbol); - } - has(symbol) { - return this.map.has(String(getSymbolId(symbol))); - } - delete(symbol) { - this.map.delete(String(getSymbolId(symbol))); - } - forEach(cb) { - this.map.forEach(cb); - } - forEachEntry(cb) { - return forEachEntry(this.map, cb); - } - clone() { - const clone2 = new SymbolSet(); - copyEntries(this.map, clone2.map); - return clone2; - } - size() { - return this.map.size; - } - }; - } - }); - - // src/services/refactors/convertOverloadListToSingleSignature.ts - function getRefactorActionsToConvertOverloadsToOneSignature(context) { - const { file, startPosition, program } = context; - const info = getConvertableOverloadListAtPosition(file, startPosition, program); - if (!info) - return emptyArray; - return [{ - name: refactorName5, - description: refactorDescription, - actions: [functionOverloadAction] - }]; - } - function getRefactorEditsToConvertOverloadsToOneSignature(context) { - const { file, startPosition, program } = context; - const signatureDecls = getConvertableOverloadListAtPosition(file, startPosition, program); - if (!signatureDecls) - return void 0; - const checker = program.getTypeChecker(); - const lastDeclaration = signatureDecls[signatureDecls.length - 1]; - let updated = lastDeclaration; - switch (lastDeclaration.kind) { - case 172 /* MethodSignature */: { - updated = factory.updateMethodSignature( - lastDeclaration, - lastDeclaration.modifiers, - lastDeclaration.name, - lastDeclaration.questionToken, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type - ); - break; - } - case 173 /* MethodDeclaration */: { - updated = factory.updateMethodDeclaration( - lastDeclaration, - lastDeclaration.modifiers, - lastDeclaration.asteriskToken, - lastDeclaration.name, - lastDeclaration.questionToken, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type, - lastDeclaration.body - ); - break; - } - case 178 /* CallSignature */: { - updated = factory.updateCallSignature( - lastDeclaration, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type - ); - break; - } - case 175 /* Constructor */: { - updated = factory.updateConstructorDeclaration( - lastDeclaration, - lastDeclaration.modifiers, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.body - ); - break; - } - case 179 /* ConstructSignature */: { - updated = factory.updateConstructSignature( - lastDeclaration, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type - ); - break; - } - case 261 /* FunctionDeclaration */: { - updated = factory.updateFunctionDeclaration( - lastDeclaration, - lastDeclaration.modifiers, - lastDeclaration.asteriskToken, - lastDeclaration.name, - lastDeclaration.typeParameters, - getNewParametersForCombinedSignature(signatureDecls), - lastDeclaration.type, - lastDeclaration.body - ); - break; - } - default: - return Debug.failBadSyntaxKind(lastDeclaration, "Unhandled signature kind in overload list conversion refactoring"); - } - if (updated === lastDeclaration) { - return; - } - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => { - t.replaceNodeRange(file, signatureDecls[0], signatureDecls[signatureDecls.length - 1], updated); - }); - return { renameFilename: void 0, renameLocation: void 0, edits }; - function getNewParametersForCombinedSignature(signatureDeclarations) { - const lastSig = signatureDeclarations[signatureDeclarations.length - 1]; - if (isFunctionLikeDeclaration(lastSig) && lastSig.body) { - signatureDeclarations = signatureDeclarations.slice(0, signatureDeclarations.length - 1); - } - return factory.createNodeArray([ - factory.createParameterDeclaration( - /*modifiers*/ - void 0, - factory.createToken(26 /* DotDotDotToken */), - "args", - /*questionToken*/ - void 0, - factory.createUnionTypeNode(map(signatureDeclarations, convertSignatureParametersToTuple)) - ) - ]); - } - function convertSignatureParametersToTuple(decl) { - const members = map(decl.parameters, convertParameterToNamedTupleMember); - return setEmitFlags(factory.createTupleTypeNode(members), some(members, (m) => !!length(getSyntheticLeadingComments(m))) ? 0 /* None */ : 1 /* SingleLine */); - } - function convertParameterToNamedTupleMember(p) { - Debug.assert(isIdentifier(p.name)); - const result = setTextRange(factory.createNamedTupleMember( - p.dotDotDotToken, - p.name, - p.questionToken, - p.type || factory.createKeywordTypeNode(133 /* AnyKeyword */) - ), p); - const parameterDocComment = p.symbol && p.symbol.getDocumentationComment(checker); - if (parameterDocComment) { - const newComment = displayPartsToString(parameterDocComment); - if (newComment.length) { - setSyntheticLeadingComments(result, [{ - text: `* -${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} - `, - kind: 3 /* MultiLineCommentTrivia */, - pos: -1, - end: -1, - hasTrailingNewLine: true, - hasLeadingNewline: true - }]); - } - } - return result; - } - } - function isConvertableSignatureDeclaration(d) { - switch (d.kind) { - case 172 /* MethodSignature */: - case 173 /* MethodDeclaration */: - case 178 /* CallSignature */: - case 175 /* Constructor */: - case 179 /* ConstructSignature */: - case 261 /* FunctionDeclaration */: - return true; - } - return false; - } - function getConvertableOverloadListAtPosition(file, startPosition, program) { - const node = getTokenAtPosition(file, startPosition); - const containingDecl = findAncestor(node, isConvertableSignatureDeclaration); - if (!containingDecl) { - return; - } - if (isFunctionLikeDeclaration(containingDecl) && containingDecl.body && rangeContainsPosition(containingDecl.body, startPosition)) { - return; - } - const checker = program.getTypeChecker(); - const signatureSymbol = containingDecl.symbol; - if (!signatureSymbol) { - return; - } - const decls = signatureSymbol.declarations; - if (length(decls) <= 1) { - return; - } - if (!every(decls, (d) => getSourceFileOfNode(d) === file)) { - return; - } - if (!isConvertableSignatureDeclaration(decls[0])) { - return; - } - const kindOne = decls[0].kind; - if (!every(decls, (d) => d.kind === kindOne)) { - return; - } - const signatureDecls = decls; - if (some(signatureDecls, (d) => !!d.typeParameters || some(d.parameters, (p) => !!p.modifiers || !isIdentifier(p.name)))) { - return; - } - const signatures = mapDefined(signatureDecls, (d) => checker.getSignatureFromDeclaration(d)); - if (length(signatures) !== length(decls)) { - return; - } - const returnOne = checker.getReturnTypeOfSignature(signatures[0]); - if (!every(signatures, (s) => checker.getReturnTypeOfSignature(s) === returnOne)) { - return; - } - return signatureDecls; - } - var refactorName5, refactorDescription, functionOverloadAction; - var init_convertOverloadListToSingleSignature = __esm({ - "src/services/refactors/convertOverloadListToSingleSignature.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName5 = "Convert overload list to single signature"; - refactorDescription = Diagnostics.Convert_overload_list_to_single_signature.message; - functionOverloadAction = { - name: refactorName5, - description: refactorDescription, - kind: "refactor.rewrite.function.overloadList" - }; - registerRefactor(refactorName5, { - kinds: [functionOverloadAction.kind], - getEditsForAction: getRefactorEditsToConvertOverloadsToOneSignature, - getAvailableActions: getRefactorActionsToConvertOverloadsToOneSignature - }); - } - }); - - // src/services/refactors/addOrRemoveBracesToArrowFunction.ts - function getRefactorActionsToRemoveFunctionBraces(context) { - const { file, startPosition, triggerReason } = context; - const info = getConvertibleArrowFunctionAtPosition(file, startPosition, triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - return [{ - name: refactorName6, - description: refactorDescription2, - actions: [ - info.addBraces ? addBracesAction : removeBracesAction - ] - }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorName6, - description: refactorDescription2, - actions: [ - { ...addBracesAction, notApplicableReason: info.error }, - { ...removeBracesAction, notApplicableReason: info.error } - ] - }]; - } - return emptyArray; - } - function getRefactorEditsToRemoveFunctionBraces(context, actionName2) { - const { file, startPosition } = context; - const info = getConvertibleArrowFunctionAtPosition(file, startPosition); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const { expression, returnStatement, func } = info; - let body; - if (actionName2 === addBracesAction.name) { - const returnStatement2 = factory.createReturnStatement(expression); - body = factory.createBlock( - [returnStatement2], - /*multiLine*/ - true - ); - copyLeadingComments( - expression, - returnStatement2, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - true - ); - } else if (actionName2 === removeBracesAction.name && returnStatement) { - const actualExpression = expression || factory.createVoidZero(); - body = needsParentheses(actualExpression) ? factory.createParenthesizedExpression(actualExpression) : actualExpression; - copyTrailingAsLeadingComments( - returnStatement, - body, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - copyLeadingComments( - returnStatement, - body, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - copyTrailingComments( - returnStatement, - body, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - } else { - Debug.fail("invalid action"); - } - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => { - t.replaceNode(file, func.body, body); - }); - return { renameFilename: void 0, renameLocation: void 0, edits }; - } - function getConvertibleArrowFunctionAtPosition(file, startPosition, considerFunctionBodies = true, kind) { - const node = getTokenAtPosition(file, startPosition); - const func = getContainingFunction(node); - if (!func) { - return { - error: getLocaleSpecificMessage(Diagnostics.Could_not_find_a_containing_arrow_function) - }; - } - if (!isArrowFunction(func)) { - return { - error: getLocaleSpecificMessage(Diagnostics.Containing_function_is_not_an_arrow_function) - }; - } - if (!rangeContainsRange(func, node) || rangeContainsRange(func.body, node) && !considerFunctionBodies) { - return void 0; - } - if (refactorKindBeginsWith(addBracesAction.kind, kind) && isExpression(func.body)) { - return { func, addBraces: true, expression: func.body }; - } else if (refactorKindBeginsWith(removeBracesAction.kind, kind) && isBlock(func.body) && func.body.statements.length === 1) { - const firstStatement = first(func.body.statements); - if (isReturnStatement(firstStatement)) { - return { func, addBraces: false, expression: firstStatement.expression, returnStatement: firstStatement }; - } - } - return void 0; - } - var refactorName6, refactorDescription2, addBracesAction, removeBracesAction; - var init_addOrRemoveBracesToArrowFunction = __esm({ - "src/services/refactors/addOrRemoveBracesToArrowFunction.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName6 = "Add or remove braces in an arrow function"; - refactorDescription2 = Diagnostics.Add_or_remove_braces_in_an_arrow_function.message; - addBracesAction = { - name: "Add braces to arrow function", - description: Diagnostics.Add_braces_to_arrow_function.message, - kind: "refactor.rewrite.arrow.braces.add" - }; - removeBracesAction = { - name: "Remove braces from arrow function", - description: Diagnostics.Remove_braces_from_arrow_function.message, - kind: "refactor.rewrite.arrow.braces.remove" - }; - registerRefactor(refactorName6, { - kinds: [removeBracesAction.kind], - getEditsForAction: getRefactorEditsToRemoveFunctionBraces, - getAvailableActions: getRefactorActionsToRemoveFunctionBraces - }); - } - }); - - // src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts - var ts_refactor_addOrRemoveBracesToArrowFunction_exports = {}; - var init_ts_refactor_addOrRemoveBracesToArrowFunction = __esm({ - "src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts"() { - "use strict"; - init_convertOverloadListToSingleSignature(); - init_addOrRemoveBracesToArrowFunction(); - } - }); - - // src/services/refactors/convertArrowFunctionOrFunctionExpression.ts - function getRefactorActionsToConvertFunctionExpressions(context) { - const { file, startPosition, program, kind } = context; - const info = getFunctionInfo(file, startPosition, program); - if (!info) - return emptyArray; - const { selectedVariableDeclaration, func } = info; - const possibleActions = []; - const errors = []; - if (refactorKindBeginsWith(toNamedFunctionAction.kind, kind)) { - const error = selectedVariableDeclaration || isArrowFunction(func) && isVariableDeclaration(func.parent) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_named_function); - if (error) { - errors.push({ ...toNamedFunctionAction, notApplicableReason: error }); - } else { - possibleActions.push(toNamedFunctionAction); - } - } - if (refactorKindBeginsWith(toAnonymousFunctionAction.kind, kind)) { - const error = !selectedVariableDeclaration && isArrowFunction(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_anonymous_function); - if (error) { - errors.push({ ...toAnonymousFunctionAction, notApplicableReason: error }); - } else { - possibleActions.push(toAnonymousFunctionAction); - } - } - if (refactorKindBeginsWith(toArrowFunctionAction.kind, kind)) { - const error = isFunctionExpression(func) ? void 0 : getLocaleSpecificMessage(Diagnostics.Could_not_convert_to_arrow_function); - if (error) { - errors.push({ ...toArrowFunctionAction, notApplicableReason: error }); - } else { - possibleActions.push(toArrowFunctionAction); - } - } - return [{ - name: refactorName7, - description: refactorDescription3, - actions: possibleActions.length === 0 && context.preferences.provideRefactorNotApplicableReason ? errors : possibleActions - }]; - } - function getRefactorEditsToConvertFunctionExpressions(context, actionName2) { - const { file, startPosition, program } = context; - const info = getFunctionInfo(file, startPosition, program); - if (!info) - return void 0; - const { func } = info; - const edits = []; - switch (actionName2) { - case toAnonymousFunctionAction.name: - edits.push(...getEditInfoForConvertToAnonymousFunction(context, func)); - break; - case toNamedFunctionAction.name: - const variableInfo = getVariableInfo(func); - if (!variableInfo) - return void 0; - edits.push(...getEditInfoForConvertToNamedFunction(context, func, variableInfo)); - break; - case toArrowFunctionAction.name: - if (!isFunctionExpression(func)) - return void 0; - edits.push(...getEditInfoForConvertToArrowFunction(context, func)); - break; - default: - return Debug.fail("invalid action"); - } - return { renameFilename: void 0, renameLocation: void 0, edits }; - } - function containingThis(node) { - let containsThis = false; - node.forEachChild(function checkThis(child) { - if (isThis(child)) { - containsThis = true; - return; - } - if (!isClassLike(child) && !isFunctionDeclaration(child) && !isFunctionExpression(child)) { - forEachChild(child, checkThis); - } - }); - return containsThis; - } - function getFunctionInfo(file, startPosition, program) { - const token = getTokenAtPosition(file, startPosition); - const typeChecker = program.getTypeChecker(); - const func = tryGetFunctionFromVariableDeclaration(file, typeChecker, token.parent); - if (func && !containingThis(func.body) && !typeChecker.containsArgumentsReference(func)) { - return { selectedVariableDeclaration: true, func }; - } - const maybeFunc = getContainingFunction(token); - if (maybeFunc && (isFunctionExpression(maybeFunc) || isArrowFunction(maybeFunc)) && !rangeContainsRange(maybeFunc.body, token) && !containingThis(maybeFunc.body) && !typeChecker.containsArgumentsReference(maybeFunc)) { - if (isFunctionExpression(maybeFunc) && isFunctionReferencedInFile(file, typeChecker, maybeFunc)) - return void 0; - return { selectedVariableDeclaration: false, func: maybeFunc }; - } - return void 0; - } - function isSingleVariableDeclaration(parent2) { - return isVariableDeclaration(parent2) || isVariableDeclarationList(parent2) && parent2.declarations.length === 1; - } - function tryGetFunctionFromVariableDeclaration(sourceFile, typeChecker, parent2) { - if (!isSingleVariableDeclaration(parent2)) { - return void 0; - } - const variableDeclaration = isVariableDeclaration(parent2) ? parent2 : first(parent2.declarations); - const initializer = variableDeclaration.initializer; - if (initializer && (isArrowFunction(initializer) || isFunctionExpression(initializer) && !isFunctionReferencedInFile(sourceFile, typeChecker, initializer))) { - return initializer; - } - return void 0; - } - function convertToBlock(body) { - if (isExpression(body)) { - const returnStatement = factory.createReturnStatement(body); - const file = body.getSourceFile(); - setTextRange(returnStatement, body); - suppressLeadingAndTrailingTrivia(returnStatement); - copyTrailingAsLeadingComments( - body, - returnStatement, - file, - /*commentKind*/ - void 0, - /*hasTrailingNewLine*/ - true - ); - return factory.createBlock( - [returnStatement], - /*multiLine*/ - true - ); - } else { - return body; - } - } - function getVariableInfo(func) { - const variableDeclaration = func.parent; - if (!isVariableDeclaration(variableDeclaration) || !isVariableDeclarationInVariableStatement(variableDeclaration)) - return void 0; - const variableDeclarationList = variableDeclaration.parent; - const statement = variableDeclarationList.parent; - if (!isVariableDeclarationList(variableDeclarationList) || !isVariableStatement(statement) || !isIdentifier(variableDeclaration.name)) - return void 0; - return { variableDeclaration, variableDeclarationList, statement, name: variableDeclaration.name }; - } - function getEditInfoForConvertToAnonymousFunction(context, func) { - const { file } = context; - const body = convertToBlock(func.body); - const newNode = factory.createFunctionExpression( - func.modifiers, - func.asteriskToken, - /*name*/ - void 0, - func.typeParameters, - func.parameters, - func.type, - body - ); - return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode)); - } - function getEditInfoForConvertToNamedFunction(context, func, variableInfo) { - const { file } = context; - const body = convertToBlock(func.body); - const { variableDeclaration, variableDeclarationList, statement, name } = variableInfo; - suppressLeadingTrivia(statement); - const modifiersFlags = getCombinedModifierFlags(variableDeclaration) & 1 /* Export */ | getEffectiveModifierFlags(func); - const modifiers = factory.createModifiersFromModifierFlags(modifiersFlags); - const newNode = factory.createFunctionDeclaration(length(modifiers) ? modifiers : void 0, func.asteriskToken, name, func.typeParameters, func.parameters, func.type, body); - if (variableDeclarationList.declarations.length === 1) { - return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, statement, newNode)); - } else { - return ts_textChanges_exports.ChangeTracker.with(context, (t) => { - t.delete(file, variableDeclaration); - t.insertNodeAfter(file, statement, newNode); - }); - } - } - function getEditInfoForConvertToArrowFunction(context, func) { - const { file } = context; - const statements = func.body.statements; - const head = statements[0]; - let body; - if (canBeConvertedToExpression(func.body, head)) { - body = head.expression; - suppressLeadingAndTrailingTrivia(body); - copyComments(head, body); - } else { - body = func.body; - } - const newNode = factory.createArrowFunction(func.modifiers, func.typeParameters, func.parameters, func.type, factory.createToken(39 /* EqualsGreaterThanToken */), body); - return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, func, newNode)); - } - function canBeConvertedToExpression(body, head) { - return body.statements.length === 1 && (isReturnStatement(head) && !!head.expression); - } - function isFunctionReferencedInFile(sourceFile, typeChecker, node) { - return !!node.name && ts_FindAllReferences_exports.Core.isSymbolReferencedInFile(node.name, typeChecker, sourceFile); - } - var refactorName7, refactorDescription3, toAnonymousFunctionAction, toNamedFunctionAction, toArrowFunctionAction; - var init_convertArrowFunctionOrFunctionExpression = __esm({ - "src/services/refactors/convertArrowFunctionOrFunctionExpression.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName7 = "Convert arrow function or function expression"; - refactorDescription3 = getLocaleSpecificMessage(Diagnostics.Convert_arrow_function_or_function_expression); - toAnonymousFunctionAction = { - name: "Convert to anonymous function", - description: getLocaleSpecificMessage(Diagnostics.Convert_to_anonymous_function), - kind: "refactor.rewrite.function.anonymous" - }; - toNamedFunctionAction = { - name: "Convert to named function", - description: getLocaleSpecificMessage(Diagnostics.Convert_to_named_function), - kind: "refactor.rewrite.function.named" - }; - toArrowFunctionAction = { - name: "Convert to arrow function", - description: getLocaleSpecificMessage(Diagnostics.Convert_to_arrow_function), - kind: "refactor.rewrite.function.arrow" - }; - registerRefactor(refactorName7, { - kinds: [ - toAnonymousFunctionAction.kind, - toNamedFunctionAction.kind, - toArrowFunctionAction.kind - ], - getEditsForAction: getRefactorEditsToConvertFunctionExpressions, - getAvailableActions: getRefactorActionsToConvertFunctionExpressions - }); - } - }); - - // src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts - var ts_refactor_convertArrowFunctionOrFunctionExpression_exports = {}; - var init_ts_refactor_convertArrowFunctionOrFunctionExpression = __esm({ - "src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts"() { - "use strict"; - init_convertArrowFunctionOrFunctionExpression(); - } - }); - - // src/services/refactors/convertParamsToDestructuredObject.ts - function getRefactorActionsToConvertParametersToDestructuredObject(context) { - const { file, startPosition } = context; - const isJSFile = isSourceFileJS(file); - if (isJSFile) - return emptyArray; - const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker()); - if (!functionDeclaration) - return emptyArray; - return [{ - name: refactorName8, - description: refactorDescription4, - actions: [toDestructuredAction] - }]; - } - function getRefactorEditsToConvertParametersToDestructuredObject(context, actionName2) { - Debug.assert(actionName2 === refactorName8, "Unexpected action name"); - const { file, startPosition, program, cancellationToken, host } = context; - const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); - if (!functionDeclaration || !cancellationToken) - return void 0; - const groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken); - if (groupedReferences.valid) { - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange37(file, program, host, t, functionDeclaration, groupedReferences)); - return { renameFilename: void 0, renameLocation: void 0, edits }; - } - return { edits: [] }; - } - function doChange37(sourceFile, program, host, changes, functionDeclaration, groupedReferences) { - const signature = groupedReferences.signature; - const newFunctionDeclarationParams = map(createNewParameters(functionDeclaration, program, host), (param) => getSynthesizedDeepClone(param)); - if (signature) { - const newSignatureParams = map(createNewParameters(signature, program, host), (param) => getSynthesizedDeepClone(param)); - replaceParameters(signature, newSignatureParams); - } - replaceParameters(functionDeclaration, newFunctionDeclarationParams); - const functionCalls = sortAndDeduplicate( - groupedReferences.functionCalls, - /*comparer*/ - (a, b) => compareValues(a.pos, b.pos) - ); - for (const call of functionCalls) { - if (call.arguments && call.arguments.length) { - const newArgument = getSynthesizedDeepClone( - createNewArgument(functionDeclaration, call.arguments), - /*includeTrivia*/ - true - ); - changes.replaceNodeRange( - getSourceFileOfNode(call), - first(call.arguments), - last(call.arguments), - newArgument, - { leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include } - ); - } - } - function replaceParameters(declarationOrSignature, parameterDeclarations) { - changes.replaceNodeRangeWithNodes( - sourceFile, - first(declarationOrSignature.parameters), - last(declarationOrSignature.parameters), - parameterDeclarations, - { - joiner: ", ", - // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter - indentation: 0, - leadingTriviaOption: ts_textChanges_exports.LeadingTriviaOption.IncludeAll, - trailingTriviaOption: ts_textChanges_exports.TrailingTriviaOption.Include - } - ); - } - } - function getGroupedReferences(functionDeclaration, program, cancellationToken) { - const functionNames = getFunctionNames(functionDeclaration); - const classNames = isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : []; - const names = deduplicate([...functionNames, ...classNames], equateValues); - const checker = program.getTypeChecker(); - const references = flatMap( - names, - /*mapfn*/ - (name) => ts_FindAllReferences_exports.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken) - ); - const groupedReferences = groupReferences(references); - if (!every( - groupedReferences.declarations, - /*callback*/ - (decl) => contains(names, decl) - )) { - groupedReferences.valid = false; - } - return groupedReferences; - function groupReferences(referenceEntries) { - const classReferences = { accessExpressions: [], typeUsages: [] }; - const groupedReferences2 = { functionCalls: [], declarations: [], classReferences, valid: true }; - const functionSymbols = map(functionNames, getSymbolTargetAtLocation); - const classSymbols = map(classNames, getSymbolTargetAtLocation); - const isConstructor = isConstructorDeclaration(functionDeclaration); - const contextualSymbols = map(functionNames, (name) => getSymbolForContextualType(name, checker)); - for (const entry of referenceEntries) { - if (entry.kind === ts_FindAllReferences_exports.EntryKind.Span) { - groupedReferences2.valid = false; - continue; - } - if (contains(contextualSymbols, getSymbolTargetAtLocation(entry.node))) { - if (isValidMethodSignature(entry.node.parent)) { - groupedReferences2.signature = entry.node.parent; - continue; - } - const call = entryToFunctionCall(entry); - if (call) { - groupedReferences2.functionCalls.push(call); - continue; - } - } - const contextualSymbol = getSymbolForContextualType(entry.node, checker); - if (contextualSymbol && contains(contextualSymbols, contextualSymbol)) { - const decl = entryToDeclaration(entry); - if (decl) { - groupedReferences2.declarations.push(decl); - continue; - } - } - if (contains(functionSymbols, getSymbolTargetAtLocation(entry.node)) || isNewExpressionTarget(entry.node)) { - const importOrExportReference = entryToImportOrExport(entry); - if (importOrExportReference) { - continue; - } - const decl = entryToDeclaration(entry); - if (decl) { - groupedReferences2.declarations.push(decl); - continue; - } - const call = entryToFunctionCall(entry); - if (call) { - groupedReferences2.functionCalls.push(call); - continue; - } - } - if (isConstructor && contains(classSymbols, getSymbolTargetAtLocation(entry.node))) { - const importOrExportReference = entryToImportOrExport(entry); - if (importOrExportReference) { - continue; - } - const decl = entryToDeclaration(entry); - if (decl) { - groupedReferences2.declarations.push(decl); - continue; - } - const accessExpression = entryToAccessExpression(entry); - if (accessExpression) { - classReferences.accessExpressions.push(accessExpression); - continue; - } - if (isClassDeclaration(functionDeclaration.parent)) { - const type = entryToType(entry); - if (type) { - classReferences.typeUsages.push(type); - continue; - } - } - } - groupedReferences2.valid = false; - } - return groupedReferences2; - } - function getSymbolTargetAtLocation(node) { - const symbol = checker.getSymbolAtLocation(node); - return symbol && getSymbolTarget(symbol, checker); - } - } - function getSymbolForContextualType(node, checker) { - const element = getContainingObjectLiteralElement(node); - if (element) { - const contextualType = checker.getContextualTypeForObjectLiteralElement(element); - const symbol = contextualType == null ? void 0 : contextualType.getSymbol(); - if (symbol && !(getCheckFlags(symbol) & 6 /* Synthetic */)) { - return symbol; - } - } - } - function entryToImportOrExport(entry) { - const node = entry.node; - if (isImportSpecifier(node.parent) || isImportClause(node.parent) || isImportEqualsDeclaration(node.parent) || isNamespaceImport(node.parent)) { - return node; - } - if (isExportSpecifier(node.parent) || isExportAssignment(node.parent)) { - return node; - } - return void 0; - } - function entryToDeclaration(entry) { - if (isDeclaration(entry.node.parent)) { - return entry.node; - } - return void 0; - } - function entryToFunctionCall(entry) { - if (entry.node.parent) { - const functionReference = entry.node; - const parent2 = functionReference.parent; - switch (parent2.kind) { - case 212 /* CallExpression */: - case 213 /* NewExpression */: - const callOrNewExpression = tryCast(parent2, isCallOrNewExpression); - if (callOrNewExpression && callOrNewExpression.expression === functionReference) { - return callOrNewExpression; - } - break; - case 210 /* PropertyAccessExpression */: - const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); - if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { - const callOrNewExpression2 = tryCast(propertyAccessExpression.parent, isCallOrNewExpression); - if (callOrNewExpression2 && callOrNewExpression2.expression === propertyAccessExpression) { - return callOrNewExpression2; - } - } - break; - case 211 /* ElementAccessExpression */: - const elementAccessExpression = tryCast(parent2, isElementAccessExpression); - if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { - const callOrNewExpression2 = tryCast(elementAccessExpression.parent, isCallOrNewExpression); - if (callOrNewExpression2 && callOrNewExpression2.expression === elementAccessExpression) { - return callOrNewExpression2; - } - } - break; - } - } - return void 0; - } - function entryToAccessExpression(entry) { - if (entry.node.parent) { - const reference = entry.node; - const parent2 = reference.parent; - switch (parent2.kind) { - case 210 /* PropertyAccessExpression */: - const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); - if (propertyAccessExpression && propertyAccessExpression.expression === reference) { - return propertyAccessExpression; - } - break; - case 211 /* ElementAccessExpression */: - const elementAccessExpression = tryCast(parent2, isElementAccessExpression); - if (elementAccessExpression && elementAccessExpression.expression === reference) { - return elementAccessExpression; - } - break; - } - } - return void 0; - } - function entryToType(entry) { - const reference = entry.node; - if (getMeaningFromLocation(reference) === 2 /* Type */ || isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) { - return reference; - } - return void 0; - } - function getFunctionDeclarationAtPosition(file, startPosition, checker) { - const node = getTouchingToken(file, startPosition); - const functionDeclaration = getContainingFunctionDeclaration(node); - if (isTopLevelJSDoc(node)) - return void 0; - if (functionDeclaration && isValidFunctionDeclaration(functionDeclaration, checker) && rangeContainsRange(functionDeclaration, node) && !(functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node))) - return functionDeclaration; - return void 0; - } - function isTopLevelJSDoc(node) { - const containingJSDoc = findAncestor(node, isJSDocNode); - if (containingJSDoc) { - const containingNonJSDoc = findAncestor(containingJSDoc, (n) => !isJSDocNode(n)); - return !!containingNonJSDoc && isFunctionLikeDeclaration(containingNonJSDoc); - } - return false; - } - function isValidMethodSignature(node) { - return isMethodSignature(node) && (isInterfaceDeclaration(node.parent) || isTypeLiteralNode(node.parent)); - } - function isValidFunctionDeclaration(functionDeclaration, checker) { - var _a; - if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) - return false; - switch (functionDeclaration.kind) { - case 261 /* FunctionDeclaration */: - return hasNameOrDefault(functionDeclaration) && isSingleImplementation(functionDeclaration, checker); - case 173 /* MethodDeclaration */: - if (isObjectLiteralExpression(functionDeclaration.parent)) { - const contextualSymbol = getSymbolForContextualType(functionDeclaration.name, checker); - return ((_a = contextualSymbol == null ? void 0 : contextualSymbol.declarations) == null ? void 0 : _a.length) === 1 && isSingleImplementation(functionDeclaration, checker); - } - return isSingleImplementation(functionDeclaration, checker); - case 175 /* Constructor */: - if (isClassDeclaration(functionDeclaration.parent)) { - return hasNameOrDefault(functionDeclaration.parent) && isSingleImplementation(functionDeclaration, checker); - } else { - return isValidVariableDeclaration(functionDeclaration.parent.parent) && isSingleImplementation(functionDeclaration, checker); - } - case 217 /* FunctionExpression */: - case 218 /* ArrowFunction */: - return isValidVariableDeclaration(functionDeclaration.parent); - } - return false; - } - function isSingleImplementation(functionDeclaration, checker) { - return !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); - } - function hasNameOrDefault(functionOrClassDeclaration) { - if (!functionOrClassDeclaration.name) { - const defaultKeyword = findModifier(functionOrClassDeclaration, 90 /* DefaultKeyword */); - return !!defaultKeyword; - } - return true; - } - function isValidParameterNodeArray(parameters, checker) { - return getRefactorableParametersLength(parameters) >= minimumParameterLength && every( - parameters, - /*callback*/ - (paramDecl) => isValidParameterDeclaration(paramDecl, checker) - ); - } - function isValidParameterDeclaration(parameterDeclaration, checker) { - if (isRestParameter(parameterDeclaration)) { - const type = checker.getTypeAtLocation(parameterDeclaration); - if (!checker.isArrayType(type) && !checker.isTupleType(type)) - return false; - } - return !parameterDeclaration.modifiers && isIdentifier(parameterDeclaration.name); - } - function isValidVariableDeclaration(node) { - return isVariableDeclaration(node) && isVarConst(node) && isIdentifier(node.name) && !node.type; - } - function hasThisParameter(parameters) { - return parameters.length > 0 && isThis(parameters[0].name); - } - function getRefactorableParametersLength(parameters) { - if (hasThisParameter(parameters)) { - return parameters.length - 1; - } - return parameters.length; - } - function getRefactorableParameters(parameters) { - if (hasThisParameter(parameters)) { - parameters = factory.createNodeArray(parameters.slice(1), parameters.hasTrailingComma); - } - return parameters; - } - function createPropertyOrShorthandAssignment(name, initializer) { - if (isIdentifier(initializer) && getTextOfIdentifierOrLiteral(initializer) === name) { - return factory.createShorthandPropertyAssignment(name); - } - return factory.createPropertyAssignment(name, initializer); - } - function createNewArgument(functionDeclaration, functionArguments) { - const parameters = getRefactorableParameters(functionDeclaration.parameters); - const hasRestParameter2 = isRestParameter(last(parameters)); - const nonRestArguments = hasRestParameter2 ? functionArguments.slice(0, parameters.length - 1) : functionArguments; - const properties = map(nonRestArguments, (arg, i) => { - const parameterName = getParameterName(parameters[i]); - const property = createPropertyOrShorthandAssignment(parameterName, arg); - suppressLeadingAndTrailingTrivia(property.name); - if (isPropertyAssignment(property)) - suppressLeadingAndTrailingTrivia(property.initializer); - copyComments(arg, property); - return property; - }); - if (hasRestParameter2 && functionArguments.length >= parameters.length) { - const restArguments = functionArguments.slice(parameters.length - 1); - const restProperty = factory.createPropertyAssignment(getParameterName(last(parameters)), factory.createArrayLiteralExpression(restArguments)); - properties.push(restProperty); - } - const objectLiteral = factory.createObjectLiteralExpression( - properties, - /*multiLine*/ - false - ); - return objectLiteral; - } - function createNewParameters(functionDeclaration, program, host) { - const checker = program.getTypeChecker(); - const refactorableParameters = getRefactorableParameters(functionDeclaration.parameters); - const bindingElements = map(refactorableParameters, createBindingElementFromParameterDeclaration); - const objectParameterName = factory.createObjectBindingPattern(bindingElements); - const objectParameterType = createParameterTypeNode(refactorableParameters); - let objectInitializer; - if (every(refactorableParameters, isOptionalParameter)) { - objectInitializer = factory.createObjectLiteralExpression(); - } - const objectParameter = factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - objectParameterName, - /*questionToken*/ - void 0, - objectParameterType, - objectInitializer - ); - if (hasThisParameter(functionDeclaration.parameters)) { - const thisParameter = functionDeclaration.parameters[0]; - const newThisParameter = factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - thisParameter.name, - /*questionToken*/ - void 0, - thisParameter.type - ); - suppressLeadingAndTrailingTrivia(newThisParameter.name); - copyComments(thisParameter.name, newThisParameter.name); - if (thisParameter.type) { - suppressLeadingAndTrailingTrivia(newThisParameter.type); - copyComments(thisParameter.type, newThisParameter.type); - } - return factory.createNodeArray([newThisParameter, objectParameter]); - } - return factory.createNodeArray([objectParameter]); - function createBindingElementFromParameterDeclaration(parameterDeclaration) { - const element = factory.createBindingElement( - /*dotDotDotToken*/ - void 0, - /*propertyName*/ - void 0, - getParameterName(parameterDeclaration), - isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? factory.createArrayLiteralExpression() : parameterDeclaration.initializer - ); - suppressLeadingAndTrailingTrivia(element); - if (parameterDeclaration.initializer && element.initializer) { - copyComments(parameterDeclaration.initializer, element.initializer); - } - return element; - } - function createParameterTypeNode(parameters) { - const members = map(parameters, createPropertySignatureFromParameterDeclaration); - const typeNode = addEmitFlags(factory.createTypeLiteralNode(members), 1 /* SingleLine */); - return typeNode; - } - function createPropertySignatureFromParameterDeclaration(parameterDeclaration) { - let parameterType = parameterDeclaration.type; - if (!parameterType && (parameterDeclaration.initializer || isRestParameter(parameterDeclaration))) { - parameterType = getTypeNode3(parameterDeclaration); - } - const propertySignature = factory.createPropertySignature( - /*modifiers*/ - void 0, - getParameterName(parameterDeclaration), - isOptionalParameter(parameterDeclaration) ? factory.createToken(58 /* QuestionToken */) : parameterDeclaration.questionToken, - parameterType - ); - suppressLeadingAndTrailingTrivia(propertySignature); - copyComments(parameterDeclaration.name, propertySignature.name); - if (parameterDeclaration.type && propertySignature.type) { - copyComments(parameterDeclaration.type, propertySignature.type); - } - return propertySignature; - } - function getTypeNode3(node) { - const type = checker.getTypeAtLocation(node); - return getTypeNodeIfAccessible(type, node, program, host); - } - function isOptionalParameter(parameterDeclaration) { - if (isRestParameter(parameterDeclaration)) { - const type = checker.getTypeAtLocation(parameterDeclaration); - return !checker.isTupleType(type); - } - return checker.isOptionalParameter(parameterDeclaration); - } - } - function getParameterName(paramDeclaration) { - return getTextOfIdentifierOrLiteral(paramDeclaration.name); - } - function getClassNames(constructorDeclaration) { - switch (constructorDeclaration.parent.kind) { - case 262 /* ClassDeclaration */: - const classDeclaration = constructorDeclaration.parent; - if (classDeclaration.name) - return [classDeclaration.name]; - const defaultModifier = Debug.checkDefined( - findModifier(classDeclaration, 90 /* DefaultKeyword */), - "Nameless class declaration should be a default export" - ); - return [defaultModifier]; - case 230 /* ClassExpression */: - const classExpression = constructorDeclaration.parent; - const variableDeclaration = constructorDeclaration.parent.parent; - const className = classExpression.name; - if (className) - return [className, variableDeclaration.name]; - return [variableDeclaration.name]; - } - } - function getFunctionNames(functionDeclaration) { - switch (functionDeclaration.kind) { - case 261 /* FunctionDeclaration */: - if (functionDeclaration.name) - return [functionDeclaration.name]; - const defaultModifier = Debug.checkDefined( - findModifier(functionDeclaration, 90 /* DefaultKeyword */), - "Nameless function declaration should be a default export" - ); - return [defaultModifier]; - case 173 /* MethodDeclaration */: - return [functionDeclaration.name]; - case 175 /* Constructor */: - const ctrKeyword = Debug.checkDefined( - findChildOfKind(functionDeclaration, 137 /* ConstructorKeyword */, functionDeclaration.getSourceFile()), - "Constructor declaration should have constructor keyword" - ); - if (functionDeclaration.parent.kind === 230 /* ClassExpression */) { - const variableDeclaration = functionDeclaration.parent.parent; - return [variableDeclaration.name, ctrKeyword]; - } - return [ctrKeyword]; - case 218 /* ArrowFunction */: - return [functionDeclaration.parent.name]; - case 217 /* FunctionExpression */: - if (functionDeclaration.name) - return [functionDeclaration.name, functionDeclaration.parent.name]; - return [functionDeclaration.parent.name]; - default: - return Debug.assertNever(functionDeclaration, `Unexpected function declaration kind ${functionDeclaration.kind}`); - } - } - var refactorName8, minimumParameterLength, refactorDescription4, toDestructuredAction; - var init_convertParamsToDestructuredObject = __esm({ - "src/services/refactors/convertParamsToDestructuredObject.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName8 = "Convert parameters to destructured object"; - minimumParameterLength = 1; - refactorDescription4 = getLocaleSpecificMessage(Diagnostics.Convert_parameters_to_destructured_object); - toDestructuredAction = { - name: refactorName8, - description: refactorDescription4, - kind: "refactor.rewrite.parameters.toDestructured" - }; - registerRefactor(refactorName8, { - kinds: [toDestructuredAction.kind], - getEditsForAction: getRefactorEditsToConvertParametersToDestructuredObject, - getAvailableActions: getRefactorActionsToConvertParametersToDestructuredObject - }); - } - }); - - // src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts - var ts_refactor_convertParamsToDestructuredObject_exports = {}; - var init_ts_refactor_convertParamsToDestructuredObject = __esm({ - "src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts"() { - "use strict"; - init_convertParamsToDestructuredObject(); - } - }); - - // src/services/refactors/convertStringOrTemplateLiteral.ts - function getRefactorActionsToConvertToTemplateString(context) { - const { file, startPosition } = context; - const node = getNodeOrParentOfParentheses(file, startPosition); - const maybeBinary = getParentBinaryExpression(node); - const refactorInfo = { name: refactorName9, description: refactorDescription5, actions: [] }; - if (isBinaryExpression(maybeBinary) && treeToArray(maybeBinary).isValidConcatenation) { - refactorInfo.actions.push(convertStringAction); - return [refactorInfo]; - } else if (context.preferences.provideRefactorNotApplicableReason) { - refactorInfo.actions.push({ - ...convertStringAction, - notApplicableReason: getLocaleSpecificMessage(Diagnostics.Can_only_convert_string_concatenation) - }); - return [refactorInfo]; - } - return emptyArray; - } - function getNodeOrParentOfParentheses(file, startPosition) { - const node = getTokenAtPosition(file, startPosition); - const nestedBinary = getParentBinaryExpression(node); - const isNonStringBinary = !treeToArray(nestedBinary).isValidConcatenation; - if (isNonStringBinary && isParenthesizedExpression(nestedBinary.parent) && isBinaryExpression(nestedBinary.parent.parent)) { - return nestedBinary.parent.parent; - } - return node; - } - function getRefactorEditsToConvertToTemplateString(context, actionName2) { - const { file, startPosition } = context; - const node = getNodeOrParentOfParentheses(file, startPosition); - switch (actionName2) { - case refactorDescription5: - return { edits: getEditsForToTemplateLiteral(context, node) }; - default: - return Debug.fail("invalid action"); - } - } - function getEditsForToTemplateLiteral(context, node) { - const maybeBinary = getParentBinaryExpression(node); - const file = context.file; - const templateLiteral = nodesToTemplate(treeToArray(maybeBinary), file); - const trailingCommentRanges = getTrailingCommentRanges(file.text, maybeBinary.end); - if (trailingCommentRanges) { - const lastComment = trailingCommentRanges[trailingCommentRanges.length - 1]; - const trailingRange = { pos: trailingCommentRanges[0].pos, end: lastComment.end }; - return ts_textChanges_exports.ChangeTracker.with(context, (t) => { - t.deleteRange(file, trailingRange); - t.replaceNode(file, maybeBinary, templateLiteral); - }); - } else { - return ts_textChanges_exports.ChangeTracker.with(context, (t) => t.replaceNode(file, maybeBinary, templateLiteral)); - } - } - function isNotEqualsOperator(node) { - return node.operatorToken.kind !== 64 /* EqualsToken */; - } - function getParentBinaryExpression(expr) { - const container = findAncestor(expr.parent, (n) => { - switch (n.kind) { - case 210 /* PropertyAccessExpression */: - case 211 /* ElementAccessExpression */: - return false; - case 227 /* TemplateExpression */: - case 225 /* BinaryExpression */: - return !(isBinaryExpression(n.parent) && isNotEqualsOperator(n.parent)); - default: - return "quit"; - } - }); - return container || expr; - } - function treeToArray(current) { - const loop = (current2) => { - if (!isBinaryExpression(current2)) { - return { - nodes: [current2], - operators: [], - validOperators: true, - hasString: isStringLiteral(current2) || isNoSubstitutionTemplateLiteral(current2) - }; - } - const { nodes: nodes2, operators: operators2, hasString: leftHasString, validOperators: leftOperatorValid } = loop(current2.left); - if (!(leftHasString || isStringLiteral(current2.right) || isTemplateExpression(current2.right))) { - return { nodes: [current2], operators: [], hasString: false, validOperators: true }; - } - const currentOperatorValid = current2.operatorToken.kind === 40 /* PlusToken */; - const validOperators2 = leftOperatorValid && currentOperatorValid; - nodes2.push(current2.right); - operators2.push(current2.operatorToken); - return { nodes: nodes2, operators: operators2, hasString: true, validOperators: validOperators2 }; - }; - const { nodes, operators, validOperators, hasString } = loop(current); - return { nodes, operators, isValidConcatenation: validOperators && hasString }; - } - function escapeRawStringForTemplate(s) { - return s.replace(/\\.|[$`]/g, (m) => m[0] === "\\" ? m : "\\" + m); - } - function getRawTextOfTemplate(node) { - const rightShaving = isTemplateHead(node) || isTemplateMiddle(node) ? -2 : -1; - return getTextOfNode(node).slice(1, rightShaving); - } - function concatConsecutiveString(index, nodes) { - const indexes = []; - let text = "", rawText = ""; - while (index < nodes.length) { - const node = nodes[index]; - if (isStringLiteralLike(node)) { - text += node.text; - rawText += escapeRawStringForTemplate(getTextOfNode(node).slice(1, -1)); - indexes.push(index); - index++; - } else if (isTemplateExpression(node)) { - text += node.head.text; - rawText += getRawTextOfTemplate(node.head); - break; - } else { - break; - } - } - return [index, text, rawText, indexes]; - } - function nodesToTemplate({ nodes, operators }, file) { - const copyOperatorComments = copyTrailingOperatorComments(operators, file); - const copyCommentFromStringLiterals = copyCommentFromMultiNode(nodes, file, copyOperatorComments); - const [begin, headText, rawHeadText, headIndexes] = concatConsecutiveString(0, nodes); - if (begin === nodes.length) { - const noSubstitutionTemplateLiteral = factory.createNoSubstitutionTemplateLiteral(headText, rawHeadText); - copyCommentFromStringLiterals(headIndexes, noSubstitutionTemplateLiteral); - return noSubstitutionTemplateLiteral; - } - const templateSpans = []; - const templateHead = factory.createTemplateHead(headText, rawHeadText); - copyCommentFromStringLiterals(headIndexes, templateHead); - for (let i = begin; i < nodes.length; i++) { - const currentNode = getExpressionFromParenthesesOrExpression(nodes[i]); - copyOperatorComments(i, currentNode); - const [newIndex, subsequentText, rawSubsequentText, stringIndexes] = concatConsecutiveString(i + 1, nodes); - i = newIndex - 1; - const isLast = i === nodes.length - 1; - if (isTemplateExpression(currentNode)) { - const spans = map(currentNode.templateSpans, (span, index) => { - copyExpressionComments(span); - 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)); - }); - templateSpans.push(...spans); - } else { - const templatePart = isLast ? factory.createTemplateTail(subsequentText, rawSubsequentText) : factory.createTemplateMiddle(subsequentText, rawSubsequentText); - copyCommentFromStringLiterals(stringIndexes, templatePart); - templateSpans.push(factory.createTemplateSpan(currentNode, templatePart)); - } - } - return factory.createTemplateExpression(templateHead, templateSpans); - } - function copyExpressionComments(node) { - const file = node.getSourceFile(); - copyTrailingComments( - node, - node.expression, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - copyTrailingAsLeadingComments( - node.expression, - node.expression, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - } - function getExpressionFromParenthesesOrExpression(node) { - if (isParenthesizedExpression(node)) { - copyExpressionComments(node); - node = node.expression; - } - return node; - } - var refactorName9, refactorDescription5, convertStringAction, copyTrailingOperatorComments, copyCommentFromMultiNode; - var init_convertStringOrTemplateLiteral = __esm({ - "src/services/refactors/convertStringOrTemplateLiteral.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName9 = "Convert to template string"; - refactorDescription5 = getLocaleSpecificMessage(Diagnostics.Convert_to_template_string); - convertStringAction = { - name: refactorName9, - description: refactorDescription5, - kind: "refactor.rewrite.string" - }; - registerRefactor(refactorName9, { - kinds: [convertStringAction.kind], - getEditsForAction: getRefactorEditsToConvertToTemplateString, - getAvailableActions: getRefactorActionsToConvertToTemplateString - }); - copyTrailingOperatorComments = (operators, file) => (index, targetNode) => { - if (index < operators.length) { - copyTrailingComments( - operators[index], - targetNode, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - } - }; - copyCommentFromMultiNode = (nodes, file, copyOperatorComments) => (indexes, targetNode) => { - while (indexes.length > 0) { - const index = indexes.shift(); - copyTrailingComments( - nodes[index], - targetNode, - file, - 3 /* MultiLineCommentTrivia */, - /*hasTrailingNewLine*/ - false - ); - copyOperatorComments(index, targetNode); - } - }; - } - }); - - // src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts - var ts_refactor_convertStringOrTemplateLiteral_exports = {}; - var init_ts_refactor_convertStringOrTemplateLiteral = __esm({ - "src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts"() { - "use strict"; - init_convertStringOrTemplateLiteral(); - } - }); - - // src/services/refactors/convertToOptionalChainExpression.ts - function getRefactorActionsToConvertToOptionalChain(context) { - const info = getInfo20(context, context.triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - return [{ - name: refactorName10, - description: convertToOptionalChainExpressionMessage, - actions: [toOptionalChainAction] - }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorName10, - description: convertToOptionalChainExpressionMessage, - actions: [{ ...toOptionalChainAction, notApplicableReason: info.error }] - }]; - } - return emptyArray; - } - function getRefactorEditsToConvertToOptionalChain(context, actionName2) { - const info = getInfo20(context); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_textChanges_exports.ChangeTracker.with( - context, - (t) => doChange38(context.file, context.program.getTypeChecker(), t, info, actionName2) - ); - return { edits, renameFilename: void 0, renameLocation: void 0 }; - } - function isValidExpression(node) { - return isBinaryExpression(node) || isConditionalExpression(node); - } - function isValidStatement(node) { - return isExpressionStatement(node) || isReturnStatement(node) || isVariableStatement(node); - } - function isValidExpressionOrStatement(node) { - return isValidExpression(node) || isValidStatement(node); - } - function getInfo20(context, considerEmptySpans = true) { - const { file, program } = context; - const span = getRefactorContextSpan(context); - const forEmptySpan = span.length === 0; - if (forEmptySpan && !considerEmptySpans) - return void 0; - const startToken = getTokenAtPosition(file, span.start); - const endToken = findTokenOnLeftOfPosition(file, span.start + span.length); - const adjustedSpan = createTextSpanFromBounds(startToken.pos, endToken && endToken.end >= startToken.pos ? endToken.getEnd() : startToken.getEnd()); - const parent2 = forEmptySpan ? getValidParentNodeOfEmptySpan(startToken) : getValidParentNodeContainingSpan(startToken, adjustedSpan); - const expression = parent2 && isValidExpressionOrStatement(parent2) ? getExpression(parent2) : void 0; - if (!expression) - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; - const checker = program.getTypeChecker(); - return isConditionalExpression(expression) ? getConditionalInfo(expression, checker) : getBinaryInfo(expression); - } - function getConditionalInfo(expression, checker) { - const condition = expression.condition; - const finalExpression = getFinalExpressionInChain(expression.whenTrue); - if (!finalExpression || checker.isNullableType(checker.getTypeAtLocation(finalExpression))) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; - } - if ((isPropertyAccessExpression(condition) || isIdentifier(condition)) && getMatchingStart(condition, finalExpression.expression)) { - return { finalExpression, occurrences: [condition], expression }; - } else if (isBinaryExpression(condition)) { - const occurrences = getOccurrencesInExpression(finalExpression.expression, condition); - return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) }; - } - } - function getBinaryInfo(expression) { - if (expression.operatorToken.kind !== 56 /* AmpersandAmpersandToken */) { - return { error: getLocaleSpecificMessage(Diagnostics.Can_only_convert_logical_AND_access_chains) }; - } - const finalExpression = getFinalExpressionInChain(expression.right); - if (!finalExpression) - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_convertible_access_expression) }; - const occurrences = getOccurrencesInExpression(finalExpression.expression, expression.left); - return occurrences ? { finalExpression, occurrences, expression } : { error: getLocaleSpecificMessage(Diagnostics.Could_not_find_matching_access_expressions) }; - } - function getOccurrencesInExpression(matchTo, expression) { - const occurrences = []; - while (isBinaryExpression(expression) && expression.operatorToken.kind === 56 /* AmpersandAmpersandToken */) { - const match = getMatchingStart(skipParentheses(matchTo), skipParentheses(expression.right)); - if (!match) { - break; - } - occurrences.push(match); - matchTo = match; - expression = expression.left; - } - const finalMatch = getMatchingStart(matchTo, expression); - if (finalMatch) { - occurrences.push(finalMatch); - } - return occurrences.length > 0 ? occurrences : void 0; - } - function getMatchingStart(chain, subchain) { - if (!isIdentifier(subchain) && !isPropertyAccessExpression(subchain) && !isElementAccessExpression(subchain)) { - return void 0; - } - return chainStartsWith(chain, subchain) ? subchain : void 0; - } - function chainStartsWith(chain, subchain) { - while (isCallExpression(chain) || isPropertyAccessExpression(chain) || isElementAccessExpression(chain)) { - if (getTextOfChainNode(chain) === getTextOfChainNode(subchain)) - break; - chain = chain.expression; - } - while (isPropertyAccessExpression(chain) && isPropertyAccessExpression(subchain) || isElementAccessExpression(chain) && isElementAccessExpression(subchain)) { - if (getTextOfChainNode(chain) !== getTextOfChainNode(subchain)) - return false; - chain = chain.expression; - subchain = subchain.expression; - } - return isIdentifier(chain) && isIdentifier(subchain) && chain.getText() === subchain.getText(); - } - function getTextOfChainNode(node) { - if (isIdentifier(node) || isStringOrNumericLiteralLike(node)) { - return node.getText(); - } - if (isPropertyAccessExpression(node)) { - return getTextOfChainNode(node.name); - } - if (isElementAccessExpression(node)) { - return getTextOfChainNode(node.argumentExpression); - } - return void 0; - } - function getValidParentNodeContainingSpan(node, span) { - while (node.parent) { - if (isValidExpressionOrStatement(node) && span.length !== 0 && node.end >= span.start + span.length) { - return node; - } - node = node.parent; - } - return void 0; - } - function getValidParentNodeOfEmptySpan(node) { - while (node.parent) { - if (isValidExpressionOrStatement(node) && !isValidExpressionOrStatement(node.parent)) { - return node; - } - node = node.parent; - } - return void 0; - } - function getExpression(node) { - if (isValidExpression(node)) { - return node; - } - if (isVariableStatement(node)) { - const variable = getSingleVariableOfVariableStatement(node); - const initializer = variable == null ? void 0 : variable.initializer; - return initializer && isValidExpression(initializer) ? initializer : void 0; - } - return node.expression && isValidExpression(node.expression) ? node.expression : void 0; - } - function getFinalExpressionInChain(node) { - node = skipParentheses(node); - if (isBinaryExpression(node)) { - return getFinalExpressionInChain(node.left); - } else if ((isPropertyAccessExpression(node) || isElementAccessExpression(node) || isCallExpression(node)) && !isOptionalChain(node)) { - return node; - } - return void 0; - } - function convertOccurrences(checker, toConvert, occurrences) { - if (isPropertyAccessExpression(toConvert) || isElementAccessExpression(toConvert) || isCallExpression(toConvert)) { - const chain = convertOccurrences(checker, toConvert.expression, occurrences); - const lastOccurrence = occurrences.length > 0 ? occurrences[occurrences.length - 1] : void 0; - const isOccurrence = (lastOccurrence == null ? void 0 : lastOccurrence.getText()) === toConvert.expression.getText(); - if (isOccurrence) - occurrences.pop(); - if (isCallExpression(toConvert)) { - return isOccurrence ? factory.createCallChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.typeArguments, toConvert.arguments) : factory.createCallChain(chain, toConvert.questionDotToken, toConvert.typeArguments, toConvert.arguments); - } else if (isPropertyAccessExpression(toConvert)) { - return isOccurrence ? factory.createPropertyAccessChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.name) : factory.createPropertyAccessChain(chain, toConvert.questionDotToken, toConvert.name); - } else if (isElementAccessExpression(toConvert)) { - return isOccurrence ? factory.createElementAccessChain(chain, factory.createToken(29 /* QuestionDotToken */), toConvert.argumentExpression) : factory.createElementAccessChain(chain, toConvert.questionDotToken, toConvert.argumentExpression); - } - } - return toConvert; - } - function doChange38(sourceFile, checker, changes, info, _actionName) { - const { finalExpression, occurrences, expression } = info; - const firstOccurrence = occurrences[occurrences.length - 1]; - const convertedChain = convertOccurrences(checker, finalExpression, occurrences); - if (convertedChain && (isPropertyAccessExpression(convertedChain) || isElementAccessExpression(convertedChain) || isCallExpression(convertedChain))) { - if (isBinaryExpression(expression)) { - changes.replaceNodeRange(sourceFile, firstOccurrence, finalExpression, convertedChain); - } else if (isConditionalExpression(expression)) { - changes.replaceNode( - sourceFile, - expression, - factory.createBinaryExpression(convertedChain, factory.createToken(61 /* QuestionQuestionToken */), expression.whenFalse) - ); - } - } - } - var refactorName10, convertToOptionalChainExpressionMessage, toOptionalChainAction; - var init_convertToOptionalChainExpression = __esm({ - "src/services/refactors/convertToOptionalChainExpression.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName10 = "Convert to optional chain expression"; - convertToOptionalChainExpressionMessage = getLocaleSpecificMessage(Diagnostics.Convert_to_optional_chain_expression); - toOptionalChainAction = { - name: refactorName10, - description: convertToOptionalChainExpressionMessage, - kind: "refactor.rewrite.expression.optionalChain" - }; - registerRefactor(refactorName10, { - kinds: [toOptionalChainAction.kind], - getEditsForAction: getRefactorEditsToConvertToOptionalChain, - getAvailableActions: getRefactorActionsToConvertToOptionalChain - }); - } - }); - - // src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts - var ts_refactor_convertToOptionalChainExpression_exports = {}; - var init_ts_refactor_convertToOptionalChainExpression = __esm({ - "src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts"() { - "use strict"; - init_convertToOptionalChainExpression(); - } - }); - - // src/services/refactors/extractSymbol.ts - function getRefactorActionsToExtractSymbol(context) { - const requestedRefactor = context.kind; - const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context), context.triggerReason === "invoked"); - const targetRange = rangeToExtract.targetRange; - if (targetRange === void 0) { - if (!rangeToExtract.errors || rangeToExtract.errors.length === 0 || !context.preferences.provideRefactorNotApplicableReason) { - return emptyArray; - } - const errors = []; - if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { - errors.push({ - name: refactorName11, - description: extractFunctionAction.description, - actions: [{ ...extractFunctionAction, notApplicableReason: getStringError(rangeToExtract.errors) }] - }); - } - if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { - errors.push({ - name: refactorName11, - description: extractConstantAction.description, - actions: [{ ...extractConstantAction, notApplicableReason: getStringError(rangeToExtract.errors) }] - }); - } - return errors; - } - const extractions = getPossibleExtractions(targetRange, context); - if (extractions === void 0) { - return emptyArray; - } - const functionActions = []; - const usedFunctionNames = /* @__PURE__ */ new Map(); - let innermostErrorFunctionAction; - const constantActions = []; - const usedConstantNames = /* @__PURE__ */ new Map(); - let innermostErrorConstantAction; - let i = 0; - for (const { functionExtraction, constantExtraction } of extractions) { - if (refactorKindBeginsWith(extractFunctionAction.kind, requestedRefactor)) { - const description2 = functionExtraction.description; - if (functionExtraction.errors.length === 0) { - if (!usedFunctionNames.has(description2)) { - usedFunctionNames.set(description2, true); - functionActions.push({ - description: description2, - name: `function_scope_${i}`, - kind: extractFunctionAction.kind - }); - } - } else if (!innermostErrorFunctionAction) { - innermostErrorFunctionAction = { - description: description2, - name: `function_scope_${i}`, - notApplicableReason: getStringError(functionExtraction.errors), - kind: extractFunctionAction.kind - }; - } - } - if (refactorKindBeginsWith(extractConstantAction.kind, requestedRefactor)) { - const description2 = constantExtraction.description; - if (constantExtraction.errors.length === 0) { - if (!usedConstantNames.has(description2)) { - usedConstantNames.set(description2, true); - constantActions.push({ - description: description2, - name: `constant_scope_${i}`, - kind: extractConstantAction.kind - }); - } - } else if (!innermostErrorConstantAction) { - innermostErrorConstantAction = { - description: description2, - name: `constant_scope_${i}`, - notApplicableReason: getStringError(constantExtraction.errors), - kind: extractConstantAction.kind - }; - } - } - i++; - } - const infos = []; - if (functionActions.length) { - infos.push({ - name: refactorName11, - description: getLocaleSpecificMessage(Diagnostics.Extract_function), - actions: functionActions - }); - } else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorFunctionAction) { - infos.push({ - name: refactorName11, - description: getLocaleSpecificMessage(Diagnostics.Extract_function), - actions: [innermostErrorFunctionAction] - }); - } - if (constantActions.length) { - infos.push({ - name: refactorName11, - description: getLocaleSpecificMessage(Diagnostics.Extract_constant), - actions: constantActions - }); - } else if (context.preferences.provideRefactorNotApplicableReason && innermostErrorConstantAction) { - infos.push({ - name: refactorName11, - description: getLocaleSpecificMessage(Diagnostics.Extract_constant), - actions: [innermostErrorConstantAction] - }); - } - return infos.length ? infos : emptyArray; - function getStringError(errors) { - let error = errors[0].messageText; - if (typeof error !== "string") { - error = error.messageText; - } - return error; - } - } - function getRefactorEditsToExtractSymbol(context, actionName2) { - const rangeToExtract = getRangeToExtract2(context.file, getRefactorContextSpan(context)); - const targetRange = rangeToExtract.targetRange; - const parsedFunctionIndexMatch = /^function_scope_(\d+)$/.exec(actionName2); - if (parsedFunctionIndexMatch) { - const index = +parsedFunctionIndexMatch[1]; - Debug.assert(isFinite(index), "Expected to parse a finite number from the function scope index"); - return getFunctionExtractionAtIndex(targetRange, context, index); - } - const parsedConstantIndexMatch = /^constant_scope_(\d+)$/.exec(actionName2); - if (parsedConstantIndexMatch) { - const index = +parsedConstantIndexMatch[1]; - Debug.assert(isFinite(index), "Expected to parse a finite number from the constant scope index"); - return getConstantExtractionAtIndex(targetRange, context, index); - } - Debug.fail("Unrecognized action name"); - } - function getRangeToExtract2(sourceFile, span, invoked = true) { - const { length: length2 } = span; - if (length2 === 0 && !invoked) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractEmpty)] }; - } - const cursorRequest = length2 === 0 && invoked; - const startToken = findFirstNonJsxWhitespaceToken(sourceFile, span.start); - const endToken = findTokenOnLeftOfPosition(sourceFile, textSpanEnd(span)); - const adjustedSpan = startToken && endToken && invoked ? getAdjustedSpanFromNodes(startToken, endToken, sourceFile) : span; - const start = cursorRequest ? getExtractableParent(startToken) : getParentNodeInSpan(startToken, sourceFile, adjustedSpan); - const end = cursorRequest ? start : getParentNodeInSpan(endToken, sourceFile, adjustedSpan); - let rangeFacts = 0 /* None */; - let thisNode; - if (!start || !end) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; - } - if (start.flags & 8388608 /* JSDoc */) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractJSDoc)] }; - } - if (start.parent !== end.parent) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; - } - if (start !== end) { - if (!isBlockLike(start.parent)) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; - } - const statements = []; - for (const statement of start.parent.statements) { - if (statement === start || statements.length) { - const errors2 = checkNode(statement); - if (errors2) { - return { errors: errors2 }; - } - statements.push(statement); - } - if (statement === end) { - break; - } - } - if (!statements.length) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; - } - return { targetRange: { range: statements, facts: rangeFacts, thisNode } }; - } - if (isReturnStatement(start) && !start.expression) { - return { errors: [createFileDiagnostic(sourceFile, span.start, length2, Messages.cannotExtractRange)] }; - } - const node = refineNode(start); - const errors = checkRootNode(node) || checkNode(node); - if (errors) { - return { errors }; - } - return { targetRange: { range: getStatementOrExpressionRange(node), facts: rangeFacts, thisNode } }; - function refineNode(node2) { - if (isReturnStatement(node2)) { - if (node2.expression) { - return node2.expression; - } - } else if (isVariableStatement(node2) || isVariableDeclarationList(node2)) { - const declarations = isVariableStatement(node2) ? node2.declarationList.declarations : node2.declarations; - let numInitializers = 0; - let lastInitializer; - for (const declaration of declarations) { - if (declaration.initializer) { - numInitializers++; - lastInitializer = declaration.initializer; - } - } - if (numInitializers === 1) { - return lastInitializer; - } - } else if (isVariableDeclaration(node2)) { - if (node2.initializer) { - return node2.initializer; - } - } - return node2; - } - function checkRootNode(node2) { - if (isIdentifier(isExpressionStatement(node2) ? node2.expression : node2)) { - return [createDiagnosticForNode(node2, Messages.cannotExtractIdentifier)]; - } - return void 0; - } - function checkForStaticContext(nodeToCheck, containingClass) { - let current = nodeToCheck; - while (current !== containingClass) { - if (current.kind === 171 /* PropertyDeclaration */) { - if (isStatic(current)) { - rangeFacts |= 32 /* InStaticRegion */; - } - break; - } else if (current.kind === 168 /* Parameter */) { - const ctorOrMethod = getContainingFunction(current); - if (ctorOrMethod.kind === 175 /* Constructor */) { - rangeFacts |= 32 /* InStaticRegion */; - } - break; - } else if (current.kind === 173 /* MethodDeclaration */) { - if (isStatic(current)) { - rangeFacts |= 32 /* InStaticRegion */; - } - } - current = current.parent; - } - } - function checkNode(nodeToCheck) { - let PermittedJumps; - ((PermittedJumps2) => { - PermittedJumps2[PermittedJumps2["None"] = 0] = "None"; - PermittedJumps2[PermittedJumps2["Break"] = 1] = "Break"; - PermittedJumps2[PermittedJumps2["Continue"] = 2] = "Continue"; - PermittedJumps2[PermittedJumps2["Return"] = 4] = "Return"; - })(PermittedJumps || (PermittedJumps = {})); - Debug.assert(nodeToCheck.pos <= nodeToCheck.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (1)"); - Debug.assert(!positionIsSynthesized(nodeToCheck.pos), "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809 (2)"); - if (!isStatement(nodeToCheck) && !(isExpressionNode(nodeToCheck) && isExtractableExpression(nodeToCheck)) && !isStringLiteralJsxAttribute(nodeToCheck)) { - return [createDiagnosticForNode(nodeToCheck, Messages.statementOrExpressionExpected)]; - } - if (nodeToCheck.flags & 16777216 /* Ambient */) { - return [createDiagnosticForNode(nodeToCheck, Messages.cannotExtractAmbientBlock)]; - } - const containingClass = getContainingClass(nodeToCheck); - if (containingClass) { - checkForStaticContext(nodeToCheck, containingClass); - } - let errors2; - let permittedJumps = 4 /* Return */; - let seenLabels; - visit(nodeToCheck); - if (rangeFacts & 8 /* UsesThis */) { - const container = getThisContainer( - nodeToCheck, - /*includeArrowFunctions*/ - false, - /*includeClassComputedPropertyName*/ - false - ); - if (container.kind === 261 /* FunctionDeclaration */ || container.kind === 173 /* MethodDeclaration */ && container.parent.kind === 209 /* ObjectLiteralExpression */ || container.kind === 217 /* FunctionExpression */) { - rangeFacts |= 16 /* UsesThisInFunction */; - } - } - return errors2; - function visit(node2) { - if (errors2) { - return true; - } - if (isDeclaration(node2)) { - const declaringNode = node2.kind === 259 /* VariableDeclaration */ ? node2.parent.parent : node2; - if (hasSyntacticModifier(declaringNode, 1 /* Export */)) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity)); - return true; - } - } - switch (node2.kind) { - case 271 /* ImportDeclaration */: - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractImport)); - return true; - case 276 /* ExportAssignment */: - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractExportedEntity)); - return true; - case 108 /* SuperKeyword */: - if (node2.parent.kind === 212 /* CallExpression */) { - const containingClass2 = getContainingClass(node2); - if (containingClass2 === void 0 || containingClass2.pos < span.start || containingClass2.end >= span.start + span.length) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractSuper)); - return true; - } - } else { - rangeFacts |= 8 /* UsesThis */; - thisNode = node2; - } - break; - case 218 /* ArrowFunction */: - forEachChild(node2, function check(n) { - if (isThis(n)) { - rangeFacts |= 8 /* UsesThis */; - thisNode = node2; - } else if (isClassLike(n) || isFunctionLike(n) && !isArrowFunction(n)) { - return false; - } else { - forEachChild(n, check); - } - }); - case 262 /* ClassDeclaration */: - case 261 /* FunctionDeclaration */: - if (isSourceFile(node2.parent) && node2.parent.externalModuleIndicator === void 0) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.functionWillNotBeVisibleInTheNewScope)); - } - case 230 /* ClassExpression */: - case 217 /* FunctionExpression */: - case 173 /* MethodDeclaration */: - case 175 /* Constructor */: - case 176 /* GetAccessor */: - case 177 /* SetAccessor */: - return false; - } - const savedPermittedJumps = permittedJumps; - switch (node2.kind) { - case 244 /* IfStatement */: - permittedJumps &= ~4 /* Return */; - break; - case 257 /* TryStatement */: - permittedJumps = 0 /* None */; - break; - case 240 /* Block */: - if (node2.parent && node2.parent.kind === 257 /* TryStatement */ && node2.parent.finallyBlock === node2) { - permittedJumps = 4 /* Return */; - } - break; - case 296 /* DefaultClause */: - case 295 /* CaseClause */: - permittedJumps |= 1 /* Break */; - break; - default: - if (isIterationStatement( - node2, - /*lookInLabeledStatements*/ - false - )) { - permittedJumps |= 1 /* Break */ | 2 /* Continue */; - } - break; - } - switch (node2.kind) { - case 196 /* ThisType */: - case 110 /* ThisKeyword */: - rangeFacts |= 8 /* UsesThis */; - thisNode = node2; - break; - case 255 /* LabeledStatement */: { - const label = node2.label; - (seenLabels || (seenLabels = [])).push(label.escapedText); - forEachChild(node2, visit); - seenLabels.pop(); - break; - } - case 251 /* BreakStatement */: - case 250 /* ContinueStatement */: { - const label = node2.label; - if (label) { - if (!contains(seenLabels, label.escapedText)) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); - } - } else { - if (!(permittedJumps & (node2.kind === 251 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); - } - } - break; - } - case 222 /* AwaitExpression */: - rangeFacts |= 4 /* IsAsyncFunction */; - break; - case 228 /* YieldExpression */: - rangeFacts |= 2 /* IsGenerator */; - break; - case 252 /* ReturnStatement */: - if (permittedJumps & 4 /* Return */) { - rangeFacts |= 1 /* HasReturn */; - } else { - (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.cannotExtractRangeContainingConditionalReturnStatement)); - } - break; - default: - forEachChild(node2, visit); - break; - } - permittedJumps = savedPermittedJumps; - } - } - } - function getAdjustedSpanFromNodes(startNode2, endNode2, sourceFile) { - const start = startNode2.getStart(sourceFile); - let end = endNode2.getEnd(); - if (sourceFile.text.charCodeAt(end) === 59 /* semicolon */) { - end++; - } - return { start, length: end - start }; - } - function getStatementOrExpressionRange(node) { - if (isStatement(node)) { - return [node]; - } - if (isExpressionNode(node)) { - return isExpressionStatement(node.parent) ? [node.parent] : node; - } - if (isStringLiteralJsxAttribute(node)) { - return node; - } - return void 0; - } - function isScope(node) { - return isArrowFunction(node) ? isFunctionBody(node.body) : isFunctionLikeDeclaration(node) || isSourceFile(node) || isModuleBlock(node) || isClassLike(node); - } - function collectEnclosingScopes(range) { - let current = isReadonlyArray(range.range) ? first(range.range) : range.range; - if (range.facts & 8 /* UsesThis */ && !(range.facts & 16 /* UsesThisInFunction */)) { - const containingClass = getContainingClass(current); - if (containingClass) { - const containingFunction = findAncestor(current, isFunctionLikeDeclaration); - return containingFunction ? [containingFunction, containingClass] : [containingClass]; - } - } - const scopes = []; - while (true) { - current = current.parent; - if (current.kind === 168 /* Parameter */) { - current = findAncestor(current, (parent2) => isFunctionLikeDeclaration(parent2)).parent; - } - if (isScope(current)) { - scopes.push(current); - if (current.kind === 311 /* SourceFile */) { - return scopes; - } - } - } - } - function getFunctionExtractionAtIndex(targetRange, context, requestedChangesIndex) { - const { scopes, readsAndWrites: { target, usagesPerScope, functionErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); - Debug.assert(!functionErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); - context.cancellationToken.throwIfCancellationRequested(); - return extractFunctionInScope(target, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], exposedVariableDeclarations, targetRange, context); - } - function getConstantExtractionAtIndex(targetRange, context, requestedChangesIndex) { - const { scopes, readsAndWrites: { target, usagesPerScope, constantErrorsPerScope, exposedVariableDeclarations } } = getPossibleExtractionsWorker(targetRange, context); - Debug.assert(!constantErrorsPerScope[requestedChangesIndex].length, "The extraction went missing? How?"); - Debug.assert(exposedVariableDeclarations.length === 0, "Extract constant accepted a range containing a variable declaration?"); - context.cancellationToken.throwIfCancellationRequested(); - const expression = isExpression(target) ? target : target.statements[0].expression; - return extractConstantInScope(expression, scopes[requestedChangesIndex], usagesPerScope[requestedChangesIndex], targetRange.facts, context); - } - function getPossibleExtractions(targetRange, context) { - const { scopes, readsAndWrites: { functionErrorsPerScope, constantErrorsPerScope } } = getPossibleExtractionsWorker(targetRange, context); - const extractions = scopes.map((scope, i) => { - const functionDescriptionPart = getDescriptionForFunctionInScope(scope); - const constantDescriptionPart = getDescriptionForConstantInScope(scope); - const scopeDescription = isFunctionLikeDeclaration(scope) ? getDescriptionForFunctionLikeDeclaration(scope) : isClassLike(scope) ? getDescriptionForClassLikeDeclaration(scope) : getDescriptionForModuleLikeDeclaration(scope); - let functionDescription; - let constantDescription; - if (scopeDescription === 1 /* Global */) { - functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "global"]); - constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "global"]); - } else if (scopeDescription === 0 /* Module */) { - functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [functionDescriptionPart, "module"]); - constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1_scope), [constantDescriptionPart, "module"]); - } else { - functionDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [functionDescriptionPart, scopeDescription]); - constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_1), [constantDescriptionPart, scopeDescription]); - } - if (i === 0 && !isClassLike(scope)) { - constantDescription = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Extract_to_0_in_enclosing_scope), [constantDescriptionPart]); - } - return { - functionExtraction: { - description: functionDescription, - errors: functionErrorsPerScope[i] - }, - constantExtraction: { - description: constantDescription, - errors: constantErrorsPerScope[i] - } - }; - }); - return extractions; - } - function getPossibleExtractionsWorker(targetRange, context) { - const { file: sourceFile } = context; - const scopes = collectEnclosingScopes(targetRange); - const enclosingTextRange = getEnclosingTextRange(targetRange, sourceFile); - const readsAndWrites = collectReadsAndWrites( - targetRange, - scopes, - enclosingTextRange, - sourceFile, - context.program.getTypeChecker(), - context.cancellationToken - ); - return { scopes, readsAndWrites }; - } - function getDescriptionForFunctionInScope(scope) { - return isFunctionLikeDeclaration(scope) ? "inner function" : isClassLike(scope) ? "method" : "function"; - } - function getDescriptionForConstantInScope(scope) { - return isClassLike(scope) ? "readonly field" : "constant"; - } - function getDescriptionForFunctionLikeDeclaration(scope) { - switch (scope.kind) { - case 175 /* Constructor */: - return "constructor"; - case 217 /* FunctionExpression */: - case 261 /* FunctionDeclaration */: - return scope.name ? `function '${scope.name.text}'` : ANONYMOUS; - case 218 /* ArrowFunction */: - return "arrow function"; - case 173 /* MethodDeclaration */: - return `method '${scope.name.getText()}'`; - case 176 /* GetAccessor */: - return `'get ${scope.name.getText()}'`; - case 177 /* SetAccessor */: - return `'set ${scope.name.getText()}'`; - default: - Debug.assertNever(scope, `Unexpected scope kind ${scope.kind}`); - } - } - function getDescriptionForClassLikeDeclaration(scope) { - return scope.kind === 262 /* ClassDeclaration */ ? scope.name ? `class '${scope.name.text}'` : "anonymous class declaration" : scope.name ? `class expression '${scope.name.text}'` : "anonymous class expression"; - } - function getDescriptionForModuleLikeDeclaration(scope) { - return scope.kind === 267 /* ModuleBlock */ ? `namespace '${scope.parent.name.getText()}'` : scope.externalModuleIndicator ? 0 /* Module */ : 1 /* Global */; - } - function extractFunctionInScope(node, scope, { usages: usagesInScope, typeParameterUsages, substitutions }, exposedVariableDeclarations, range, context) { - const checker = context.program.getTypeChecker(); - const scriptTarget = getEmitScriptTarget(context.program.getCompilerOptions()); - const importAdder = ts_codefix_exports.createImportAdder(context.file, context.program, context.preferences, context.host); - const file = scope.getSourceFile(); - const functionNameText = getUniqueName(isClassLike(scope) ? "newMethod" : "newFunction", file); - const isJS = isInJSFile(scope); - const functionName = factory.createIdentifier(functionNameText); - let returnType; - const parameters = []; - const callArguments = []; - let writes; - usagesInScope.forEach((usage, name) => { - let typeNode; - if (!isJS) { - let type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); - type = checker.getBaseTypeOfLiteralType(type); - typeNode = ts_codefix_exports.typeToAutoImportableTypeNode(checker, importAdder, type, scope, scriptTarget, 1 /* NoTruncation */); - } - const paramDecl = factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - /*name*/ - name, - /*questionToken*/ - void 0, - typeNode - ); - parameters.push(paramDecl); - if (usage.usage === 2 /* Write */) { - (writes || (writes = [])).push(usage); - } - callArguments.push(factory.createIdentifier(name)); - }); - const typeParametersAndDeclarations = arrayFrom(typeParameterUsages.values(), (type) => ({ type, declaration: getFirstDeclarationBeforePosition(type, context.startPosition) })); - const sortedTypeParametersAndDeclarations = typeParametersAndDeclarations.sort(compareTypesByDeclarationOrder); - const typeParameters = sortedTypeParametersAndDeclarations.length === 0 ? void 0 : mapDefined(sortedTypeParametersAndDeclarations, ({ declaration }) => declaration); - const callTypeArguments = typeParameters !== void 0 ? typeParameters.map((decl) => factory.createTypeReferenceNode( - decl.name, - /*typeArguments*/ - void 0 - )) : void 0; - if (isExpression(node) && !isJS) { - const contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); - } - const { body, returnValueProperty } = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & 1 /* HasReturn */)); - suppressLeadingAndTrailingTrivia(body); - let newFunction; - const callThis = !!(range.facts & 16 /* UsesThisInFunction */); - if (isClassLike(scope)) { - const modifiers = isJS ? [] : [factory.createModifier(123 /* PrivateKeyword */)]; - if (range.facts & 32 /* InStaticRegion */) { - modifiers.push(factory.createModifier(126 /* StaticKeyword */)); - } - if (range.facts & 4 /* IsAsyncFunction */) { - modifiers.push(factory.createModifier(134 /* AsyncKeyword */)); - } - newFunction = factory.createMethodDeclaration( - modifiers.length ? modifiers : void 0, - range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0, - functionName, - /*questionToken*/ - void 0, - typeParameters, - parameters, - returnType, - body - ); - } else { - if (callThis) { - parameters.unshift( - factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - /*name*/ - "this", - /*questionToken*/ - void 0, - checker.typeToTypeNode( - checker.getTypeAtLocation(range.thisNode), - scope, - 1 /* NoTruncation */ - ), - /*initializer*/ - void 0 - ) - ); - } - newFunction = factory.createFunctionDeclaration( - range.facts & 4 /* IsAsyncFunction */ ? [factory.createToken(134 /* AsyncKeyword */)] : void 0, - range.facts & 2 /* IsGenerator */ ? factory.createToken(42 /* AsteriskToken */) : void 0, - functionName, - typeParameters, - parameters, - returnType, - body - ); - } - const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); - const minInsertionPos = (isReadonlyArray(range.range) ? last(range.range) : range.range).end; - const nodeToInsertBefore = getNodeToInsertFunctionBefore(minInsertionPos, scope); - if (nodeToInsertBefore) { - changeTracker.insertNodeBefore( - context.file, - nodeToInsertBefore, - newFunction, - /*blankLineBetween*/ - true - ); - } else { - changeTracker.insertNodeAtEndOfScope(context.file, scope, newFunction); - } - importAdder.writeFixes(changeTracker); - const newNodes = []; - const called = getCalledExpression(scope, range, functionNameText); - if (callThis) { - callArguments.unshift(factory.createIdentifier("this")); - } - let call = factory.createCallExpression( - callThis ? factory.createPropertyAccessExpression( - called, - "call" - ) : called, - callTypeArguments, - // Note that no attempt is made to take advantage of type argument inference - callArguments - ); - if (range.facts & 2 /* IsGenerator */) { - call = factory.createYieldExpression(factory.createToken(42 /* AsteriskToken */), call); - } - if (range.facts & 4 /* IsAsyncFunction */) { - call = factory.createAwaitExpression(call); - } - if (isInJSXContent(node)) { - call = factory.createJsxExpression( - /*dotDotDotToken*/ - void 0, - call - ); - } - if (exposedVariableDeclarations.length && !writes) { - Debug.assert(!returnValueProperty, "Expected no returnValueProperty"); - Debug.assert(!(range.facts & 1 /* HasReturn */), "Expected RangeFacts.HasReturn flag to be unset"); - if (exposedVariableDeclarations.length === 1) { - const variableDeclaration = exposedVariableDeclarations[0]; - newNodes.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - getSynthesizedDeepClone(variableDeclaration.name), - /*exclamationToken*/ - void 0, - /*type*/ - getSynthesizedDeepClone(variableDeclaration.type), - /*initializer*/ - call - )], - variableDeclaration.parent.flags - ) - )); - } else { - const bindingElements = []; - const typeElements = []; - let commonNodeFlags = exposedVariableDeclarations[0].parent.flags; - let sawExplicitType = false; - for (const variableDeclaration of exposedVariableDeclarations) { - bindingElements.push(factory.createBindingElement( - /*dotDotDotToken*/ - void 0, - /*propertyName*/ - void 0, - /*name*/ - getSynthesizedDeepClone(variableDeclaration.name) - )); - const variableType = checker.typeToTypeNode( - checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), - scope, - 1 /* NoTruncation */ - ); - typeElements.push(factory.createPropertySignature( - /*modifiers*/ - void 0, - /*name*/ - variableDeclaration.symbol.name, - /*questionToken*/ - void 0, - /*type*/ - variableType - )); - sawExplicitType = sawExplicitType || variableDeclaration.type !== void 0; - commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; - } - const typeLiteral = sawExplicitType ? factory.createTypeLiteralNode(typeElements) : void 0; - if (typeLiteral) { - setEmitFlags(typeLiteral, 1 /* SingleLine */); - } - newNodes.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - factory.createObjectBindingPattern(bindingElements), - /*exclamationToken*/ - void 0, - /*type*/ - typeLiteral, - /*initializer*/ - call - )], - commonNodeFlags - ) - )); - } - } else if (exposedVariableDeclarations.length || writes) { - if (exposedVariableDeclarations.length) { - for (const variableDeclaration of exposedVariableDeclarations) { - let flags = variableDeclaration.parent.flags; - if (flags & 2 /* Const */) { - flags = flags & ~2 /* Const */ | 1 /* Let */; - } - newNodes.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - variableDeclaration.symbol.name, - /*exclamationToken*/ - void 0, - getTypeDeepCloneUnionUndefined(variableDeclaration.type) - )], - flags - ) - )); - } - } - if (returnValueProperty) { - newNodes.push(factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList( - [factory.createVariableDeclaration( - returnValueProperty, - /*exclamationToken*/ - void 0, - getTypeDeepCloneUnionUndefined(returnType) - )], - 1 /* Let */ - ) - )); - } - const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); - if (returnValueProperty) { - assignments.unshift(factory.createShorthandPropertyAssignment(returnValueProperty)); - } - if (assignments.length === 1) { - Debug.assert(!returnValueProperty, "Shouldn't have returnValueProperty here"); - newNodes.push(factory.createExpressionStatement(factory.createAssignment(assignments[0].name, call))); - if (range.facts & 1 /* HasReturn */) { - newNodes.push(factory.createReturnStatement()); - } - } else { - newNodes.push(factory.createExpressionStatement(factory.createAssignment(factory.createObjectLiteralExpression(assignments), call))); - if (returnValueProperty) { - newNodes.push(factory.createReturnStatement(factory.createIdentifier(returnValueProperty))); - } - } - } else { - if (range.facts & 1 /* HasReturn */) { - newNodes.push(factory.createReturnStatement(call)); - } else if (isReadonlyArray(range.range)) { - newNodes.push(factory.createExpressionStatement(call)); - } else { - newNodes.push(call); - } - } - if (isReadonlyArray(range.range)) { - changeTracker.replaceNodeRangeWithNodes(context.file, first(range.range), last(range.range), newNodes); - } else { - changeTracker.replaceNodeWithNodes(context.file, range.range, newNodes); - } - const edits = changeTracker.getChanges(); - const renameRange = isReadonlyArray(range.range) ? first(range.range) : range.range; - const renameFilename = renameRange.getSourceFile().fileName; - const renameLocation = getRenameLocation( - edits, - renameFilename, - functionNameText, - /*preferLastLocation*/ - false - ); - return { renameFilename, renameLocation, edits }; - function getTypeDeepCloneUnionUndefined(typeNode) { - if (typeNode === void 0) { - return void 0; - } - const clone2 = getSynthesizedDeepClone(typeNode); - let withoutParens = clone2; - while (isParenthesizedTypeNode(withoutParens)) { - withoutParens = withoutParens.type; - } - return isUnionTypeNode(withoutParens) && find(withoutParens.types, (t) => t.kind === 157 /* UndefinedKeyword */) ? clone2 : factory.createUnionTypeNode([clone2, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); - } - } - function extractConstantInScope(node, scope, { substitutions }, rangeFacts, context) { - const checker = context.program.getTypeChecker(); - const file = scope.getSourceFile(); - const localNameText = isPropertyAccessExpression(node) && !isClassLike(scope) && !checker.resolveName( - node.name.text, - node, - 111551 /* Value */, - /*excludeGlobals*/ - false - ) && !isPrivateIdentifier(node.name) && !identifierToKeywordKind(node.name) ? node.name.text : getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file); - const isJS = isInJSFile(scope); - let variableType = isJS || !checker.isContextSensitive(node) ? void 0 : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); - let initializer = transformConstantInitializer(skipParentheses(node), substitutions); - ({ variableType, initializer } = transformFunctionInitializerAndType(variableType, initializer)); - suppressLeadingAndTrailingTrivia(initializer); - const changeTracker = ts_textChanges_exports.ChangeTracker.fromContext(context); - if (isClassLike(scope)) { - Debug.assert(!isJS, "Cannot extract to a JS class"); - const modifiers = []; - modifiers.push(factory.createModifier(123 /* PrivateKeyword */)); - if (rangeFacts & 32 /* InStaticRegion */) { - modifiers.push(factory.createModifier(126 /* StaticKeyword */)); - } - modifiers.push(factory.createModifier(148 /* ReadonlyKeyword */)); - const newVariable = factory.createPropertyDeclaration( - modifiers, - localNameText, - /*questionOrExclamationToken*/ - void 0, - variableType, - initializer - ); - let localReference = factory.createPropertyAccessExpression( - rangeFacts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.getText()) : factory.createThis(), - factory.createIdentifier(localNameText) - ); - if (isInJSXContent(node)) { - localReference = factory.createJsxExpression( - /*dotDotDotToken*/ - void 0, - localReference - ); - } - const maxInsertionPos = node.pos; - const nodeToInsertBefore = getNodeToInsertPropertyBefore(maxInsertionPos, scope); - changeTracker.insertNodeBefore( - context.file, - nodeToInsertBefore, - newVariable, - /*blankLineBetween*/ - true - ); - changeTracker.replaceNode(context.file, node, localReference); - } else { - const newVariableDeclaration = factory.createVariableDeclaration( - localNameText, - /*exclamationToken*/ - void 0, - variableType, - initializer - ); - const oldVariableDeclaration = getContainingVariableDeclarationIfInList(node, scope); - if (oldVariableDeclaration) { - changeTracker.insertNodeBefore(context.file, oldVariableDeclaration, newVariableDeclaration); - const localReference = factory.createIdentifier(localNameText); - changeTracker.replaceNode(context.file, node, localReference); - } else if (node.parent.kind === 243 /* ExpressionStatement */ && scope === findAncestor(node, isScope)) { - const newVariableStatement = factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */) - ); - changeTracker.replaceNode(context.file, node.parent, newVariableStatement); - } else { - const newVariableStatement = factory.createVariableStatement( - /*modifiers*/ - void 0, - factory.createVariableDeclarationList([newVariableDeclaration], 2 /* Const */) - ); - const nodeToInsertBefore = getNodeToInsertConstantBefore(node, scope); - if (nodeToInsertBefore.pos === 0) { - changeTracker.insertNodeAtTopOfFile( - context.file, - newVariableStatement, - /*blankLineBetween*/ - false - ); - } else { - changeTracker.insertNodeBefore( - context.file, - nodeToInsertBefore, - newVariableStatement, - /*blankLineBetween*/ - false - ); - } - if (node.parent.kind === 243 /* ExpressionStatement */) { - changeTracker.delete(context.file, node.parent); - } else { - let localReference = factory.createIdentifier(localNameText); - if (isInJSXContent(node)) { - localReference = factory.createJsxExpression( - /*dotDotDotToken*/ - void 0, - localReference - ); - } - changeTracker.replaceNode(context.file, node, localReference); - } - } - } - const edits = changeTracker.getChanges(); - const renameFilename = node.getSourceFile().fileName; - const renameLocation = getRenameLocation( - edits, - renameFilename, - localNameText, - /*preferLastLocation*/ - true - ); - return { renameFilename, renameLocation, edits }; - function transformFunctionInitializerAndType(variableType2, initializer2) { - if (variableType2 === void 0) - return { variableType: variableType2, initializer: initializer2 }; - if (!isFunctionExpression(initializer2) && !isArrowFunction(initializer2) || !!initializer2.typeParameters) - return { variableType: variableType2, initializer: initializer2 }; - const functionType = checker.getTypeAtLocation(node); - const functionSignature = singleOrUndefined(checker.getSignaturesOfType(functionType, 0 /* Call */)); - if (!functionSignature) - return { variableType: variableType2, initializer: initializer2 }; - if (!!functionSignature.getTypeParameters()) - return { variableType: variableType2, initializer: initializer2 }; - const parameters = []; - let hasAny = false; - for (const p of initializer2.parameters) { - if (p.type) { - parameters.push(p); - } else { - 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, 1 /* NoTruncation */), - p.initializer - )); - } - } - if (hasAny) - return { variableType: variableType2, initializer: initializer2 }; - variableType2 = void 0; - if (isArrowFunction(initializer2)) { - initializer2 = factory.updateArrowFunction( - initializer2, - canHaveModifiers(node) ? getModifiers(node) : void 0, - initializer2.typeParameters, - parameters, - initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), - initializer2.equalsGreaterThanToken, - initializer2.body - ); - } else { - if (functionSignature && !!functionSignature.thisParameter) { - const firstParameter = firstOrUndefined(parameters); - if (!firstParameter || isIdentifier(firstParameter.name) && firstParameter.name.escapedText !== "this") { - const thisType = checker.getTypeOfSymbolAtLocation(functionSignature.thisParameter, node); - parameters.splice(0, 0, factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "this", - /*questionToken*/ - void 0, - checker.typeToTypeNode(thisType, scope, 1 /* NoTruncation */) - )); - } - } - initializer2 = factory.updateFunctionExpression( - initializer2, - canHaveModifiers(node) ? getModifiers(node) : void 0, - initializer2.asteriskToken, - initializer2.name, - initializer2.typeParameters, - parameters, - initializer2.type || checker.typeToTypeNode(functionSignature.getReturnType(), scope, 1 /* NoTruncation */), - initializer2.body - ); - } - return { variableType: variableType2, initializer: initializer2 }; - } - } - function getContainingVariableDeclarationIfInList(node, scope) { - let prevNode; - while (node !== void 0 && node !== scope) { - if (isVariableDeclaration(node) && node.initializer === prevNode && isVariableDeclarationList(node.parent) && node.parent.declarations.length > 1) { - return node; - } - prevNode = node; - node = node.parent; - } - } - function getFirstDeclarationBeforePosition(type, position) { - let firstDeclaration; - const symbol = type.symbol; - if (symbol && symbol.declarations) { - for (const declaration of symbol.declarations) { - if ((firstDeclaration === void 0 || declaration.pos < firstDeclaration.pos) && declaration.pos < position) { - firstDeclaration = declaration; - } - } - } - return firstDeclaration; - } - function compareTypesByDeclarationOrder({ type: type1, declaration: declaration1 }, { type: type2, declaration: declaration2 }) { - return compareProperties(declaration1, declaration2, "pos", compareValues) || compareStringsCaseSensitive( - type1.symbol ? type1.symbol.getName() : "", - type2.symbol ? type2.symbol.getName() : "" - ) || compareValues(type1.id, type2.id); - } - function getCalledExpression(scope, range, functionNameText) { - const functionReference = factory.createIdentifier(functionNameText); - if (isClassLike(scope)) { - const lhs = range.facts & 32 /* InStaticRegion */ ? factory.createIdentifier(scope.name.text) : factory.createThis(); - return factory.createPropertyAccessExpression(lhs, functionReference); - } else { - return functionReference; - } - } - function transformFunctionBody(body, exposedVariableDeclarations, writes, substitutions, hasReturn2) { - const hasWritesOrVariableDeclarations = writes !== void 0 || exposedVariableDeclarations.length > 0; - if (isBlock(body) && !hasWritesOrVariableDeclarations && substitutions.size === 0) { - return { body: factory.createBlock( - body.statements, - /*multiLine*/ - true - ), returnValueProperty: void 0 }; - } - let returnValueProperty; - let ignoreReturns = false; - const statements = factory.createNodeArray(isBlock(body) ? body.statements.slice(0) : [isStatement(body) ? body : factory.createReturnStatement(skipParentheses(body))]); - if (hasWritesOrVariableDeclarations || substitutions.size) { - const rewrittenStatements = visitNodes2(statements, visitor, isStatement).slice(); - if (hasWritesOrVariableDeclarations && !hasReturn2 && isStatement(body)) { - const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); - if (assignments.length === 1) { - rewrittenStatements.push(factory.createReturnStatement(assignments[0].name)); - } else { - rewrittenStatements.push(factory.createReturnStatement(factory.createObjectLiteralExpression(assignments))); - } - } - return { body: factory.createBlock( - rewrittenStatements, - /*multiLine*/ - true - ), returnValueProperty }; - } else { - return { body: factory.createBlock( - statements, - /*multiLine*/ - true - ), returnValueProperty: void 0 }; - } - function visitor(node) { - if (!ignoreReturns && isReturnStatement(node) && hasWritesOrVariableDeclarations) { - const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes); - if (node.expression) { - if (!returnValueProperty) { - returnValueProperty = "__return"; - } - assignments.unshift(factory.createPropertyAssignment(returnValueProperty, visitNode(node.expression, visitor, isExpression))); - } - if (assignments.length === 1) { - return factory.createReturnStatement(assignments[0].name); - } else { - return factory.createReturnStatement(factory.createObjectLiteralExpression(assignments)); - } - } else { - const oldIgnoreReturns = ignoreReturns; - ignoreReturns = ignoreReturns || isFunctionLikeDeclaration(node) || isClassLike(node); - const substitution = substitutions.get(getNodeId(node).toString()); - const result = substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext); - ignoreReturns = oldIgnoreReturns; - return result; - } - } - } - function transformConstantInitializer(initializer, substitutions) { - return substitutions.size ? visitor(initializer) : initializer; - function visitor(node) { - const substitution = substitutions.get(getNodeId(node).toString()); - return substitution ? getSynthesizedDeepClone(substitution) : visitEachChild(node, visitor, nullTransformationContext); - } - } - function getStatementsOrClassElements(scope) { - if (isFunctionLikeDeclaration(scope)) { - const body = scope.body; - if (isBlock(body)) { - return body.statements; - } - } else if (isModuleBlock(scope) || isSourceFile(scope)) { - return scope.statements; - } else if (isClassLike(scope)) { - return scope.members; - } else { - assertType(scope); - } - return emptyArray; - } - function getNodeToInsertFunctionBefore(minPos, scope) { - return find(getStatementsOrClassElements(scope), (child) => child.pos >= minPos && isFunctionLikeDeclaration(child) && !isConstructorDeclaration(child)); - } - function getNodeToInsertPropertyBefore(maxPos, scope) { - const members = scope.members; - Debug.assert(members.length > 0, "Found no members"); - let prevMember; - let allProperties = true; - for (const member of members) { - if (member.pos > maxPos) { - return prevMember || members[0]; - } - if (allProperties && !isPropertyDeclaration(member)) { - if (prevMember !== void 0) { - return member; - } - allProperties = false; - } - prevMember = member; - } - if (prevMember === void 0) - return Debug.fail(); - return prevMember; - } - function getNodeToInsertConstantBefore(node, scope) { - Debug.assert(!isClassLike(scope)); - let prevScope; - for (let curr = node; curr !== scope; curr = curr.parent) { - if (isScope(curr)) { - prevScope = curr; - } - } - for (let curr = (prevScope || node).parent; ; curr = curr.parent) { - if (isBlockLike(curr)) { - let prevStatement; - for (const statement of curr.statements) { - if (statement.pos > node.pos) { - break; - } - prevStatement = statement; - } - if (!prevStatement && isCaseClause(curr)) { - Debug.assert(isSwitchStatement(curr.parent.parent), "Grandparent isn't a switch statement"); - return curr.parent.parent; - } - return Debug.checkDefined(prevStatement, "prevStatement failed to get set"); - } - Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope"); - } - } - function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) { - const variableAssignments = map(exposedVariableDeclarations, (v) => factory.createShorthandPropertyAssignment(v.symbol.name)); - const writeAssignments = map(writes, (w) => factory.createShorthandPropertyAssignment(w.symbol.name)); - return variableAssignments === void 0 ? writeAssignments : writeAssignments === void 0 ? variableAssignments : variableAssignments.concat(writeAssignments); - } - function isReadonlyArray(v) { - return isArray(v); - } - function getEnclosingTextRange(targetRange, sourceFile) { - return isReadonlyArray(targetRange.range) ? { pos: first(targetRange.range).getStart(sourceFile), end: last(targetRange.range).getEnd() } : targetRange.range; - } - function collectReadsAndWrites(targetRange, scopes, enclosingTextRange, sourceFile, checker, cancellationToken) { - const allTypeParameterUsages = /* @__PURE__ */ new Map(); - const usagesPerScope = []; - const substitutionsPerScope = []; - const functionErrorsPerScope = []; - const constantErrorsPerScope = []; - const visibleDeclarationsInExtractedRange = []; - const exposedVariableSymbolSet = /* @__PURE__ */ new Map(); - const exposedVariableDeclarations = []; - let firstExposedNonVariableDeclaration; - const expression = !isReadonlyArray(targetRange.range) ? targetRange.range : targetRange.range.length === 1 && isExpressionStatement(targetRange.range[0]) ? targetRange.range[0].expression : void 0; - let expressionDiagnostic; - if (expression === void 0) { - const statements = targetRange.range; - const start = first(statements).getStart(); - const end = last(statements).end; - expressionDiagnostic = createFileDiagnostic(sourceFile, start, end - start, Messages.expressionExpected); - } else if (checker.getTypeAtLocation(expression).flags & (16384 /* Void */ | 131072 /* Never */)) { - expressionDiagnostic = createDiagnosticForNode(expression, Messages.uselessConstantType); - } - for (const scope of scopes) { - usagesPerScope.push({ usages: /* @__PURE__ */ new Map(), typeParameterUsages: /* @__PURE__ */ new Map(), substitutions: /* @__PURE__ */ new Map() }); - substitutionsPerScope.push(/* @__PURE__ */ new Map()); - functionErrorsPerScope.push([]); - const constantErrors = []; - if (expressionDiagnostic) { - constantErrors.push(expressionDiagnostic); - } - if (isClassLike(scope) && isInJSFile(scope)) { - constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); - } - if (isArrowFunction(scope) && !isBlock(scope.body)) { - constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToExpressionArrowFunction)); - } - constantErrorsPerScope.push(constantErrors); - } - const seenUsages = /* @__PURE__ */ new Map(); - const target = isReadonlyArray(targetRange.range) ? factory.createBlock(targetRange.range) : targetRange.range; - const unmodifiedNode = isReadonlyArray(targetRange.range) ? first(targetRange.range) : targetRange.range; - const inGenericContext = isInGenericContext(unmodifiedNode); - collectUsages(target); - if (inGenericContext && !isReadonlyArray(targetRange.range) && !isJsxAttribute(targetRange.range)) { - const contextualType = checker.getContextualType(targetRange.range); - recordTypeParameterUsages(contextualType); - } - if (allTypeParameterUsages.size > 0) { - const seenTypeParameterUsages = /* @__PURE__ */ new Map(); - let i = 0; - for (let curr = unmodifiedNode; curr !== void 0 && i < scopes.length; curr = curr.parent) { - if (curr === scopes[i]) { - seenTypeParameterUsages.forEach((typeParameter, id) => { - usagesPerScope[i].typeParameterUsages.set(id, typeParameter); - }); - i++; - } - if (isDeclarationWithTypeParameters(curr)) { - for (const typeParameterDecl of getEffectiveTypeParameterDeclarations(curr)) { - const typeParameter = checker.getTypeAtLocation(typeParameterDecl); - if (allTypeParameterUsages.has(typeParameter.id.toString())) { - seenTypeParameterUsages.set(typeParameter.id.toString(), typeParameter); - } - } - } - } - Debug.assert(i === scopes.length, "Should have iterated all scopes"); - } - if (visibleDeclarationsInExtractedRange.length) { - const containingLexicalScopeOfExtraction = isBlockScope(scopes[0], scopes[0].parent) ? scopes[0] : getEnclosingBlockScopeContainer(scopes[0]); - forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); - } - for (let i = 0; i < scopes.length; i++) { - const scopeUsages = usagesPerScope[i]; - if (i > 0 && (scopeUsages.usages.size > 0 || scopeUsages.typeParameterUsages.size > 0)) { - const errorNode = isReadonlyArray(targetRange.range) ? targetRange.range[0] : targetRange.range; - constantErrorsPerScope[i].push(createDiagnosticForNode(errorNode, Messages.cannotAccessVariablesFromNestedScopes)); - } - if (targetRange.facts & 16 /* UsesThisInFunction */ && isClassLike(scopes[i])) { - functionErrorsPerScope[i].push(createDiagnosticForNode(targetRange.thisNode, Messages.cannotExtractFunctionsContainingThisToMethod)); - } - let hasWrite = false; - let readonlyClassPropertyWrite; - usagesPerScope[i].usages.forEach((value) => { - if (value.usage === 2 /* Write */) { - hasWrite = true; - if (value.symbol.flags & 106500 /* ClassMember */ && value.symbol.valueDeclaration && hasEffectiveModifier(value.symbol.valueDeclaration, 64 /* Readonly */)) { - readonlyClassPropertyWrite = value.symbol.valueDeclaration; - } - } - }); - Debug.assert(isReadonlyArray(targetRange.range) || exposedVariableDeclarations.length === 0, "No variable declarations expected if something was extracted"); - if (hasWrite && !isReadonlyArray(targetRange.range)) { - const diag2 = createDiagnosticForNode(targetRange.range, Messages.cannotWriteInExpression); - functionErrorsPerScope[i].push(diag2); - constantErrorsPerScope[i].push(diag2); - } else if (readonlyClassPropertyWrite && i > 0) { - const diag2 = createDiagnosticForNode(readonlyClassPropertyWrite, Messages.cannotExtractReadonlyPropertyInitializerOutsideConstructor); - functionErrorsPerScope[i].push(diag2); - constantErrorsPerScope[i].push(diag2); - } else if (firstExposedNonVariableDeclaration) { - const diag2 = createDiagnosticForNode(firstExposedNonVariableDeclaration, Messages.cannotExtractExportedEntity); - functionErrorsPerScope[i].push(diag2); - constantErrorsPerScope[i].push(diag2); - } - } - return { target, usagesPerScope, functionErrorsPerScope, constantErrorsPerScope, exposedVariableDeclarations }; - function isInGenericContext(node) { - return !!findAncestor(node, (n) => isDeclarationWithTypeParameters(n) && getEffectiveTypeParameterDeclarations(n).length !== 0); - } - function recordTypeParameterUsages(type) { - const symbolWalker = checker.getSymbolWalker(() => (cancellationToken.throwIfCancellationRequested(), true)); - const { visitedTypes } = symbolWalker.walkType(type); - for (const visitedType of visitedTypes) { - if (visitedType.isTypeParameter()) { - allTypeParameterUsages.set(visitedType.id.toString(), visitedType); - } - } - } - function collectUsages(node, valueUsage = 1 /* Read */) { - if (inGenericContext) { - const type = checker.getTypeAtLocation(node); - recordTypeParameterUsages(type); - } - if (isDeclaration(node) && node.symbol) { - visibleDeclarationsInExtractedRange.push(node); - } - if (isAssignmentExpression(node)) { - collectUsages(node.left, 2 /* Write */); - collectUsages(node.right); - } else if (isUnaryExpressionWithWrite(node)) { - collectUsages(node.operand, 2 /* Write */); - } else if (isPropertyAccessExpression(node) || isElementAccessExpression(node)) { - forEachChild(node, collectUsages); - } else if (isIdentifier(node)) { - if (!node.parent) { - return; - } - if (isQualifiedName(node.parent) && node !== node.parent.left) { - return; - } - if (isPropertyAccessExpression(node.parent) && node !== node.parent.expression) { - return; - } - recordUsage( - node, - valueUsage, - /*isTypeNode*/ - isPartOfTypeNode(node) - ); - } else { - forEachChild(node, collectUsages); - } - } - function recordUsage(n, usage, isTypeNode2) { - const symbolId = recordUsagebySymbol(n, usage, isTypeNode2); - if (symbolId) { - for (let i = 0; i < scopes.length; i++) { - const substitution = substitutionsPerScope[i].get(symbolId); - if (substitution) { - usagesPerScope[i].substitutions.set(getNodeId(n).toString(), substitution); - } - } - } - } - function recordUsagebySymbol(identifier, usage, isTypeName) { - const symbol = getSymbolReferencedByIdentifier(identifier); - if (!symbol) { - return void 0; - } - const symbolId = getSymbolId(symbol).toString(); - const lastUsage = seenUsages.get(symbolId); - if (lastUsage && lastUsage >= usage) { - return symbolId; - } - seenUsages.set(symbolId, usage); - if (lastUsage) { - for (const perScope of usagesPerScope) { - const prevEntry = perScope.usages.get(identifier.text); - if (prevEntry) { - perScope.usages.set(identifier.text, { usage, symbol, node: identifier }); - } - } - return symbolId; - } - const decls = symbol.getDeclarations(); - const declInFile = decls && find(decls, (d) => d.getSourceFile() === sourceFile); - if (!declInFile) { - return void 0; - } - if (rangeContainsStartEnd(enclosingTextRange, declInFile.getStart(), declInFile.end)) { - return void 0; - } - if (targetRange.facts & 2 /* IsGenerator */ && usage === 2 /* Write */) { - const diag2 = createDiagnosticForNode(identifier, Messages.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators); - for (const errors of functionErrorsPerScope) { - errors.push(diag2); - } - for (const errors of constantErrorsPerScope) { - errors.push(diag2); - } - } - for (let i = 0; i < scopes.length; i++) { - const scope = scopes[i]; - const resolvedSymbol = checker.resolveName( - symbol.name, - scope, - symbol.flags, - /*excludeGlobals*/ - false - ); - if (resolvedSymbol === symbol) { - continue; - } - if (!substitutionsPerScope[i].has(symbolId)) { - const substitution = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.exportSymbol || symbol, scope, isTypeName); - if (substitution) { - substitutionsPerScope[i].set(symbolId, substitution); - } else if (isTypeName) { - if (!(symbol.flags & 262144 /* TypeParameter */)) { - const diag2 = createDiagnosticForNode(identifier, Messages.typeWillNotBeVisibleInTheNewScope); - functionErrorsPerScope[i].push(diag2); - constantErrorsPerScope[i].push(diag2); - } - } else { - usagesPerScope[i].usages.set(identifier.text, { usage, symbol, node: identifier }); - } - } - } - return symbolId; - } - function checkForUsedDeclarations(node) { - if (node === targetRange.range || isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node) >= 0) { - return; - } - const sym = isIdentifier(node) ? getSymbolReferencedByIdentifier(node) : checker.getSymbolAtLocation(node); - if (sym) { - const decl = find(visibleDeclarationsInExtractedRange, (d) => d.symbol === sym); - if (decl) { - if (isVariableDeclaration(decl)) { - const idString = decl.symbol.id.toString(); - if (!exposedVariableSymbolSet.has(idString)) { - exposedVariableDeclarations.push(decl); - exposedVariableSymbolSet.set(idString, true); - } - } else { - firstExposedNonVariableDeclaration = firstExposedNonVariableDeclaration || decl; - } - } - } - forEachChild(node, checkForUsedDeclarations); - } - function getSymbolReferencedByIdentifier(identifier) { - return identifier.parent && isShorthandPropertyAssignment(identifier.parent) && identifier.parent.name === identifier ? checker.getShorthandAssignmentValueSymbol(identifier.parent) : checker.getSymbolAtLocation(identifier); - } - function tryReplaceWithQualifiedNameOrPropertyAccess(symbol, scopeDecl, isTypeNode2) { - if (!symbol) { - return void 0; - } - const decls = symbol.getDeclarations(); - if (decls && decls.some((d) => d.parent === scopeDecl)) { - return factory.createIdentifier(symbol.name); - } - const prefix = tryReplaceWithQualifiedNameOrPropertyAccess(symbol.parent, scopeDecl, isTypeNode2); - if (prefix === void 0) { - return void 0; - } - return isTypeNode2 ? factory.createQualifiedName(prefix, factory.createIdentifier(symbol.name)) : factory.createPropertyAccessExpression(prefix, symbol.name); - } - } - function getExtractableParent(node) { - return findAncestor(node, (node2) => node2.parent && isExtractableExpression(node2) && !isBinaryExpression(node2.parent)); - } - function isExtractableExpression(node) { - const { parent: parent2 } = node; - switch (parent2.kind) { - case 305 /* EnumMember */: - return false; - } - switch (node.kind) { - case 11 /* StringLiteral */: - return parent2.kind !== 271 /* ImportDeclaration */ && parent2.kind !== 275 /* ImportSpecifier */; - case 229 /* SpreadElement */: - case 205 /* ObjectBindingPattern */: - case 207 /* BindingElement */: - return false; - case 80 /* Identifier */: - return parent2.kind !== 207 /* BindingElement */ && parent2.kind !== 275 /* ImportSpecifier */ && parent2.kind !== 280 /* ExportSpecifier */; - } - return true; - } - function isBlockLike(node) { - switch (node.kind) { - case 240 /* Block */: - case 311 /* SourceFile */: - case 267 /* ModuleBlock */: - case 295 /* CaseClause */: - return true; - default: - return false; - } - } - function isInJSXContent(node) { - return isStringLiteralJsxAttribute(node) || (isJsxElement(node) || isJsxSelfClosingElement(node) || isJsxFragment(node)) && (isJsxElement(node.parent) || isJsxFragment(node.parent)); - } - function isStringLiteralJsxAttribute(node) { - return isStringLiteral(node) && node.parent && isJsxAttribute(node.parent); - } - var refactorName11, extractConstantAction, extractFunctionAction, Messages, RangeFacts; - var init_extractSymbol = __esm({ - "src/services/refactors/extractSymbol.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName11 = "Extract Symbol"; - extractConstantAction = { - name: "Extract Constant", - description: getLocaleSpecificMessage(Diagnostics.Extract_constant), - kind: "refactor.extract.constant" - }; - extractFunctionAction = { - name: "Extract Function", - description: getLocaleSpecificMessage(Diagnostics.Extract_function), - kind: "refactor.extract.function" - }; - registerRefactor(refactorName11, { - kinds: [ - extractConstantAction.kind, - extractFunctionAction.kind - ], - getEditsForAction: getRefactorEditsToExtractSymbol, - getAvailableActions: getRefactorActionsToExtractSymbol - }); - ((Messages2) => { - function createMessage(message) { - return { message, code: 0, category: 3 /* Message */, key: message }; - } - Messages2.cannotExtractRange = createMessage("Cannot extract range."); - Messages2.cannotExtractImport = createMessage("Cannot extract import statement."); - Messages2.cannotExtractSuper = createMessage("Cannot extract super call."); - Messages2.cannotExtractJSDoc = createMessage("Cannot extract JSDoc."); - Messages2.cannotExtractEmpty = createMessage("Cannot extract empty range."); - Messages2.expressionExpected = createMessage("expression expected."); - Messages2.uselessConstantType = createMessage("No reason to extract constant of type."); - Messages2.statementOrExpressionExpected = createMessage("Statement or expression expected."); - Messages2.cannotExtractRangeContainingConditionalBreakOrContinueStatements = createMessage("Cannot extract range containing conditional break or continue statements."); - Messages2.cannotExtractRangeContainingConditionalReturnStatement = createMessage("Cannot extract range containing conditional return statement."); - Messages2.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange = createMessage("Cannot extract range containing labeled break or continue with target outside of the range."); - Messages2.cannotExtractRangeThatContainsWritesToReferencesLocatedOutsideOfTheTargetRangeInGenerators = createMessage("Cannot extract range containing writes to references located outside of the target range in generators."); - Messages2.typeWillNotBeVisibleInTheNewScope = createMessage("Type will not visible in the new scope."); - Messages2.functionWillNotBeVisibleInTheNewScope = createMessage("Function will not visible in the new scope."); - Messages2.cannotExtractIdentifier = createMessage("Select more than a single identifier."); - Messages2.cannotExtractExportedEntity = createMessage("Cannot extract exported declaration"); - Messages2.cannotWriteInExpression = createMessage("Cannot write back side-effects when extracting an expression"); - Messages2.cannotExtractReadonlyPropertyInitializerOutsideConstructor = createMessage("Cannot move initialization of read-only class property outside of the constructor"); - Messages2.cannotExtractAmbientBlock = createMessage("Cannot extract code from ambient contexts"); - Messages2.cannotAccessVariablesFromNestedScopes = createMessage("Cannot access variables from nested scopes"); - Messages2.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); - Messages2.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); - Messages2.cannotExtractFunctionsContainingThisToMethod = createMessage("Cannot extract functions containing this to method"); - })(Messages || (Messages = {})); - RangeFacts = /* @__PURE__ */ ((RangeFacts2) => { - RangeFacts2[RangeFacts2["None"] = 0] = "None"; - RangeFacts2[RangeFacts2["HasReturn"] = 1] = "HasReturn"; - RangeFacts2[RangeFacts2["IsGenerator"] = 2] = "IsGenerator"; - RangeFacts2[RangeFacts2["IsAsyncFunction"] = 4] = "IsAsyncFunction"; - RangeFacts2[RangeFacts2["UsesThis"] = 8] = "UsesThis"; - RangeFacts2[RangeFacts2["UsesThisInFunction"] = 16] = "UsesThisInFunction"; - RangeFacts2[RangeFacts2["InStaticRegion"] = 32] = "InStaticRegion"; - return RangeFacts2; - })(RangeFacts || {}); - } - }); - - // src/services/_namespaces/ts.refactor.extractSymbol.ts - var ts_refactor_extractSymbol_exports = {}; - __export(ts_refactor_extractSymbol_exports, { - Messages: () => Messages, - RangeFacts: () => RangeFacts, - getRangeToExtract: () => getRangeToExtract2, - getRefactorActionsToExtractSymbol: () => getRefactorActionsToExtractSymbol, - getRefactorEditsToExtractSymbol: () => getRefactorEditsToExtractSymbol - }); - var init_ts_refactor_extractSymbol = __esm({ - "src/services/_namespaces/ts.refactor.extractSymbol.ts"() { - "use strict"; - init_extractSymbol(); - } - }); - - // src/services/refactors/generateGetAccessorAndSetAccessor.ts - var actionName, actionDescription, generateGetSetAction; - var init_generateGetAccessorAndSetAccessor = __esm({ - "src/services/refactors/generateGetAccessorAndSetAccessor.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - actionName = "Generate 'get' and 'set' accessors"; - actionDescription = Diagnostics.Generate_get_and_set_accessors.message; - generateGetSetAction = { - name: actionName, - description: actionDescription, - kind: "refactor.rewrite.property.generateAccessors" - }; - registerRefactor(actionName, { - kinds: [generateGetSetAction.kind], - getEditsForAction: function getRefactorActionsToGenerateGetAndSetAccessors(context, actionName2) { - if (!context.endPosition) - return void 0; - const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition); - Debug.assert(info && !isRefactorErrorInfo(info), "Expected applicable refactor info"); - const edits = ts_codefix_exports.generateAccessorFromProperty(context.file, context.program, context.startPosition, context.endPosition, context, actionName2); - if (!edits) - return void 0; - const renameFilename = context.file.fileName; - const nameNeedRename = info.renameAccessor ? info.accessorName : info.fieldName; - const renameLocationOffset = isIdentifier(nameNeedRename) ? 0 : -1; - const renameLocation = renameLocationOffset + getRenameLocation( - edits, - renameFilename, - nameNeedRename.text, - /*preferLastLocation*/ - isParameter(info.declaration) - ); - return { renameFilename, renameLocation, edits }; - }, - getAvailableActions(context) { - if (!context.endPosition) - return emptyArray; - const info = ts_codefix_exports.getAccessorConvertiblePropertyAtPosition(context.file, context.program, context.startPosition, context.endPosition, context.triggerReason === "invoked"); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - return [{ - name: actionName, - description: actionDescription, - actions: [generateGetSetAction] - }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: actionName, - description: actionDescription, - actions: [{ ...generateGetSetAction, notApplicableReason: info.error }] - }]; - } - return emptyArray; - } - }); - } - }); - - // src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts - var ts_refactor_generateGetAccessorAndSetAccessor_exports = {}; - var init_ts_refactor_generateGetAccessorAndSetAccessor = __esm({ - "src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts"() { - "use strict"; - init_generateGetAccessorAndSetAccessor(); - } - }); - - // src/services/refactors/inferFunctionReturnType.ts - function getRefactorEditsToInferReturnType(context) { - const info = getInfo21(context); - if (info && !isRefactorErrorInfo(info)) { - const edits = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange39(context.file, t, info.declaration, info.returnTypeNode)); - return { renameFilename: void 0, renameLocation: void 0, edits }; - } - return void 0; - } - function getRefactorActionsToInferReturnType(context) { - const info = getInfo21(context); - if (!info) - return emptyArray; - if (!isRefactorErrorInfo(info)) { - return [{ - name: refactorName12, - description: refactorDescription6, - actions: [inferReturnTypeAction] - }]; - } - if (context.preferences.provideRefactorNotApplicableReason) { - return [{ - name: refactorName12, - description: refactorDescription6, - actions: [{ ...inferReturnTypeAction, notApplicableReason: info.error }] - }]; - } - return emptyArray; - } - function doChange39(sourceFile, changes, declaration, typeNode) { - const closeParen = findChildOfKind(declaration, 22 /* CloseParenToken */, sourceFile); - const needParens = isArrowFunction(declaration) && closeParen === void 0; - const endNode2 = needParens ? first(declaration.parameters) : closeParen; - if (endNode2) { - if (needParens) { - changes.insertNodeBefore(sourceFile, endNode2, factory.createToken(21 /* OpenParenToken */)); - changes.insertNodeAfter(sourceFile, endNode2, factory.createToken(22 /* CloseParenToken */)); - } - changes.insertNodeAt(sourceFile, endNode2.end, typeNode, { prefix: ": " }); - } - } - function getInfo21(context) { - if (isInJSFile(context.file) || !refactorKindBeginsWith(inferReturnTypeAction.kind, context.kind)) - return; - const token = getTokenAtPosition(context.file, context.startPosition); - const declaration = findAncestor(token, (n) => isBlock(n) || n.parent && isArrowFunction(n.parent) && (n.kind === 39 /* EqualsGreaterThanToken */ || n.parent.body === n) ? "quit" : isConvertibleDeclaration(n)); - if (!declaration || !declaration.body || declaration.type) { - return { error: getLocaleSpecificMessage(Diagnostics.Return_type_must_be_inferred_from_a_function) }; - } - const typeChecker = context.program.getTypeChecker(); - const returnType = tryGetReturnType(typeChecker, declaration); - if (!returnType) { - return { error: getLocaleSpecificMessage(Diagnostics.Could_not_determine_function_return_type) }; - } - const returnTypeNode = typeChecker.typeToTypeNode(returnType, declaration, 1 /* NoTruncation */); - if (returnTypeNode) { - return { declaration, returnTypeNode }; - } - } - function isConvertibleDeclaration(node) { - switch (node.kind) { - case 261 /* FunctionDeclaration */: - case 217 /* FunctionExpression */: - case 218 /* ArrowFunction */: - case 173 /* MethodDeclaration */: - return true; - default: - return false; - } - } - function tryGetReturnType(typeChecker, node) { - if (typeChecker.isImplementationOfOverload(node)) { - const signatures = typeChecker.getTypeAtLocation(node).getCallSignatures(); - if (signatures.length > 1) { - return typeChecker.getUnionType(mapDefined(signatures, (s) => s.getReturnType())); - } - } - const signature = typeChecker.getSignatureFromDeclaration(node); - if (signature) { - return typeChecker.getReturnTypeOfSignature(signature); - } - } - var refactorName12, refactorDescription6, inferReturnTypeAction; - var init_inferFunctionReturnType = __esm({ - "src/services/refactors/inferFunctionReturnType.ts"() { - "use strict"; - init_ts4(); - init_ts_refactor(); - refactorName12 = "Infer function return type"; - refactorDescription6 = Diagnostics.Infer_function_return_type.message; - inferReturnTypeAction = { - name: refactorName12, - description: refactorDescription6, - kind: "refactor.rewrite.function.returnType" - }; - registerRefactor(refactorName12, { - kinds: [inferReturnTypeAction.kind], - getEditsForAction: getRefactorEditsToInferReturnType, - getAvailableActions: getRefactorActionsToInferReturnType - }); - } - }); - - // src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts - var ts_refactor_inferFunctionReturnType_exports = {}; - var init_ts_refactor_inferFunctionReturnType = __esm({ - "src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts"() { - "use strict"; - init_inferFunctionReturnType(); - } - }); - - // src/services/_namespaces/ts.refactor.ts - var ts_refactor_exports = {}; - __export(ts_refactor_exports, { - addOrRemoveBracesToArrowFunction: () => ts_refactor_addOrRemoveBracesToArrowFunction_exports, - convertArrowFunctionOrFunctionExpression: () => ts_refactor_convertArrowFunctionOrFunctionExpression_exports, - convertParamsToDestructuredObject: () => ts_refactor_convertParamsToDestructuredObject_exports, - convertStringOrTemplateLiteral: () => ts_refactor_convertStringOrTemplateLiteral_exports, - convertToOptionalChainExpression: () => ts_refactor_convertToOptionalChainExpression_exports, - doChangeNamedToNamespaceOrDefault: () => doChangeNamedToNamespaceOrDefault, - extractSymbol: () => ts_refactor_extractSymbol_exports, - generateGetAccessorAndSetAccessor: () => ts_refactor_generateGetAccessorAndSetAccessor_exports, - getApplicableRefactors: () => getApplicableRefactors, - getEditsForRefactor: () => getEditsForRefactor, - inferFunctionReturnType: () => ts_refactor_inferFunctionReturnType_exports, - isRefactorErrorInfo: () => isRefactorErrorInfo, - refactorKindBeginsWith: () => refactorKindBeginsWith, - registerRefactor: () => registerRefactor - }); - var init_ts_refactor = __esm({ - "src/services/_namespaces/ts.refactor.ts"() { - "use strict"; - init_refactorProvider(); - init_convertExport(); - init_convertImport(); - init_extractType(); - init_helpers2(); - init_moveToNewFile(); - init_ts_refactor_addOrRemoveBracesToArrowFunction(); - init_ts_refactor_convertArrowFunctionOrFunctionExpression(); - init_ts_refactor_convertParamsToDestructuredObject(); - init_ts_refactor_convertStringOrTemplateLiteral(); - init_ts_refactor_convertToOptionalChainExpression(); - init_ts_refactor_extractSymbol(); - init_ts_refactor_generateGetAccessorAndSetAccessor(); - init_ts_refactor_inferFunctionReturnType(); - } - }); - // src/services/rename.ts function getRenameInfo(program, sourceFile, position, preferences) { const node = getAdjustedRenameLocation(getTouchingPropertyName(sourceFile, position)); @@ -163839,7 +164644,7 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} displayParts.push(spacePart()); displayParts.push(operatorPart(64 /* EqualsToken */)); displayParts.push(spacePart()); - addRange(displayParts, typeToDisplayParts(typeChecker, isConstTypeReference(location.parent) ? typeChecker.getTypeAtLocation(location.parent) : typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); + addRange(displayParts, typeToDisplayParts(typeChecker, location.parent && isConstTypeReference(location.parent) ? typeChecker.getTypeAtLocation(location.parent) : typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { prefixNextMeaning(); @@ -163915,12 +164720,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} } if (symbol.flags & 2097152 /* Alias */) { prefixNextMeaning(); - if (!hasAddedSymbolInfo) { + if (!hasAddedSymbolInfo || documentation.length === 0 && tags.length === 0) { const resolvedSymbol = typeChecker.getAliasedSymbol(symbol); if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { const resolvedNode = resolvedSymbol.declarations[0]; const declarationName = getNameOfDeclaration(resolvedNode); - if (declarationName) { + if (declarationName && !hasAddedSymbolInfo) { const isExternalModuleDeclaration = isModuleWithStringLiteralName(resolvedNode) && hasSyntacticModifier(resolvedNode, 2 /* Ambient */); const shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind( @@ -164460,16 +165265,6 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} function getMembersOrProperties(node) { return isObjectLiteralExpression(node) ? node.properties : node.members; } - function getNewFileText(statements, scriptKind, newLineCharacter, formatContext) { - return changesToText.newFileChangesWorker( - /*oldFile*/ - void 0, - scriptKind, - statements, - newLineCharacter, - formatContext - ); - } function applyChanges(text, changes) { for (let i = changes.length - 1; i >= 0; i--) { const { span, newText } = changes[i]; @@ -164827,7 +165622,6 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} this.newLineCharacter = newLineCharacter; this.formatContext = formatContext; this.changes = []; - this.newFiles = []; this.classesWithNodesInsertedAtStart = /* @__PURE__ */ new Map(); // Set implemented as Map this.deletedNodes = []; @@ -164943,6 +165737,12 @@ ${newComment.split("\n").map((c) => ` * ${c}`).join("\n")} this.insertNodeAt(sourceFile, pos, insert, options); } } + insertStatementsInNewFile(fileName, statements, oldFile) { + if (!this.newFileChanges) { + this.newFileChanges = createMultiMap(); + } + this.newFileChanges.add(fileName, { oldFile, statements }); + } insertFirstParameter(sourceFile, parameters, newParam) { const p0 = firstOrUndefined(parameters); if (p0) { @@ -165338,13 +166138,15 @@ ${options.prefix}` : "\n" : options.prefix this.finishDeleteDeclarations(); this.finishClassesWithNodesInsertedAtStart(); const changes = changesToText.getTextChangesFromChanges(this.changes, this.newLineCharacter, this.formatContext, validate); - for (const { oldFile, fileName, statements } of this.newFiles) { - changes.push(changesToText.newFileChanges(oldFile, fileName, statements, this.newLineCharacter, this.formatContext)); + if (this.newFileChanges) { + this.newFileChanges.forEach((insertions, fileName) => { + changes.push(changesToText.newFileChanges(fileName, insertions, this.newLineCharacter, this.formatContext)); + }); } return changes; } createNewFile(oldFile, fileName, statements) { - this.newFiles.push({ oldFile, fileName, statements }); + this.insertStatementsInNewFile(fileName, statements, oldFile); } }; ((changesToText2) => { @@ -165357,8 +166159,9 @@ ${options.prefix}` : "\n" : options.prefix } const textChanges2 = mapDefined(normalized, (c) => { const span = createTextSpanFromRange(c.range); - const newText = computeNewText(c, sourceFile, newLineCharacter, formatContext, validate); - if (span.length === newText.length && stringContainsAt(sourceFile.text, newText, span.start)) { + const targetSourceFile = c.kind === 1 /* ReplaceWithSingleNode */ ? getSourceFileOfNode(getOriginalNode(c.node)) ?? c.sourceFile : c.kind === 2 /* ReplaceWithMultipleNodes */ ? getSourceFileOfNode(getOriginalNode(c.nodes[0])) ?? c.sourceFile : c.sourceFile; + const newText = computeNewText(c, targetSourceFile, sourceFile, newLineCharacter, formatContext, validate); + if (span.length === newText.length && stringContainsAt(targetSourceFile.text, newText, span.start)) { return void 0; } return createTextChange(span, newText); @@ -165367,13 +166170,13 @@ ${options.prefix}` : "\n" : options.prefix }); } changesToText2.getTextChangesFromChanges = getTextChangesFromChanges; - function newFileChanges(oldFile, fileName, statements, newLineCharacter, formatContext) { - const text = newFileChangesWorker(oldFile, getScriptKindFromFileName(fileName), statements, newLineCharacter, formatContext); + function newFileChanges(fileName, insertions, newLineCharacter, formatContext) { + const text = newFileChangesWorker(getScriptKindFromFileName(fileName), insertions, newLineCharacter, formatContext); return { fileName, textChanges: [createTextChange(createTextSpan(0, 0), text)], isNewFile: true }; } changesToText2.newFileChanges = newFileChanges; - function newFileChangesWorker(oldFile, scriptKind, statements, newLineCharacter, formatContext) { - const nonFormattedText = statements.map((s) => s === 4 /* NewLineTrivia */ ? "" : getNonformattedText(s, oldFile, newLineCharacter).text).join(newLineCharacter); + function newFileChangesWorker(scriptKind, insertions, newLineCharacter, formatContext) { + const nonFormattedText = flatMap(insertions, (insertion) => insertion.statements.map((s) => s === 4 /* NewLineTrivia */ ? "" : getNonformattedText(s, insertion.oldFile, newLineCharacter).text)).join(newLineCharacter); const sourceFile = createSourceFile( "any file name", nonFormattedText, @@ -165386,7 +166189,7 @@ ${options.prefix}` : "\n" : options.prefix return applyChanges(nonFormattedText, changes) + newLineCharacter; } changesToText2.newFileChangesWorker = newFileChangesWorker; - function computeNewText(change, sourceFile, newLineCharacter, formatContext, validate) { + function computeNewText(change, targetSourceFile, sourceFile, newLineCharacter, formatContext, validate) { var _a; if (change.kind === 0 /* Remove */) { return ""; @@ -165395,17 +166198,17 @@ ${options.prefix}` : "\n" : options.prefix return change.text; } const { options = {}, range: { pos } } = change; - const format = (n) => getFormattedTextOfNode(n, sourceFile, pos, options, newLineCharacter, formatContext, validate); + const format = (n) => getFormattedTextOfNode(n, targetSourceFile, sourceFile, pos, options, newLineCharacter, formatContext, validate); const text = change.kind === 2 /* ReplaceWithMultipleNodes */ ? change.nodes.map((n) => removeSuffix(format(n), newLineCharacter)).join(((_a = change.options) == null ? void 0 : _a.joiner) || newLineCharacter) : format(change.node); - const noIndent = options.indentation !== void 0 || getLineStartPositionForPosition(pos, sourceFile) === pos ? text : text.replace(/^\s+/, ""); + const noIndent = options.indentation !== void 0 || getLineStartPositionForPosition(pos, targetSourceFile) === pos ? text : text.replace(/^\s+/, ""); return (options.prefix || "") + noIndent + (!options.suffix || endsWith(noIndent, options.suffix) ? "" : options.suffix); } - function getFormattedTextOfNode(nodeIn, sourceFile, pos, { indentation, prefix, delta }, newLineCharacter, formatContext, validate) { - const { node, text } = getNonformattedText(nodeIn, sourceFile, newLineCharacter); + function getFormattedTextOfNode(nodeIn, targetSourceFile, sourceFile, pos, { indentation, prefix, delta }, newLineCharacter, formatContext, validate) { + const { node, text } = getNonformattedText(nodeIn, targetSourceFile, newLineCharacter); if (validate) validate(node, text); - const formatOptions = getFormatCodeSettingsForWriting(formatContext, sourceFile); - const initialIndentation = indentation !== void 0 ? indentation : ts_formatting_exports.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || getLineStartPositionForPosition(pos, sourceFile) === pos); + const formatOptions = getFormatCodeSettingsForWriting(formatContext, targetSourceFile); + const initialIndentation = indentation !== void 0 ? indentation : ts_formatting_exports.SmartIndenter.getIndentation(pos, sourceFile, formatOptions, prefix === newLineCharacter || getLineStartPositionForPosition(pos, targetSourceFile) === pos); if (delta === void 0) { delta = ts_formatting_exports.SmartIndenter.shouldIndentChildNode(formatOptions, nodeIn) ? formatOptions.indentSize || 0 : 0; } @@ -165415,7 +166218,7 @@ ${options.prefix}` : "\n" : options.prefix return getLineAndCharacterOfPosition(this, pos2); } }; - const changes = ts_formatting_exports.formatNodeGivenIndentation(node, file, sourceFile.languageVariant, initialIndentation, delta, { ...formatContext, options: formatOptions }); + const changes = ts_formatting_exports.formatNodeGivenIndentation(node, file, targetSourceFile.languageVariant, initialIndentation, delta, { ...formatContext, options: formatOptions }); return applyChanges(text, changes); } function getNonformattedText(node, sourceFile, newLineCharacter) { @@ -165576,7 +166379,6 @@ ${options.prefix}` : "\n" : options.prefix assignPositionsToNode: () => assignPositionsToNode, createWriter: () => createWriter, deleteNode: () => deleteNode, - getNewFileText: () => getNewFileText, isThisTypeAnnotatable: () => isThisTypeAnnotatable, isValidLocationToAddComment: () => isValidLocationToAddComment }); @@ -168501,9 +169303,9 @@ ${options.prefix}` : "\n" : options.prefix init_ts5(); init_deprecate(); addObjectAllocatorPatcher((objectAllocator2) => { - const Identifier73 = objectAllocator2.getIdentifierConstructor(); - if (!hasProperty(Identifier73.prototype, "originalKeywordKind")) { - Object.defineProperty(Identifier73.prototype, "originalKeywordKind", { + const Identifier74 = objectAllocator2.getIdentifierConstructor(); + if (!hasProperty(Identifier74.prototype, "originalKeywordKind")) { + Object.defineProperty(Identifier74.prototype, "originalKeywordKind", { get: deprecate(function() { return identifierToKeywordKind(this); }, { @@ -168515,8 +169317,8 @@ ${options.prefix}` : "\n" : options.prefix }) }); } - if (!hasProperty(Identifier73.prototype, "isInJSDocNamespace")) { - Object.defineProperty(Identifier73.prototype, "isInJSDocNamespace", { + if (!hasProperty(Identifier74.prototype, "isInJSDocNamespace")) { + Object.defineProperty(Identifier74.prototype, "isInJSDocNamespace", { get: deprecate(function() { return this.flags & 2048 /* IdentifierIsInJSDocNamespace */ ? true : void 0; }, { @@ -168927,6 +169729,7 @@ ${options.prefix}` : "\n" : options.prefix createMemberAccessForPropertyName: () => createMemberAccessForPropertyName, createModeAwareCache: () => createModeAwareCache, createModeAwareCacheKey: () => createModeAwareCacheKey, + createModuleNotFoundChain: () => createModuleNotFoundChain, createModuleResolutionCache: () => createModuleResolutionCache, createModuleResolutionLoader: () => createModuleResolutionLoader, createModuleSpecifierResolutionHost: () => createModuleSpecifierResolutionHost, @@ -169061,6 +169864,7 @@ ${options.prefix}` : "\n" : options.prefix fileExtensionIs: () => fileExtensionIs, fileExtensionIsOneOf: () => fileExtensionIsOneOf, fileIncludeReasonToDiagnostics: () => fileIncludeReasonToDiagnostics, + fileShouldUseJavaScriptRequire: () => fileShouldUseJavaScriptRequire, filter: () => filter, filterMutate: () => filterMutate, filterSemanticDiagnostics: () => filterSemanticDiagnostics, @@ -169296,6 +170100,7 @@ ${options.prefix}` : "\n" : options.prefix getImportNeedsImportStarHelper: () => getImportNeedsImportStarHelper, getIndentSize: () => getIndentSize, getIndentString: () => getIndentString, + getInferredLibraryNameResolveFrom: () => getInferredLibraryNameResolveFrom, getInitializedVariables: () => getInitializedVariables, getInitializerOfBinaryExpression: () => getInitializerOfBinaryExpression, getInitializerOfBindingOrAssignmentElement: () => getInitializerOfBindingOrAssignmentElement, @@ -169416,6 +170221,7 @@ ${options.prefix}` : "\n" : options.prefix getOperatorAssociativity: () => getOperatorAssociativity, getOperatorPrecedence: () => getOperatorPrecedence, getOptionFromName: () => getOptionFromName, + getOptionsForLibraryResolution: () => getOptionsForLibraryResolution, getOptionsNameMap: () => getOptionsNameMap, getOrCreateEmitNode: () => getOrCreateEmitNode, getOrCreateExternalHelpersModuleNameIfNeeded: () => getOrCreateExternalHelpersModuleNameIfNeeded, @@ -169806,7 +170612,6 @@ ${options.prefix}` : "\n" : options.prefix isEmptyObjectLiteral: () => isEmptyObjectLiteral, isEmptyStatement: () => isEmptyStatement, isEmptyStringLiteral: () => isEmptyStringLiteral, - isEndOfDeclarationMarker: () => isEndOfDeclarationMarker, isEntityName: () => isEntityName, isEntityNameExpression: () => isEntityNameExpression, isEnumConst: () => isEnumConst, @@ -170037,7 +170842,6 @@ ${options.prefix}` : "\n" : options.prefix isLogicalOrCoalescingBinaryOperator: () => isLogicalOrCoalescingBinaryOperator, isMappedTypeNode: () => isMappedTypeNode, isMemberName: () => isMemberName, - isMergeDeclarationMarker: () => isMergeDeclarationMarker, isMetaProperty: () => isMetaProperty, isMethodDeclaration: () => isMethodDeclaration, isMethodOrAccessor: () => isMethodOrAccessor, @@ -170527,6 +171331,7 @@ ${options.prefix}` : "\n" : options.prefix resolutionExtensionIsTSOrJson: () => resolutionExtensionIsTSOrJson, resolveConfigFileProjectName: () => resolveConfigFileProjectName, resolveJSModule: () => resolveJSModule, + resolveLibrary: () => resolveLibrary, resolveModuleName: () => resolveModuleName, resolveModuleNameFromCache: () => resolveModuleNameFromCache, resolvePackageNameToPackageJson: () => resolvePackageNameToPackageJson, diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 9fb36b5c5bb..5f70f8de5fb 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -54,7 +54,7 @@ var path = __toESM(require("path")); // src/compiler/corePublic.ts var versionMajorMinor = "5.1"; -var version = "5.1.0-beta"; +var version = "5.1.1-rc"; // src/compiler/core.ts var emptyArray = []; @@ -2854,10 +2854,8 @@ var SyntaxKind = /* @__PURE__ */ ((SyntaxKind4) => { SyntaxKind4[SyntaxKind4["NotEmittedStatement"] = 358] = "NotEmittedStatement"; SyntaxKind4[SyntaxKind4["PartiallyEmittedExpression"] = 359] = "PartiallyEmittedExpression"; SyntaxKind4[SyntaxKind4["CommaListExpression"] = 360] = "CommaListExpression"; - SyntaxKind4[SyntaxKind4["MergeDeclarationMarker"] = 361] = "MergeDeclarationMarker"; - SyntaxKind4[SyntaxKind4["EndOfDeclarationMarker"] = 362] = "EndOfDeclarationMarker"; - SyntaxKind4[SyntaxKind4["SyntheticReferenceExpression"] = 363] = "SyntheticReferenceExpression"; - SyntaxKind4[SyntaxKind4["Count"] = 364] = "Count"; + SyntaxKind4[SyntaxKind4["SyntheticReferenceExpression"] = 361] = "SyntheticReferenceExpression"; + SyntaxKind4[SyntaxKind4["Count"] = 362] = "Count"; SyntaxKind4[SyntaxKind4["FirstAssignment"] = 64 /* EqualsToken */] = "FirstAssignment"; SyntaxKind4[SyntaxKind4["LastAssignment"] = 79 /* CaretEqualsToken */] = "LastAssignment"; SyntaxKind4[SyntaxKind4["FirstCompoundAssignment"] = 65 /* PlusEqualsToken */] = "FirstCompoundAssignment"; @@ -3304,9 +3302,8 @@ var EmitFlags = /* @__PURE__ */ ((EmitFlags3) => { EmitFlags3[EmitFlags3["ReuseTempVariableScope"] = 1048576] = "ReuseTempVariableScope"; EmitFlags3[EmitFlags3["CustomPrologue"] = 2097152] = "CustomPrologue"; EmitFlags3[EmitFlags3["NoHoisting"] = 4194304] = "NoHoisting"; - EmitFlags3[EmitFlags3["HasEndOfDeclarationMarker"] = 8388608] = "HasEndOfDeclarationMarker"; - EmitFlags3[EmitFlags3["Iterator"] = 16777216] = "Iterator"; - EmitFlags3[EmitFlags3["NoAsciiEscaping"] = 33554432] = "NoAsciiEscaping"; + EmitFlags3[EmitFlags3["Iterator"] = 8388608] = "Iterator"; + EmitFlags3[EmitFlags3["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; return EmitFlags3; })(EmitFlags || {}); var commentPragmas = { @@ -3692,9 +3689,6 @@ var curSysLog = noop; function sysLog(s) { return curSysLog(s); } -function setSysLog(logger) { - curSysLog = logger; -} function createDirectoryWatcherSupportingRecursive({ watchDirectory, useCaseSensitiveFileNames, @@ -6351,6 +6345,7 @@ var Diagnostics = { List_of_folders_to_include_type_definitions_from: diag(6161, 3 /* Message */, "List_of_folders_to_include_type_definitions_from_6161", "List of folders to include type definitions from."), Disable_size_limitations_on_JavaScript_projects: diag(6162, 3 /* Message */, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."), The_character_set_of_the_input_files: diag(6163, 3 /* Message */, "The_character_set_of_the_input_files_6163", "The character set of the input files."), + Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1: diag(6164, 3 /* Message */, "Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1_6164", "Skipping module '{0}' that looks like an absolute URI, target file types: {1}."), Do_not_truncate_error_messages: diag(6165, 3 /* Message */, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."), Output_directory_for_generated_declaration_files: diag(6166, 3 /* Message */, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."), A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl: diag(6167, 3 /* Message */, "A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl_6167", "A series of entries which re-map imports to lookup locations relative to the 'baseUrl'."), @@ -6830,6 +6825,7 @@ var Diagnostics = { You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder: diag(8036, 1 /* Error */, "You_cannot_rename_elements_that_are_defined_in_another_node_modules_folder_8036", "You cannot rename elements that are defined in another 'node_modules' folder."), Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files: diag(8037, 1 /* Error */, "Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files_8037", "Type satisfaction expressions can only be used in TypeScript files."), Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export: diag(8038, 1 /* Error */, "Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export_8038", "Decorators may not appear after 'export' or 'export default' if they also appear before 'export'."), + A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag: diag(8039, 1 /* Error */, "A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag_8039", "A JSDoc '@template' tag may not follow a '@typedef', '@callback', or '@overload' tag"), Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9005, 1 /* Error */, "Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_9005", "Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit."), Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit: diag(9006, 1 /* Error */, "Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotati_9006", "Declaration emit for this file requires using private name '{0}' from module '{1}'. An explicit type annotation may unblock declaration emit."), JSX_attributes_must_only_be_assigned_a_non_empty_expression: diag(17e3, 1 /* Error */, "JSX_attributes_must_only_be_assigned_a_non_empty_expression_17000", "JSX attributes must only be assigned a non-empty 'expression'."), @@ -7081,6 +7077,7 @@ var Diagnostics = { Use_Number_isNaN_in_all_conditions: diag(95175, 3 /* Message */, "Use_Number_isNaN_in_all_conditions_95175", "Use `Number.isNaN` in all conditions."), Convert_typedef_to_TypeScript_type: diag(95176, 3 /* Message */, "Convert_typedef_to_TypeScript_type_95176", "Convert typedef to TypeScript type."), Convert_all_typedef_to_TypeScript_types: diag(95177, 3 /* Message */, "Convert_all_typedef_to_TypeScript_types_95177", "Convert all typedef to TypeScript types."), + Move_to_file: diag(95178, 3 /* Message */, "Move_to_file_95178", "Move to file"), No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer: diag(18004, 1 /* Error */, "No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer_18004", "No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer."), Classes_may_not_have_a_field_named_constructor: diag(18006, 1 /* Error */, "Classes_may_not_have_a_field_named_constructor_18006", "Classes may not have a field named 'constructor'."), JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array: diag(18007, 1 /* Error */, "JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array_18007", "JSX expressions may not use the comma operator. Did you mean to write an array?"), @@ -9807,7 +9804,6 @@ function isLeftHandSideExpressionKind(kind) { case 283 /* JsxElement */: case 284 /* JsxSelfClosingElement */: case 287 /* JsxFragment */: - case 294 /* JsxNamespacedName */: case 214 /* TaggedTemplateExpression */: case 208 /* ArrayLiteralExpression */: case 216 /* ParenthesizedExpression */: @@ -9906,7 +9902,7 @@ function isDeclarationStatementKind(kind) { return kind === 261 /* FunctionDeclaration */ || kind === 281 /* MissingDeclaration */ || kind === 262 /* ClassDeclaration */ || kind === 263 /* InterfaceDeclaration */ || kind === 264 /* TypeAliasDeclaration */ || kind === 265 /* EnumDeclaration */ || kind === 266 /* ModuleDeclaration */ || kind === 271 /* ImportDeclaration */ || kind === 270 /* ImportEqualsDeclaration */ || kind === 277 /* ExportDeclaration */ || kind === 276 /* ExportAssignment */ || kind === 269 /* NamespaceExportDeclaration */; } function isStatementKindButNotDeclarationKind(kind) { - return kind === 251 /* BreakStatement */ || kind === 250 /* ContinueStatement */ || kind === 258 /* DebuggerStatement */ || kind === 245 /* DoStatement */ || kind === 243 /* ExpressionStatement */ || kind === 241 /* EmptyStatement */ || kind === 248 /* ForInStatement */ || kind === 249 /* ForOfStatement */ || kind === 247 /* ForStatement */ || kind === 244 /* IfStatement */ || kind === 255 /* LabeledStatement */ || kind === 252 /* ReturnStatement */ || kind === 254 /* SwitchStatement */ || kind === 256 /* ThrowStatement */ || kind === 257 /* TryStatement */ || kind === 242 /* VariableStatement */ || kind === 246 /* WhileStatement */ || kind === 253 /* WithStatement */ || kind === 358 /* NotEmittedStatement */ || kind === 362 /* EndOfDeclarationMarker */ || kind === 361 /* MergeDeclarationMarker */; + return kind === 251 /* BreakStatement */ || kind === 250 /* ContinueStatement */ || kind === 258 /* DebuggerStatement */ || kind === 245 /* DoStatement */ || kind === 243 /* ExpressionStatement */ || kind === 241 /* EmptyStatement */ || kind === 248 /* ForInStatement */ || kind === 249 /* ForOfStatement */ || kind === 247 /* ForStatement */ || kind === 244 /* IfStatement */ || kind === 255 /* LabeledStatement */ || kind === 252 /* ReturnStatement */ || kind === 254 /* SwitchStatement */ || kind === 256 /* ThrowStatement */ || kind === 257 /* TryStatement */ || kind === 242 /* VariableStatement */ || kind === 246 /* WhileStatement */ || kind === 253 /* WithStatement */ || kind === 358 /* NotEmittedStatement */; } function isDeclaration(node) { if (node.kind === 167 /* TypeParameter */) { @@ -10007,10 +10003,15 @@ function createSingleLineStringWriter() { clear: () => str = "" }; } -function copyEntries(source, target) { - source.forEach((value, key) => { - target.set(key, value); - }); +function forEachKey(map2, callback) { + const iterator = map2.keys(); + for (const key of iterator) { + const result = callback(key); + if (result) { + return result; + } + } + return void 0; } function getFullWidth(node) { return node.end - node.pos; @@ -10109,6 +10110,8 @@ function tryGetTextOfPropertyName(name) { if (isStringOrNumericLiteralLike(name.expression)) return escapeLeadingUnderscores(name.expression.text); return void 0; + case 294 /* JsxNamespacedName */: + return getEscapedTextOfJsxNamespacedName(name); default: return Debug.assertNever(name); } @@ -10493,6 +10496,7 @@ function canHaveJSDoc(node) { case 171 /* PropertyDeclaration */: case 170 /* PropertySignature */: case 252 /* ReturnStatement */: + case 239 /* SemicolonClassElement */: case 177 /* SetAccessor */: case 303 /* ShorthandPropertyAssignment */: case 304 /* SpreadAssignment */: @@ -10579,7 +10583,7 @@ function isDynamicName(name) { return !isStringOrNumericLiteralLike(expr) && !isSignedNumericLiteral(expr); } function getTextOfIdentifierOrLiteral(node) { - return isMemberName(node) ? idText(node) : node.text; + return isMemberName(node) ? idText(node) : isJsxNamespacedName(node) ? getTextOfJsxNamespacedName(node) : node.text; } function nodeIsSynthesized(range) { return positionIsSynthesized(range.pos) || positionIsSynthesized(range.end); @@ -10971,10 +10975,6 @@ function directoryProbablyExists(directoryName, host) { function closeFileWatcher(watcher) { watcher.close(); } -function clearMap(map2, onDeleteValue) { - map2.forEach(onDeleteValue); - map2.clear(); -} function getLastChild(node) { let lastChild; forEachChild( @@ -11483,7 +11483,7 @@ function getScriptKindFromFileName(fileName) { var supportedTSExtensions = [[".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */], [".cts" /* Cts */, ".d.cts" /* Dcts */], [".mts" /* Mts */, ".d.mts" /* Dmts */]]; var supportedTSExtensionsFlat = flatten(supportedTSExtensions); var supportedTSExtensionsWithJson = [...supportedTSExtensions, [".json" /* Json */]]; -var supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */, ".cts" /* Cts */, ".mts" /* Mts */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".cts" /* Cts */, ".mts" /* Mts */]; +var supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".d.cts" /* Dcts */, ".d.mts" /* Dmts */, ".cts" /* Cts */, ".mts" /* Mts */, ".ts" /* Ts */, ".tsx" /* Tsx */]; var supportedJSExtensions = [[".js" /* Js */, ".jsx" /* Jsx */], [".mjs" /* Mjs */], [".cjs" /* Cjs */]]; var supportedJSExtensionsFlat = flatten(supportedJSExtensions); var allSupportedExtensions = [[".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".js" /* Js */, ".jsx" /* Jsx */], [".cts" /* Cts */, ".d.cts" /* Dcts */, ".cjs" /* Cjs */], [".mts" /* Mts */, ".d.mts" /* Dmts */, ".mjs" /* Mjs */]]; @@ -11662,6 +11662,12 @@ function isJsxAttributeName(node) { const kind = node.kind; return kind === 80 /* Identifier */ || kind === 294 /* JsxNamespacedName */; } +function getEscapedTextOfJsxNamespacedName(node) { + return `${node.namespace.escapedText}:${idText(node.name)}`; +} +function getTextOfJsxNamespacedName(node) { + return `${idText(node.namespace)}:${idText(node.name)}`; +} // src/compiler/factory/baseNodeFactory.ts function createBaseNodeFactory() { @@ -12747,8 +12753,6 @@ function createNodeFactory(flags, baseFactory2) { updatePartiallyEmittedExpression, createCommaListExpression, updateCommaListExpression, - createEndOfDeclarationMarker, - createMergeDeclarationMarker, createSyntheticReferenceExpression, updateSyntheticReferenceExpression, cloneNode, @@ -15816,20 +15820,8 @@ function createNodeFactory(flags, baseFactory2) { function updateCommaListExpression(node, elements) { return node.elements !== elements ? update(createCommaListExpression(elements), node) : node; } - function createEndOfDeclarationMarker(original) { - const node = createBaseNode(362 /* EndOfDeclarationMarker */); - node.emitNode = {}; - node.original = original; - return node; - } - function createMergeDeclarationMarker(original) { - const node = createBaseNode(361 /* MergeDeclarationMarker */); - node.emitNode = {}; - node.original = original; - return node; - } function createSyntheticReferenceExpression(expression, thisArg) { - const node = createBaseNode(363 /* SyntheticReferenceExpression */); + const node = createBaseNode(361 /* SyntheticReferenceExpression */); node.expression = expression; node.thisArg = thisArg; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.thisArg); @@ -16221,8 +16213,8 @@ function createNodeFactory(flags, baseFactory2) { function inlineExpressions(expressions) { return expressions.length > 10 ? createCommaListExpression(expressions) : reduceLeft(expressions, factory2.createComma); } - function getName(node, allowComments, allowSourceMaps, emitFlags = 0) { - const nodeName = getNameOfDeclaration(node); + function getName(node, allowComments, allowSourceMaps, emitFlags = 0, ignoreAssignedName) { + const nodeName = ignoreAssignedName ? node && getNonAssignedNameOfDeclaration(node) : getNameOfDeclaration(node); if (nodeName && isIdentifier(nodeName) && !isGeneratedIdentifier(nodeName)) { const name = setParent(setTextRange(cloneNode(nodeName), nodeName), nodeName.parent); emitFlags |= getEmitFlags(nodeName); @@ -16239,8 +16231,8 @@ function createNodeFactory(flags, baseFactory2) { function getInternalName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */ | 65536 /* InternalName */); } - function getLocalName(node, allowComments, allowSourceMaps) { - return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */); + function getLocalName(node, allowComments, allowSourceMaps, ignoreAssignedName) { + return getName(node, allowComments, allowSourceMaps, 32768 /* LocalName */, ignoreAssignedName); } function getExportName(node, allowComments, allowSourceMaps) { return getName(node, allowComments, allowSourceMaps, 16384 /* ExportName */); @@ -17123,6 +17115,9 @@ function isJsxClosingFragment(node) { function isJsxAttributes(node) { return node.kind === 291 /* JsxAttributes */; } +function isJsxNamespacedName(node) { + return node.kind === 294 /* JsxNamespacedName */; +} function isDefaultClause(node) { return node.kind === 296 /* DefaultClause */; } @@ -19221,8 +19216,13 @@ var Parser; return tokenIsIdentifierOrKeyword(token()) || token() === 19 /* OpenBraceToken */; case 14 /* JsxChildren */: return true; + case 25 /* JSDocComment */: + return true; + case 26 /* Count */: + return Debug.fail("ParsingContext.Count used as a context"); + default: + Debug.assertNever(parsingContext2, "Non-exhaustive case in 'isListElement'."); } - return Debug.fail("Non-exhaustive case in 'isListElement'."); } function isValidHeritageClauseObjectLiteral() { Debug.assert(token() === 19 /* OpenBraceToken */); @@ -19316,7 +19316,8 @@ var Parser; return false; } function isInSomeParsingContext() { - for (let kind = 0; kind < 25 /* Count */; kind++) { + Debug.assert(parsingContext, "Missing parsing context"); + for (let kind = 0; kind < 26 /* Count */; kind++) { if (parsingContext & 1 << kind) { if (isListElement( kind, @@ -19575,7 +19576,9 @@ var Parser; return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); case 24 /* AssertEntries */: return parseErrorAtCurrentToken(Diagnostics.Identifier_or_string_literal_expected); - case 25 /* Count */: + case 25 /* JSDocComment */: + return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); + case 26 /* Count */: return Debug.fail("ParsingContext.Count used as a context"); default: Debug.assertNever(context); @@ -21626,7 +21629,11 @@ var Parser; } function parseJsxElementName() { const pos = getNodePos(); - let expression = parseJsxTagName(); + const initialExpression = parseJsxTagName(); + if (isJsxNamespacedName(initialExpression)) { + return initialExpression; + } + let expression = initialExpression; while (parseOptional(25 /* DotToken */)) { expression = finishNode(factoryCreatePropertyAccessExpression(expression, parseRightSideOfDot( /*allowIdentifierNames*/ @@ -23156,11 +23163,11 @@ var Parser; } function parseClassElement() { const pos = getNodePos(); + const hasJSDoc = hasPrecedingJSDocComment(); if (token() === 27 /* SemicolonToken */) { nextToken(); - return finishNode(factory2.createSemicolonClassElement(), pos); + return withJSDoc(finishNode(factory2.createSemicolonClassElement(), pos), hasJSDoc); } - const hasJSDoc = hasPrecedingJSDocComment(); const modifiers = parseModifiers( /*allowDecorators*/ true, @@ -23707,7 +23714,8 @@ var Parser; ParsingContext2[ParsingContext2["HeritageClauses"] = 22] = "HeritageClauses"; ParsingContext2[ParsingContext2["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers"; ParsingContext2[ParsingContext2["AssertEntries"] = 24] = "AssertEntries"; - ParsingContext2[ParsingContext2["Count"] = 25] = "Count"; + ParsingContext2[ParsingContext2["JSDocComment"] = 25] = "JSDocComment"; + ParsingContext2[ParsingContext2["Count"] = 26] = "Count"; })(ParsingContext || (ParsingContext = {})); let Tristate; ((Tristate2) => { @@ -23829,6 +23837,8 @@ var Parser; PropertyLikeParse2[PropertyLikeParse2["CallbackParameter"] = 4] = "CallbackParameter"; })(PropertyLikeParse || (PropertyLikeParse = {})); function parseJSDocCommentWorker(start = 0, length2) { + const saveParsingContext = parsingContext; + parsingContext |= 1 << 25 /* JSDocComment */; const content = sourceText; const end = length2 === void 0 ? content.length : start + length2; length2 = end - start; @@ -23845,7 +23855,10 @@ var Parser; let commentsPos; let comments = []; const parts = []; - return scanner.scanRange(start + 3, length2 - 5, () => { + const result = scanner.scanRange(start + 3, length2 - 5, doJSDocScan); + parsingContext = saveParsingContext; + return result; + function doJSDocScan() { let state = 1 /* SawAsterisk */; let margin; let indent2 = start - (content.lastIndexOf("\n", start) + 1) + 4; @@ -23941,7 +23954,7 @@ var Parser; Debug.assertIsDefined(commentsPos, "having parsed tags implies that the end of the comment span should be set"); const tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd); return finishNode(factory2.createJSDocComment(parts.length ? createNodeArray(parts, start, commentsPos) : trimmedComments.length ? trimmedComments : void 0, tagsArray), start, end); - }); + } function removeLeadingNewlines(comments2) { while (comments2.length && (comments2[0] === "\n" || comments2[0] === "\r")) { comments2.shift(); @@ -24300,8 +24313,8 @@ var Parser; typeExpression = nestedTypeLiteral; isNameFirst = true; } - const result = target === 1 /* Property */ ? factory2.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) : factory2.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment); - return finishNode(result, start2); + const result2 = target === 1 /* Property */ ? factory2.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) : factory2.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment); + return finishNode(result2, start2); } function parseNestedTypeLiteral(typeExpression, name, target, indent2) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { @@ -24311,6 +24324,8 @@ var Parser; while (child = tryParse(() => parseChildParameterOrPropertyTag(target, indent2, name))) { if (child.kind === 347 /* JSDocParameterTag */ || child.kind === 354 /* JSDocPropertyTag */) { children = append(children, child); + } else if (child.kind === 351 /* JSDocTemplateTag */) { + parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag); } } if (children) { @@ -24398,7 +24413,9 @@ var Parser; const usedBrace = parseOptional(19 /* OpenBraceToken */); const pos = getNodePos(); const expression = parsePropertyAccessEntityNameExpression(); + scanner.setInJSDocType(true); const typeArguments = tryParseTypeArguments(); + scanner.setInJSDocType(false); const node = factory2.createExpressionWithTypeArguments(expression, typeArguments); const res = finishNode(node, pos); if (usedBrace) { @@ -24447,6 +24464,9 @@ var Parser; let jsDocPropertyTags; let hasChildren = false; while (child = tryParse(() => parseChildPropertyTag(indent2))) { + if (child.kind === 351 /* JSDocTemplateTag */) { + break; + } hasChildren = true; if (child.kind === 350 /* JSDocTypeTag */) { if (childTypeTag) { @@ -24506,6 +24526,10 @@ var Parser; let child; let parameters; while (child = tryParse(() => parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent2))) { + if (child.kind === 351 /* JSDocTemplateTag */) { + parseErrorAtRange(child.tagName, Diagnostics.A_JSDoc_template_tag_may_not_follow_a_typedef_callback_or_overload_tag); + break; + } parameters = append(parameters, child); } return createNodeArray(parameters || [], pos); @@ -24600,7 +24624,7 @@ var Parser; const start2 = scanner.getTokenFullStart(); nextTokenJSDoc(); const tagName = parseJSDocIdentifierName(); - skipWhitespace(); + const indentText = skipWhitespaceOrAsterisk(); let t; switch (tagName.escapedText) { case "type": @@ -24614,6 +24638,8 @@ var Parser; case "param": t = 2 /* Parameter */ | 4 /* CallbackParameter */; break; + case "template": + return parseTemplateTag(start2, tagName, indent2, indentText); default: return false; } @@ -24701,9 +24727,9 @@ var Parser; const end2 = scanner.getTokenEnd(); const originalKeywordKind = token(); const text = internIdentifier(scanner.getTokenValue()); - const result = finishNode(factoryCreateIdentifier(text, originalKeywordKind), start2, end2); + const result2 = finishNode(factoryCreateIdentifier(text, originalKeywordKind), start2, end2); nextTokenJSDoc(); - return result; + return result2; } } })(JSDocParser = Parser2.JSDocParser || (Parser2.JSDocParser = {})); @@ -27607,8 +27633,6 @@ function nodeModuleNameResolverWorker(features, moduleName, containingDirectory, const diagnosticState = { ...state, features: state.features & ~8 /* Exports */, - failedLookupLocations: [], - affectingLocations: [], reportDiagnostic: noop }; const diagnosticResult = tryResolve(extensions & (1 /* TypeScript */ | 4 /* Declaration */), diagnosticState); @@ -27648,6 +27672,12 @@ function nodeModuleNameResolverWorker(features, moduleName, containingDirectory, resolved2 = loadModuleFromSelfNameReference(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); } if (!resolved2) { + if (moduleName.indexOf(":") > -1) { + if (traceEnabled) { + trace(host, Diagnostics.Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); + } + return void 0; + } if (traceEnabled) { trace(host, Diagnostics.Loading_module_0_from_node_modules_folder_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); } @@ -27734,22 +27764,22 @@ var nodeModulesPathPart = "/node_modules/"; function pathContainsNodeModules(path2) { return stringContains(path2, nodeModulesPathPart); } -function parseNodeModuleFromPath(resolved) { +function parseNodeModuleFromPath(resolved, isFolder) { const path2 = normalizePath(resolved); const idx = path2.lastIndexOf(nodeModulesPathPart); if (idx === -1) { return void 0; } const indexAfterNodeModules = idx + nodeModulesPathPart.length; - let indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path2, indexAfterNodeModules); + let indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path2, indexAfterNodeModules, isFolder); if (path2.charCodeAt(indexAfterNodeModules) === 64 /* at */) { - indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path2, indexAfterPackageName); + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path2, indexAfterPackageName, isFolder); } return path2.slice(0, indexAfterPackageName); } -function moveToNextDirectorySeparatorIfAvailable(path2, prevSeparatorIndex) { +function moveToNextDirectorySeparatorIfAvailable(path2, prevSeparatorIndex, isFolder) { const nextSeparatorIndex = path2.indexOf(directorySeparator, prevSeparatorIndex + 1); - return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + return nextSeparatorIndex === -1 ? isFolder ? path2.length : prevSeparatorIndex : nextSeparatorIndex; } function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) { return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); @@ -28564,7 +28594,7 @@ function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, node return withPackageId(packageInfo, fromDirectory); } const loader = (extensions2, candidate2, onlyRecordFailures, state2) => { - let pathAndExtension = loadModuleFromFile(extensions2, candidate2, onlyRecordFailures, state2) || loadNodeModuleFromDirectoryWorker( + let pathAndExtension = (rest || !(state2.features & 32 /* EsmMode */)) && loadModuleFromFile(extensions2, candidate2, onlyRecordFailures, state2) || loadNodeModuleFromDirectoryWorker( extensions2, candidate2, onlyRecordFailures, @@ -30478,104 +30508,6 @@ function createBracketsMap() { } // src/compiler/watchUtilities.ts -function getWatchFactory(host, watchLogLevel, log2, getDetailWatchInfo2) { - setSysLog(watchLogLevel === 2 /* Verbose */ ? log2 : noop); - const plainInvokeFactory = { - watchFile: (file, callback, pollingInterval, options) => host.watchFile(file, callback, pollingInterval, options), - watchDirectory: (directory, callback, flags, options) => host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0, options) - }; - const triggerInvokingFactory = watchLogLevel !== 0 /* None */ ? { - watchFile: createTriggerLoggingAddWatch("watchFile"), - watchDirectory: createTriggerLoggingAddWatch("watchDirectory") - } : void 0; - const factory2 = watchLogLevel === 2 /* Verbose */ ? { - watchFile: createFileWatcherWithLogging, - watchDirectory: createDirectoryWatcherWithLogging - } : triggerInvokingFactory || plainInvokeFactory; - const excludeWatcherFactory = watchLogLevel === 2 /* Verbose */ ? createExcludeWatcherWithLogging : returnNoopFileWatcher; - return { - watchFile: createExcludeHandlingAddWatch("watchFile"), - watchDirectory: createExcludeHandlingAddWatch("watchDirectory") - }; - function createExcludeHandlingAddWatch(key) { - return (file, cb, flags, options, detailInfo1, detailInfo2) => { - var _a; - return !matchesExclude(file, key === "watchFile" ? options == null ? void 0 : options.excludeFiles : options == null ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames(), ((_a = host.getCurrentDirectory) == null ? void 0 : _a.call(host)) || "") ? factory2[key].call( - /*thisArgs*/ - void 0, - file, - cb, - flags, - options, - detailInfo1, - detailInfo2 - ) : excludeWatcherFactory(file, flags, options, detailInfo1, detailInfo2); - }; - } - function useCaseSensitiveFileNames() { - return typeof host.useCaseSensitiveFileNames === "boolean" ? host.useCaseSensitiveFileNames : host.useCaseSensitiveFileNames(); - } - function createExcludeWatcherWithLogging(file, flags, options, detailInfo1, detailInfo2) { - log2(`ExcludeWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`); - return { - close: () => log2(`ExcludeWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`) - }; - } - function createFileWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) { - log2(`FileWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`); - const watcher = triggerInvokingFactory.watchFile(file, cb, flags, options, detailInfo1, detailInfo2); - return { - close: () => { - log2(`FileWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`); - watcher.close(); - } - }; - } - function createDirectoryWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) { - const watchInfo = `DirectoryWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`; - log2(watchInfo); - const start = timestamp(); - const watcher = triggerInvokingFactory.watchDirectory(file, cb, flags, options, detailInfo1, detailInfo2); - const elapsed = timestamp() - start; - log2(`Elapsed:: ${elapsed}ms ${watchInfo}`); - return { - close: () => { - const watchInfo2 = `DirectoryWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`; - log2(watchInfo2); - const start2 = timestamp(); - watcher.close(); - const elapsed2 = timestamp() - start2; - log2(`Elapsed:: ${elapsed2}ms ${watchInfo2}`); - } - }; - } - function createTriggerLoggingAddWatch(key) { - return (file, cb, flags, options, detailInfo1, detailInfo2) => plainInvokeFactory[key].call( - /*thisArgs*/ - void 0, - file, - (...args) => { - const triggerredInfo = `${key === "watchFile" ? "FileWatcher" : "DirectoryWatcher"}:: Triggered with ${args[0]} ${args[1] !== void 0 ? args[1] : ""}:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`; - log2(triggerredInfo); - const start = timestamp(); - cb.call( - /*thisArg*/ - void 0, - ...args - ); - const elapsed = timestamp() - start; - log2(`Elapsed:: ${elapsed}ms ${triggerredInfo}`); - }, - flags, - options, - detailInfo1, - detailInfo2 - ); - } - function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3) { - return `WatchInfo: ${file} ${flags} ${JSON.stringify(options)} ${getDetailWatchInfo3 ? getDetailWatchInfo3(detailInfo1, detailInfo2) : detailInfo2 === void 0 ? detailInfo1 : `${detailInfo1} ${detailInfo2}`}`; - } -} function getFallbackOptions(options) { const fallbackPolling = options == null ? void 0 : options.fallbackPolling; return { @@ -31154,8 +31086,6 @@ var screenStartingMessageCodes = [ Diagnostics.Starting_compilation_in_watch_mode.code, Diagnostics.File_change_detected_Starting_incremental_compilation.code ]; -var noopFileWatcher = { close: noop }; -var returnNoopFileWatcher = () => noopFileWatcher; // src/jsTyping/_namespaces/ts.JsTyping.ts var ts_JsTyping_exports = {}; @@ -31480,11 +31410,11 @@ function renderPackageNameValidationFailureWorker(typing, result, name, isScopeN // src/jsTyping/shared.ts var ActionSet = "action::set"; -var ActionInvalidate = "action::invalidate"; var ActionPackageInstalled = "action::packageInstalled"; var EventTypesRegistry = "event::typesRegistry"; var EventBeginInstallTypes = "event::beginInstallTypes"; var EventEndInstallTypes = "event::endInstallTypes"; +var ActionWatchTypingLocations = "action::watchTypingLocations"; var Arguments; ((Arguments2) => { Arguments2.GlobalCacheLocation = "--globalTypingsCacheLocation"; @@ -31544,19 +31474,6 @@ function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remainin } return { command, remaining: remaining - toSlice }; } -function endsWith2(str, suffix, caseSensitive) { - const expectedPos = str.length - suffix.length; - return expectedPos >= 0 && (str.indexOf(suffix, expectedPos) === expectedPos || !caseSensitive && compareStringsCaseInsensitive(str.substr(expectedPos), suffix) === 0 /* EqualTo */); -} -function isPackageOrBowerJson(fileName, caseSensitive) { - return endsWith2(fileName, "/package.json", caseSensitive) || endsWith2(fileName, "/bower.json", caseSensitive); -} -function sameFiles(a, b, caseSensitive) { - return a === b || !caseSensitive && compareStringsCaseInsensitive(a, b) === 0 /* EqualTo */; -} -function getDetailWatchInfo(projectName, watchers) { - return `Project: ${projectName} watcher already invoked: ${watchers == null ? void 0 : watchers.isInvoked}`; -} var TypingsInstaller = class { constructor(installTypingHost, globalCachePath, safeListPath, typesMapLocation2, throttleLimit, log2 = nullLog) { this.installTypingHost = installTypingHost; @@ -31574,13 +31491,10 @@ var TypingsInstaller = class { this.installRunCount = 1; this.inFlightRequestCount = 0; this.latestDistTag = "latest"; - this.toCanonicalFileName = createGetCanonicalFileName(installTypingHost.useCaseSensitiveFileNames); - this.globalCachePackageJsonPath = combinePaths(globalCachePath, "package.json"); const isLoggingEnabled = this.log.isEnabled(); if (isLoggingEnabled) { this.log.writeLine(`Global cache location '${globalCachePath}', safe file path '${safeListPath}', types map path ${typesMapLocation2}`); } - this.watchFactory = getWatchFactory(this.installTypingHost, isLoggingEnabled ? 2 /* Verbose */ : 0 /* None */, (s) => this.log.writeLine(s), getDetailWatchInfo); this.processCacheLocation(this.globalCachePath); } closeProject(req) { @@ -31597,8 +31511,8 @@ var TypingsInstaller = class { } return; } - clearMap(watchers, closeFileWatcher); this.projectWatchers.delete(projectName); + this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files: [] }); if (this.log.isEnabled()) { this.log.writeLine(`Closing file watchers for project '${projectName}' - done.`); } @@ -31631,7 +31545,7 @@ var TypingsInstaller = class { if (this.log.isEnabled()) { this.log.writeLine(`Finished typings discovery: ${JSON.stringify(discoverTypingsResult)}`); } - this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch, req.projectRootPath, req.watchOptions); + this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch); if (discoverTypingsResult.newTypingNames.length) { this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames); } else { @@ -31832,75 +31746,19 @@ var TypingsInstaller = class { host.createDirectory(directory); } } - watchFiles(projectName, files, projectRootPath, options) { + watchFiles(projectName, files) { if (!files.length) { this.closeWatchers(projectName); return; } - let watchers = this.projectWatchers.get(projectName); - const toRemove = /* @__PURE__ */ new Map(); - if (!watchers) { - watchers = /* @__PURE__ */ new Map(); - this.projectWatchers.set(projectName, watchers); + const existing = this.projectWatchers.get(projectName); + const newSet = new Set(files); + if (!existing || forEachKey(newSet, (s) => !existing.has(s)) || forEachKey(existing, (s) => !newSet.has(s))) { + this.projectWatchers.set(projectName, newSet); + this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files }); } else { - copyEntries(watchers, toRemove); + this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files: void 0 }); } - watchers.isInvoked = false; - const isLoggingEnabled = this.log.isEnabled(); - const createProjectWatcher = (path2, projectWatcherType) => { - const canonicalPath = this.toCanonicalFileName(path2); - toRemove.delete(canonicalPath); - if (watchers.has(canonicalPath)) { - return; - } - if (isLoggingEnabled) { - this.log.writeLine(`${projectWatcherType}:: Added:: WatchInfo: ${path2}`); - } - const watcher = projectWatcherType === "FileWatcher" /* FileWatcher */ ? this.watchFactory.watchFile(path2, () => { - if (!watchers.isInvoked) { - watchers.isInvoked = true; - this.sendResponse({ projectName, kind: ActionInvalidate }); - } - }, 2e3 /* High */, options, projectName, watchers) : this.watchFactory.watchDirectory(path2, (f) => { - if (watchers.isInvoked || !fileExtensionIs(f, ".json" /* Json */)) { - return; - } - if (isPackageOrBowerJson(f, this.installTypingHost.useCaseSensitiveFileNames) && !sameFiles(f, this.globalCachePackageJsonPath, this.installTypingHost.useCaseSensitiveFileNames)) { - watchers.isInvoked = true; - this.sendResponse({ projectName, kind: ActionInvalidate }); - } - }, 1 /* Recursive */, options, projectName, watchers); - watchers.set(canonicalPath, isLoggingEnabled ? { - close: () => { - this.log.writeLine(`${projectWatcherType}:: Closed:: WatchInfo: ${path2}`); - watcher.close(); - } - } : watcher); - }; - for (const file of files) { - if (file.endsWith("/package.json") || file.endsWith("/bower.json")) { - createProjectWatcher(file, "FileWatcher" /* FileWatcher */); - continue; - } - if (containsPath(projectRootPath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) { - const subDirectory = file.indexOf(directorySeparator, projectRootPath.length + 1); - if (subDirectory !== -1) { - createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */); - } else { - createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); - } - continue; - } - if (containsPath(this.globalCachePath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) { - createProjectWatcher(this.globalCachePath, "DirectoryWatcher" /* DirectoryWatcher */); - continue; - } - createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); - } - toRemove.forEach((watch, path2) => { - watch.close(); - watchers.delete(path2); - }); } createSetTypings(request, typings) { return { diff --git a/package.json b/package.json index e8a98465d3d..6226e1cd7e9 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "typescript", "author": "Microsoft Corp.", "homepage": "https://www.typescriptlang.org/", - "version": "5.1.0-beta", + "version": "5.1.1-rc", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [ diff --git a/src/compiler/corePublic.ts b/src/compiler/corePublic.ts index cfe5ea2eddf..98acdaa9d18 100644 --- a/src/compiler/corePublic.ts +++ b/src/compiler/corePublic.ts @@ -4,7 +4,7 @@ export const versionMajorMinor = "5.1"; // The following is baselined as a literal template type without intervention /** The version of the TypeScript compiler release */ // eslint-disable-next-line @typescript-eslint/no-inferrable-types -export const version = "5.1.0-beta" as string; +export const version = "5.1.1-rc" as string; /** * Type of objects whose values are all of the same type.