diff --git a/goldens/public-api/angular_devkit/schematics/index.api.md b/goldens/public-api/angular_devkit/schematics/index.api.md index e72c46745599..de17a0462162 100644 --- a/goldens/public-api/angular_devkit/schematics/index.api.md +++ b/goldens/public-api/angular_devkit/schematics/index.api.md @@ -206,6 +206,8 @@ export interface CreateFileAction extends ActionBase { export class DelegateTree implements Tree_2 { constructor(_other: Tree_2); // (undocumented) + [x: symbol]: () => this; + // (undocumented) get actions(): Action[]; // (undocumented) apply(action: Action, strategy?: MergeStrategy): void; @@ -518,6 +520,8 @@ export class HostSink extends SimpleSinkBase { export class HostTree implements Tree_2 { constructor(_backend?: virtualFs.ReadonlyHost<{}>); // (undocumented) + [x: symbol]: () => this; + // (undocumented) get actions(): Action[]; // (undocumented) apply(action: Action, strategy?: MergeStrategy): void; diff --git a/package.json b/package.json index 0dc7734f0bd5..2122b4f6ca60 100644 --- a/package.json +++ b/package.json @@ -52,23 +52,23 @@ }, "devDependencies": { "@ampproject/remapping": "2.3.0", - "@angular/animations": "19.0.1", + "@angular/animations": "19.1.0-next.0", "@angular/bazel": "patch:@angular/bazel@https%3A//github.com/angular/bazel-builds.git%23commit=07617f0f8540d27f8895b1820a6f994e1e5b7277#~/.yarn/patches/@angular-bazel-https-9848736cf4.patch", "@angular/build-tooling": "https://github.com/angular/dev-infra-private-build-tooling-builds.git#41d5efafd8094da3c8455e1b54b381e346d0c7a9", - "@angular/cdk": "19.0.0", - "@angular/common": "19.0.1", - "@angular/compiler": "19.0.1", - "@angular/compiler-cli": "19.0.1", - "@angular/core": "19.0.1", - "@angular/forms": "19.0.1", - "@angular/localize": "19.0.1", - "@angular/material": "19.0.0", + "@angular/cdk": "19.1.0-next.0", + "@angular/common": "19.1.0-next.0", + "@angular/compiler": "19.1.0-next.0", + "@angular/compiler-cli": "19.1.0-next.0", + "@angular/core": "19.1.0-next.0", + "@angular/forms": "19.1.0-next.0", + "@angular/localize": "19.1.0-next.0", + "@angular/material": "19.1.0-next.0", "@angular/ng-dev": "https://github.com/angular/dev-infra-private-ng-dev-builds.git#47ccf2ca29307997c021994c859c03c71fae686e", - "@angular/platform-browser": "19.0.1", - "@angular/platform-browser-dynamic": "19.0.1", - "@angular/platform-server": "19.0.1", - "@angular/router": "19.0.1", - "@angular/service-worker": "19.0.1", + "@angular/platform-browser": "19.1.0-next.0", + "@angular/platform-browser-dynamic": "19.1.0-next.0", + "@angular/platform-server": "19.1.0-next.0", + "@angular/router": "19.1.0-next.0", + "@angular/service-worker": "19.1.0-next.0", "@babel/core": "7.26.0", "@babel/generator": "7.26.2", "@babel/helper-annotate-as-pure": "7.25.9", @@ -168,7 +168,7 @@ "magic-string": "0.30.14", "mini-css-extract-plugin": "2.9.2", "mrmime": "2.0.0", - "ng-packagr": "19.0.1", + "ng-packagr": "19.1.0-next.0", "npm": "^10.8.1", "npm-package-arg": "12.0.0", "npm-pick-manifest": "10.0.0", @@ -202,7 +202,7 @@ "tree-kill": "1.2.2", "ts-node": "^10.9.1", "tslib": "2.8.1", - "typescript": "5.6.3", + "typescript": "5.7.2", "undici": "6.21.0", "unenv": "^1.10.0", "verdaccio": "6.0.2", diff --git a/packages/angular/build/package.json b/packages/angular/build/package.json index cccd124fd894..4a954ad9aedd 100644 --- a/packages/angular/build/package.json +++ b/packages/angular/build/package.json @@ -57,7 +57,7 @@ "less": "^4.2.0", "postcss": "^8.4.0", "tailwindcss": "^2.0.0 || ^3.0.0", - "typescript": ">=5.5 <5.7" + "typescript": ">=5.5 <5.8" }, "peerDependenciesMeta": { "@angular/localize": { diff --git a/packages/angular/ssr/package.json b/packages/angular/ssr/package.json index d0573b6b03be..4b676444ed3c 100644 --- a/packages/angular/ssr/package.json +++ b/packages/angular/ssr/package.json @@ -22,12 +22,12 @@ "@angular/router": "^19.0.0" }, "devDependencies": { - "@angular/common": "19.0.1", - "@angular/compiler": "19.0.1", - "@angular/core": "19.0.1", - "@angular/platform-browser": "19.0.1", - "@angular/platform-server": "19.0.1", - "@angular/router": "19.0.1", + "@angular/common": "19.1.0-next.0", + "@angular/compiler": "19.1.0-next.0", + "@angular/core": "19.1.0-next.0", + "@angular/platform-browser": "19.1.0-next.0", + "@angular/platform-server": "19.1.0-next.0", + "@angular/router": "19.1.0-next.0", "@bazel/runfiles": "^5.8.1" }, "sideEffects": false, diff --git a/packages/angular_devkit/build_angular/package.json b/packages/angular_devkit/build_angular/package.json index 388843165bf5..e51a8014872f 100644 --- a/packages/angular_devkit/build_angular/package.json +++ b/packages/angular_devkit/build_angular/package.json @@ -82,7 +82,7 @@ "ng-packagr": "^19.0.0", "protractor": "^7.0.0", "tailwindcss": "^2.0.0 || ^3.0.0", - "typescript": ">=5.5 <5.7" + "typescript": ">=5.5 <5.8" }, "peerDependenciesMeta": { "@angular/localize": { diff --git a/packages/angular_devkit/core/node/host.ts b/packages/angular_devkit/core/node/host.ts index 578296d3749c..422a95af2b01 100644 --- a/packages/angular_devkit/core/node/host.ts +++ b/packages/angular_devkit/core/node/host.ts @@ -71,7 +71,7 @@ export class NodeJsAsyncHost implements virtualFs.Host { read(path: Path): Observable { return observableFrom(fsPromises.readFile(getSystemPath(path))).pipe( - map((buffer) => new Uint8Array(buffer).buffer as virtualFs.FileBuffer), + map((buffer) => new Uint8Array(buffer).buffer), ); } @@ -169,7 +169,7 @@ export class NodeJsSyncHost implements virtualFs.Host { return new Observable((obs) => { const buffer = readFileSync(getSystemPath(path)); - obs.next(new Uint8Array(buffer).buffer as virtualFs.FileBuffer); + obs.next(new Uint8Array(buffer).buffer); obs.complete(); }); } diff --git a/packages/ngtools/webpack/package.json b/packages/ngtools/webpack/package.json index 5f75e6abb705..acaa155d2709 100644 --- a/packages/ngtools/webpack/package.json +++ b/packages/ngtools/webpack/package.json @@ -22,14 +22,14 @@ "homepage": "https://github.com/angular/angular-cli/tree/main/packages/ngtools/webpack", "peerDependencies": { "@angular/compiler-cli": "^19.0.0", - "typescript": ">=5.5 <5.7", + "typescript": ">=5.5 <5.8", "webpack": "^5.54.0" }, "devDependencies": { "@angular-devkit/core": "0.0.0-PLACEHOLDER", - "@angular/compiler": "19.0.1", - "@angular/compiler-cli": "19.0.1", - "typescript": "5.6.3", + "@angular/compiler": "19.1.0-next.0", + "@angular/compiler-cli": "19.1.0-next.0", + "typescript": "5.7.2", "webpack": "5.96.1" } } diff --git a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/BUILD.bazel b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/BUILD.bazel index 42927c5a88db..0da24bacd4ff 100644 --- a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/BUILD.bazel +++ b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/BUILD.bazel @@ -1,11 +1,11 @@ load("//tools:defaults.bzl", "ts_library") -# files fetched on 2024-09-10 from -# https://github.com/microsoft/TypeScript/releases/tag/v5.6.2 +# files fetched on 2024-11-28 from +# https://github.com/microsoft/TypeScript/releases/tag/v5.7.2 # Commands to download: -# curl https://raw.githubusercontent.com/microsoft/TypeScript/v5.6.2/lib/typescript.d.ts -o packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.d.ts -# curl https://raw.githubusercontent.com/microsoft/TypeScript/v5.6.2/lib/typescript.js -o packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.js +# curl https://raw.githubusercontent.com/microsoft/TypeScript/v5.7.2/lib/typescript.d.ts -o packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.d.ts +# curl https://raw.githubusercontent.com/microsoft/TypeScript/v5.7.2/lib/typescript.js -o packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.js licenses(["notice"]) # Apache 2.0 diff --git a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.d.ts b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.d.ts index 963c5732b922..6780dd1ddb94 100644 --- a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.d.ts +++ b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.d.ts @@ -107,6 +107,7 @@ declare namespace ts { GetApplicableRefactors = "getApplicableRefactors", GetEditsForRefactor = "getEditsForRefactor", GetMoveToRefactoringFileSuggestions = "getMoveToRefactoringFileSuggestions", + PreparePasteEdits = "preparePasteEdits", GetPasteEdits = "getPasteEdits", OrganizeImports = "organizeImports", GetEditsForFileRename = "getEditsForFileRename", @@ -363,6 +364,10 @@ declare namespace ts { * Indicate if the file name list of the project is needed */ needFileNameList: boolean; + /** + * if true returns details about default configured project calculation + */ + needDefaultConfiguredProjectInfo?: boolean; } /** * A request to get the project information of the current file. @@ -386,6 +391,17 @@ declare namespace ts { */ projectFileName: string; } + /** + * Details about the default project for the file if tsconfig file is found + */ + export interface DefaultConfiguredProjectInfo { + /** List of config files looked and did not match because file was not part of root file names */ + notMatchedByConfig?: readonly string[]; + /** List of projects which were loaded but file was not part of the project or is file from referenced project */ + notInProject?: readonly string[]; + /** Configured project used as default */ + defaultProject?: string; + } /** * Response message body for "projectInfo" request */ @@ -403,6 +419,10 @@ declare namespace ts { * Indicates if the project has a active language service instance */ languageServiceDisabled?: boolean; + /** + * Information about default project + */ + configuredProjectInfo?: DefaultConfiguredProjectInfo; } /** * Represents diagnostic info that includes location of diagnostic in two forms @@ -495,6 +515,19 @@ declare namespace ts { files: string[]; }; } + /** + * Request to check if `pasteEdits` should be provided for a given location post copying text from that location. + */ + export interface PreparePasteEditsRequest extends FileRequest { + command: CommandTypes.PreparePasteEdits; + arguments: PreparePasteEditsRequestArgs; + } + export interface PreparePasteEditsRequestArgs extends FileRequestArgs { + copiedTextSpan: TextSpan[]; + } + export interface PreparePasteEditsResponse extends Response { + body: boolean; + } /** * Request refactorings at a given position post pasting text from some other location. */ @@ -2507,6 +2540,7 @@ declare namespace ts { ES2021 = "es2021", ES2022 = "es2022", ES2023 = "es2023", + ES2024 = "es2024", ESNext = "esnext", JSON = "json", Latest = "esnext", @@ -2808,7 +2842,6 @@ declare namespace ts { abstract class Project implements LanguageServiceHost, ModuleResolutionHost { readonly projectKind: ProjectKind; readonly projectService: ProjectService; - private documentRegistry; private compilerOptions; compileOnSaveEnabled: boolean; protected watchOptions: WatchOptions | undefined; @@ -2828,7 +2861,6 @@ declare namespace ts { private lastReportedFileNames; private lastReportedVersion; protected projectErrors: Diagnostic[] | undefined; - protected isInitialLoadPending: () => boolean; private typingsCache; private typingWatchers; private readonly cancellationToken; @@ -2842,14 +2874,14 @@ declare namespace ts { readonly jsDocParsingMode: JSDocParsingMode | undefined; isKnownTypesPackageName(name: string): boolean; installPackage(options: InstallPackageOptions): Promise; - getCompilationSettings(): ts.CompilerOptions; - getCompilerOptions(): ts.CompilerOptions; + getCompilationSettings(): CompilerOptions; + getCompilerOptions(): CompilerOptions; getNewLine(): string; getProjectVersion(): string; getProjectReferences(): readonly ProjectReference[] | undefined; getScriptFileNames(): string[]; private getOrCreateScriptInfoAndAttachToProject; - getScriptKind(fileName: string): ts.ScriptKind; + getScriptKind(fileName: string): ScriptKind; getScriptVersion(filename: string): string; getScriptSnapshot(filename: string): IScriptSnapshot | undefined; getCancellationToken(): HostCancellationToken; @@ -2885,16 +2917,16 @@ declare namespace ts { getProjectName(): string; protected removeLocalTypingsFromTypeAcquisition(newTypeAcquisition: TypeAcquisition): TypeAcquisition; getExternalFiles(updateLevel?: ProgramUpdateLevel): SortedReadonlyArray; - getSourceFile(path: Path): ts.SourceFile | undefined; + getSourceFile(path: Path): SourceFile | undefined; close(): void; private detachScriptInfoIfNotRoot; isClosed(): boolean; hasRoots(): boolean; getRootFiles(): NormalizedPath[]; - getRootScriptInfos(): ts.server.ScriptInfo[]; + getRootScriptInfos(): ScriptInfo[]; getScriptInfos(): ScriptInfo[]; getExcludedFiles(): readonly NormalizedPath[]; - getFileNames(excludeFilesFromExternalLibraries?: boolean, excludeConfigFiles?: boolean): ts.server.NormalizedPath[]; + getFileNames(excludeFilesFromExternalLibraries?: boolean, excludeConfigFiles?: boolean): NormalizedPath[]; hasConfigFile(configFilePath: NormalizedPath): boolean; containsScriptInfo(info: ScriptInfo): boolean; containsFile(filename: NormalizedPath, requireOpen?: boolean): boolean; @@ -2919,19 +2951,18 @@ declare namespace ts { private isValidGeneratedFileWatcher; private clearGeneratedFileWatch; getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined; - getScriptInfo(uncheckedFileName: string): ts.server.ScriptInfo | undefined; + getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined; filesToString(writeProjectFileNames: boolean): string; private filesToStringWorker; setCompilerOptions(compilerOptions: CompilerOptions): void; setTypeAcquisition(newTypeAcquisition: TypeAcquisition | undefined): void; - getTypeAcquisition(): ts.TypeAcquisition; + getTypeAcquisition(): TypeAcquisition; protected removeRoot(info: ScriptInfo): void; protected enableGlobalPlugins(options: CompilerOptions): void; protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void; /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ refreshDiagnostics(): void; private isDefaultProjectForOpenFiles; - private getCompilerOptionsForNoDtsResolutionProject; } /** * If a file is opened and no tsconfig (or jsconfig) is found, @@ -2958,7 +2989,7 @@ declare namespace ts { getScriptFileNames(): string[]; getLanguageService(): never; getHostForAutoImportProvider(): never; - getProjectReferences(): readonly ts.ProjectReference[] | undefined; + getProjectReferences(): readonly ProjectReference[] | undefined; } /** * If a file is opened, the server will look for a tsconfig (or jsconfig) @@ -2975,7 +3006,7 @@ declare namespace ts { * @returns: true if set of files in the project stays the same and false - otherwise. */ updateGraph(): boolean; - getConfigFilePath(): ts.server.NormalizedPath; + getConfigFilePath(): NormalizedPath; getProjectReferences(): readonly ProjectReference[] | undefined; updateReferences(refs: readonly ProjectReference[] | undefined): void; /** @@ -2999,14 +3030,14 @@ declare namespace ts { compileOnSaveEnabled: boolean; excludedFiles: readonly NormalizedPath[]; updateGraph(): boolean; - getExcludedFiles(): readonly ts.server.NormalizedPath[]; + getExcludedFiles(): readonly NormalizedPath[]; } function convertFormatOptions(protocolOptions: protocol.FormatCodeSettings): FormatCodeSettings; function convertCompilerOptions(protocolOptions: protocol.ExternalProjectCompilerOptions): CompilerOptions & protocol.CompileOnSaveMixin; function convertWatchOptions(protocolOptions: protocol.ExternalProjectCompilerOptions, currentDirectory?: string): WatchOptionsAndErrors | undefined; function convertTypeAcquisition(protocolOptions: protocol.InferredProjectCompilerOptions): TypeAcquisition | undefined; function tryConvertScriptKindName(scriptKindName: protocol.ScriptKindName | ScriptKind): ScriptKind; - function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind.Unknown | ScriptKind.JS | ScriptKind.JSX | ScriptKind.TS | ScriptKind.TSX; + function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind; const maxProgramSizeForNonTsFiles: number; const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; interface ProjectsUpdatedInBackgroundEvent { @@ -3277,6 +3308,7 @@ declare namespace ts { private deleteScriptInfo; private configFileExists; private createConfigFileWatcherForParsedConfig; + private ensureConfigFileWatcherForProject; private forEachConfigFileLocation; private getConfigFileNameForFileFromCache; private setConfigFileNameForFileInCache; @@ -3290,6 +3322,7 @@ declare namespace ts { private updateNonInferredProjectFiles; private updateRootAndOptionsOfNonInferredProject; private reloadFileNamesOfParsedConfig; + private setProjectForReload; private clearSemanticCache; private getOrCreateInferredProjectForProjectRootPathIfEnabled; private getOrCreateSingleInferredProjectIfEnabled; @@ -3336,6 +3369,8 @@ declare namespace ts { private getOrCreateOpenScriptInfo; private assignProjectToOpenedScriptInfo; private tryFindDefaultConfiguredProjectForOpenScriptInfo; + private isMatchedByConfig; + private tryFindDefaultConfiguredProjectForOpenScriptInfoOrClosedFileInfo; private tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo; private ensureProjectChildren; private cleanupConfiguredProjects; @@ -3480,9 +3515,11 @@ declare namespace ts { private getDocumentHighlights; private provideInlayHints; private mapCode; + private getCopilotRelatedInfo; private setCompilerOptionsForInferredProjects; private getProjectInfo; private getProjectInfoWorker; + private getDefaultConfiguredProjectInfo; private getRenameInfo; private getProjects; private getDefaultProject; @@ -3535,6 +3572,7 @@ declare namespace ts { private getApplicableRefactors; private getEditsForRefactor; private getMoveToRefactoringFileSuggestions; + private preparePasteEdits; private getPasteEdits; private organizeImports; private getEditsForFileRename; @@ -3595,7 +3633,7 @@ declare namespace ts { readDirectory(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[] | undefined, depth?: number): string[]; } } - const versionMajorMinor = "5.6"; + const versionMajorMinor = "5.7"; /** The version of the TypeScript compiler release */ const version: string; /** @@ -3983,10 +4021,11 @@ declare namespace ts { JSDocImportTag = 351, SyntaxList = 352, NotEmittedStatement = 353, - PartiallyEmittedExpression = 354, - CommaListExpression = 355, - SyntheticReferenceExpression = 356, - Count = 357, + NotEmittedTypeElement = 354, + PartiallyEmittedExpression = 355, + CommaListExpression = 356, + SyntheticReferenceExpression = 357, + Count = 358, FirstAssignment = 64, LastAssignment = 79, FirstCompoundAssignment = 65, @@ -5098,7 +5137,7 @@ declare namespace ts { interface InstanceofExpression extends BinaryExpression { readonly operatorToken: Token; } - type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator | JsxOpeningLikeElement | InstanceofExpression; + type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator | JsxCallLike | InstanceofExpression; interface AsExpression extends Expression { readonly kind: SyntaxKind.AsExpression; readonly expression: Expression; @@ -5134,6 +5173,7 @@ declare namespace ts { readonly closingElement: JsxClosingElement; } type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; + type JsxCallLike = JsxOpeningLikeElement | JsxOpeningFragment; type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; type JsxAttributeName = Identifier | JsxNamespacedName; type JsxTagNameExpression = Identifier | ThisExpression | JsxTagNamePropertyAccess | JsxNamespacedName; @@ -5212,6 +5252,9 @@ declare namespace ts { interface NotEmittedStatement extends Statement { readonly kind: SyntaxKind.NotEmittedStatement; } + interface NotEmittedTypeElement extends TypeElement { + readonly kind: SyntaxKind.NotEmittedTypeElement; + } /** * A list of comma-separated expressions. This node is only created by transformations. */ @@ -6115,7 +6158,7 @@ declare namespace ts { getPrivateIdentifierPropertyOfType(leftType: Type, name: string, location: Node): Symbol | undefined; getIndexInfoOfType(type: Type, kind: IndexKind): IndexInfo | undefined; getIndexInfosOfType(type: Type): readonly IndexInfo[]; - getIndexInfosOfIndexSymbol: (indexSymbol: Symbol) => IndexInfo[]; + getIndexInfosOfIndexSymbol: (indexSymbol: Symbol, siblingSymbols?: Symbol[] | undefined) => IndexInfo[]; getSignaturesOfType(type: Type, kind: SignatureKind): readonly Signature[]; getIndexTypeOfType(type: Type, kind: IndexKind): Type | undefined; getBaseTypes(type: InterfaceType): BaseType[]; @@ -6982,6 +7025,7 @@ declare namespace ts { moduleDetection?: ModuleDetectionKind; newLine?: NewLineKind; noEmit?: boolean; + noCheck?: boolean; noEmitHelpers?: boolean; noEmitOnError?: boolean; noErrorTruncation?: boolean; @@ -7021,6 +7065,7 @@ declare namespace ts { removeComments?: boolean; resolvePackageJsonExports?: boolean; resolvePackageJsonImports?: boolean; + rewriteRelativeImportExtensions?: boolean; rootDir?: string; rootDirs?: string[]; skipLibCheck?: boolean; @@ -7131,6 +7176,7 @@ declare namespace ts { ES2021 = 8, ES2022 = 9, ES2023 = 10, + ES2024 = 11, ESNext = 99, JSON = 100, Latest = 99, @@ -7813,6 +7859,7 @@ declare namespace ts { createSourceFile(statements: readonly Statement[], endOfFileToken: EndOfFileToken, flags: NodeFlags): SourceFile; updateSourceFile(node: SourceFile, statements: readonly Statement[], isDeclarationFile?: boolean, referencedFiles?: readonly FileReference[], typeReferences?: readonly FileReference[], hasNoDefaultLib?: boolean, libReferences?: readonly FileReference[]): SourceFile; createNotEmittedStatement(original: Node): NotEmittedStatement; + createNotEmittedTypeElement(): NotEmittedTypeElement; createPartiallyEmittedExpression(expression: Expression, original?: Node): PartiallyEmittedExpression; updatePartiallyEmittedExpression(node: PartiallyEmittedExpression, expression: Expression): PartiallyEmittedExpression; createCommaListExpression(elements: readonly Expression[]): CommaListExpression; @@ -8694,6 +8741,7 @@ declare namespace ts { function isTypeOnlyImportDeclaration(node: Node): node is TypeOnlyImportDeclaration; function isTypeOnlyExportDeclaration(node: Node): node is TypeOnlyExportDeclaration; function isTypeOnlyImportOrExportDeclaration(node: Node): node is TypeOnlyAliasDeclaration; + function isPartOfTypeOnlyImportOrExportDeclaration(node: Node): boolean; function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken; function isImportAttributeName(node: Node): node is ImportAttributeName; function isModifier(node: Node): node is Modifier; @@ -8742,6 +8790,7 @@ declare namespace ts { function isJsxAttributeLike(node: Node): node is JsxAttributeLike; function isStringLiteralOrJsxExpression(node: Node): node is StringLiteral | JsxExpression; function isJsxOpeningLikeElement(node: Node): node is JsxOpeningLikeElement; + function isJsxCallLike(node: Node): node is JsxCallLike; function isCaseOrDefaultClause(node: Node): node is CaseOrDefaultClause; /** True if node is of a kind that may contain comment text. */ function isJSDocCommentContainingNode(node: Node): boolean; @@ -9120,6 +9169,7 @@ declare namespace ts { jsDocParsingMode?: JSDocParsingMode; } function parseCommandLine(commandLine: readonly string[], readFile?: (path: string) => string | undefined): ParsedCommandLine; + function parseBuildCommand(commandLine: readonly string[]): ParsedBuildCommand; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ @@ -9174,6 +9224,13 @@ declare namespace ts { options: TypeAcquisition; errors: Diagnostic[]; }; + /** Parsed command line for build */ + interface ParsedBuildCommand { + buildOptions: BuildOptions; + watchOptions: WatchOptions | undefined; + projects: string[]; + errors: Diagnostic[]; + } type DiagnosticReporter = (diagnostic: Diagnostic) => void; /** * Reports config file diagnostics @@ -9901,6 +9958,8 @@ declare namespace ts { emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult | undefined; } type InvalidatedProject = UpdateOutputFileStampsProject | BuildInvalidedProject; + /** Returns true if commandline is --build and needs to be parsed useing parseBuildCommand */ + function isBuildCommand(commandLineArgs: readonly string[]): boolean; function getDefaultFormatCodeSettings(newLineCharacter?: string): FormatCodeSettings; /** * Represents an immutable snapshot of a script at a specified time.Once acquired, the @@ -10175,6 +10234,7 @@ declare namespace ts { uncommentSelection(fileName: string, textRange: TextRange): TextChange[]; getSupportedCodeFixes(fileName?: string): readonly string[]; dispose(): void; + preparePasteEditsForFile(fileName: string, copiedTextRanges: TextRange[]): boolean; getPasteEdits(args: PasteEditsArgs, formatOptions: FormatCodeSettings): PasteEdits; } interface JsxClosingTagInfo { diff --git a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.js b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.js index 90f3266ee69f..33387eadeb84 100644 --- a/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.js +++ b/packages/schematics/angular/third_party/github.com/Microsoft/TypeScript/lib/typescript.js @@ -144,6 +144,7 @@ __export(typescript_exports, { PollingWatchKind: () => PollingWatchKind, PragmaKindFlags: () => PragmaKindFlags, PredicateSemantics: () => PredicateSemantics, + PreparePasteEdits: () => ts_preparePasteEdits_exports, PrivateIdentifierKind: () => PrivateIdentifierKind, ProcessLevel: () => ProcessLevel, ProgramUpdateLevel: () => ProgramUpdateLevel, @@ -239,7 +240,6 @@ __export(typescript_exports, { buildOverload: () => buildOverload, bundlerModuleNameResolver: () => bundlerModuleNameResolver, canBeConvertedToAsync: () => canBeConvertedToAsync, - canEmitTsBuildInfo: () => canEmitTsBuildInfo, canHaveDecorators: () => canHaveDecorators, canHaveExportModifier: () => canHaveExportModifier, canHaveFlowNode: () => canHaveFlowNode, @@ -259,6 +259,7 @@ __export(typescript_exports, { canWatchAffectingLocation: () => canWatchAffectingLocation, canWatchAtTypes: () => canWatchAtTypes, canWatchDirectoryOrFile: () => canWatchDirectoryOrFile, + canWatchDirectoryOrFilePath: () => canWatchDirectoryOrFilePath, cartesianProduct: () => cartesianProduct, cast: () => cast, chainBundle: () => chainBundle, @@ -529,6 +530,7 @@ __export(typescript_exports, { escapeTemplateSubstitution: () => escapeTemplateSubstitution, evaluatorResult: () => evaluatorResult, every: () => every, + exclusivelyPrefixedNodeCoreModules: () => exclusivelyPrefixedNodeCoreModules, executeCommandLine: () => executeCommandLine, expandPreOrPostfixIncrementOrDecrementExpression: () => expandPreOrPostfixIncrementOrDecrementExpression, explainFiles: () => explainFiles, @@ -541,7 +543,6 @@ __export(typescript_exports, { extensionsNotSupportingExtensionlessResolution: () => extensionsNotSupportingExtensionlessResolution, externalHelpersModuleNameText: () => externalHelpersModuleNameText, factory: () => factory, - fileContainsPackageImport: () => fileContainsPackageImport, fileExtensionIs: () => fileExtensionIs, fileExtensionIsOneOf: () => fileExtensionIsOneOf, fileIncludeReasonToDiagnostics: () => fileIncludeReasonToDiagnostics, @@ -591,8 +592,10 @@ __export(typescript_exports, { forEach: () => forEach, forEachAncestor: () => forEachAncestor, forEachAncestorDirectory: () => forEachAncestorDirectory, + forEachAncestorDirectoryStoppingAtGlobalCache: () => forEachAncestorDirectoryStoppingAtGlobalCache, forEachChild: () => forEachChild, forEachChildRecursively: () => forEachChildRecursively, + forEachDynamicImportOrRequireCall: () => forEachDynamicImportOrRequireCall, forEachEmittedFile: () => forEachEmittedFile, forEachEnclosingBlockScopeContainer: () => forEachEnclosingBlockScopeContainer, forEachEntry: () => forEachEntry, @@ -633,6 +636,7 @@ __export(typescript_exports, { getAllKeys: () => getAllKeys, getAllProjectOutputs: () => getAllProjectOutputs, getAllSuperTypeNodes: () => getAllSuperTypeNodes, + getAllowImportingTsExtensions: () => getAllowImportingTsExtensions, getAllowJSCompilerOption: () => getAllowJSCompilerOption, getAllowSyntheticDefaultImports: () => getAllowSyntheticDefaultImports, getAncestor: () => getAncestor, @@ -941,6 +945,7 @@ __export(typescript_exports, { getPositionOfLineAndCharacter: () => getPositionOfLineAndCharacter, getPossibleGenericSignatures: () => getPossibleGenericSignatures, getPossibleOriginalInputExtensionForExtension: () => getPossibleOriginalInputExtensionForExtension, + getPossibleOriginalInputPathWithoutChangingExt: () => getPossibleOriginalInputPathWithoutChangingExt, getPossibleTypeArgumentsInfo: () => getPossibleTypeArgumentsInfo, getPreEmitDiagnostics: () => getPreEmitDiagnostics, getPrecedingNonSpaceCharacterPosition: () => getPrecedingNonSpaceCharacterPosition, @@ -1204,7 +1209,7 @@ __export(typescript_exports, { isBooleanLiteral: () => isBooleanLiteral, isBreakOrContinueStatement: () => isBreakOrContinueStatement, isBreakStatement: () => isBreakStatement, - isBuild: () => isBuild, + isBuildCommand: () => isBuildCommand, isBuildInfoFile: () => isBuildInfoFile, isBuilderProgram: () => isBuilderProgram, isBundle: () => isBundle, @@ -1391,7 +1396,7 @@ __export(typescript_exports, { isImportSpecifier: () => isImportSpecifier, isImportTypeAssertionContainer: () => isImportTypeAssertionContainer, isImportTypeNode: () => isImportTypeNode, - isImportableFile: () => isImportableFile, + isImportable: () => isImportable, isInComment: () => isInComment, isInCompoundLikeAssignment: () => isInCompoundLikeAssignment, isInExpressionContext: () => isInExpressionContext, @@ -1490,6 +1495,7 @@ __export(typescript_exports, { isJsxAttributeLike: () => isJsxAttributeLike, isJsxAttributeName: () => isJsxAttributeName, isJsxAttributes: () => isJsxAttributes, + isJsxCallLike: () => isJsxCallLike, isJsxChild: () => isJsxChild, isJsxClosingElement: () => isJsxClosingElement, isJsxClosingFragment: () => isJsxClosingFragment, @@ -1572,6 +1578,7 @@ __export(typescript_exports, { isNamespaceReexportDeclaration: () => isNamespaceReexportDeclaration, isNewExpression: () => isNewExpression, isNewExpressionTarget: () => isNewExpressionTarget, + isNewScopeNode: () => isNewScopeNode, isNoSubstitutionTemplateLiteral: () => isNoSubstitutionTemplateLiteral, isNodeArray: () => isNodeArray, isNodeArrayMultiLine: () => isNodeArrayMultiLine, @@ -1620,6 +1627,7 @@ __export(typescript_exports, { isParseTreeNode: () => isParseTreeNode, isPartOfParameterDeclaration: () => isPartOfParameterDeclaration, isPartOfTypeNode: () => isPartOfTypeNode, + isPartOfTypeOnlyImportOrExportDeclaration: () => isPartOfTypeOnlyImportOrExportDeclaration, isPartOfTypeQuery: () => isPartOfTypeQuery, isPartiallyEmittedExpression: () => isPartiallyEmittedExpression, isPatternMatch: () => isPatternMatch, @@ -1688,6 +1696,7 @@ __export(typescript_exports, { isSimpleInlineableExpression: () => isSimpleInlineableExpression, isSimpleParameterList: () => isSimpleParameterList, isSingleOrDoubleQuote: () => isSingleOrDoubleQuote, + isSolutionConfig: () => isSolutionConfig, isSourceElement: () => isSourceElement, isSourceFile: () => isSourceFile, isSourceFileFromLibrary: () => isSourceFileFromLibrary, @@ -1796,7 +1805,6 @@ __export(typescript_exports, { isVariableDeclarationInitializedToRequire: () => isVariableDeclarationInitializedToRequire, isVariableDeclarationList: () => isVariableDeclarationList, isVariableLike: () => isVariableLike, - isVariableLikeOrAccessor: () => isVariableLikeOrAccessor, isVariableStatement: () => isVariableStatement, isVoidExpression: () => isVoidExpression, isWatchSet: () => isWatchSet, @@ -1833,6 +1841,7 @@ __export(typescript_exports, { matchPatternOrExact: () => matchPatternOrExact, matchedText: () => matchedText, matchesExclude: () => matchesExclude, + matchesExcludeWorker: () => matchesExcludeWorker, maxBy: () => maxBy, maybeBind: () => maybeBind, maybeSetLocalizedDiagnosticMessages: () => maybeSetLocalizedDiagnosticMessages, @@ -1872,6 +1881,7 @@ __export(typescript_exports, { noTransformers: () => noTransformers, noTruncationMaximumTruncationLength: () => noTruncationMaximumTruncationLength, nodeCanBeDecorated: () => nodeCanBeDecorated, + nodeCoreModules: () => nodeCoreModules, nodeHasName: () => nodeHasName, nodeIsDecorated: () => nodeIsDecorated, nodeIsMissing: () => nodeIsMissing, @@ -2016,6 +2026,7 @@ __export(typescript_exports, { returnTrue: () => returnTrue, returnUndefined: () => returnUndefined, returnsPromise: () => returnsPromise, + rewriteModuleSpecifier: () => rewriteModuleSpecifier, sameFlatMap: () => sameFlatMap, sameMap: () => sameMap, sameMapping: () => sameMapping, @@ -2061,6 +2072,7 @@ __export(typescript_exports, { setValueDeclaration: () => setValueDeclaration, shouldAllowImportingTsExtension: () => shouldAllowImportingTsExtension, shouldPreserveConstEnums: () => shouldPreserveConstEnums, + shouldRewriteModuleSpecifier: () => shouldRewriteModuleSpecifier, shouldUseUriStyleNodeCoreModules: () => shouldUseUriStyleNodeCoreModules, showModuleSpecifier: () => showModuleSpecifier, signatureHasRestParameter: () => signatureHasRestParameter, @@ -2118,6 +2130,7 @@ __export(typescript_exports, { tagNamesAreEquivalent: () => tagNamesAreEquivalent, takeWhile: () => takeWhile, targetOptionDeclaration: () => targetOptionDeclaration, + targetToLibMap: () => targetToLibMap, testFormatSettings: () => testFormatSettings, textChangeRangeIsUnchanged: () => textChangeRangeIsUnchanged, textChangeRangeNewSpan: () => textChangeRangeNewSpan, @@ -2211,6 +2224,7 @@ __export(typescript_exports, { tryRemoveExtension: () => tryRemoveExtension, tryRemovePrefix: () => tryRemovePrefix, tryRemoveSuffix: () => tryRemoveSuffix, + tscBuildOption: () => tscBuildOption, typeAcquisitionDeclarations: () => typeAcquisitionDeclarations, typeAliasNamePart: () => typeAliasNamePart, typeDirectiveIsEqualTo: () => typeDirectiveIsEqualTo, @@ -2222,6 +2236,7 @@ __export(typescript_exports, { unescapeLeadingUnderscores: () => unescapeLeadingUnderscores, unmangleScopedPackageName: () => unmangleScopedPackageName, unorderedRemoveItem: () => unorderedRemoveItem, + unprefixedNodeCoreModules: () => unprefixedNodeCoreModules, unreachableCodeIsError: () => unreachableCodeIsError, unsetNodeChildren: () => unsetNodeChildren, unusedLabelIsError: () => unusedLabelIsError, @@ -2262,8 +2277,8 @@ __export(typescript_exports, { module.exports = __toCommonJS(typescript_exports); // src/compiler/corePublic.ts -var versionMajorMinor = "5.6"; -var version = "5.6.2"; +var versionMajorMinor = "5.7"; +var version = "5.7.2"; var Comparison = /* @__PURE__ */ ((Comparison3) => { Comparison3[Comparison3["LessThan"] = -1] = "LessThan"; Comparison3[Comparison3["EqualTo"] = 0] = "EqualTo"; @@ -2731,7 +2746,10 @@ function deduplicateSorted(array, comparer) { for (let i = 1; i < array.length; i++) { const next = array[i]; switch (comparer(next, last2)) { + // equality comparison case true: + // relational comparison + // falls through case 0 /* EqualTo */: continue; case -1 /* LessThan */: @@ -3616,7 +3634,7 @@ function findBestPatternMatch(values, getPattern, candidate) { for (let i = 0; i < values.length; i++) { const v = values[i]; const pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + if (pattern.prefix.length > longestMatchPrefixLength && isPatternMatch(pattern, candidate)) { longestMatchPrefixLength = pattern.prefix.length; matchedValue = v; } @@ -5852,10 +5870,11 @@ var SyntaxKind = /* @__PURE__ */ ((SyntaxKind5) => { SyntaxKind5[SyntaxKind5["JSDocImportTag"] = 351] = "JSDocImportTag"; SyntaxKind5[SyntaxKind5["SyntaxList"] = 352] = "SyntaxList"; SyntaxKind5[SyntaxKind5["NotEmittedStatement"] = 353] = "NotEmittedStatement"; - SyntaxKind5[SyntaxKind5["PartiallyEmittedExpression"] = 354] = "PartiallyEmittedExpression"; - SyntaxKind5[SyntaxKind5["CommaListExpression"] = 355] = "CommaListExpression"; - SyntaxKind5[SyntaxKind5["SyntheticReferenceExpression"] = 356] = "SyntheticReferenceExpression"; - SyntaxKind5[SyntaxKind5["Count"] = 357] = "Count"; + SyntaxKind5[SyntaxKind5["NotEmittedTypeElement"] = 354] = "NotEmittedTypeElement"; + SyntaxKind5[SyntaxKind5["PartiallyEmittedExpression"] = 355] = "PartiallyEmittedExpression"; + SyntaxKind5[SyntaxKind5["CommaListExpression"] = 356] = "CommaListExpression"; + SyntaxKind5[SyntaxKind5["SyntheticReferenceExpression"] = 357] = "SyntheticReferenceExpression"; + SyntaxKind5[SyntaxKind5["Count"] = 358] = "Count"; SyntaxKind5[SyntaxKind5["FirstAssignment"] = 64 /* EqualsToken */] = "FirstAssignment"; SyntaxKind5[SyntaxKind5["LastAssignment"] = 79 /* CaretEqualsToken */] = "LastAssignment"; SyntaxKind5[SyntaxKind5["FirstCompoundAssignment"] = 65 /* PlusEqualsToken */] = "FirstCompoundAssignment"; @@ -6755,6 +6774,7 @@ var ScriptTarget = /* @__PURE__ */ ((ScriptTarget12) => { ScriptTarget12[ScriptTarget12["ES2021"] = 8] = "ES2021"; ScriptTarget12[ScriptTarget12["ES2022"] = 9] = "ES2022"; ScriptTarget12[ScriptTarget12["ES2023"] = 10] = "ES2023"; + ScriptTarget12[ScriptTarget12["ES2024"] = 11] = "ES2024"; ScriptTarget12[ScriptTarget12["ESNext"] = 99] = "ESNext"; ScriptTarget12[ScriptTarget12["JSON"] = 100] = "JSON"; ScriptTarget12[ScriptTarget12["Latest"] = 99 /* ESNext */] = "Latest"; @@ -7031,43 +7051,42 @@ var InternalEmitFlags = /* @__PURE__ */ ((InternalEmitFlags3) => { InternalEmitFlags3[InternalEmitFlags3["TransformPrivateStaticElements"] = 32] = "TransformPrivateStaticElements"; return InternalEmitFlags3; })(InternalEmitFlags || {}); -var LanguageFeatureMinimumTarget = /* @__PURE__ */ ((LanguageFeatureMinimumTarget2) => { - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["Classes"] = 2 /* ES2015 */] = "Classes"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["ForOf"] = 2 /* ES2015 */] = "ForOf"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["Generators"] = 2 /* ES2015 */] = "Generators"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["Iteration"] = 2 /* ES2015 */] = "Iteration"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["SpreadElements"] = 2 /* ES2015 */] = "SpreadElements"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["RestElements"] = 2 /* ES2015 */] = "RestElements"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["TaggedTemplates"] = 2 /* ES2015 */] = "TaggedTemplates"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["DestructuringAssignment"] = 2 /* ES2015 */] = "DestructuringAssignment"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["BindingPatterns"] = 2 /* ES2015 */] = "BindingPatterns"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["ArrowFunctions"] = 2 /* ES2015 */] = "ArrowFunctions"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["BlockScopedVariables"] = 2 /* ES2015 */] = "BlockScopedVariables"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["ObjectAssign"] = 2 /* ES2015 */] = "ObjectAssign"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["RegularExpressionFlagsUnicode"] = 2 /* ES2015 */] = "RegularExpressionFlagsUnicode"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["RegularExpressionFlagsSticky"] = 2 /* ES2015 */] = "RegularExpressionFlagsSticky"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["Exponentiation"] = 3 /* ES2016 */] = "Exponentiation"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["AsyncFunctions"] = 4 /* ES2017 */] = "AsyncFunctions"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["ForAwaitOf"] = 5 /* ES2018 */] = "ForAwaitOf"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["AsyncGenerators"] = 5 /* ES2018 */] = "AsyncGenerators"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["AsyncIteration"] = 5 /* ES2018 */] = "AsyncIteration"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["ObjectSpreadRest"] = 5 /* ES2018 */] = "ObjectSpreadRest"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["RegularExpressionFlagsDotAll"] = 5 /* ES2018 */] = "RegularExpressionFlagsDotAll"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["BindinglessCatch"] = 6 /* ES2019 */] = "BindinglessCatch"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["BigInt"] = 7 /* ES2020 */] = "BigInt"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["NullishCoalesce"] = 7 /* ES2020 */] = "NullishCoalesce"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["OptionalChaining"] = 7 /* ES2020 */] = "OptionalChaining"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["LogicalAssignment"] = 8 /* ES2021 */] = "LogicalAssignment"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["TopLevelAwait"] = 9 /* ES2022 */] = "TopLevelAwait"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["ClassFields"] = 9 /* ES2022 */] = "ClassFields"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["PrivateNamesAndClassStaticBlocks"] = 9 /* ES2022 */] = "PrivateNamesAndClassStaticBlocks"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["RegularExpressionFlagsHasIndices"] = 9 /* ES2022 */] = "RegularExpressionFlagsHasIndices"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["ShebangComments"] = 99 /* ESNext */] = "ShebangComments"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["UsingAndAwaitUsing"] = 99 /* ESNext */] = "UsingAndAwaitUsing"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["ClassAndClassElementDecorators"] = 99 /* ESNext */] = "ClassAndClassElementDecorators"; - LanguageFeatureMinimumTarget2[LanguageFeatureMinimumTarget2["RegularExpressionFlagsUnicodeSets"] = 99 /* ESNext */] = "RegularExpressionFlagsUnicodeSets"; - return LanguageFeatureMinimumTarget2; -})(LanguageFeatureMinimumTarget || {}); +var LanguageFeatureMinimumTarget = { + Classes: 2 /* ES2015 */, + ForOf: 2 /* ES2015 */, + Generators: 2 /* ES2015 */, + Iteration: 2 /* ES2015 */, + SpreadElements: 2 /* ES2015 */, + RestElements: 2 /* ES2015 */, + TaggedTemplates: 2 /* ES2015 */, + DestructuringAssignment: 2 /* ES2015 */, + BindingPatterns: 2 /* ES2015 */, + ArrowFunctions: 2 /* ES2015 */, + BlockScopedVariables: 2 /* ES2015 */, + ObjectAssign: 2 /* ES2015 */, + RegularExpressionFlagsUnicode: 2 /* ES2015 */, + RegularExpressionFlagsSticky: 2 /* ES2015 */, + Exponentiation: 3 /* ES2016 */, + AsyncFunctions: 4 /* ES2017 */, + ForAwaitOf: 5 /* ES2018 */, + AsyncGenerators: 5 /* ES2018 */, + AsyncIteration: 5 /* ES2018 */, + ObjectSpreadRest: 5 /* ES2018 */, + RegularExpressionFlagsDotAll: 5 /* ES2018 */, + BindinglessCatch: 6 /* ES2019 */, + BigInt: 7 /* ES2020 */, + NullishCoalesce: 7 /* ES2020 */, + OptionalChaining: 7 /* ES2020 */, + LogicalAssignment: 8 /* ES2021 */, + TopLevelAwait: 9 /* ES2022 */, + ClassFields: 9 /* ES2022 */, + PrivateNamesAndClassStaticBlocks: 9 /* ES2022 */, + RegularExpressionFlagsHasIndices: 9 /* ES2022 */, + ShebangComments: 10 /* ES2023 */, + RegularExpressionFlagsUnicodeSets: 11 /* ES2024 */, + UsingAndAwaitUsing: 99 /* ESNext */, + ClassAndClassElementDecorators: 99 /* ESNext */ +}; var ExternalEmitHelpers = /* @__PURE__ */ ((ExternalEmitHelpers2) => { ExternalEmitHelpers2[ExternalEmitHelpers2["Extends"] = 1] = "Extends"; ExternalEmitHelpers2[ExternalEmitHelpers2["Assign"] = 2] = "Assign"; @@ -7095,6 +7114,7 @@ var ExternalEmitHelpers = /* @__PURE__ */ ((ExternalEmitHelpers2) => { ExternalEmitHelpers2[ExternalEmitHelpers2["SetFunctionName"] = 4194304] = "SetFunctionName"; ExternalEmitHelpers2[ExternalEmitHelpers2["PropKey"] = 8388608] = "PropKey"; ExternalEmitHelpers2[ExternalEmitHelpers2["AddDisposableResourceAndDisposeResources"] = 16777216] = "AddDisposableResourceAndDisposeResources"; + ExternalEmitHelpers2[ExternalEmitHelpers2["RewriteRelativeImportExtension"] = 33554432] = "RewriteRelativeImportExtension"; ExternalEmitHelpers2[ExternalEmitHelpers2["FirstEmitHelper"] = 1 /* Extends */] = "FirstEmitHelper"; ExternalEmitHelpers2[ExternalEmitHelpers2["LastEmitHelper"] = 16777216 /* AddDisposableResourceAndDisposeResources */] = "LastEmitHelper"; ExternalEmitHelpers2[ExternalEmitHelpers2["ForOfIncludes"] = 256 /* Values */] = "ForOfIncludes"; @@ -7995,6 +8015,7 @@ function createSystemWatchFunctions({ return generateWatchFileOptions(4 /* UseFsEvents */, 2 /* DynamicPriority */, options); case "UseFsEventsOnParentDirectory": useNonPollingWatchers2 = true; + // fall through default: return useNonPollingWatchers2 ? ( // Use notifications from FS to watch with falling back to fs.watchFile @@ -8243,6 +8264,7 @@ var sys = (() => { let profilePath = "./profile.cpuprofile"; const isMacOs = process.platform === "darwin"; const isLinuxOrMacOs = process.platform === "linux" || isMacOs; + const statSyncOptions = { throwIfNoEntry: false }; const platform = _os.platform(); const useCaseSensitiveFileNames2 = isFileSystemCaseSensitive(); const fsRealpath = !!_fs.realpathSync.native ? process.platform === "win32" ? fsRealPathHandlingLongPath : _fs.realpathSync.native : _fs.realpathSync; @@ -8324,12 +8346,9 @@ var sys = (() => { return process.memoryUsage().heapUsed; }, getFileSize(path) { - try { - const stat = statSync(path); - if (stat == null ? void 0 : stat.isFile()) { - return stat.size; - } - } catch { + const stat = statSync(path); + if (stat == null ? void 0 : stat.isFile()) { + return stat.size; } return 0; }, @@ -8372,7 +8391,11 @@ var sys = (() => { }; return nodeSystem; function statSync(path) { - return _fs.statSync(path, { throwIfNoEntry: false }); + try { + return _fs.statSync(path, statSyncOptions); + } catch { + return void 0; + } } function enableCPUProfiler(path, cb) { if (activeSession) { @@ -8426,11 +8449,8 @@ var sys = (() => { activeSession.post("Profiler.stop", (err, { profile }) => { var _a; if (!err) { - try { - if ((_a = statSync(profilePath)) == null ? void 0 : _a.isDirectory()) { - profilePath = _path.join(profilePath, `${(/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-")}+P${process.pid}.cpuprofile`); - } - } catch { + if ((_a = statSync(profilePath)) == null ? void 0 : _a.isDirectory()) { + profilePath = _path.join(profilePath, `${(/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-")}+P${process.pid}.cpuprofile`); } try { _fs.mkdirSync(_path.dirname(profilePath), { recursive: true }); @@ -8549,12 +8569,8 @@ var sys = (() => { let stat; if (typeof dirent === "string" || dirent.isSymbolicLink()) { const name = combinePaths(path, entry); - try { - stat = statSync(name); - if (!stat) { - continue; - } - } catch { + stat = statSync(name); + if (!stat) { continue; } } else { @@ -8577,25 +8593,17 @@ var sys = (() => { return matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames2, process.cwd(), depth, getAccessibleFileSystemEntries, realpath); } function fileSystemEntryExists(path, entryKind) { - const originalStackTraceLimit = Error.stackTraceLimit; - Error.stackTraceLimit = 0; - try { - const stat = statSync(path); - if (!stat) { - return false; - } - switch (entryKind) { - case 0 /* File */: - return stat.isFile(); - case 1 /* Directory */: - return stat.isDirectory(); - default: - return false; - } - } catch { + const stat = statSync(path); + if (!stat) { return false; - } finally { - Error.stackTraceLimit = originalStackTraceLimit; + } + switch (entryKind) { + case 0 /* File */: + return stat.isFile(); + case 1 /* Directory */: + return stat.isDirectory(); + default: + return false; } } function fileExists(path) { @@ -8619,15 +8627,7 @@ var sys = (() => { } function getModifiedTime3(path) { var _a; - const originalStackTraceLimit = Error.stackTraceLimit; - Error.stackTraceLimit = 0; - try { - return (_a = statSync(path)) == null ? void 0 : _a.mtime; - } catch { - return void 0; - } finally { - Error.stackTraceLimit = originalStackTraceLimit; - } + return (_a = statSync(path)) == null ? void 0 : _a.mtime; } function setModifiedTime(path, time) { try { @@ -9537,6 +9537,10 @@ var Diagnostics = { /*reportsDeprecated*/ true ), + Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute: diag(1541, 1 /* Error */, "Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribut_1541", "Type-only import of an ECMAScript module from a CommonJS module must have a 'resolution-mode' attribute."), + Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute: diag(1542, 1 /* Error */, "Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute_1542", "Type import of an ECMAScript module from a CommonJS module must have a 'resolution-mode' attribute."), + Importing_a_JSON_file_into_an_ECMAScript_module_requires_a_type_Colon_json_import_attribute_when_module_is_set_to_0: diag(1543, 1 /* Error */, "Importing_a_JSON_file_into_an_ECMAScript_module_requires_a_type_Colon_json_import_attribute_when_mod_1543", `Importing a JSON file into an ECMAScript module requires a 'type: "json"' import attribute when 'module' is set to '{0}'.`), + Named_imports_from_a_JSON_file_into_an_ECMAScript_module_are_not_allowed_when_module_is_set_to_0: diag(1544, 1 /* Error */, "Named_imports_from_a_JSON_file_into_an_ECMAScript_module_are_not_allowed_when_module_is_set_to_0_1544", "Named imports from a JSON file into an ECMAScript module are not allowed when 'module' is set to '{0}'."), The_types_of_0_are_incompatible_between_these_types: diag(2200, 1 /* Error */, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, 1 /* Error */, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag( @@ -10108,6 +10112,12 @@ var Diagnostics = { This_expression_is_always_nullish: diag(2871, 1 /* Error */, "This_expression_is_always_nullish_2871", "This expression is always nullish."), This_kind_of_expression_is_always_truthy: diag(2872, 1 /* Error */, "This_kind_of_expression_is_always_truthy_2872", "This kind of expression is always truthy."), This_kind_of_expression_is_always_falsy: diag(2873, 1 /* Error */, "This_kind_of_expression_is_always_falsy_2873", "This kind of expression is always falsy."), + This_JSX_tag_requires_0_to_be_in_scope_but_it_could_not_be_found: diag(2874, 1 /* Error */, "This_JSX_tag_requires_0_to_be_in_scope_but_it_could_not_be_found_2874", "This JSX tag requires '{0}' to be in scope, but it could not be found."), + This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_for_the_appropriate_package_installed: diag(2875, 1 /* Error */, "This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_fo_2875", "This JSX tag requires the module path '{0}' to exist, but none could be found. Make sure you have types for the appropriate package installed."), + This_relative_import_path_is_unsafe_to_rewrite_because_it_looks_like_a_file_name_but_actually_resolves_to_0: diag(2876, 1 /* Error */, "This_relative_import_path_is_unsafe_to_rewrite_because_it_looks_like_a_file_name_but_actually_resolv_2876", 'This relative import path is unsafe to rewrite because it looks like a file name, but actually resolves to "{0}".'), + This_import_uses_a_0_extension_to_resolve_to_an_input_TypeScript_file_but_will_not_be_rewritten_during_emit_because_it_is_not_a_relative_path: diag(2877, 1 /* Error */, "This_import_uses_a_0_extension_to_resolve_to_an_input_TypeScript_file_but_will_not_be_rewritten_duri_2877", "This import uses a '{0}' extension to resolve to an input TypeScript file, but will not be rewritten during emit because it is not a relative path."), + This_import_path_is_unsafe_to_rewrite_because_it_resolves_to_another_project_and_the_relative_path_between_the_projects_output_files_is_not_the_same_as_the_relative_path_between_its_input_files: diag(2878, 1 /* Error */, "This_import_path_is_unsafe_to_rewrite_because_it_resolves_to_another_project_and_the_relative_path_b_2878", "This import path is unsafe to rewrite because it resolves to another project, and the relative path between the projects' output files is not the same as the relative path between its input files."), + Using_JSX_fragments_requires_fragment_factory_0_to_be_in_scope_but_it_could_not_be_found: diag(2879, 1 /* Error */, "Using_JSX_fragments_requires_fragment_factory_0_to_be_in_scope_but_it_could_not_be_found_2879", "Using JSX fragments requires fragment factory '{0}' to be in scope, but it could not be found."), Import_declaration_0_is_using_private_name_1: diag(4e3, 1 /* Error */, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, 1 /* Error */, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, 1 /* Error */, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -10283,7 +10293,6 @@ var Diagnostics = { Option_0_1_has_been_removed_Please_remove_it_from_your_configuration: diag(5108, 1 /* Error */, "Option_0_1_has_been_removed_Please_remove_it_from_your_configuration_5108", "Option '{0}={1}' has been removed. Please remove it from your configuration."), Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1: diag(5109, 1 /* Error */, "Option_moduleResolution_must_be_set_to_0_or_left_unspecified_when_option_module_is_set_to_1_5109", "Option 'moduleResolution' must be set to '{0}' (or left unspecified) when option 'module' is set to '{1}'."), Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1: diag(5110, 1 /* Error */, "Option_module_must_be_set_to_0_when_option_moduleResolution_is_set_to_1_5110", "Option 'module' must be set to '{0}' when option 'moduleResolution' is set to '{1}'."), - Option_tsBuildInfoFile_cannot_be_specified_without_specifying_option_incremental_or_composite_or_if_not_running_tsc_b: diag(5111, 1 /* Error */, "Option_tsBuildInfoFile_cannot_be_specified_without_specifying_option_incremental_or_composite_or_if__5111", "Option 'tsBuildInfoFile' cannot be specified without specifying option 'incremental' or 'composite' or if not running 'tsc -b'."), Generates_a_sourcemap_for_each_corresponding_d_ts_file: diag(6e3, 3 /* Message */, "Generates_a_sourcemap_for_each_corresponding_d_ts_file_6000", "Generates a sourcemap for each corresponding '.d.ts' file."), Concatenate_and_emit_output_to_single_file: diag(6001, 3 /* Message */, "Concatenate_and_emit_output_to_single_file_6001", "Concatenate and emit output to single file."), Generates_corresponding_d_ts_file: diag(6002, 3 /* Message */, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."), @@ -10665,6 +10674,7 @@ var Diagnostics = { Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0: diag(6418, 3 /* Message */, "Searching_all_ancestor_node_modules_directories_for_fallback_extensions_Colon_0_6418", "Searching all ancestor node_modules directories for fallback extensions: {0}."), Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_program_needs_to_report_errors: diag(6419, 3 /* Message */, "Project_0_is_out_of_date_because_buildinfo_file_1_indicates_that_program_needs_to_report_errors_6419", "Project '{0}' is out of date because buildinfo file '{1}' indicates that program needs to report errors."), Project_0_is_out_of_date_because_1: diag(6420, 3 /* Message */, "Project_0_is_out_of_date_because_1_6420", "Project '{0}' is out of date because {1}."), + Rewrite_ts_tsx_mts_and_cts_file_extensions_in_relative_import_paths_to_their_JavaScript_equivalent_in_output_files: diag(6421, 3 /* Message */, "Rewrite_ts_tsx_mts_and_cts_file_extensions_in_relative_import_paths_to_their_JavaScript_equivalent_i_6421", "Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files."), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, 3 /* Message */, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, 3 /* Message */, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, 3 /* Message */, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -10844,7 +10854,7 @@ var Diagnostics = { _0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: diag(7022, 1 /* Error */, "_0_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_and_is_referenced_directly_or__7022", "'{0}' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer."), _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7023, 1 /* Error */, "_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_reference_7023", "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: diag(7024, 1 /* Error */, "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions."), - Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation: diag(7025, 1 /* Error */, "Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_retu_7025", "Generator implicitly has yield type '{0}' because it does not yield any values. Consider supplying a return type annotation."), + Generator_implicitly_has_yield_type_0_Consider_supplying_a_return_type_annotation: diag(7025, 1 /* Error */, "Generator_implicitly_has_yield_type_0_Consider_supplying_a_return_type_annotation_7025", "Generator implicitly has yield type '{0}'. Consider supplying a return type annotation."), JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: diag(7026, 1 /* Error */, "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists."), Unreachable_code_detected: diag( 7027, @@ -10935,7 +10945,7 @@ var Diagnostics = { 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."), Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations: diag(9007, 1 /* Error */, "Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9007", "Function must have an explicit return type annotation with --isolatedDeclarations."), Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations: diag(9008, 1 /* Error */, "Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9008", "Method must have an explicit return type annotation with --isolatedDeclarations."), - At_least_one_accessor_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations: diag(9009, 1 /* Error */, "At_least_one_accessor_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations_9009", "At least one accessor must have an explicit return type annotation with --isolatedDeclarations."), + At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations: diag(9009, 1 /* Error */, "At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9009", "At least one accessor must have an explicit type annotation with --isolatedDeclarations."), Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations: diag(9010, 1 /* Error */, "Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9010", "Variable must have an explicit type annotation with --isolatedDeclarations."), Parameter_must_have_an_explicit_type_annotation_with_isolatedDeclarations: diag(9011, 1 /* Error */, "Parameter_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9011", "Parameter must have an explicit type annotation with --isolatedDeclarations."), Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations: diag(9012, 1 /* Error */, "Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations_9012", "Property must have an explicit type annotation with --isolatedDeclarations."), @@ -10950,7 +10960,7 @@ var Diagnostics = { Extends_clause_can_t_contain_an_expression_with_isolatedDeclarations: diag(9021, 1 /* Error */, "Extends_clause_can_t_contain_an_expression_with_isolatedDeclarations_9021", "Extends clause can't contain an expression with --isolatedDeclarations."), Inference_from_class_expressions_is_not_supported_with_isolatedDeclarations: diag(9022, 1 /* Error */, "Inference_from_class_expressions_is_not_supported_with_isolatedDeclarations_9022", "Inference from class expressions is not supported with --isolatedDeclarations."), Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations_Add_an_explicit_declaration_for_the_properties_assigned_to_this_function: diag(9023, 1 /* Error */, "Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations__9023", "Assigning properties to functions without declaring them is not supported with --isolatedDeclarations. Add an explicit declaration for the properties assigned to this function."), - Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_it_s_type_This_is_not_supported_with_isolatedDeclarations: diag(9025, 1 /* Error */, "Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_it_s_type_This_is_not_su_9025", "Declaration emit for this parameter requires implicitly adding undefined to it's type. This is not supported with --isolatedDeclarations."), + Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_its_type_This_is_not_supported_with_isolatedDeclarations: diag(9025, 1 /* Error */, "Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_its_type_This_is_not_sup_9025", "Declaration emit for this parameter requires implicitly adding undefined to its type. This is not supported with --isolatedDeclarations."), Declaration_emit_for_this_file_requires_preserving_this_import_for_augmentations_This_is_not_supported_with_isolatedDeclarations: diag(9026, 1 /* Error */, "Declaration_emit_for_this_file_requires_preserving_this_import_for_augmentations_This_is_not_support_9026", "Declaration emit for this file requires preserving this import for augmentations. This is not supported with --isolatedDeclarations."), Add_a_type_annotation_to_the_variable_0: diag(9027, 1 /* Error */, "Add_a_type_annotation_to_the_variable_0_9027", "Add a type annotation to the variable {0}."), Add_a_type_annotation_to_the_parameter_0: diag(9028, 1 /* Error */, "Add_a_type_annotation_to_the_parameter_0_9028", "Add a type annotation to the parameter {0}."), @@ -11244,6 +11254,8 @@ var Diagnostics = { Add_all_optional_parameters: diag(95193, 3 /* Message */, "Add_all_optional_parameters_95193", "Add all optional parameters"), Wrap_in_parentheses: diag(95194, 3 /* Message */, "Wrap_in_parentheses_95194", "Wrap in parentheses"), Wrap_all_invalid_decorator_expressions_in_parentheses: diag(95195, 3 /* Message */, "Wrap_all_invalid_decorator_expressions_in_parentheses_95195", "Wrap all invalid decorator expressions in parentheses"), + Add_resolution_mode_import_attribute: diag(95196, 3 /* Message */, "Add_resolution_mode_import_attribute_95196", "Add 'resolution-mode' import attribute"), + Add_resolution_mode_import_attribute_to_all_type_only_imports_that_need_it: diag(95197, 3 /* Message */, "Add_resolution_mode_import_attribute_to_all_type_only_imports_that_need_it_95197", "Add 'resolution-mode' import attribute to all type-only imports that need it"), 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?"), @@ -11459,11 +11471,11 @@ var charCodeToRegExpFlag = /* @__PURE__ */ new Map([ [121 /* y */, 128 /* Sticky */] ]); var regExpFlagToFirstAvailableLanguageVersion = /* @__PURE__ */ new Map([ - [1 /* HasIndices */, 9 /* RegularExpressionFlagsHasIndices */], - [16 /* DotAll */, 5 /* RegularExpressionFlagsDotAll */], - [32 /* Unicode */, 2 /* RegularExpressionFlagsUnicode */], - [64 /* UnicodeSets */, 99 /* RegularExpressionFlagsUnicodeSets */], - [128 /* Sticky */, 2 /* RegularExpressionFlagsSticky */] + [1 /* HasIndices */, LanguageFeatureMinimumTarget.RegularExpressionFlagsHasIndices], + [16 /* DotAll */, LanguageFeatureMinimumTarget.RegularExpressionFlagsDotAll], + [32 /* Unicode */, LanguageFeatureMinimumTarget.RegularExpressionFlagsUnicode], + [64 /* UnicodeSets */, LanguageFeatureMinimumTarget.RegularExpressionFlagsUnicodeSets], + [128 /* Sticky */, LanguageFeatureMinimumTarget.RegularExpressionFlagsSticky] ]); var unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6e3, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43e3, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; var unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6e3, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43e3, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500]; @@ -11532,6 +11544,7 @@ function computeLineStarts(text) { if (text.charCodeAt(pos) === 10 /* lineFeed */) { pos++; } + // falls through case 10 /* lineFeed */: result.push(lineStart); lineStart = pos; @@ -11634,6 +11647,8 @@ function couldStartTrivia(text, pos) { case 12 /* formFeed */: case 32 /* space */: case 47 /* slash */: + // starts of normal trivia + // falls through case 60 /* lessThan */: case 124 /* bar */: case 61 /* equals */: @@ -11657,6 +11672,7 @@ function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) { if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { pos++; } + // falls through case 10 /* lineFeed */: pos++; if (stopAfterLineBreak) { @@ -11803,6 +11819,7 @@ function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) { if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { pos++; } + // falls through case 10 /* lineFeed */: pos++; if (trailing) { @@ -12368,12 +12385,16 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan if (pos >= end || !isDigit(charCodeUnchecked(pos))) { return "\0"; } + // '\01', '\011' + // falls through case 49 /* _1 */: case 50 /* _2 */: case 51 /* _3 */: if (pos < end && isOctalDigit(charCodeUnchecked(pos))) { pos++; } + // '\17', '\177' + // falls through case 52 /* _4 */: case 53 /* _5 */: case 54 /* _6 */: @@ -12471,10 +12492,13 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } tokenFlags |= 4096 /* HexEscape */; return String.fromCharCode(parseInt(text.substring(start2 + 2, pos), 16)); + // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence), + // the line terminator is interpreted to be "the empty code unit sequence". case 13 /* carriageReturn */: if (pos < end && charCodeUnchecked(pos) === 10 /* lineFeed */) { pos++; } + // falls through case 10 /* lineFeed */: case 8232 /* lineSeparator */: case 8233 /* paragraphSeparator */: @@ -12905,6 +12929,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan tokenFlags |= 256 /* OctalSpecifier */; return token = checkBigIntSuffix(); } + // falls through case 49 /* _1 */: case 50 /* _2 */: case 51 /* _3 */: @@ -13424,6 +13449,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan break; } } + // falls through case 42 /* asterisk */: case 43 /* plus */: case 63 /* question */: @@ -13454,6 +13480,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan if (isInGroup) { return; } + // falls through case 93 /* closeBracket */: case 125 /* closeBrace */: if (anyUnicodeModeOrNonAnnexB || ch === 41 /* closeParen */) { @@ -13516,6 +13543,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan error2(Diagnostics.q_is_only_available_inside_character_class, pos - 2, 2); break; } + // falls through default: Debug.assert(scanCharacterClassEscape() || scanDecimalEscape() || scanCharacterEscape( /*atomEscape*/ @@ -13653,6 +13681,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan let start2 = pos; let operand; switch (text.slice(pos, pos + 2)) { + // TODO: don't use slice case "--": case "&&": error2(Diagnostics.Expected_a_class_set_operand); @@ -13758,6 +13787,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } start2 = pos; switch (text.slice(pos, pos + 2)) { + // TODO: don't use slice case "--": case "&&": error2(Diagnostics.Operators_must_not_be_mixed_within_a_character_class_Wrap_it_in_a_nested_class_instead, pos, 2); @@ -13855,6 +13885,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } } pos--; + // falls through default: return scanClassSetCharacter(); } @@ -14001,6 +14032,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan return true; case 80 /* P */: isCharacterComplement = true; + // falls through case 112 /* p */: pos++; if (charCodeChecked(pos) === 123 /* openBrace */) { @@ -14308,6 +14340,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan if (charCodeUnchecked(pos) === 10 /* lineFeed */) { pos++; } + // falls through case 10 /* lineFeed */: tokenFlags |= 1 /* PrecedingLineBreak */; return token = 4 /* NewLineTrivia */; @@ -14512,28 +14545,33 @@ function isExternalModuleNameRelative(moduleName) { function sortAndDeduplicateDiagnostics(diagnostics) { return sortAndDeduplicate(diagnostics, compareDiagnostics, diagnosticsEqualityComparer); } +var targetToLibMap = /* @__PURE__ */ new Map([ + [99 /* ESNext */, "lib.esnext.full.d.ts"], + [10 /* ES2023 */, "lib.es2023.full.d.ts"], + [9 /* ES2022 */, "lib.es2022.full.d.ts"], + [8 /* ES2021 */, "lib.es2021.full.d.ts"], + [7 /* ES2020 */, "lib.es2020.full.d.ts"], + [6 /* ES2019 */, "lib.es2019.full.d.ts"], + [5 /* ES2018 */, "lib.es2018.full.d.ts"], + [4 /* ES2017 */, "lib.es2017.full.d.ts"], + [3 /* ES2016 */, "lib.es2016.full.d.ts"], + [2 /* ES2015 */, "lib.es6.d.ts"] + // We don't use lib.es2015.full.d.ts due to breaking change. +]); function getDefaultLibFileName(options) { - switch (getEmitScriptTarget(options)) { + const target = getEmitScriptTarget(options); + switch (target) { case 99 /* ESNext */: - return "lib.esnext.full.d.ts"; case 10 /* ES2023 */: - return "lib.es2023.full.d.ts"; case 9 /* ES2022 */: - return "lib.es2022.full.d.ts"; case 8 /* ES2021 */: - return "lib.es2021.full.d.ts"; case 7 /* ES2020 */: - return "lib.es2020.full.d.ts"; case 6 /* ES2019 */: - return "lib.es2019.full.d.ts"; case 5 /* ES2018 */: - return "lib.es2018.full.d.ts"; case 4 /* ES2017 */: - return "lib.es2017.full.d.ts"; case 3 /* ES2016 */: - return "lib.es2016.full.d.ts"; case 2 /* ES2015 */: - return "lib.es6.d.ts"; + return targetToLibMap.get(target); default: return "lib.d.ts"; } @@ -15326,6 +15364,9 @@ function isTypeOnlyExportDeclaration(node) { function isTypeOnlyImportOrExportDeclaration(node) { return isTypeOnlyImportDeclaration(node) || isTypeOnlyExportDeclaration(node); } +function isPartOfTypeOnlyImportOrExportDeclaration(node) { + return findAncestor(node, isTypeOnlyImportOrExportDeclaration) !== void 0; +} function isStringTextContainingNode(node) { return node.kind === 11 /* StringLiteral */ || isTemplateLiteralKind(node.kind); } @@ -15474,7 +15515,7 @@ function isModifierLike(node) { } function isTypeElement(node) { const kind = node.kind; - return kind === 180 /* ConstructSignature */ || kind === 179 /* CallSignature */ || kind === 171 /* PropertySignature */ || kind === 173 /* MethodSignature */ || kind === 181 /* IndexSignature */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */; + return kind === 180 /* ConstructSignature */ || kind === 179 /* CallSignature */ || kind === 171 /* PropertySignature */ || kind === 173 /* MethodSignature */ || kind === 181 /* IndexSignature */ || kind === 177 /* GetAccessor */ || kind === 178 /* SetAccessor */ || kind === 354 /* NotEmittedTypeElement */; } function isClassOrTypeElement(node) { return isTypeElement(node) || isClassElement(node); @@ -15536,7 +15577,9 @@ function isObjectBindingOrAssignmentElement(node) { switch (node.kind) { case 208 /* BindingElement */: case 303 /* PropertyAssignment */: + // AssignmentProperty case 304 /* ShorthandPropertyAssignment */: + // AssignmentProperty case 305 /* SpreadAssignment */: return true; } @@ -15554,11 +15597,17 @@ function isArrayBindingOrAssignmentElement(node) { switch (node.kind) { case 208 /* BindingElement */: case 232 /* OmittedExpression */: + // Elision case 230 /* SpreadElement */: + // AssignmentRestElement case 209 /* ArrayLiteralExpression */: + // ArrayAssignmentPattern case 210 /* ObjectLiteralExpression */: + // ObjectAssignmentPattern case 80 /* Identifier */: + // DestructuringAssignmentTarget case 211 /* PropertyAccessExpression */: + // DestructuringAssignmentTarget case 212 /* ElementAccessExpression */: return true; } @@ -15581,13 +15630,16 @@ function isCallLikeOrFunctionLikeExpression(node) { } function isCallLikeExpression(node) { switch (node.kind) { - case 286 /* JsxOpeningElement */: - case 285 /* JsxSelfClosingElement */: case 213 /* CallExpression */: case 214 /* NewExpression */: case 215 /* TaggedTemplateExpression */: case 170 /* Decorator */: + case 286 /* JsxOpeningElement */: + case 285 /* JsxSelfClosingElement */: + case 289 /* JsxOpeningFragment */: return true; + case 226 /* BinaryExpression */: + return node.operatorToken.kind === 104 /* InstanceOfKeyword */; default: return false; } @@ -15619,6 +15671,7 @@ function isLeftHandSideExpressionKind(kind) { case 218 /* FunctionExpression */: case 80 /* Identifier */: case 81 /* PrivateIdentifier */: + // technically this is only an Expression if it's in a `#field in expr` BinaryExpression case 14 /* RegularExpressionLiteral */: case 9 /* NumericLiteral */: case 10 /* BigIntLiteral */: @@ -15634,6 +15687,7 @@ function isLeftHandSideExpressionKind(kind) { case 233 /* ExpressionWithTypeArguments */: case 236 /* MetaProperty */: case 102 /* ImportKeyword */: + // technically this is only an Expression if it's in a CallExpression case 282 /* MissingDeclaration */: return true; default: @@ -15690,8 +15744,8 @@ function isExpressionKind(kind) { case 230 /* SpreadElement */: case 234 /* AsExpression */: case 232 /* OmittedExpression */: - case 355 /* CommaListExpression */: - case 354 /* PartiallyEmittedExpression */: + case 356 /* CommaListExpression */: + case 355 /* PartiallyEmittedExpression */: case 238 /* SatisfiesExpression */: return true; default: @@ -15928,6 +15982,10 @@ function isJsxOpeningLikeElement(node) { const kind = node.kind; return kind === 286 /* JsxOpeningElement */ || kind === 285 /* JsxSelfClosingElement */; } +function isJsxCallLike(node) { + const kind = node.kind; + return kind === 286 /* JsxOpeningElement */ || kind === 285 /* JsxSelfClosingElement */ || kind === 289 /* JsxOpeningFragment */; +} function isCaseOrDefaultClause(node) { const kind = node.kind; return kind === 296 /* CaseClause */ || kind === 297 /* DefaultClause */; @@ -16568,11 +16626,45 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( AsyncIterator: new Map(Object.entries({ es2015: emptyArray })), + ArrayBuffer: new Map(Object.entries({ + es2024: [ + "maxByteLength", + "resizable", + "resize", + "detached", + "transfer", + "transferToFixedLength" + ] + })), Atomics: new Map(Object.entries({ - es2017: emptyArray + es2017: [ + "add", + "and", + "compareExchange", + "exchange", + "isLockFree", + "load", + "or", + "store", + "sub", + "wait", + "notify", + "xor" + ], + es2024: [ + "waitAsync" + ] })), SharedArrayBuffer: new Map(Object.entries({ - es2017: emptyArray + es2017: [ + "byteLength", + "slice" + ], + es2024: [ + "growable", + "maxByteLength", + "grow" + ] })), AsyncIterable: new Map(Object.entries({ es2018: emptyArray @@ -16594,6 +16686,9 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2018: [ "dotAll" + ], + es2024: [ + "unicodeSets" ] })), Reflect: new Map(Object.entries({ @@ -16640,6 +16735,9 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2022: [ "hasOwn" + ], + es2024: [ + "groupBy" ] })), NumberConstructor: new Map(Object.entries({ @@ -16680,11 +16778,25 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( "values" ] })), + MapConstructor: new Map(Object.entries({ + es2024: [ + "groupBy" + ] + })), Set: new Map(Object.entries({ es2015: [ "entries", "keys", "values" + ], + esnext: [ + "union", + "intersection", + "difference", + "symmetricDifference", + "isSubsetOf", + "isSupersetOf", + "isDisjointFrom" ] })), PromiseConstructor: new Map(Object.entries({ @@ -16699,6 +16811,9 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2021: [ "any" + ], + es2024: [ + "withResolvers" ] })), Symbol: new Map(Object.entries({ @@ -16765,7 +16880,7 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( es2022: [ "at" ], - esnext: [ + es2024: [ "isWellFormed", "toWellFormed" ] @@ -16810,6 +16925,11 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( SymbolConstructor: new Map(Object.entries({ es2020: [ "matchAll" + ], + esnext: [ + "metadata", + "dispose", + "asyncDispose" ] })), DataView: new Map(Object.entries({ @@ -17430,6 +17550,8 @@ function getErrorSpanForNode(sourceFile, node) { } return getSpanOfTokenAtPosition(sourceFile, pos2); } + // This list is a work in progress. Add missing node kinds to improve their error + // spans. case 260 /* VariableDeclaration */: case 208 /* BindingElement */: case 263 /* ClassDeclaration */: @@ -17601,6 +17723,8 @@ function isPartOfTypeNode(node) { return isPartOfTypeExpressionWithTypeArguments(node); case 168 /* TypeParameter */: return node.parent.kind === 200 /* MappedType */ || node.parent.kind === 195 /* InferType */; + // Identifiers and qualified names may be type nodes, depending on their context. Climb + // above them to find the lowest container case 80 /* Identifier */: if (node.parent.kind === 166 /* QualifiedName */ && node.parent.right === node) { node = node.parent; @@ -17608,6 +17732,7 @@ function isPartOfTypeNode(node) { node = node.parent; } Debug.assert(node.kind === 80 /* Identifier */ || node.kind === 166 /* QualifiedName */ || node.kind === 211 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'."); + // falls through case 166 /* QualifiedName */: case 211 /* PropertyAccessExpression */: case 110 /* ThisKeyword */: { @@ -17749,9 +17874,6 @@ function isVariableLike(node) { } return false; } -function isVariableLikeOrAccessor(node) { - return isVariableLike(node) || isAccessor(node); -} function isVariableDeclarationInVariableStatement(node) { return node.parent.kind === 261 /* VariableDeclarationList */ && node.parent.parent.kind === 243 /* VariableStatement */; } @@ -17876,6 +17998,7 @@ function getThisContainer(node, includeArrowFunctions, includeClassComputedPrope if (!includeArrowFunctions) { continue; } + // falls through case 262 /* FunctionDeclaration */: case 218 /* FunctionExpression */: case 267 /* ModuleDeclaration */: @@ -17898,6 +18021,8 @@ function getThisContainer(node, includeArrowFunctions, includeClassComputedPrope } function isThisContainerOrFunctionBlock(node) { switch (node.kind) { + // Arrow functions use the same scope, but may do so in a "delayed" manner + // For example, `const getThis = () => this` may be before a super() call in a derived constructor case 219 /* ArrowFunction */: case 262 /* FunctionDeclaration */: case 218 /* FunctionExpression */: @@ -17964,6 +18089,7 @@ function getSuperContainer(node, stopOnFunctions) { if (!stopOnFunctions) { continue; } + // falls through case 172 /* PropertyDeclaration */: case 171 /* PropertySignature */: case 174 /* MethodDeclaration */: @@ -18017,6 +18143,7 @@ function getEntityNameFromTypeNode(node) { return node.typeName; case 233 /* ExpressionWithTypeArguments */: return isEntityNameExpression(node.expression) ? node.expression : void 0; + // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. case 80 /* Identifier */: case 166 /* QualifiedName */: return node; @@ -18032,6 +18159,8 @@ function getInvokedExpression(node) { return node.tagName; case 226 /* BinaryExpression */: return node.right; + case 289 /* JsxOpeningFragment */: + return node; default: return node.expression; } @@ -18181,6 +18310,7 @@ function isExpressionNode(node) { if (node.parent.kind === 186 /* TypeQuery */ || isJSDocLinkLike(node.parent) || isJSDocNameReference(node.parent) || isJSDocMemberName(node.parent) || isJSXTagName(node)) { return true; } + // falls through case 9 /* NumericLiteral */: case 10 /* BigIntLiteral */: case 11 /* StringLiteral */: @@ -18635,12 +18765,17 @@ function tryGetImportFromModuleSpecifier(node) { false ) ? node.parent : void 0; case 201 /* LiteralType */: - Debug.assert(isStringLiteral(node)); + if (!isStringLiteral(node)) { + break; + } return tryCast(node.parent.parent, isImportTypeNode); default: return void 0; } } +function shouldRewriteModuleSpecifier(specifier, compilerOptions) { + return !!compilerOptions.rewriteRelativeImportExtensions && pathIsRelative(specifier) && !isDeclarationFileName(specifier) && hasTSFileExtension(specifier); +} function getExternalModuleName(node) { switch (node.kind) { case 272 /* ImportDeclaration */: @@ -18685,17 +18820,15 @@ function forEachImportClauseDeclaration(node, action) { } } function hasQuestionToken(node) { - if (node) { - switch (node.kind) { - case 169 /* Parameter */: - case 174 /* MethodDeclaration */: - case 173 /* MethodSignature */: - case 304 /* ShorthandPropertyAssignment */: - case 303 /* PropertyAssignment */: - case 172 /* PropertyDeclaration */: - case 171 /* PropertySignature */: - return node.questionToken !== void 0; - } + switch (node.kind) { + case 169 /* Parameter */: + case 174 /* MethodDeclaration */: + case 173 /* MethodSignature */: + case 304 /* ShorthandPropertyAssignment */: + case 303 /* PropertyAssignment */: + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + return node.questionToken !== void 0; } return false; } @@ -19095,6 +19228,7 @@ function getDeclarationFromName(name) { case 15 /* NoSubstitutionTemplateLiteral */: case 9 /* NumericLiteral */: if (isComputedPropertyName(parent2)) return parent2.parent; + // falls through case 80 /* Identifier */: if (isDeclaration(parent2)) { return parent2.name === name ? parent2 : void 0; @@ -19265,6 +19399,7 @@ function getFunctionFlags(node) { if (node.asteriskToken) { flags |= 1 /* Generator */; } + // falls through case 219 /* ArrowFunction */: if (hasSyntacticModifier(node, 1024 /* Async */)) { flags |= 2 /* Async */; @@ -19535,7 +19670,7 @@ var OperatorPrecedence = /* @__PURE__ */ ((OperatorPrecedence2) => { })(OperatorPrecedence || {}); function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { switch (nodeKind) { - case 355 /* CommaListExpression */: + case 356 /* CommaListExpression */: return 0 /* Comma */; case 230 /* SpreadElement */: return 1 /* Spread */; @@ -19567,6 +19702,7 @@ function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) { default: return getBinaryOperatorPrecedence(operatorKind); } + // TODO: Should prefix `++` and `--` be moved to the `Update` precedence? case 216 /* TypeAssertionExpression */: case 235 /* NonNullExpression */: case 224 /* PrefixUnaryExpression */: @@ -19749,7 +19885,7 @@ function hasInvalidEscape(template) { } var doubleQuoteEscapedCharsRegExp = /[\\"\u0000-\u001f\u2028\u2029\u0085]/g; var singleQuoteEscapedCharsRegExp = /[\\'\u0000-\u001f\u2028\u2029\u0085]/g; -var backtickQuoteEscapedCharsRegExp = /\r\n|[\\`\u0000-\u001f\u2028\u2029\u0085]/g; +var backtickQuoteEscapedCharsRegExp = /\r\n|[\\`\u0000-\u0009\u000b-\u001f\u2028\u2029\u0085]/g; var escapedCharsMap = new Map(Object.entries({ " ": "\\t", "\v": "\\v", @@ -20069,6 +20205,12 @@ function getDeclarationEmitExtensionForPath(path) { function getPossibleOriginalInputExtensionForExtension(path) { return fileExtensionIsOneOf(path, [".d.mts" /* Dmts */, ".mjs" /* Mjs */, ".mts" /* Mts */]) ? [".mts" /* Mts */, ".mjs" /* Mjs */] : fileExtensionIsOneOf(path, [".d.cts" /* Dcts */, ".cjs" /* Cjs */, ".cts" /* Cts */]) ? [".cts" /* Cts */, ".cjs" /* Cjs */] : fileExtensionIsOneOf(path, [`.d.json.ts`]) ? [".json" /* Json */] : [".tsx" /* Tsx */, ".ts" /* Ts */, ".jsx" /* Jsx */, ".js" /* Js */]; } +function getPossibleOriginalInputPathWithoutChangingExt(filePath, ignoreCase, outputDir, getCommonSourceDirectory2) { + return outputDir ? resolvePath( + getCommonSourceDirectory2(), + getRelativePathFromDirectory(outputDir, filePath, ignoreCase) + ) : filePath; +} function getPathsBasePath(options, host) { var _a; if (!options.paths) return void 0; @@ -20942,6 +21084,12 @@ function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sour ); return getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos)); } +function rangeContainsRange(r1, r2) { + return startEndContainsRange(r1.pos, r1.end, r2); +} +function startEndContainsRange(start, end, range) { + return start <= range.pos && end >= range.end; +} function getPreviousNonWhitespacePosition(pos, stopPos = 0, sourceFile) { while (pos-- > stopPos) { if (!isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) { @@ -21026,6 +21174,9 @@ function accessKind(node) { return node === parent2.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent2.parent); case 209 /* ArrayLiteralExpression */: return accessKind(parent2); + case 249 /* ForInStatement */: + case 250 /* ForOfStatement */: + return node === parent2.initializer ? 1 /* Write */ : 0 /* Read */; default: return 0 /* Read */; } @@ -21118,11 +21269,11 @@ function getLastChild(node) { }); return lastChild; } -function addToSeen(seen, key, value = true) { +function addToSeen(seen, key) { if (seen.has(key)) { return false; } - seen.set(key, value); + seen.add(key); return true; } function isObjectTypeDeclaration(node) { @@ -21198,11 +21349,12 @@ function getLeftmostExpression(node, stopAtCallExpressions) { if (stopAtCallExpressions) { return node; } + // falls through case 234 /* AsExpression */: case 212 /* ElementAccessExpression */: case 211 /* PropertyAccessExpression */: case 235 /* NonNullExpression */: - case 354 /* PartiallyEmittedExpression */: + case 355 /* PartiallyEmittedExpression */: case 238 /* SatisfiesExpression */: node = node.expression; continue; @@ -21602,7 +21754,13 @@ function importSyntaxAffectsModuleResolution(options) { function createComputedCompilerOptions(options) { return options; } -var computedOptions = createComputedCompilerOptions({ +var _computedOptions = createComputedCompilerOptions({ + allowImportingTsExtensions: { + dependencies: ["rewriteRelativeImportExtensions"], + computeValue: (compilerOptions) => { + return !!(compilerOptions.allowImportingTsExtensions || compilerOptions.rewriteRelativeImportExtensions); + } + }, target: { dependencies: ["module"], computeValue: (compilerOptions) => { @@ -21613,7 +21771,7 @@ var computedOptions = createComputedCompilerOptions({ module: { dependencies: ["target"], computeValue: (compilerOptions) => { - return typeof compilerOptions.module === "number" ? compilerOptions.module : computedOptions.target.computeValue(compilerOptions) >= 2 /* ES2015 */ ? 5 /* ES2015 */ : 1 /* CommonJS */; + return typeof compilerOptions.module === "number" ? compilerOptions.module : _computedOptions.target.computeValue(compilerOptions) >= 2 /* ES2015 */ ? 5 /* ES2015 */ : 1 /* CommonJS */; } }, moduleResolution: { @@ -21621,7 +21779,7 @@ var computedOptions = createComputedCompilerOptions({ computeValue: (compilerOptions) => { let moduleResolution = compilerOptions.moduleResolution; if (moduleResolution === void 0) { - switch (computedOptions.module.computeValue(compilerOptions)) { + switch (_computedOptions.module.computeValue(compilerOptions)) { case 1 /* CommonJS */: moduleResolution = 2 /* Node10 */; break; @@ -21645,7 +21803,7 @@ var computedOptions = createComputedCompilerOptions({ moduleDetection: { dependencies: ["module", "target"], computeValue: (compilerOptions) => { - return compilerOptions.moduleDetection || (computedOptions.module.computeValue(compilerOptions) === 100 /* Node16 */ || computedOptions.module.computeValue(compilerOptions) === 199 /* NodeNext */ ? 3 /* Force */ : 2 /* Auto */); + return compilerOptions.moduleDetection || (_computedOptions.module.computeValue(compilerOptions) === 100 /* Node16 */ || _computedOptions.module.computeValue(compilerOptions) === 199 /* NodeNext */ ? 3 /* Force */ : 2 /* Auto */); } }, isolatedModules: { @@ -21660,7 +21818,7 @@ var computedOptions = createComputedCompilerOptions({ if (compilerOptions.esModuleInterop !== void 0) { return compilerOptions.esModuleInterop; } - switch (computedOptions.module.computeValue(compilerOptions)) { + switch (_computedOptions.module.computeValue(compilerOptions)) { case 100 /* Node16 */: case 199 /* NodeNext */: case 200 /* Preserve */: @@ -21675,13 +21833,13 @@ var computedOptions = createComputedCompilerOptions({ if (compilerOptions.allowSyntheticDefaultImports !== void 0) { return compilerOptions.allowSyntheticDefaultImports; } - return computedOptions.esModuleInterop.computeValue(compilerOptions) || computedOptions.module.computeValue(compilerOptions) === 4 /* System */ || computedOptions.moduleResolution.computeValue(compilerOptions) === 100 /* Bundler */; + return _computedOptions.esModuleInterop.computeValue(compilerOptions) || _computedOptions.module.computeValue(compilerOptions) === 4 /* System */ || _computedOptions.moduleResolution.computeValue(compilerOptions) === 100 /* Bundler */; } }, resolvePackageJsonExports: { dependencies: ["moduleResolution"], computeValue: (compilerOptions) => { - const moduleResolution = computedOptions.moduleResolution.computeValue(compilerOptions); + const moduleResolution = _computedOptions.moduleResolution.computeValue(compilerOptions); if (!moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) { return false; } @@ -21700,7 +21858,7 @@ var computedOptions = createComputedCompilerOptions({ resolvePackageJsonImports: { dependencies: ["moduleResolution", "resolvePackageJsonExports"], computeValue: (compilerOptions) => { - const moduleResolution = computedOptions.moduleResolution.computeValue(compilerOptions); + const moduleResolution = _computedOptions.moduleResolution.computeValue(compilerOptions); if (!moduleResolutionSupportsPackageJsonExportsAndImports(moduleResolution)) { return false; } @@ -21722,7 +21880,7 @@ var computedOptions = createComputedCompilerOptions({ if (compilerOptions.resolveJsonModule !== void 0) { return compilerOptions.resolveJsonModule; } - return computedOptions.moduleResolution.computeValue(compilerOptions) === 100 /* Bundler */; + return _computedOptions.moduleResolution.computeValue(compilerOptions) === 100 /* Bundler */; } }, declaration: { @@ -21734,7 +21892,7 @@ var computedOptions = createComputedCompilerOptions({ preserveConstEnums: { dependencies: ["isolatedModules", "verbatimModuleSyntax"], computeValue: (compilerOptions) => { - return !!(compilerOptions.preserveConstEnums || computedOptions.isolatedModules.computeValue(compilerOptions)); + return !!(compilerOptions.preserveConstEnums || _computedOptions.isolatedModules.computeValue(compilerOptions)); } }, incremental: { @@ -21746,7 +21904,7 @@ var computedOptions = createComputedCompilerOptions({ declarationMap: { dependencies: ["declaration", "composite"], computeValue: (compilerOptions) => { - return !!(compilerOptions.declarationMap && computedOptions.declaration.computeValue(compilerOptions)); + return !!(compilerOptions.declarationMap && _computedOptions.declaration.computeValue(compilerOptions)); } }, allowJs: { @@ -21758,7 +21916,7 @@ var computedOptions = createComputedCompilerOptions({ useDefineForClassFields: { dependencies: ["target", "module"], computeValue: (compilerOptions) => { - return compilerOptions.useDefineForClassFields === void 0 ? computedOptions.target.computeValue(compilerOptions) >= 9 /* ES2022 */ : compilerOptions.useDefineForClassFields; + return compilerOptions.useDefineForClassFields === void 0 ? _computedOptions.target.computeValue(compilerOptions) >= 9 /* ES2022 */ : compilerOptions.useDefineForClassFields; } }, noImplicitAny: { @@ -21816,22 +21974,24 @@ var computedOptions = createComputedCompilerOptions({ } } }); -var getEmitScriptTarget = computedOptions.target.computeValue; -var getEmitModuleKind = computedOptions.module.computeValue; -var getEmitModuleResolutionKind = computedOptions.moduleResolution.computeValue; -var getEmitModuleDetectionKind = computedOptions.moduleDetection.computeValue; -var getIsolatedModules = computedOptions.isolatedModules.computeValue; -var getESModuleInterop = computedOptions.esModuleInterop.computeValue; -var getAllowSyntheticDefaultImports = computedOptions.allowSyntheticDefaultImports.computeValue; -var getResolvePackageJsonExports = computedOptions.resolvePackageJsonExports.computeValue; -var getResolvePackageJsonImports = computedOptions.resolvePackageJsonImports.computeValue; -var getResolveJsonModule = computedOptions.resolveJsonModule.computeValue; -var getEmitDeclarations = computedOptions.declaration.computeValue; -var shouldPreserveConstEnums = computedOptions.preserveConstEnums.computeValue; -var isIncrementalCompilation = computedOptions.incremental.computeValue; -var getAreDeclarationMapsEnabled = computedOptions.declarationMap.computeValue; -var getAllowJSCompilerOption = computedOptions.allowJs.computeValue; -var getUseDefineForClassFields = computedOptions.useDefineForClassFields.computeValue; +var computedOptions = _computedOptions; +var getAllowImportingTsExtensions = _computedOptions.allowImportingTsExtensions.computeValue; +var getEmitScriptTarget = _computedOptions.target.computeValue; +var getEmitModuleKind = _computedOptions.module.computeValue; +var getEmitModuleResolutionKind = _computedOptions.moduleResolution.computeValue; +var getEmitModuleDetectionKind = _computedOptions.moduleDetection.computeValue; +var getIsolatedModules = _computedOptions.isolatedModules.computeValue; +var getESModuleInterop = _computedOptions.esModuleInterop.computeValue; +var getAllowSyntheticDefaultImports = _computedOptions.allowSyntheticDefaultImports.computeValue; +var getResolvePackageJsonExports = _computedOptions.resolvePackageJsonExports.computeValue; +var getResolvePackageJsonImports = _computedOptions.resolvePackageJsonImports.computeValue; +var getResolveJsonModule = _computedOptions.resolveJsonModule.computeValue; +var getEmitDeclarations = _computedOptions.declaration.computeValue; +var shouldPreserveConstEnums = _computedOptions.preserveConstEnums.computeValue; +var isIncrementalCompilation = _computedOptions.incremental.computeValue; +var getAreDeclarationMapsEnabled = _computedOptions.declarationMap.computeValue; +var getAllowJSCompilerOption = _computedOptions.allowJs.computeValue; +var getUseDefineForClassFields = _computedOptions.useDefineForClassFields.computeValue; function emitModuleKindIsNonNodeESM(moduleKind) { return moduleKind >= 5 /* ES2015 */ && moduleKind <= 99 /* ESNext */; } @@ -22376,8 +22536,33 @@ function tryParsePattern(pattern) { suffix: pattern.substr(indexOfStar + 1) }; } +var parsedPatternsCache = /* @__PURE__ */ new WeakMap(); function tryParsePatterns(paths) { - return mapDefined(getOwnKeys(paths), (path) => tryParsePattern(path)); + let result = parsedPatternsCache.get(paths); + if (result !== void 0) { + return result; + } + let matchableStringSet; + let patterns; + const pathList = getOwnKeys(paths); + for (const path of pathList) { + const patternOrStr = tryParsePattern(path); + if (patternOrStr === void 0) { + continue; + } else if (typeof patternOrStr === "string") { + (matchableStringSet ?? (matchableStringSet = /* @__PURE__ */ new Set())).add(patternOrStr); + } else { + (patterns ?? (patterns = [])).push(patternOrStr); + } + } + parsedPatternsCache.set( + paths, + result = { + matchableStringSet, + patterns + } + ); + return result; } function positionIsSynthesized(pos) { return !(pos >= 0); @@ -22405,15 +22590,13 @@ var emptyFileSystemEntries = { files: emptyArray, directories: emptyArray }; -function matchPatternOrExact(patternOrStrings, candidate) { - const patterns = []; - for (const patternOrString of patternOrStrings) { - if (patternOrString === candidate) { - return candidate; - } - if (!isString(patternOrString)) { - patterns.push(patternOrString); - } +function matchPatternOrExact(parsedPatterns, candidate) { + const { matchableStringSet, patterns } = parsedPatterns; + if (matchableStringSet == null ? void 0 : matchableStringSet.has(candidate)) { + return candidate; + } + if (patterns === void 0 || patterns.length === 0) { + return void 0; } return findBestPatternMatch(patterns, (_) => _, candidate); } @@ -22490,6 +22673,7 @@ function isJsonEqual(a, b) { function parsePseudoBigInt(stringValue) { let log2Base; switch (stringValue.charCodeAt(1)) { + // "x" in "0x123" case 98 /* b */: case 66 /* B */: log2Base = 1; @@ -22737,7 +22921,7 @@ function getContainingNodeArray(node) { return parent2.types; case 189 /* TupleType */: case 209 /* ArrayLiteralExpression */: - case 355 /* CommaListExpression */: + case 356 /* CommaListExpression */: case 275 /* NamedImports */: case 279 /* NamedExports */: return parent2.elements; @@ -23276,6 +23460,7 @@ function createNameResolver({ switch (location.kind) { case 307 /* SourceFile */: if (!isExternalOrCommonJsModule(location)) break; + // falls through case 267 /* ModuleDeclaration */: const moduleExports = ((_a = getSymbolOfDeclaration(location)) == null ? void 0 : _a.exports) || emptySymbols; if (location.kind === 307 /* SourceFile */ || isModuleDeclaration(location) && location.flags & 33554432 /* Ambient */ && !isGlobalScopeAugmentation(location)) { @@ -23359,6 +23544,14 @@ function createNameResolver({ } } break; + // It is not legal to reference a class's own type parameters from a computed property name that + // belongs to the class. For example: + // + // function foo() { return '' } + // class C { // <-- Class's own type parameter T + // [foo()]() { } // <-- Reference to T from class's own computed property + // } + // case 167 /* ComputedPropertyName */: grandparent = location.parent.parent; if (isClassLike(grandparent) || grandparent.kind === 264 /* InterfaceDeclaration */) { @@ -23374,6 +23567,7 @@ function createNameResolver({ if (getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */) { break; } + // falls through case 174 /* MethodDeclaration */: case 176 /* Constructor */: case 177 /* GetAccessor */: @@ -23616,6 +23810,9 @@ function hasInferredType(node) { case 260 /* VariableDeclaration */: case 277 /* ExportAssignment */: case 303 /* PropertyAssignment */: + case 304 /* ShorthandPropertyAssignment */: + case 341 /* JSDocParameterTag */: + case 348 /* JSDocPropertyTag */: return true; default: assertType(node); @@ -23626,6 +23823,118 @@ function isSideEffectImport(node) { const ancestor = findAncestor(node, isImportDeclaration); return !!ancestor && !ancestor.importClause; } +var unprefixedNodeCoreModulesList = [ + "assert", + "assert/strict", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "diagnostics_channel", + "dns", + "dns/promises", + "domain", + "events", + "fs", + "fs/promises", + "http", + "http2", + "https", + "inspector", + "inspector/promises", + "module", + "net", + "os", + "path", + "path/posix", + "path/win32", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "readline/promises", + "repl", + "stream", + "stream/consumers", + "stream/promises", + "stream/web", + "string_decoder", + "sys", + "test/mock_loader", + "timers", + "timers/promises", + "tls", + "trace_events", + "tty", + "url", + "util", + "util/types", + "v8", + "vm", + "wasi", + "worker_threads", + "zlib" +]; +var unprefixedNodeCoreModules = new Set(unprefixedNodeCoreModulesList); +var exclusivelyPrefixedNodeCoreModules = /* @__PURE__ */ new Set([ + "node:sea", + "node:sqlite", + "node:test", + "node:test/reporters" +]); +var nodeCoreModules = /* @__PURE__ */ new Set([ + ...unprefixedNodeCoreModulesList, + ...unprefixedNodeCoreModulesList.map((name) => `node:${name}`), + ...exclusivelyPrefixedNodeCoreModules +]); +function forEachDynamicImportOrRequireCall(file, includeTypeSpaceImports, requireStringLiteralLikeArgument, cb) { + const isJavaScriptFile = isInJSFile(file); + const r = /import|require/g; + while (r.exec(file.text) !== null) { + const node = getNodeAtPosition( + file, + r.lastIndex, + /*includeJSDoc*/ + includeTypeSpaceImports + ); + if (isJavaScriptFile && isRequireCall(node, requireStringLiteralLikeArgument)) { + cb(node, node.arguments[0]); + } else if (isImportCall(node) && node.arguments.length >= 1 && (!requireStringLiteralLikeArgument || isStringLiteralLike(node.arguments[0]))) { + cb(node, node.arguments[0]); + } else if (includeTypeSpaceImports && isLiteralImportTypeNode(node)) { + cb(node, node.argument.literal); + } else if (includeTypeSpaceImports && isJSDocImportTag(node)) { + const moduleNameExpr = getExternalModuleName(node); + if (moduleNameExpr && isStringLiteral(moduleNameExpr) && moduleNameExpr.text) { + cb(node, moduleNameExpr); + } + } + } +} +function getNodeAtPosition(sourceFile, position, includeJSDoc) { + const isJavaScriptFile = isInJSFile(sourceFile); + let current = sourceFile; + const getContainingChild = (child) => { + if (child.pos <= position && (position < child.end || position === child.end && child.kind === 1 /* EndOfFileToken */)) { + return child; + } + }; + while (true) { + const child = isJavaScriptFile && includeJSDoc && hasJSDocNodes(current) && forEach(current.jsDoc, getContainingChild) || forEachChild(current, getContainingChild); + if (!child) { + return current; + } + current = child; + } +} +function isNewScopeNode(node) { + return isFunctionLike(node) || isJSDocSignature(node) || isMappedTypeNode(node); +} // src/compiler/factory/baseNodeFactory.ts function createBaseNodeFactory() { @@ -23949,6 +24258,7 @@ function createParenthesizerRules(factory2) { function parenthesizeConstituentTypeOfUnionType(type) { switch (type.kind) { case 192 /* UnionType */: + // Not strictly necessary, but a union containing a union should have been flattened case 193 /* IntersectionType */: return factory2.createParenthesizedType(type); } @@ -24730,6 +25040,7 @@ function createNodeFactory(flags, baseFactory2) { createSyntheticExpression, createSyntaxList: createSyntaxList3, createNotEmittedStatement, + createNotEmittedTypeElement, createPartiallyEmittedExpression, updatePartiallyEmittedExpression, createCommaListExpression, @@ -27756,7 +28067,7 @@ function createNodeFactory(flags, baseFactory2) { return node; } function createPartiallyEmittedExpression(expression, original) { - const node = createBaseNode(354 /* PartiallyEmittedExpression */); + const node = createBaseNode(355 /* PartiallyEmittedExpression */); node.expression = expression; node.original = original; node.transformFlags |= propagateChildFlags(node.expression) | 1 /* ContainsTypeScript */; @@ -27766,6 +28077,9 @@ function createNodeFactory(flags, baseFactory2) { function updatePartiallyEmittedExpression(node, expression) { return node.expression !== expression ? update(createPartiallyEmittedExpression(expression, node.original), node) : node; } + function createNotEmittedTypeElement() { + return createBaseNode(354 /* NotEmittedTypeElement */); + } function flattenCommaElements(node) { if (nodeIsSynthesized(node) && !isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) { if (isCommaListExpression(node)) { @@ -27778,7 +28092,7 @@ function createNodeFactory(flags, baseFactory2) { return node; } function createCommaListExpression(elements) { - const node = createBaseNode(355 /* CommaListExpression */); + const node = createBaseNode(356 /* CommaListExpression */); node.elements = createNodeArray(sameFlatMap(elements, flattenCommaElements)); node.transformFlags |= propagateChildrenFlags(node.elements); return node; @@ -27787,7 +28101,7 @@ function createNodeFactory(flags, baseFactory2) { return node.elements !== elements ? update(createCommaListExpression(elements), node) : node; } function createSyntheticReferenceExpression(expression, thisArg) { - const node = createBaseNode(356 /* SyntheticReferenceExpression */); + const node = createBaseNode(357 /* SyntheticReferenceExpression */); node.expression = expression; node.thisArg = thisArg; node.transformFlags |= propagateChildFlags(node.expression) | propagateChildFlags(node.thisArg); @@ -28034,7 +28348,7 @@ function createNodeFactory(flags, baseFactory2) { return updateNonNullExpression(outerExpression, expression); case 233 /* ExpressionWithTypeArguments */: return updateExpressionWithTypeArguments(outerExpression, expression, outerExpression.typeArguments); - case 354 /* PartiallyEmittedExpression */: + case 355 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression); } } @@ -28579,7 +28893,7 @@ function getTransformFlagsSubtreeExclusions(kind) { case 216 /* TypeAssertionExpression */: case 238 /* SatisfiesExpression */: case 234 /* AsExpression */: - case 354 /* PartiallyEmittedExpression */: + case 355 /* PartiallyEmittedExpression */: case 217 /* ParenthesizedExpression */: case 108 /* SuperKeyword */: return -2147483648 /* OuterExpressionExcludes */; @@ -28952,7 +29266,9 @@ function createEmitHelperFactory(context) { createClassPrivateFieldInHelper, // 'using' helpers createAddDisposableResourceHelper, - createDisposeResourcesHelper + createDisposeResourcesHelper, + // --rewriteRelativeImportExtensions helpers + createRewriteRelativeImportExtensionsHelper }; function getUnscopedHelperName(name) { return setEmitFlags(factory2.createIdentifier(name), 8192 /* HelperName */ | 4 /* AdviseOnEmitNode */); @@ -29441,6 +29757,15 @@ function createEmitHelperFactory(context) { [envBinding] ); } + function createRewriteRelativeImportExtensionsHelper(expression) { + context.requestEmitHelper(rewriteRelativeImportExtensionsHelper); + return factory2.createCallExpression( + getUnscopedHelperName("__rewriteRelativeImportExtension"), + /*typeArguments*/ + void 0, + context.getCompilerOptions().jsx === 1 /* Preserve */ ? [expression, factory2.createTrue()] : [expression] + ); + } } function compareEmitHelpers(x, y) { if (x === y) return 0 /* EqualTo */; @@ -29821,13 +30146,23 @@ var importStarHelper = { dependencies: [createBindingHelper, setModuleDefaultHelper], priority: 2, text: ` - var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - };` + var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; + })();` }; var importDefaultHelper = { name: "typescript:commonjsimportdefault", @@ -29946,6 +30281,20 @@ var disposeResourcesHelper = { return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; });` }; +var rewriteRelativeImportExtensionsHelper = { + name: "typescript:rewriteRelativeImportExtensions", + importName: "__rewriteRelativeImportExtension", + scoped: false, + text: ` + var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) { + if (typeof path === "string" && /^\\.\\.?\\//.test(path)) { + return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); + }); + } + return path; + };` +}; var asyncSuperHelper = { name: "typescript:async-super", scoped: true, @@ -30288,10 +30637,10 @@ function isSyntheticExpression(node) { return node.kind === 237 /* SyntheticExpression */; } function isPartiallyEmittedExpression(node) { - return node.kind === 354 /* PartiallyEmittedExpression */; + return node.kind === 355 /* PartiallyEmittedExpression */; } function isCommaListExpression(node) { - return node.kind === 355 /* CommaListExpression */; + return node.kind === 356 /* CommaListExpression */; } function isTemplateSpan(node) { return node.kind === 239 /* TemplateSpan */; @@ -30447,7 +30796,7 @@ function isNotEmittedStatement(node) { return node.kind === 353 /* NotEmittedStatement */; } function isSyntheticReference(node) { - return node.kind === 356 /* SyntheticReferenceExpression */; + return node.kind === 357 /* SyntheticReferenceExpression */; } function isExternalModuleReference(node) { return node.kind === 283 /* ExternalModuleReference */; @@ -31070,7 +31419,7 @@ function isOuterExpression(node, kinds = 31 /* All */) { return (kinds & 16 /* ExpressionsWithTypeArguments */) !== 0; case 235 /* NonNullExpression */: return (kinds & 4 /* NonNullAssertions */) !== 0; - case 354 /* PartiallyEmittedExpression */: + case 355 /* PartiallyEmittedExpression */: return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0; } return false; @@ -31108,23 +31457,21 @@ function hasRecordedExternalHelpers(sourceFile) { } function createExternalHelpersImportDeclarationIfNeeded(nodeFactory, helperFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault) { if (compilerOptions.importHelpers && isEffectiveExternalModule(sourceFile, compilerOptions)) { - let namedBindings; const moduleKind = getEmitModuleKind(compilerOptions); - if (moduleKind >= 5 /* ES2015 */ && moduleKind <= 99 /* ESNext */ || getImpliedNodeFormatForEmitWorker(sourceFile, compilerOptions) === 99 /* ESNext */) { - const helpers = getEmitHelpers(sourceFile); + const impliedModuleKind = getImpliedNodeFormatForEmitWorker(sourceFile, compilerOptions); + const helpers = getImportedHelpers(sourceFile); + if (moduleKind >= 5 /* ES2015 */ && moduleKind <= 99 /* ESNext */ || impliedModuleKind === 99 /* ESNext */ || impliedModuleKind === void 0 && moduleKind === 200 /* Preserve */) { if (helpers) { const helperNames = []; for (const helper of helpers) { - if (!helper.scoped) { - const importName = helper.importName; - if (importName) { - pushIfUnique(helperNames, importName); - } + const importName = helper.importName; + if (importName) { + pushIfUnique(helperNames, importName); } } if (some(helperNames)) { helperNames.sort(compareStringsCaseSensitive); - namedBindings = nodeFactory.createNamedImports( + const namedBindings = nodeFactory.createNamedImports( map(helperNames, (name) => isFileLevelUniqueName(sourceFile, name) ? nodeFactory.createImportSpecifier( /*isTypeOnly*/ false, @@ -31141,57 +31488,54 @@ function createExternalHelpersImportDeclarationIfNeeded(nodeFactory, helperFacto const parseNode = getOriginalNode(sourceFile, isSourceFile); const emitNode = getOrCreateEmitNode(parseNode); emitNode.externalHelpers = true; + const externalHelpersImportDeclaration = nodeFactory.createImportDeclaration( + /*modifiers*/ + void 0, + nodeFactory.createImportClause( + /*isTypeOnly*/ + false, + /*name*/ + void 0, + namedBindings + ), + nodeFactory.createStringLiteral(externalHelpersModuleNameText), + /*attributes*/ + void 0 + ); + addInternalEmitFlags(externalHelpersImportDeclaration, 2 /* NeverApplyImportHelper */); + return externalHelpersImportDeclaration; } } } else { - const externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(nodeFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar || hasImportDefault); + const externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(nodeFactory, sourceFile, compilerOptions, helpers, hasExportStarsToExportValues, hasImportStar || hasImportDefault); if (externalHelpersModuleName) { - namedBindings = nodeFactory.createNamespaceImport(externalHelpersModuleName); - } - } - if (namedBindings) { - const externalHelpersImportDeclaration = nodeFactory.createImportDeclaration( - /*modifiers*/ - void 0, - nodeFactory.createImportClause( + const externalHelpersImportDeclaration = nodeFactory.createImportEqualsDeclaration( + /*modifiers*/ + void 0, /*isTypeOnly*/ false, - /*name*/ - void 0, - namedBindings - ), - nodeFactory.createStringLiteral(externalHelpersModuleNameText), - /*attributes*/ - void 0 - ); - addInternalEmitFlags(externalHelpersImportDeclaration, 2 /* NeverApplyImportHelper */); - return externalHelpersImportDeclaration; + externalHelpersModuleName, + nodeFactory.createExternalModuleReference(nodeFactory.createStringLiteral(externalHelpersModuleNameText)) + ); + addInternalEmitFlags(externalHelpersImportDeclaration, 2 /* NeverApplyImportHelper */); + return externalHelpersImportDeclaration; + } } } } -function getOrCreateExternalHelpersModuleNameIfNeeded(factory2, node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) { - if (compilerOptions.importHelpers && isEffectiveExternalModule(node, compilerOptions)) { - const externalHelpersModuleName = getExternalHelpersModuleName(node); - if (externalHelpersModuleName) { - return externalHelpersModuleName; - } - let create = (hasExportStarsToExportValues || getESModuleInterop(compilerOptions) && hasImportStarOrImportDefault) && getEmitModuleFormatOfFileWorker(node, compilerOptions) < 4 /* System */; - if (!create) { - const helpers = getEmitHelpers(node); - if (helpers) { - for (const helper of helpers) { - if (!helper.scoped) { - create = true; - break; - } - } - } - } - if (create) { - const parseNode = getOriginalNode(node, isSourceFile); - const emitNode = getOrCreateEmitNode(parseNode); - return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = factory2.createUniqueName(externalHelpersModuleNameText)); - } +function getImportedHelpers(sourceFile) { + return filter(getEmitHelpers(sourceFile), (helper) => !helper.scoped); +} +function getOrCreateExternalHelpersModuleNameIfNeeded(factory2, node, compilerOptions, helpers, hasExportStarsToExportValues, hasImportStarOrImportDefault) { + const externalHelpersModuleName = getExternalHelpersModuleName(node); + if (externalHelpersModuleName) { + return externalHelpersModuleName; + } + const create = some(helpers) || (hasExportStarsToExportValues || getESModuleInterop(compilerOptions) && hasImportStarOrImportDefault) && getEmitModuleFormatOfFileWorker(node, compilerOptions) < 4 /* System */; + if (create) { + const parseNode = getOriginalNode(node, isSourceFile); + const emitNode = getOrCreateEmitNode(parseNode); + return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = factory2.createUniqueName(externalHelpersModuleNameText)); } } function getLocalNameForExternalImport(factory2, node, sourceFile) { @@ -31514,10 +31858,13 @@ var BinaryExpressionState; switch (currentState) { case enter: if (machine.onLeft) return left; + // falls through case left: if (machine.onOperator) return operator; + // falls through case operator: if (machine.onRight) return right; + // falls through case right: return exit; case exit: @@ -32145,7 +32492,7 @@ var forEachChildTable = { [282 /* MissingDeclaration */]: function forEachChildInMissingDeclaration(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.modifiers); }, - [355 /* CommaListExpression */]: function forEachChildInCommaListExpression(node, cbNode, cbNodes) { + [356 /* CommaListExpression */]: function forEachChildInCommaListExpression(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.elements); }, [284 /* JsxElement */]: function forEachChildInJsxElement(node, cbNode, cbNodes) { @@ -32241,7 +32588,7 @@ var forEachChildTable = { [331 /* JSDocDeprecatedTag */]: forEachChildInJSDocTag, [337 /* JSDocOverrideTag */]: forEachChildInJSDocTag, [351 /* JSDocImportTag */]: forEachChildInJSDocImportTag, - [354 /* PartiallyEmittedExpression */]: forEachChildInPartiallyEmittedExpression + [355 /* PartiallyEmittedExpression */]: forEachChildInPartiallyEmittedExpression }; function forEachChildInCallOrConstructSignature(node, cbNode, cbNodes) { return visitNodes(cbNode, cbNodes, node.typeParameters) || visitNodes(cbNode, cbNodes, node.parameters) || visitNode2(cbNode, node.type); @@ -32611,6 +32958,7 @@ var Parser; expression2 = parseLiteralNode(); break; } + // falls through default: expression2 = parseObjectLiteralExpression(); break; @@ -33452,10 +33800,12 @@ var Parser; case 90 /* DefaultKeyword */: return nextTokenCanFollowDefaultKeyword(); case 126 /* StaticKeyword */: + nextToken(); + return canFollowModifier(); case 139 /* GetKeyword */: case 153 /* SetKeyword */: nextToken(); - return canFollowModifier(); + return canFollowGetOrSetKeyword(); default: return nextTokenIsOnSameLineAndCanFollowModifier(); } @@ -33473,6 +33823,9 @@ var Parser; function canFollowModifier() { return token() === 23 /* OpenBracketToken */ || token() === 19 /* OpenBraceToken */ || token() === 42 /* AsteriskToken */ || token() === 26 /* DotDotDotToken */ || isLiteralPropertyName(); } + function canFollowGetOrSetKeyword() { + return token() === 23 /* OpenBracketToken */ || isLiteralPropertyName(); + } function nextTokenCanFollowDefaultKeyword() { nextToken(); return token() === 86 /* ClassKeyword */ || token() === 100 /* FunctionKeyword */ || token() === 120 /* InterfaceKeyword */ || token() === 60 /* AtToken */ || token() === 128 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine) || token() === 134 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine); @@ -33532,6 +33885,7 @@ var Parser; case 25 /* DotToken */: return true; } + // falls through case 11 /* ArgumentExpressions */: return token() === 26 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: @@ -33565,6 +33919,7 @@ var Parser; return true; case 26 /* Count */: return Debug.fail("ParsingContext.Count used as a context"); + // Not a real context, only a marker. default: Debug.assertNever(parsingContext2, "Non-exhaustive case in 'isListElement'."); } @@ -33881,6 +34236,7 @@ var Parser; case 3 /* SwitchClauseStatements */: return parseErrorAtCurrentToken(Diagnostics.Statement_expected); case 18 /* RestProperties */: + // fallthrough case 4 /* TypeMembers */: return parseErrorAtCurrentToken(Diagnostics.Property_or_signature_expected); case 5 /* ClassMembers */: @@ -33928,6 +34284,7 @@ var Parser; return parseErrorAtCurrentToken(Diagnostics.Identifier_expected); case 26 /* Count */: return Debug.fail("ParsingContext.Count used as a context"); + // Not a real context, only a marker. default: Debug.assertNever(context); } @@ -34852,10 +35209,12 @@ var Parser; return tryParse(parseKeywordAndNoDot) || parseTypeReference(); case 67 /* AsteriskEqualsToken */: scanner2.reScanAsteriskEqualsToken(); + // falls through case 42 /* AsteriskToken */: return parseJSDocAllType(); case 61 /* QuestionQuestionToken */: scanner2.reScanQuestionToken(); + // falls through case 58 /* QuestionToken */: return parseJSDocUnknownOrNullableType(); case 100 /* FunctionKeyword */: @@ -35733,6 +36092,7 @@ var Parser; if (isAwaitExpression2()) { return parseAwaitExpression(); } + // falls through default: return parseUpdateExpression(); } @@ -35752,6 +36112,8 @@ var Parser; if (languageVariant !== 1 /* JSX */) { return false; } + // We are in JSX context and the token is part of JSXElement. + // falls through default: return true; } @@ -36325,10 +36687,16 @@ var Parser; } function canFollowTypeArgumentsInExpression() { switch (token()) { + // These tokens can follow a type argument list in a call expression. case 21 /* OpenParenToken */: + // foo( case 15 /* NoSubstitutionTemplateLiteral */: + // foo `...` case 16 /* TemplateHead */: return true; + // A type argument list followed by `<` never makes sense, and a type argument list followed + // by `>` is ambiguous with a (re-scanned) `>>` operator, so we disqualify both. Also, in + // this context, `+` and `-` are unary operators, not binary operators. case 30 /* LessThanToken */: case 32 /* GreaterThanToken */: case 40 /* PlusToken */: @@ -36346,6 +36714,7 @@ var Parser; false ); } + // falls through case 9 /* NumericLiteral */: case 10 /* BigIntLiteral */: case 11 /* StringLiteral */: @@ -36849,6 +37218,27 @@ var Parser; return isUsingDeclaration(); case 135 /* AwaitKeyword */: return isAwaitUsingDeclaration(); + // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers; + // however, an identifier cannot be followed by another identifier on the same line. This is what we + // count on to parse out the respective declarations. For instance, we exploit this to say that + // + // namespace n + // + // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees + // + // namespace + // n + // + // as the identifier 'namespace' on one line followed by the identifier 'n' on another. + // We need to look one token ahead to see if it permissible to try parsing a declaration. + // + // *Note*: 'interface' is actually a strict mode reserved word. So while + // + // "use strict" + // interface + // I {} + // + // could be legal, it would add complexity for very little gain. case 120 /* InterfaceKeyword */: case 156 /* TypeKeyword */: return nextTokenIsIdentifierOnSameLine(); @@ -36921,6 +37311,9 @@ var Parser; case 111 /* ThrowKeyword */: case 113 /* TryKeyword */: case 89 /* DebuggerKeyword */: + // 'catch' and 'finally' do not actually indicate that the code is part of a statement, + // however, we say they are here so that we may gracefully parse them and error later. + // falls through case 85 /* CatchKeyword */: case 98 /* FinallyKeyword */: return true; @@ -37059,6 +37452,8 @@ var Parser; case 111 /* ThrowKeyword */: return parseThrowStatement(); case 113 /* TryKeyword */: + // Include 'catch' and 'finally' for error recovery. + // falls through case 85 /* CatchKeyword */: case 98 /* FinallyKeyword */: return parseTryStatement(); @@ -37477,10 +37872,15 @@ var Parser; } switch (token()) { case 21 /* OpenParenToken */: + // Method declaration case 30 /* LessThanToken */: + // Generic Method declaration case 54 /* ExclamationToken */: + // Non-null assertion on property name case 59 /* ColonToken */: + // Type Annotation for declaration case 64 /* EqualsToken */: + // Initializer for declaration case 58 /* QuestionToken */: return true; default: @@ -38387,6 +38787,7 @@ var Parser; linkEnd = scanner2.getTokenEnd(); break; } + // fallthrough if it's not a {@link sequence default: state = 2 /* SavingComments */; pushComment(scanner2.getTokenText()); @@ -38645,6 +39046,8 @@ var Parser; indent3 += 1; break; } + // record the * as a comment + // falls through default: if (state !== 3 /* SavingBackticks */) { state = 2 /* SavingComments */; @@ -39616,9 +40019,10 @@ function getDeclarationFileExtension(fileName) { return standardExtension; } if (fileExtensionIs(fileName, ".ts" /* Ts */)) { - const index = getBaseFileName(fileName).lastIndexOf(".d."); + const baseName = getBaseFileName(fileName); + const index = baseName.lastIndexOf(".d."); if (index >= 0) { - return fileName.substring(index); + return baseName.substring(index); } } return void 0; @@ -39725,6 +40129,7 @@ function processPragmasIntoFields(context, reportDiagnostic) { case "jsximportsource": case "jsxruntime": return; + // Accessed directly default: Debug.fail("Unhandled pragma kind"); } @@ -39862,6 +40267,7 @@ var libEntries = [ ["es2021", "lib.es2021.d.ts"], ["es2022", "lib.es2022.d.ts"], ["es2023", "lib.es2023.d.ts"], + ["es2024", "lib.es2024.d.ts"], ["esnext", "lib.esnext.d.ts"], // Host only ["dom", "lib.dom.d.ts"], @@ -39884,6 +40290,7 @@ var libEntries = [ ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"], ["es2016.array.include", "lib.es2016.array.include.d.ts"], ["es2016.intl", "lib.es2016.intl.d.ts"], + ["es2017.arraybuffer", "lib.es2017.arraybuffer.d.ts"], ["es2017.date", "lib.es2017.date.d.ts"], ["es2017.object", "lib.es2017.object.d.ts"], ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"], @@ -39916,12 +40323,18 @@ var libEntries = [ ["es2022.error", "lib.es2022.error.d.ts"], ["es2022.intl", "lib.es2022.intl.d.ts"], ["es2022.object", "lib.es2022.object.d.ts"], - ["es2022.sharedmemory", "lib.es2022.sharedmemory.d.ts"], ["es2022.string", "lib.es2022.string.d.ts"], ["es2022.regexp", "lib.es2022.regexp.d.ts"], ["es2023.array", "lib.es2023.array.d.ts"], ["es2023.collection", "lib.es2023.collection.d.ts"], ["es2023.intl", "lib.es2023.intl.d.ts"], + ["es2024.arraybuffer", "lib.es2024.arraybuffer.d.ts"], + ["es2024.collection", "lib.es2024.collection.d.ts"], + ["es2024.object", "lib.es2024.object.d.ts"], + ["es2024.promise", "lib.es2024.promise.d.ts"], + ["es2024.regexp", "lib.es2024.regexp.d.ts"], + ["es2024.sharedmemory", "lib.es2024.sharedmemory.d.ts"], + ["es2024.string", "lib.es2024.string.d.ts"], ["esnext.array", "lib.es2023.array.d.ts"], ["esnext.collection", "lib.esnext.collection.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], @@ -39930,13 +40343,13 @@ var libEntries = [ ["esnext.disposable", "lib.esnext.disposable.d.ts"], ["esnext.bigint", "lib.es2020.bigint.d.ts"], ["esnext.string", "lib.es2022.string.d.ts"], - ["esnext.promise", "lib.esnext.promise.d.ts"], + ["esnext.promise", "lib.es2024.promise.d.ts"], ["esnext.weakref", "lib.es2021.weakref.d.ts"], ["esnext.decorators", "lib.esnext.decorators.d.ts"], - ["esnext.object", "lib.esnext.object.d.ts"], + ["esnext.object", "lib.es2024.object.d.ts"], ["esnext.array", "lib.esnext.array.d.ts"], - ["esnext.regexp", "lib.esnext.regexp.d.ts"], - ["esnext.string", "lib.esnext.string.d.ts"], + ["esnext.regexp", "lib.es2024.regexp.d.ts"], + ["esnext.string", "lib.es2024.string.d.ts"], ["esnext.iterator", "lib.esnext.iterator.d.ts"], ["decorators", "lib.decorators.d.ts"], ["decorators.legacy", "lib.decorators.legacy.d.ts"] @@ -40235,6 +40648,7 @@ var targetOptionDeclaration = { es2021: 8 /* ES2021 */, es2022: 9 /* ES2022 */, es2023: 10 /* ES2023 */, + es2024: 11 /* ES2024 */, esnext: 99 /* ESNext */ })), affectsSourceFile: true, @@ -40313,15 +40727,6 @@ var commandOptionsWithoutBuild = [ paramType: Diagnostics.FILE_OR_DIRECTORY, description: Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json }, - { - name: "build", - type: "boolean", - shortName: "b", - showInSimplifiedHelpView: true, - category: Diagnostics.Command_line_Options, - description: Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date, - defaultValueDescription: false - }, { name: "showConfig", type: "boolean", @@ -40846,6 +41251,15 @@ var commandOptionsWithoutBuild = [ defaultValueDescription: false, transpileOptionValue: void 0 }, + { + name: "rewriteRelativeImportExtensions", + type: "boolean", + affectsSemanticDiagnostics: true, + affectsBuildInfo: true, + category: Diagnostics.Modules, + description: Diagnostics.Rewrite_ts_tsx_mts_and_cts_file_extensions_in_relative_import_paths_to_their_JavaScript_equivalent_in_output_files, + defaultValueDescription: false + }, { name: "resolvePackageJsonExports", type: "boolean", @@ -41306,7 +41720,17 @@ var commandLineOptionOfCustomType = optionDeclarations.filter(isCommandLineOptio function isCommandLineOptionOfCustomType(option) { return !isString(option.type); } +var tscBuildOption = { + name: "build", + type: "boolean", + shortName: "b", + showInSimplifiedHelpView: true, + category: Diagnostics.Command_line_Options, + description: Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date, + defaultValueDescription: false +}; var optionsForBuild = [ + tscBuildOption, { name: "verbose", shortName: "v", @@ -41445,8 +41869,14 @@ function getOptionName(option) { } function createUnknownOptionError(unknownOption, diagnostics, unknownOptionErrorText, node, sourceFile) { var _a; - if ((_a = diagnostics.alternateMode) == null ? void 0 : _a.getOptionsNameMap().optionsNameMap.has(unknownOption.toLowerCase())) { - return createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics.alternateMode.diagnostic, unknownOption); + const otherOption = (_a = diagnostics.alternateMode) == null ? void 0 : _a.getOptionsNameMap().optionsNameMap.get(unknownOption.toLowerCase()); + if (otherOption) { + return createDiagnosticForNodeInSourceFileOrCompilerDiagnostic( + sourceFile, + node, + otherOption !== tscBuildOption ? diagnostics.alternateMode.diagnostic : Diagnostics.Option_build_must_be_the_first_command_line_argument, + unknownOption + ); } const possibleOption = getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName); return possibleOption ? createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption); @@ -41581,6 +42011,7 @@ function parseOptionValue(args, i, diagnostics, opt, options, errors) { case "listOrElement": Debug.fail("listOrElement not supported here"); break; + // If not a primitive, the possible types are specified in what is effectively a map of options. default: options[opt.name] = parseCustomTypeOption(opt, args[i], errors); i++; @@ -41634,10 +42065,10 @@ var buildOptionsDidYouMeanDiagnostics = { unknownDidYouMeanDiagnostic: Diagnostics.Unknown_build_option_0_Did_you_mean_1, optionTypeMismatchDiagnostic: Diagnostics.Build_option_0_requires_a_value_of_type_1 }; -function parseBuildCommand(args) { +function parseBuildCommand(commandLine) { const { options, watchOptions, fileNames: projects, errors } = parseCommandLineWorker( buildOptionsDidYouMeanDiagnostics, - args + commandLine ); const buildOptions = options; if (projects.length === 0) { @@ -41921,6 +42352,7 @@ function convertToJson(sourceFile, rootExpression, errors, returnValue, jsonConv return false; case 106 /* NullKeyword */: return null; + // eslint-disable-line no-restricted-syntax case 11 /* StringLiteral */: if (!isDoubleQuotedString(valueExpression)) { errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, Diagnostics.String_literal_with_double_quotes_expected)); @@ -42014,7 +42446,7 @@ function convertToTSConfig(configParseResult, configFileName, host) { const providedKeys = new Set(optionMap.keys()); const impliedCompilerOptions = {}; for (const option in computedOptions) { - if (!providedKeys.has(option) && some(computedOptions[option].dependencies, (dep) => providedKeys.has(dep))) { + if (!providedKeys.has(option) && optionDependsOn(option, providedKeys)) { const implied = computedOptions[option].computeValue(configParseResult.options); const defaultValue = computedOptions[option].computeValue({}); if (implied !== defaultValue) { @@ -42025,6 +42457,17 @@ function convertToTSConfig(configParseResult, configFileName, host) { assign(config.compilerOptions, optionMapToObject(serializeCompilerOptions(impliedCompilerOptions, pathOptions))); return config; } +function optionDependsOn(option, dependsOn) { + const seen = /* @__PURE__ */ new Set(); + return optionDependsOnRecursive(option); + function optionDependsOnRecursive(option2) { + var _a; + if (addToSeen(seen, option2)) { + return some((_a = computedOptions[option2]) == null ? void 0 : _a.dependencies, (dep) => dependsOn.has(dep) || optionDependsOnRecursive(dep)); + } + return false; + } +} function optionMapToObject(optionMap) { return Object.fromEntries(optionMap); } @@ -42400,8 +42843,6 @@ function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, exis validatedFilesSpecBeforeSubstitution, validatedIncludeSpecsBeforeSubstitution, validatedExcludeSpecsBeforeSubstitution, - pathPatterns: void 0, - // Initialized on first use isDefaultIncludeSpec }; } @@ -42540,6 +42981,9 @@ function getErrorForNoInputFiles({ includeSpecs, excludeSpecs }, configFileName) function shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles, resolutionStack) { return fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0); } +function isSolutionConfig(config) { + return !config.fileNames.length && hasProperty(config.raw, "references"); +} function canJsonReportNoInputFiles(raw) { return !hasProperty(raw, "files") && !hasProperty(raw, "references"); } @@ -42581,7 +43025,7 @@ function parseConfig(json, sourceFile, host, basePath, configFileName, resolutio if (ownConfig.raw.compileOnSave === void 0 && result.compileOnSave) ownConfig.raw.compileOnSave = result.compileOnSave; if (sourceFile && result.extendedSourceFiles) sourceFile.extendedSourceFiles = arrayFrom(result.extendedSourceFiles.keys()); ownConfig.options = assign(result.options, ownConfig.options); - ownConfig.watchOptions = ownConfig.watchOptions && result.watchOptions ? assign(result.watchOptions, ownConfig.watchOptions) : ownConfig.watchOptions || result.watchOptions; + ownConfig.watchOptions = ownConfig.watchOptions && result.watchOptions ? assignWatchOptions(result, ownConfig.watchOptions) : ownConfig.watchOptions || result.watchOptions; } return ownConfig; function applyExtendedConfig(result, extendedConfigPath) { @@ -42605,9 +43049,14 @@ function parseConfig(json, sourceFile, host, basePath, configFileName, resolutio result.compileOnSave = extendsRaw.compileOnSave; } assign(result.options, extendedConfig.options); - result.watchOptions = result.watchOptions && extendedConfig.watchOptions ? assign({}, result.watchOptions, extendedConfig.watchOptions) : result.watchOptions || extendedConfig.watchOptions; + result.watchOptions = result.watchOptions && extendedConfig.watchOptions ? assignWatchOptions(result, extendedConfig.watchOptions) : result.watchOptions || extendedConfig.watchOptions; } } + function assignWatchOptions(result, watchOptions) { + if (result.watchOptionsCopied) return assign(result.watchOptions, watchOptions); + result.watchOptionsCopied = true; + return assign({}, result.watchOptions, watchOptions); + } } function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) { if (hasProperty(json, "excludes")) { @@ -43129,6 +43578,7 @@ function getOptionValueWithEmptyStrings(value, option) { return typeof value === "boolean" ? value : ""; case "listOrElement": if (!isArray(value)) return getOptionValueWithEmptyStrings(value, option.element); + // fall through to list case "list": const elementType = option.element; return isArray(value) ? mapDefined(value, (v) => getOptionValueWithEmptyStrings(v, elementType)) : ""; @@ -43649,7 +44099,7 @@ function getConditions(options, resolutionMode) { } function resolvePackageNameToPackageJson(packageName, containingDirectory, options, host, cache) { const moduleResolutionState = getTemporaryModuleResolutionState(cache == null ? void 0 : cache.getPackageJsonInfoCache(), host, options); - return forEachAncestorDirectory(containingDirectory, (ancestorDirectory) => { + return forEachAncestorDirectoryStoppingAtGlobalCache(host, containingDirectory, (ancestorDirectory) => { if (getBaseFileName(ancestorDirectory) !== "node_modules") { const nodeModulesFolder = combinePaths(ancestorDirectory, "node_modules"); const candidate = combinePaths(nodeModulesFolder, packageName); @@ -44105,8 +44555,7 @@ function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, co } } function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) { - var _a; - const { baseUrl, paths, configFile } = state.compilerOptions; + const { baseUrl, paths } = state.compilerOptions; if (paths && !pathIsRelative(moduleName)) { if (state.traceEnabled) { if (baseUrl) { @@ -44115,7 +44564,7 @@ function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } const baseDirectory = getPathsBasePath(state.compilerOptions, state.host); - const pathPatterns = (configFile == null ? void 0 : configFile.configFileSpecs) ? (_a = configFile.configFileSpecs).pathPatterns || (_a.pathPatterns = tryParsePatterns(paths)) : void 0; + const pathPatterns = tryParsePatterns(paths); return tryLoadModuleUsingPaths( extensions, moduleName, @@ -44427,25 +44876,28 @@ function nodeModuleNameResolverWorker(features, moduleName, containingDirectory, return toSearchResult({ resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) }); } if (!isExternalModuleNameRelative(moduleName)) { - let resolved2; if (features & 2 /* Imports */ && startsWith(moduleName, "#")) { - resolved2 = loadModuleFromImports(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); - } - if (!resolved2 && features & 4 /* SelfName */) { - resolved2 = loadModuleFromSelfNameReference(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); + const resolved3 = loadModuleFromImports(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); + if (resolved3) { + return resolved3.value && { value: { resolved: resolved3.value, isExternalLibraryImport: false } }; + } } - if (!resolved2) { - if (moduleName.includes(":")) { - 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 (features & 4 /* SelfName */) { + const resolved3 = loadModuleFromSelfNameReference(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); + if (resolved3) { + return resolved3.value && { value: { resolved: resolved3.value, isExternalLibraryImport: false } }; } + } + if (moduleName.includes(":")) { if (traceEnabled) { - trace(host, Diagnostics.Loading_module_0_from_node_modules_folder_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); + trace(host, Diagnostics.Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); } - resolved2 = loadModuleFromNearestNodeModulesDirectory(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); + return void 0; } + if (traceEnabled) { + trace(host, Diagnostics.Loading_module_0_from_node_modules_folder_target_file_types_Colon_1, moduleName, formatExtensions(extensions2)); + } + let resolved2 = loadModuleFromNearestNodeModulesDirectory(extensions2, moduleName, containingDirectory, state2, cache, redirectedReference); if (extensions2 & 4 /* Declaration */) { resolved2 ?? (resolved2 = resolveFromTypeRoot(moduleName, state2)); } @@ -44573,10 +45025,11 @@ function loadModuleFromFileNoImplicitExtensions(extensions, candidate, onlyRecor } return tryAddingExtensions(extensionless, extensions, extension, onlyRecordFailures, state); } -function loadFileNameFromPackageJsonField(extensions, candidate, onlyRecordFailures, state) { +function loadFileNameFromPackageJsonField(extensions, candidate, packageJsonValue, onlyRecordFailures, state) { if (extensions & 1 /* TypeScript */ && fileExtensionIsOneOf(candidate, supportedTSImplementationExtensions) || extensions & 4 /* Declaration */ && fileExtensionIsOneOf(candidate, supportedDeclarationExtensions)) { const result = tryFile(candidate, onlyRecordFailures, state); - return result !== void 0 ? { path: candidate, ext: tryExtractTSExtension(candidate), resolvedUsingTsExtension: void 0 } : void 0; + const ext = tryExtractTSExtension(candidate); + return result !== void 0 ? { path: candidate, ext, resolvedUsingTsExtension: packageJsonValue ? !endsWith(packageJsonValue, ext) : void 0 } : void 0; } if (state.isConfigLookup && extensions === 8 /* Json */ && fileExtensionIs(candidate, ".json" /* Json */)) { const result = tryFile(candidate, onlyRecordFailures, state); @@ -44738,6 +45191,7 @@ function loadEntrypointsFromExportMap(scope, exports2, state, extensions) { const result = loadFileNameFromPackageJsonField( extensions, finalPath, + target, /*onlyRecordFailures*/ false, state @@ -44782,7 +45236,8 @@ function getTemporaryModuleResolutionState(packageJsonInfoCache, host, options) }; } function getPackageScopeForPath(directory, state) { - return forEachAncestorDirectory( + return forEachAncestorDirectoryStoppingAtGlobalCache( + state.host, directory, (dir) => getPackageJsonInfo( dir, @@ -44878,7 +45333,14 @@ function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFail } } const loader = (extensions2, candidate2, onlyRecordFailures2, state2) => { - const fromFile = loadFileNameFromPackageJsonField(extensions2, candidate2, onlyRecordFailures2, state2); + const fromFile = loadFileNameFromPackageJsonField( + extensions2, + candidate2, + /*packageJsonValue*/ + void 0, + onlyRecordFailures2, + state2 + ); if (fromFile) { return noPackageId(fromFile); } @@ -44914,17 +45376,8 @@ function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFail if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, moduleName); } - const result = tryLoadModuleUsingPaths( - extensions, - moduleName, - candidate, - versionPaths.paths, - /*pathPatterns*/ - void 0, - loader, - onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, - state - ); + const pathPatterns = tryParsePatterns(versionPaths.paths); + const result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, pathPatterns, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); if (result) { return removeIgnoredPackageId(result.value); } @@ -44987,7 +45440,7 @@ function loadModuleFromExports(scope, extensions, subpath, state, cache, redirec mainExport = scope.contents.packageJsonContent.exports["."]; } if (mainExport) { - const loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport( + const loadModuleFromTargetExportOrImport = getLoadModuleFromTargetExportOrImport( extensions, state, cache, @@ -44997,7 +45450,7 @@ function loadModuleFromExports(scope, extensions, subpath, state, cache, redirec /*isImports*/ false ); - return loadModuleFromTargetImportOrExport( + return loadModuleFromTargetExportOrImport( mainExport, "", /*pattern*/ @@ -45015,7 +45468,7 @@ function loadModuleFromExports(scope, extensions, subpath, state, cache, redirec void 0 ); } - const result = loadModuleFromImportsOrExports( + const result = loadModuleFromExportsOrImports( extensions, state, cache, @@ -45069,7 +45522,7 @@ function loadModuleFromImports(extensions, moduleName, directory, state, cache, void 0 ); } - const result = loadModuleFromImportsOrExports( + const result = loadModuleFromExportsOrImports( extensions, state, cache, @@ -45096,19 +45549,19 @@ function comparePatternKeys(a, b) { const bPatternIndex = b.indexOf("*"); const baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; const baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; - if (baseLenA > baseLenB) return -1; - if (baseLenB > baseLenA) return 1; - if (aPatternIndex === -1) return 1; - if (bPatternIndex === -1) return -1; - if (a.length > b.length) return -1; - if (b.length > a.length) return 1; - return 0; + if (baseLenA > baseLenB) return -1 /* LessThan */; + if (baseLenB > baseLenA) return 1 /* GreaterThan */; + if (aPatternIndex === -1) return 1 /* GreaterThan */; + if (bPatternIndex === -1) return -1 /* LessThan */; + if (a.length > b.length) return -1 /* LessThan */; + if (b.length > a.length) return 1 /* GreaterThan */; + return 0 /* EqualTo */; } -function loadModuleFromImportsOrExports(extensions, state, cache, redirectedReference, moduleName, lookupTable, scope, isImports) { - const loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports); +function loadModuleFromExportsOrImports(extensions, state, cache, redirectedReference, moduleName, lookupTable, scope, isImports) { + const loadModuleFromTargetExportOrImport = getLoadModuleFromTargetExportOrImport(extensions, state, cache, redirectedReference, moduleName, scope, isImports); if (!endsWith(moduleName, directorySeparator) && !moduleName.includes("*") && hasProperty(lookupTable, moduleName)) { const target = lookupTable[moduleName]; - return loadModuleFromTargetImportOrExport( + return loadModuleFromTargetExportOrImport( target, /*subpath*/ "", @@ -45123,7 +45576,7 @@ function loadModuleFromImportsOrExports(extensions, state, cache, redirectedRefe const target = lookupTable[potentialTarget]; const starPos = potentialTarget.indexOf("*"); const subpath = moduleName.substring(potentialTarget.substring(0, starPos).length, moduleName.length - (potentialTarget.length - 1 - starPos)); - return loadModuleFromTargetImportOrExport( + return loadModuleFromTargetExportOrImport( target, subpath, /*pattern*/ @@ -45133,7 +45586,7 @@ function loadModuleFromImportsOrExports(extensions, state, cache, redirectedRefe } else if (endsWith(potentialTarget, "*") && startsWith(moduleName, potentialTarget.substring(0, potentialTarget.length - 1))) { const target = lookupTable[potentialTarget]; const subpath = moduleName.substring(potentialTarget.length - 1); - return loadModuleFromTargetImportOrExport( + return loadModuleFromTargetExportOrImport( target, subpath, /*pattern*/ @@ -45143,7 +45596,7 @@ function loadModuleFromImportsOrExports(extensions, state, cache, redirectedRefe } else if (startsWith(moduleName, potentialTarget)) { const target = lookupTable[potentialTarget]; const subpath = moduleName.substring(potentialTarget.length); - return loadModuleFromTargetImportOrExport( + return loadModuleFromTargetExportOrImport( target, subpath, /*pattern*/ @@ -45163,9 +45616,9 @@ function hasOneAsterisk(patternKey) { const firstStar = patternKey.indexOf("*"); return firstStar !== -1 && firstStar === patternKey.lastIndexOf("*"); } -function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports) { - return loadModuleFromTargetImportOrExport; - function loadModuleFromTargetImportOrExport(target, subpath, pattern, key) { +function getLoadModuleFromTargetExportOrImport(extensions, state, cache, redirectedReference, moduleName, scope, isImports) { + return loadModuleFromTargetExportOrImport; + function loadModuleFromTargetExportOrImport(target, subpath, pattern, key) { if (typeof target === "string") { if (!pattern && subpath.length > 0 && !endsWith(target, "/")) { if (state.traceEnabled) { @@ -45243,6 +45696,7 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField( extensions, finalPath, + target, /*onlyRecordFailures*/ false, state @@ -45254,7 +45708,7 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec if (condition === "default" || state.conditions.includes(condition) || isApplicableVersionedTypesKey(state.conditions, condition)) { traceIfEnabled(state, Diagnostics.Matched_0_condition_1, isImports ? "imports" : "exports", condition); const subTarget = target[condition]; - const result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern, key); + const result = loadModuleFromTargetExportOrImport(subTarget, subpath, pattern, key); if (result) { traceIfEnabled(state, Diagnostics.Resolved_under_condition_0, condition); traceIfEnabled(state, Diagnostics.Exiting_conditional_exports); @@ -45279,7 +45733,7 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec ); } for (const elem of target) { - const result = loadModuleFromTargetImportOrExport(elem, subpath, pattern, key); + const result = loadModuleFromTargetExportOrImport(elem, subpath, pattern, key); if (result) { return result; } @@ -45355,6 +45809,8 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField( extensions, possibleInputWithInputExtension, + /*packageJsonValue*/ + void 0, /*onlyRecordFailures*/ false, state @@ -45430,17 +45886,30 @@ function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, return lookup(secondaryExtensions); } function lookup(extensions2) { - return forEachAncestorDirectory(normalizeSlashes(directory), (ancestorDirectory) => { - if (getBaseFileName(ancestorDirectory) !== "node_modules") { - const resolutionFromCache = tryFindNonRelativeModuleNameInCache(cache, moduleName, mode, ancestorDirectory, redirectedReference, state); - if (resolutionFromCache) { - return resolutionFromCache; + return forEachAncestorDirectoryStoppingAtGlobalCache( + state.host, + normalizeSlashes(directory), + (ancestorDirectory) => { + if (getBaseFileName(ancestorDirectory) !== "node_modules") { + const resolutionFromCache = tryFindNonRelativeModuleNameInCache(cache, moduleName, mode, ancestorDirectory, redirectedReference, state); + if (resolutionFromCache) { + return resolutionFromCache; + } + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions2, moduleName, ancestorDirectory, state, typesScopeOnly, cache, redirectedReference)); } - return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions2, moduleName, ancestorDirectory, state, typesScopeOnly, cache, redirectedReference)); } - }); + ); } } +function forEachAncestorDirectoryStoppingAtGlobalCache(host, directory, callback) { + var _a; + const globalCache = (_a = host == null ? void 0 : host.getGlobalTypingsCacheLocation) == null ? void 0 : _a.call(host); + return forEachAncestorDirectory(directory, (ancestorDirectory) => { + const result = callback(ancestorDirectory); + if (result !== void 0) return result; + if (ancestorDirectory === globalCache) return false; + }) || void 0; +} function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) { const nodeModulesFolder = combinePaths(directory, "node_modules"); const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); @@ -45516,17 +45985,8 @@ function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, node trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, rest); } const packageDirectoryExists = nodeModulesDirectoryExists && directoryProbablyExists(packageDirectory, state.host); - const fromPaths = tryLoadModuleUsingPaths( - extensions, - rest, - packageDirectory, - versionPaths.paths, - /*pathPatterns*/ - void 0, - loader, - !packageDirectoryExists, - state - ); + const pathPatterns = tryParsePatterns(versionPaths.paths); + const fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, pathPatterns, loader, !packageDirectoryExists, state); if (fromPaths) { return fromPaths.value; } @@ -45534,7 +45994,6 @@ function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, node return loader(extensions, candidate, !nodeModulesDirectoryExists, state); } function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, pathPatterns, loader, onlyRecordFailures, state) { - pathPatterns || (pathPatterns = tryParsePatterns(paths)); const matchedPattern = matchPatternOrExact(pathPatterns, moduleName); if (matchedPattern) { const matchedStar = isString(matchedPattern) ? void 0 : matchedText(matchedPattern, moduleName); @@ -45646,28 +46105,32 @@ function classicNameResolver(moduleName, containingFile, compilerOptions, host, return { value: resolvedUsingSettings }; } if (!isExternalModuleNameRelative(moduleName)) { - const resolved2 = forEachAncestorDirectory(containingDirectory, (directory) => { - const resolutionFromCache = tryFindNonRelativeModuleNameInCache( - cache, - moduleName, - /*mode*/ - void 0, - directory, - redirectedReference, - state - ); - if (resolutionFromCache) { - return resolutionFromCache; + const resolved2 = forEachAncestorDirectoryStoppingAtGlobalCache( + state.host, + containingDirectory, + (directory) => { + const resolutionFromCache = tryFindNonRelativeModuleNameInCache( + cache, + moduleName, + /*mode*/ + void 0, + directory, + redirectedReference, + state + ); + if (resolutionFromCache) { + return resolutionFromCache; + } + const searchName = normalizePath(combinePaths(directory, moduleName)); + return toSearchResult(loadModuleFromFileNoPackageId( + extensions, + searchName, + /*onlyRecordFailures*/ + false, + state + )); } - const searchName = normalizePath(combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId( - extensions, - searchName, - /*onlyRecordFailures*/ - false, - state - )); - }); + ); if (resolved2) return resolved2; if (extensions & (1 /* TypeScript */ | 4 /* Declaration */)) { let resolved3 = loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); @@ -45710,7 +46173,7 @@ function resolveFromTypeRoot(moduleName, state) { } } function shouldAllowImportingTsExtension(compilerOptions, fromFileName) { - return !!compilerOptions.allowImportingTsExtensions || fromFileName && isDeclarationFileName(fromFileName); + return getAllowImportingTsExtensions(compilerOptions) || !!fromFileName && isDeclarationFileName(fromFileName); } function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache, packageJsonInfoCache) { const traceEnabled = isTraceEnabled(compilerOptions, host); @@ -45801,20 +46264,24 @@ function getModuleInstanceStateCached(node, visited = /* @__PURE__ */ new Map()) } function getModuleInstanceStateWorker(node, visited) { switch (node.kind) { + // 1. interface declarations, type alias declarations case 264 /* InterfaceDeclaration */: case 265 /* TypeAliasDeclaration */: return 0 /* NonInstantiated */; + // 2. const enum declarations case 266 /* EnumDeclaration */: if (isEnumConst(node)) { return 2 /* ConstEnumOnly */; } break; + // 3. non-exported import declarations case 272 /* ImportDeclaration */: case 271 /* ImportEqualsDeclaration */: if (!hasSyntacticModifier(node, 32 /* Export */)) { return 0 /* NonInstantiated */; } break; + // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain case 278 /* ExportDeclaration */: const exportDeclaration = node; if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 279 /* NamedExports */) { @@ -45831,6 +46298,7 @@ function getModuleInstanceStateWorker(node, visited) { return state; } break; + // 5. other uninstantiated module declarations. case 268 /* ModuleBlock */: { let state = 0 /* NonInstantiated */; forEachChild(node, (n) => { @@ -45948,7 +46416,7 @@ function createBinder() { var inStrictMode; var inAssignmentPattern = false; var symbolCount = 0; - var Symbol47; + var Symbol48; var classifiableNames; var unreachableFlow = createFlowNode( 1 /* Unreachable */, @@ -45977,7 +46445,7 @@ function createBinder() { inStrictMode = bindInStrictMode(file, opts); classifiableNames = /* @__PURE__ */ new Set(); symbolCount = 0; - Symbol47 = objectAllocator.getSymbolConstructor(); + Symbol48 = objectAllocator.getSymbolConstructor(); Debug.attachFlowNodeDebugInfo(unreachableFlow); Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { @@ -46028,7 +46496,7 @@ function createBinder() { } function createSymbol(flags, name) { symbolCount++; - return new Symbol47(flags, name); + return new Symbol48(flags, name); } function addDeclarationToSymbol(symbol, node, symbolFlags) { symbol.flags |= symbolFlags; @@ -46441,6 +46909,7 @@ function createBinder() { case 351 /* JSDocImportTag */: bindJSDocImportTag(node); break; + // In source files and blocks, bind functions first to match hoisting that occurs at runtime case 307 /* SourceFile */: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); @@ -46461,6 +46930,7 @@ function createBinder() { case 303 /* PropertyAssignment */: case 230 /* SpreadElement */: inAssignmentPattern = saveInAssignmentPattern; + // falls through default: bindEachChild(node); break; @@ -46482,6 +46952,7 @@ function createBinder() { if (isJSDocTypeAssertion(expr)) { return false; } + // fallthrough case 235 /* NonNullExpression */: return isNarrowingExpression(expr.expression); case 226 /* BinaryExpression */: @@ -47313,6 +47784,10 @@ function createBinder() { } function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) { switch (container.kind) { + // Modules, source files, and classes need specialized handling for how their + // members are declared (for example, a member of a class will go into a specific + // symbol table depending on if it is static or not). We defer to specialized + // handlers to take care of declaring these child members. case 267 /* ModuleDeclaration */: return declareModuleMember(node, symbolFlags, symbolExcludes); case 307 /* SourceFile */: @@ -47454,6 +47929,7 @@ function createBinder() { declareModuleMember(node, symbolFlags, symbolExcludes); break; } + // falls through default: Debug.assertNode(blockScopeContainer, canHaveLocals); if (!blockScopeContainer.locals) { @@ -47774,6 +48250,7 @@ function createBinder() { } function bindWorker(node) { switch (node.kind) { + /* Strict mode checks */ case 80 /* Identifier */: if (node.flags & 4096 /* IdentifierIsInJSDocNamespace */) { let parentNode = node.parent; @@ -47783,6 +48260,7 @@ function createBinder() { bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */); break; } + // falls through case 110 /* ThisKeyword */: if (currentFlow && (isExpression(node) || parent2.kind === 304 /* ShorthandPropertyAssignment */)) { node.flowNode = currentFlow; @@ -47871,6 +48349,7 @@ function createBinder() { return; case 182 /* TypePredicate */: break; + // Binding the children will handle everything case 168 /* TypeParameter */: return bindTypeParameter(node); case 169 /* Parameter */: @@ -47935,6 +48414,7 @@ function createBinder() { return bindObjectDefinePrototypeProperty(node); case 0 /* None */: break; + // Nothing to do default: return Debug.fail("Unknown call expression assignment declaration kind"); } @@ -47942,6 +48422,7 @@ function createBinder() { bindCallExpression(node); } break; + // Members of classes, interfaces, and modules case 231 /* ClassExpression */: case 263 /* ClassDeclaration */: inStrictMode = true; @@ -47954,10 +48435,12 @@ function createBinder() { return bindEnumDeclaration(node); case 267 /* ModuleDeclaration */: return bindModuleDeclaration(node); + // Jsx-attributes case 292 /* JsxAttributes */: return bindJsxAttributes(node); case 291 /* JsxAttribute */: return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */); + // Imports and exports case 271 /* ImportEqualsDeclaration */: case 274 /* NamespaceImport */: case 276 /* ImportSpecifier */: @@ -47978,6 +48461,7 @@ function createBinder() { if (!isFunctionLikeOrClassStaticBlockDeclaration(node.parent)) { return; } + // falls through case 268 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); case 341 /* JSDocParameterTag */: @@ -47987,6 +48471,7 @@ function createBinder() { if (node.parent.kind !== 322 /* JSDocTypeLiteral */) { break; } + // falls through case 348 /* JSDocPropertyTag */: const propTag = node; const flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 316 /* JSDocOptionalType */ ? 4 /* Property */ | 16777216 /* Optional */ : 4 /* Property */; @@ -48199,6 +48684,7 @@ function createBinder() { declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */); } break; + // Namespaces are not allowed in javascript files, so do nothing here case 267 /* ModuleDeclaration */: break; default: @@ -48695,6 +49181,7 @@ function getContainerFlags(node) { if (isObjectLiteralOrClassExpressionMethodOrAccessor(node)) { return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethodOrAccessor */; } + // falls through case 176 /* Constructor */: case 262 /* FunctionDeclaration */: case 173 /* MethodSignature */: @@ -49142,31 +49629,29 @@ function computeModuleSpecifiers(modulePaths, compilerOptions, importingSourceFi return { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true }; } } - if (!specifier) { - const local = getLocalModuleSpecifier( - modulePath.path, - info, - compilerOptions, - host, - options.overrideImportMode || importingSourceFile.impliedNodeFormat, - preferences, - /*pathsOnly*/ - modulePath.isRedirect - ); - if (!local || forAutoImport && isExcludedByRegex(local, preferences.excludeRegexes)) { - continue; - } - if (modulePath.isRedirect) { - redirectPathsSpecifiers = append(redirectPathsSpecifiers, local); - } else if (pathIsBareSpecifier(local)) { - if (pathContainsNodeModules(local)) { - relativeSpecifiers = append(relativeSpecifiers, local); - } else { - pathsSpecifiers = append(pathsSpecifiers, local); - } - } else if (forAutoImport || !importedFileIsInNodeModules || modulePath.isInNodeModules) { + const local = getLocalModuleSpecifier( + modulePath.path, + info, + compilerOptions, + host, + options.overrideImportMode || importingSourceFile.impliedNodeFormat, + preferences, + /*pathsOnly*/ + modulePath.isRedirect || !!specifier + ); + if (!local || forAutoImport && isExcludedByRegex(local, preferences.excludeRegexes)) { + continue; + } + if (modulePath.isRedirect) { + redirectPathsSpecifiers = append(redirectPathsSpecifiers, local); + } else if (pathIsBareSpecifier(local)) { + if (pathContainsNodeModules(local)) { relativeSpecifiers = append(relativeSpecifiers, local); + } else { + pathsSpecifiers = append(pathsSpecifiers, local); } + } else if (forAutoImport || !importedFileIsInNodeModules || modulePath.isInNodeModules) { + relativeSpecifiers = append(relativeSpecifiers, local); } } return (pathsSpecifiers == null ? void 0 : pathsSpecifiers.length) ? { kind: "paths", moduleSpecifiers: pathsSpecifiers, computedWithoutCache: true } : (redirectPathsSpecifiers == null ? void 0 : redirectPathsSpecifiers.length) ? { kind: "redirect", moduleSpecifiers: redirectPathsSpecifiers, computedWithoutCache: true } : (nodeModulesSpecifiers == null ? void 0 : nodeModulesSpecifiers.length) ? { kind: "node_modules", moduleSpecifiers: nodeModulesSpecifiers, computedWithoutCache: true } : { kind: "relative", moduleSpecifiers: relativeSpecifiers ?? emptyArray, computedWithoutCache: true }; @@ -49212,7 +49697,7 @@ function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, im importMode, prefersTsExtension(allowedEndings) ); - const fromPaths = pathsOnly || fromPackageJsonImports === void 0 ? paths && tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, host, compilerOptions) : void 0; + const fromPaths = pathsOnly || fromPackageJsonImports === void 0 ? paths && tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, baseDirectory, getCanonicalFileName, host, compilerOptions) : void 0; if (pathsOnly) { return fromPaths; } @@ -49268,9 +49753,11 @@ function getNearestAncestorDirectoryWithPackageJson(host, fileName) { if (host.getNearestAncestorDirectoryWithPackageJson) { return host.getNearestAncestorDirectoryWithPackageJson(fileName); } - return forEachAncestorDirectory(fileName, (directory) => { - return host.fileExists(combinePaths(directory, "package.json")) ? directory : void 0; - }); + return forEachAncestorDirectoryStoppingAtGlobalCache( + host, + fileName, + (directory) => host.fileExists(combinePaths(directory, "package.json")) ? directory : void 0 + ); } function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) { var _a; @@ -49288,25 +49775,29 @@ function forEachFileNameOfModule(importingFileName, importedFileName, host, pref } const symlinkedDirectories = (_a = host.getSymlinkCache) == null ? void 0 : _a.call(host).getSymlinkedDirectoriesByRealpath(); const fullImportedFileName = getNormalizedAbsolutePath(importedFileName, cwd); - const result = symlinkedDirectories && forEachAncestorDirectory(getDirectoryPath(fullImportedFileName), (realPathDirectory) => { - const symlinkDirectories = symlinkedDirectories.get(ensureTrailingDirectorySeparator(toPath(realPathDirectory, cwd, getCanonicalFileName))); - if (!symlinkDirectories) return void 0; - if (startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) { - return false; - } - return forEach(targets, (target) => { - if (!startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) { - return; - } - const relative = getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName); - for (const symlinkDirectory of symlinkDirectories) { - const option = resolvePath(symlinkDirectory, relative); - const result2 = cb(option, target === referenceRedirect); - shouldFilterIgnoredPaths = true; - if (result2) return result2; + const result = symlinkedDirectories && forEachAncestorDirectoryStoppingAtGlobalCache( + host, + getDirectoryPath(fullImportedFileName), + (realPathDirectory) => { + const symlinkDirectories = symlinkedDirectories.get(ensureTrailingDirectorySeparator(toPath(realPathDirectory, cwd, getCanonicalFileName))); + if (!symlinkDirectories) return void 0; + if (startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) { + return false; } - }); - }); + return forEach(targets, (target) => { + if (!startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) { + return; + } + const relative = getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName); + for (const symlinkDirectory of symlinkDirectories) { + const option = resolvePath(symlinkDirectory, relative); + const result2 = cb(option, target === referenceRedirect); + shouldFilterIgnoredPaths = true; + if (result2) return result2; + } + }); + } + ); return result || (preferSymlinks ? forEach(targets, (p) => shouldFilterIgnoredPaths && containsIgnoredPath(p) ? void 0 : cb(p, p === referenceRedirect)) : void 0); } function getAllModulePaths(info, importedFileName, host, preferences, compilerOptions, options = {}) { @@ -49435,10 +49926,11 @@ function tryGetModuleNameFromAmbientModule(moduleSymbol, checker) { return ambientModuleDeclare.name.text; } } -function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, host, compilerOptions) { +function tryGetModuleNameFromPaths(relativeToBaseUrl, paths, allowedEndings, baseDirectory, getCanonicalFileName, host, compilerOptions) { for (const key in paths) { for (const patternText2 of paths[key]) { - const pattern = normalizePath(patternText2); + const normalized = normalizePath(patternText2); + const pattern = getRelativePathIfInSameVolume(normalized, baseDirectory, getCanonicalFileName) ?? normalized; const indexOfStar = pattern.indexOf("*"); const candidates = allowedEndings.map((ending) => ({ ending, @@ -49767,6 +50259,8 @@ function tryGetModuleNameAsNodeModule({ path, isRedirect }, { getCanonicalFileNa subModuleName, versionPaths.paths, allowedEndings, + packageRootPath, + getCanonicalFileName, host, options ); @@ -50060,9 +50554,9 @@ function createTypeChecker(host) { }; var cancellationToken; var scanner2; - var Symbol47 = objectAllocator.getSymbolConstructor(); + var Symbol48 = objectAllocator.getSymbolConstructor(); var Type29 = objectAllocator.getTypeConstructor(); - var Signature14 = objectAllocator.getSignatureConstructor(); + var Signature13 = objectAllocator.getSignatureConstructor(); var typeCount = 0; var symbolCount = 0; var totalInstantiationCount = 0; @@ -50094,17 +50588,7 @@ function createTypeChecker(host) { var checkBinaryExpression = createCheckBinaryExpression(); var emitResolver = createResolver(); var nodeBuilder = createNodeBuilder(); - var syntacticNodeBuilder = createSyntacticTypeNodeBuilder(compilerOptions, { - isEntityNameVisible, - isExpandoFunctionDeclaration, - getAllAccessorDeclarations: getAllAccessorDeclarationsForDeclaration, - requiresAddingImplicitUndefined, - isUndefinedIdentifierExpression(node) { - Debug.assert(isExpressionNode(node)); - return getSymbolAtLocation(node) === undefinedSymbol; - }, - isDefinitelyReferenceToGlobalSymbolObject - }); + var syntacticNodeBuilder = createSyntacticTypeNodeBuilder(compilerOptions, nodeBuilder.syntacticBuilderResolver); var evaluate = createEvaluator({ evaluateElementAccessExpression, evaluateEntityNameExpression @@ -50205,6 +50689,7 @@ function createTypeChecker(host) { getBaseTypeOfLiteralType, getWidenedType, getWidenedLiteralType, + fillMissingTypeArguments, getTypeFromTypeNode: (nodeIn) => { const node = getParseTreeNode(nodeIn, isTypeNode); return node ? getTypeFromTypeNode(node) : errorType; @@ -50761,6 +51246,15 @@ function createTypeChecker(host) { emptyArray ); emptyJsxObjectType.objectFlags |= 2048 /* JsxAttributes */; + var emptyFreshJsxObjectType = createAnonymousType( + /*symbol*/ + void 0, + emptySymbols, + emptyArray, + emptyArray, + emptyArray + ); + emptyFreshJsxObjectType.objectFlags |= 2048 /* JsxAttributes */ | 8192 /* FreshLiteral */ | 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */; var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); emptyTypeLiteralSymbol.members = createSymbolTable(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, emptyArray); @@ -51239,7 +51733,7 @@ function createTypeChecker(host) { } function createSymbol(flags, name, checkFlags) { symbolCount++; - const symbol = new Symbol47(flags | 33554432 /* Transient */, name); + const symbol = new Symbol48(flags | 33554432 /* Transient */, name); symbol.links = new SymbolLinks(); symbol.links.checkFlags = checkFlags || 0 /* None */; return symbol; @@ -51848,6 +52342,7 @@ function createTypeChecker(host) { if (isEntityNameExpression(node.expression)) { return node.expression; } + // falls through default: return void 0; } @@ -52143,10 +52638,19 @@ function createTypeChecker(host) { function isESMFormatImportImportingCommonjsFormatFile(usageMode, targetMode) { return usageMode === 99 /* ESNext */ && targetMode === 1 /* CommonJS */; } - function isOnlyImportableAsDefault(usage) { + function isOnlyImportableAsDefault(usage, resolvedModule) { if (100 /* Node16 */ <= moduleKind && moduleKind <= 199 /* NodeNext */) { const usageMode = getEmitSyntaxForModuleSpecifierExpression(usage); - return usageMode === 99 /* ESNext */ && endsWith(usage.text, ".json" /* Json */); + if (usageMode === 99 /* ESNext */) { + resolvedModule ?? (resolvedModule = resolveExternalModuleName( + usage, + usage, + /*ignoreErrors*/ + true + )); + const targetFile = resolvedModule && getSourceFileOfModule(resolvedModule); + return targetFile && (isJsonSourceFile(targetFile) || getDeclarationFileExtension(targetFile.fileName) === ".d.json.ts"); + } } return false; } @@ -52217,7 +52721,7 @@ function createTypeChecker(host) { if (!specifier) { return exportDefaultSymbol; } - const hasDefaultOnly = isOnlyImportableAsDefault(specifier); + const hasDefaultOnly = isOnlyImportableAsDefault(specifier, moduleSymbol); const hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, specifier); if (!exportDefaultSymbol && !hasSyntheticDefault && !hasDefaultOnly) { if (hasExportAssignmentSymbol(moduleSymbol) && !allowSyntheticDefaultImports) { @@ -52419,12 +52923,14 @@ function createTypeChecker(host) { let symbolFromModule = getExportOfModule(targetSymbol, nameText, specifier, dontResolveAlias); if (symbolFromModule === void 0 && nameText === "default" /* Default */) { const file = (_a = moduleSymbol.declarations) == null ? void 0 : _a.find(isSourceFile); - if (isOnlyImportableAsDefault(moduleSpecifier) || canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { + if (isOnlyImportableAsDefault(moduleSpecifier, moduleSymbol) || canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias, moduleSpecifier)) { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } } const symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; - if (!symbol) { + if (isImportOrExportSpecifier(specifier) && isOnlyImportableAsDefault(moduleSpecifier, moduleSymbol) && nameText !== "default" /* Default */) { + error2(name, Diagnostics.Named_imports_from_a_JSON_file_into_an_ECMAScript_module_are_not_allowed_when_module_is_set_to_0, ModuleKind[moduleKind]); + } else if (!symbol) { errorNoModuleMemberSymbol(moduleSymbol, targetSymbol, node, name); } return symbol; @@ -53018,14 +53524,14 @@ function createTypeChecker(host) { return ambientModule; } const currentSourceFile = getSourceFileOfNode(location); - const contextSpecifier = isStringLiteralLike(location) ? location : ((_a = isModuleDeclaration(location) ? location : location.parent && isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : void 0) == null ? void 0 : _a.name) || ((_b = isLiteralImportTypeNode(location) ? location : void 0) == null ? void 0 : _b.argument.literal) || (isInJSFile(location) && isJSDocImportTag(location) ? location.moduleSpecifier : void 0) || (isVariableDeclaration(location) && location.initializer && isRequireCall( + const contextSpecifier = isStringLiteralLike(location) ? location : ((_a = isModuleDeclaration(location) ? location : location.parent && isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : void 0) == null ? void 0 : _a.name) || ((_b = isLiteralImportTypeNode(location) ? location : void 0) == null ? void 0 : _b.argument.literal) || (isVariableDeclaration(location) && location.initializer && isRequireCall( location.initializer, /*requireStringLiteralLikeArgument*/ true - ) ? location.initializer.arguments[0] : void 0) || ((_c = findAncestor(location, isImportCall)) == null ? void 0 : _c.arguments[0]) || ((_d = findAncestor(location, isImportDeclaration)) == null ? void 0 : _d.moduleSpecifier) || ((_e = findAncestor(location, isExternalModuleImportEqualsDeclaration)) == null ? void 0 : _e.moduleReference.expression) || ((_f = findAncestor(location, isExportDeclaration)) == null ? void 0 : _f.moduleSpecifier); + ) ? location.initializer.arguments[0] : void 0) || ((_c = findAncestor(location, isImportCall)) == null ? void 0 : _c.arguments[0]) || ((_d = findAncestor(location, or(isImportDeclaration, isJSDocImportTag, isExportDeclaration))) == null ? void 0 : _d.moduleSpecifier) || ((_e = findAncestor(location, isExternalModuleImportEqualsDeclaration)) == null ? void 0 : _e.moduleReference.expression); const mode = contextSpecifier && isStringLiteralLike(contextSpecifier) ? host.getModeForUsageLocation(currentSourceFile, contextSpecifier) : host.getDefaultResolutionModeForFile(currentSourceFile); const moduleResolutionKind = getEmitModuleResolutionKind(compilerOptions); - const resolvedModule = (_g = host.getResolvedModule(currentSourceFile, moduleReference, mode)) == null ? void 0 : _g.resolvedModule; + const resolvedModule = (_f = host.getResolvedModule(currentSourceFile, moduleReference, mode)) == null ? void 0 : _f.resolvedModule; const resolutionDiagnostic = errorNode && resolvedModule && getResolutionDiagnostic(compilerOptions, resolvedModule, currentSourceFile); const sourceFile = resolvedModule && (!resolutionDiagnostic || resolutionDiagnostic === Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set) && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { @@ -53033,7 +53539,7 @@ function createTypeChecker(host) { error2(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } if (resolvedModule.resolvedUsingTsExtension && isDeclarationFileName(moduleReference)) { - const importOrExport = ((_h = findAncestor(location, isImportDeclaration)) == null ? void 0 : _h.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); + const importOrExport = ((_g = findAncestor(location, isImportDeclaration)) == null ? void 0 : _g.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); if (errorNode && importOrExport && !importOrExport.isTypeOnly || findAncestor(location, isImportCall)) { error2( errorNode, @@ -53042,11 +53548,41 @@ function createTypeChecker(host) { ); } } else if (resolvedModule.resolvedUsingTsExtension && !shouldAllowImportingTsExtension(compilerOptions, currentSourceFile.fileName)) { - const importOrExport = ((_i = findAncestor(location, isImportDeclaration)) == null ? void 0 : _i.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); + const importOrExport = ((_h = findAncestor(location, isImportDeclaration)) == null ? void 0 : _h.importClause) || findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)); if (errorNode && !((importOrExport == null ? void 0 : importOrExport.isTypeOnly) || findAncestor(location, isImportTypeNode))) { const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference)); error2(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension); } + } else if (compilerOptions.rewriteRelativeImportExtensions && !(location.flags & 33554432 /* Ambient */) && !isDeclarationFileName(moduleReference) && !isLiteralImportTypeNode(location) && !isPartOfTypeOnlyImportOrExportDeclaration(location)) { + const shouldRewrite = shouldRewriteModuleSpecifier(moduleReference, compilerOptions); + if (!resolvedModule.resolvedUsingTsExtension && shouldRewrite) { + error2( + errorNode, + Diagnostics.This_relative_import_path_is_unsafe_to_rewrite_because_it_looks_like_a_file_name_but_actually_resolves_to_0, + getRelativePathFromFile(getNormalizedAbsolutePath(currentSourceFile.fileName, host.getCurrentDirectory()), resolvedModule.resolvedFileName, hostGetCanonicalFileName(host)) + ); + } else if (resolvedModule.resolvedUsingTsExtension && !shouldRewrite && sourceFileMayBeEmitted(sourceFile, host)) { + error2( + errorNode, + Diagnostics.This_import_uses_a_0_extension_to_resolve_to_an_input_TypeScript_file_but_will_not_be_rewritten_during_emit_because_it_is_not_a_relative_path, + getAnyExtensionFromPath(moduleReference) + ); + } else if (resolvedModule.resolvedUsingTsExtension && shouldRewrite) { + const redirect = host.getResolvedProjectReferenceToRedirect(sourceFile.path); + if (redirect) { + const ignoreCase = !host.useCaseSensitiveFileNames(); + const ownRootDir = host.getCommonSourceDirectory(); + const otherRootDir = getCommonSourceDirectoryOfConfig(redirect.commandLine, ignoreCase); + const rootDirPath = getRelativePathFromDirectory(ownRootDir, otherRootDir, ignoreCase); + const outDirPath = getRelativePathFromDirectory(compilerOptions.outDir || ownRootDir, redirect.commandLine.options.outDir || otherRootDir, ignoreCase); + if (rootDirPath !== outDirPath) { + error2( + errorNode, + Diagnostics.This_import_path_is_unsafe_to_rewrite_because_it_resolves_to_another_project_and_the_relative_path_between_the_projects_output_files_is_not_the_same_as_the_relative_path_between_its_input_files + ); + } + } + } } if (sourceFile.symbol) { if (errorNode && resolvedModule.isExternalLibraryImport && !resolutionExtensionIsTSOrJson(resolvedModule.extension)) { @@ -53072,14 +53608,11 @@ function createTypeChecker(host) { if (ext === ".ts" /* Ts */ || ext === ".js" /* Js */ || ext === ".tsx" /* Tsx */ || ext === ".jsx" /* Jsx */) { diagnosticDetails = createModeMismatchDetails(currentSourceFile); } + const message = (overrideHost == null ? void 0 : overrideHost.kind) === 272 /* ImportDeclaration */ && ((_i = overrideHost.importClause) == null ? void 0 : _i.isTypeOnly) ? Diagnostics.Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute : (overrideHost == null ? void 0 : overrideHost.kind) === 205 /* ImportType */ ? Diagnostics.Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute : Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead; diagnostics.add(createDiagnosticForNodeFromMessageChain( getSourceFileOfNode(errorNode), errorNode, - chainDiagnosticMessages( - diagnosticDetails, - Diagnostics.The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_referenced_file_is_an_ECMAScript_module_and_cannot_be_imported_with_require_Consider_writing_a_dynamic_import_0_call_instead, - moduleReference - ) + chainDiagnosticMessages(diagnosticDetails, message, moduleReference) )); } } @@ -53706,6 +54239,7 @@ function createTypeChecker(host) { if (!isExternalOrCommonJsModule(location)) { break; } + // falls through case 267 /* ModuleDeclaration */: const sym = getSymbolOfDeclaration(location); if (result = callback( @@ -53759,7 +54293,7 @@ function createTypeChecker(host) { const links = getSymbolLinks(symbol); const cache = links.accessibleChainCache || (links.accessibleChainCache = /* @__PURE__ */ new Map()); const firstRelevantLocation = forEachSymbolTableInScope(enclosingDeclaration, (_, __, ___, node) => node); - const key = `${useOnlyExternalAliasing ? 0 : 1}|${firstRelevantLocation && getNodeId(firstRelevantLocation)}|${meaning}`; + const key = `${useOnlyExternalAliasing ? 0 : 1}|${firstRelevantLocation ? getNodeId(firstRelevantLocation) : 0}|${meaning}`; if (cache.has(key)) { return cache.get(key); } @@ -54212,12 +54746,194 @@ function createTypeChecker(host) { return getTypeFromTypeNode(node); } function createNodeBuilder() { + const syntacticBuilderResolver = { + evaluateEntityNameExpression, + isExpandoFunctionDeclaration, + hasLateBindableName, + shouldRemoveDeclaration(context, node) { + return !(context.internalFlags & 8 /* AllowUnresolvedNames */ && isEntityNameExpression(node.name.expression) && checkComputedPropertyName(node.name).flags & 1 /* Any */); + }, + createRecoveryBoundary(context) { + return createRecoveryBoundary(context); + }, + isDefinitelyReferenceToGlobalSymbolObject, + getAllAccessorDeclarations: getAllAccessorDeclarationsForDeclaration, + requiresAddingImplicitUndefined(declaration, symbol, enclosingDeclaration) { + var _a; + switch (declaration.kind) { + case 172 /* PropertyDeclaration */: + case 171 /* PropertySignature */: + case 348 /* JSDocPropertyTag */: + symbol ?? (symbol = getSymbolOfDeclaration(declaration)); + const type = getTypeOfSymbol(symbol); + return !!(symbol.flags & 4 /* Property */ && symbol.flags & 16777216 /* Optional */ && isOptionalDeclaration(declaration) && ((_a = symbol.links) == null ? void 0 : _a.mappedType) && containsNonMissingUndefinedType(type)); + case 169 /* Parameter */: + case 341 /* JSDocParameterTag */: + return requiresAddingImplicitUndefined(declaration, enclosingDeclaration); + default: + Debug.assertNever(declaration); + } + }, + isOptionalParameter, + isUndefinedIdentifierExpression(node) { + Debug.assert(isExpressionNode(node)); + return getSymbolAtLocation(node) === undefinedSymbol; + }, + isEntityNameVisible(context, entityName, shouldComputeAliasToMakeVisible) { + return isEntityNameVisible(entityName, context.enclosingDeclaration, shouldComputeAliasToMakeVisible); + }, + serializeExistingTypeNode(context, typeNode, addUndefined) { + return serializeExistingTypeNode(context, typeNode, !!addUndefined); + }, + serializeReturnTypeForSignature(syntacticContext, signatureDeclaration) { + const context = syntacticContext; + const signature = getSignatureFromDeclaration(signatureDeclaration); + const returnType = context.enclosingSymbolTypes.get(getSymbolId(getSymbolOfDeclaration(signatureDeclaration))) ?? instantiateType(getReturnTypeOfSignature(signature), context.mapper); + return serializeInferredReturnTypeForSignature(context, signature, returnType); + }, + serializeTypeOfExpression(syntacticContext, expr) { + const context = syntacticContext; + const type = instantiateType(getWidenedType(getRegularTypeOfExpression(expr)), context.mapper); + return typeToTypeNodeHelper(type, context); + }, + serializeTypeOfDeclaration(syntacticContext, declaration, symbol) { + var _a; + const context = syntacticContext; + symbol ?? (symbol = getSymbolOfDeclaration(declaration)); + let type = (_a = context.enclosingSymbolTypes) == null ? void 0 : _a.get(getSymbolId(symbol)); + if (type === void 0) { + type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? instantiateType(getWidenedLiteralType(getTypeOfSymbol(symbol)), context.mapper) : errorType; + } + const addUndefinedForParameter = declaration && (isParameter(declaration) || isJSDocParameterTag(declaration)) && requiresAddingImplicitUndefined(declaration, context.enclosingDeclaration); + if (addUndefinedForParameter) { + type = getOptionalType(type); + } + return serializeInferredTypeForDeclaration(symbol, context, type); + }, + serializeNameOfParameter(context, parameter) { + return parameterToParameterDeclarationName(getSymbolOfDeclaration(parameter), parameter, context); + }, + serializeEntityName(syntacticContext, node) { + const context = syntacticContext; + const symbol = getSymbolAtLocation( + node, + /*ignoreErrors*/ + true + ); + if (!symbol) return void 0; + if (!isValueSymbolAccessible(symbol, context.enclosingDeclaration)) return void 0; + return symbolToExpression(symbol, context, 111551 /* Value */ | 1048576 /* ExportValue */); + }, + serializeTypeName(context, node, isTypeOf, typeArguments) { + return serializeTypeName(context, node, isTypeOf, typeArguments); + }, + getJsDocPropertyOverride(syntacticContext, jsDocTypeLiteral, jsDocProperty) { + const context = syntacticContext; + const name = isIdentifier(jsDocProperty.name) ? jsDocProperty.name : jsDocProperty.name.right; + const typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode2(context, jsDocTypeLiteral), name.escapedText); + const overrideTypeNode = typeViaParent && jsDocProperty.typeExpression && getTypeFromTypeNode2(context, jsDocProperty.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : void 0; + return overrideTypeNode; + }, + enterNewScope(context, node) { + if (isFunctionLike(node) || isJSDocSignature(node)) { + const signature = getSignatureFromDeclaration(node); + const expandedParams = getExpandedParameters( + signature, + /*skipUnionExpanding*/ + true + )[0]; + return enterNewScope(context, node, expandedParams, signature.typeParameters); + } else { + const typeParameters = isConditionalTypeNode(node) ? getInferTypeParameters(node) : [getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter))]; + return enterNewScope( + context, + node, + /*expandedParams*/ + void 0, + typeParameters + ); + } + }, + markNodeReuse(context, range, location) { + return setTextRange2(context, range, location); + }, + trackExistingEntityName(context, node) { + return trackExistingEntityName(node, context); + }, + trackComputedName(context, accessExpression) { + trackComputedName(accessExpression, context.enclosingDeclaration, context); + }, + getModuleSpecifierOverride(syntacticContext, parent2, lit) { + const context = syntacticContext; + if (context.bundled || context.enclosingFile !== getSourceFileOfNode(lit)) { + let name = lit.text; + const nodeSymbol = getNodeLinks(parent2).resolvedSymbol; + const meaning = parent2.isTypeOf ? 111551 /* Value */ : 788968 /* Type */; + const parentSymbol = nodeSymbol && isSymbolAccessible( + nodeSymbol, + context.enclosingDeclaration, + meaning, + /*shouldComputeAliasesToMakeVisible*/ + false + ).accessibility === 0 /* Accessible */ && lookupSymbolChain( + nodeSymbol, + context, + meaning, + /*yieldModuleSymbol*/ + true + )[0]; + if (parentSymbol && isExternalModuleSymbol(parentSymbol)) { + name = getSpecifierForModuleSymbol(parentSymbol, context); + } else { + const targetFile = getExternalModuleFileFromDeclaration(parent2); + if (targetFile) { + name = getSpecifierForModuleSymbol(targetFile.symbol, context); + } + } + if (name.includes("/node_modules/")) { + context.encounteredError = true; + if (context.tracker.reportLikelyUnsafeImportRequiredError) { + context.tracker.reportLikelyUnsafeImportRequiredError(name); + } + } + return name; + } + }, + canReuseTypeNode(context, typeNode) { + return canReuseTypeNode(context, typeNode); + }, + canReuseTypeNodeAnnotation(syntacticContext, node, existing, symbol, requiresAddingUndefined) { + var _a; + const context = syntacticContext; + if (context.enclosingDeclaration === void 0) return false; + symbol ?? (symbol = getSymbolOfDeclaration(node)); + let type = (_a = context.enclosingSymbolTypes) == null ? void 0 : _a.get(getSymbolId(symbol)); + if (type === void 0) { + if (symbol.flags & 98304 /* Accessor */) { + type = node.kind === 178 /* SetAccessor */ ? getWriteTypeOfSymbol(symbol) : getTypeOfAccessors(symbol); + } else if (isValueSignatureDeclaration(node)) { + type = getReturnTypeOfSignature(getSignatureFromDeclaration(node)); + } else { + type = getTypeOfSymbol(symbol); + } + } + let annotationType = getTypeFromTypeNodeWithoutContext(existing); + if (isErrorType(annotationType)) { + return true; + } + if (requiresAddingUndefined && annotationType) { + annotationType = getOptionalType(annotationType, !isParameter(node)); + } + return !!annotationType && typeNodeIsEquivalentToType(node, type, annotationType) && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type); + } + }; return { + syntacticBuilderResolver, typeToTypeNode: (type, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => typeToTypeNodeHelper(type, context)), typePredicateToTypePredicateNode: (typePredicate, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => typePredicateToTypePredicateNodeHelper(typePredicate, context)), - expressionOrTypeToTypeNode: (expr, type, addUndefined, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => expressionOrTypeToTypeNode(context, expr, type, addUndefined)), - serializeTypeForDeclaration: (declaration, type, symbol, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => serializeTypeForDeclaration(context, declaration, type, symbol)), - serializeReturnTypeForSignature: (signature, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => serializeReturnTypeForSignature(context, signature)), + serializeTypeForExpression: (expr, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => syntacticNodeBuilder.serializeTypeOfExpression(expr, context)), + serializeTypeForDeclaration: (declaration, symbol, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => syntacticNodeBuilder.serializeTypeOfDeclaration(declaration, symbol, context)), + serializeReturnTypeForSignature: (signature, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => syntacticNodeBuilder.serializeReturnTypeForSignature(signature, getSymbolOfDeclaration(signature), context)), indexInfoToIndexSignatureDeclaration: (indexInfo, enclosingDeclaration, flags, internalFlags, tracker) => withContext2(enclosingDeclaration, flags, internalFlags, tracker, (context) => indexInfoToIndexSignatureDeclarationHelper( indexInfo, context, @@ -54265,65 +54981,6 @@ function createTypeChecker(host) { } return range; } - function expressionOrTypeToTypeNode(context, expr, type, addUndefined) { - const restoreFlags = saveRestoreFlags(context); - if (expr && !(context.internalFlags & 2 /* NoSyntacticPrinter */)) { - syntacticNodeBuilder.serializeTypeOfExpression(expr, context, addUndefined); - } - context.internalFlags |= 2 /* NoSyntacticPrinter */; - const result = expressionOrTypeToTypeNodeHelper(context, expr, type, addUndefined); - restoreFlags(); - return result; - } - function expressionOrTypeToTypeNodeHelper(context, expr, type, addUndefined) { - if (expr) { - const typeNode = isAssertionExpression(expr) ? expr.type : isJSDocTypeAssertion(expr) ? getJSDocTypeAssertionType(expr) : void 0; - if (typeNode && !isConstTypeReference(typeNode)) { - const result = tryReuseExistingTypeNode(context, typeNode, type, expr.parent, addUndefined); - if (result) { - return result; - } - } - } - if (addUndefined) { - type = getOptionalType(type); - } - return typeToTypeNodeHelper(type, context); - } - function tryReuseExistingTypeNode(context, typeNode, type, host2, addUndefined) { - const originalType = type; - if (addUndefined) { - type = getOptionalType(type, !isParameter(host2)); - } - const clone2 = tryReuseExistingNonParameterTypeNode(context, typeNode, type, host2); - if (clone2) { - if (addUndefined && containsNonMissingUndefinedType(type) && !someType(getTypeFromTypeNode2(context, typeNode), (t) => !!(t.flags & 32768 /* Undefined */))) { - return factory.createUnionTypeNode([clone2, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); - } - return clone2; - } - if (addUndefined && originalType !== type) { - const cloneMissingUndefined = tryReuseExistingNonParameterTypeNode(context, typeNode, originalType, host2); - if (cloneMissingUndefined) { - return factory.createUnionTypeNode([cloneMissingUndefined, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); - } - } - return void 0; - } - function tryReuseExistingNonParameterTypeNode(context, existing, type, host2 = context.enclosingDeclaration, annotationType = getTypeFromTypeNode2( - context, - existing, - /*noMappedTypes*/ - true - )) { - if (annotationType && typeNodeIsEquivalentToType(host2, type, annotationType) && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) { - const result = tryReuseExistingTypeNodeHelper(context, existing); - if (result) { - return result; - } - } - return void 0; - } function symbolToNode(symbol, context, meaning) { if (context.internalFlags & 1 /* WriteComputedProps */) { if (symbol.valueDeclaration) { @@ -54347,6 +55004,7 @@ function createTypeChecker(host) { internalFlags: internalFlags || 0 /* None */, tracker: void 0, encounteredError: false, + suppressReportInferenceFallback: false, reportedDiagnostic: false, visitedTypes: void 0, symbolDepth: void 0, @@ -54365,6 +55023,7 @@ function createTypeChecker(host) { typeParameterNames: void 0, typeParameterNamesByText: void 0, typeParameterNamesByTextNextNameCount: void 0, + enclosingSymbolTypes: /* @__PURE__ */ new Map(), mapper: void 0 }; context.tracker = new SymbolTrackerImpl(context, tracker, moduleResolverHost); @@ -54374,6 +55033,19 @@ function createTypeChecker(host) { } return context.encounteredError ? void 0 : resultingNode; } + function addSymbolTypeToContext(context, symbol, type) { + const id = getSymbolId(symbol); + const oldType = context.enclosingSymbolTypes.get(id); + context.enclosingSymbolTypes.set(id, type); + return restore; + function restore() { + if (oldType) { + context.enclosingSymbolTypes.set(id, oldType); + } else { + context.enclosingSymbolTypes.delete(id); + } + } + } function saveRestoreFlags(context) { const flags = context.flags; const internalFlags = context.internalFlags; @@ -54785,8 +55457,8 @@ function createTypeChecker(host) { if (isInstantiationExpressionType) { const instantiationExpressionType = type2; const existing = instantiationExpressionType.node; - if (isTypeQueryNode(existing)) { - const typeNode = tryReuseExistingNonParameterTypeNode(context, existing, type2); + if (isTypeQueryNode(existing) && getTypeFromTypeNode2(context, existing) === type2) { + const typeNode = syntacticNodeBuilder.tryReuseExistingTypeNode(context, existing); if (typeNode) { return typeNode; } @@ -55128,6 +55800,9 @@ function createTypeChecker(host) { } function createTypeNodesFromResolvedType(resolvedType) { if (checkTruncationLength(context)) { + if (context.flags & 1 /* NoTruncation */) { + return [addSyntheticTrailingComment(factory.createNotEmittedTypeElement(), 3 /* MultiLineCommentTrivia */, "elided")]; + } return [factory.createPropertySignature( /*modifiers*/ void 0, @@ -55165,15 +55840,20 @@ function createTypeChecker(host) { } } if (checkTruncationLength(context) && i + 2 < properties.length - 1) { - typeElements.push(factory.createPropertySignature( - /*modifiers*/ - void 0, - `... ${properties.length - i} more ...`, - /*questionToken*/ - void 0, - /*type*/ - void 0 - )); + if (context.flags & 1 /* NoTruncation */) { + const typeElement = typeElements.pop(); + typeElements.push(addSyntheticTrailingComment(typeElement, 3 /* MultiLineCommentTrivia */, `... ${properties.length - i} more elided ...`)); + } else { + typeElements.push(factory.createPropertySignature( + /*modifiers*/ + void 0, + `... ${properties.length - i} more ...`, + /*questionToken*/ + void 0, + /*type*/ + void 0 + )); + } addPropertyToElementList(properties[properties.length - 1], context, typeElements); break; } @@ -55191,7 +55871,7 @@ function createTypeChecker(host) { void 0 ); } - return factory.createKeywordTypeNode(133 /* AnyKeyword */); + return addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, "elided"); } function shouldUsePlaceholderForProperty(propertySymbol, context) { var _a; @@ -55267,7 +55947,7 @@ function createTypeChecker(host) { const signatures = getSignaturesOfType(filterType(propertyType, (t) => !(t.flags & 32768 /* Undefined */)), 0 /* Call */); for (const signature of signatures) { const methodDeclaration = signatureToSignatureDeclarationHelper(signature, 173 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken }); - typeElements.push(preserveCommentsOn(methodDeclaration)); + typeElements.push(preserveCommentsOn(methodDeclaration, signature.declaration || propertySymbol.valueDeclaration)); } if (signatures.length || !optionalToken) { return; @@ -55302,8 +55982,8 @@ function createTypeChecker(host) { optionalToken, propertyTypeNode ); - typeElements.push(preserveCommentsOn(propertySignature)); - function preserveCommentsOn(node) { + typeElements.push(preserveCommentsOn(propertySignature, propertySymbol.valueDeclaration)); + function preserveCommentsOn(node, range) { var _a2; const jsdocPropertyTag = (_a2 = propertySymbol.declarations) == null ? void 0 : _a2.find((d) => d.kind === 348 /* JSDocPropertyTag */); if (jsdocPropertyTag) { @@ -55311,8 +55991,8 @@ function createTypeChecker(host) { if (commentText) { setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]); } - } else if (propertySymbol.valueDeclaration) { - setCommentRange2(context, node, propertySymbol.valueDeclaration); + } else if (range) { + setCommentRange2(context, node, range); } return node; } @@ -55327,15 +56007,17 @@ function createTypeChecker(host) { if (some(types)) { if (checkTruncationLength(context)) { if (!isBareList) { - return [factory.createTypeReferenceNode( - "...", - /*typeArguments*/ - void 0 - )]; + return [ + context.flags & 1 /* NoTruncation */ ? addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, "elided") : factory.createTypeReferenceNode( + "...", + /*typeArguments*/ + void 0 + ) + ]; } else if (types.length > 2) { return [ typeToTypeNodeHelper(types[0], context), - factory.createTypeReferenceNode( + context.flags & 1 /* NoTruncation */ ? addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, `... ${types.length - 2} more elided ...`) : factory.createTypeReferenceNode( `... ${types.length - 2} more ...`, /*typeArguments*/ void 0 @@ -55351,11 +56033,13 @@ function createTypeChecker(host) { for (const type of types) { i++; if (checkTruncationLength(context) && i + 2 < types.length - 1) { - result.push(factory.createTypeReferenceNode( - `... ${types.length - i} more ...`, - /*typeArguments*/ - void 0 - )); + result.push( + context.flags & 1 /* NoTruncation */ ? addSyntheticLeadingComment(factory.createKeywordTypeNode(133 /* AnyKeyword */), 3 /* MultiLineCommentTrivia */, `... ${types.length - i} more elided ...`) : factory.createTypeReferenceNode( + `... ${types.length - i} more ...`, + /*typeArguments*/ + void 0 + ) + ); const typeNode2 = typeToTypeNodeHelper(types[types.length - 1], context); if (typeNode2) { result.push(typeNode2); @@ -55525,14 +56209,85 @@ function createTypeChecker(host) { cleanup == null ? void 0 : cleanup(); return node; } - function isNewScopeNode(node) { - return isFunctionLike(node) || isJSDocSignature(node) || isMappedTypeNode(node); - } - function getTypeParametersInScope(node) { - return isFunctionLike(node) || isJSDocSignature(node) ? getSignatureFromDeclaration(node).typeParameters : isConditionalTypeNode(node) ? getInferTypeParameters(node) : [getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node.typeParameter))]; - } - function getParametersInScope(node) { - return isFunctionLike(node) || isJSDocSignature(node) ? getSignatureFromDeclaration(node).parameters : void 0; + function createRecoveryBoundary(context) { + if (cancellationToken && cancellationToken.throwIfCancellationRequested) { + cancellationToken.throwIfCancellationRequested(); + } + let trackedSymbols; + let unreportedErrors; + let hadError = false; + const oldTracker = context.tracker; + const oldTrackedSymbols = context.trackedSymbols; + context.trackedSymbols = void 0; + const oldEncounteredError = context.encounteredError; + context.tracker = new SymbolTrackerImpl(context, { + ...oldTracker.inner, + reportCyclicStructureError() { + markError(() => oldTracker.reportCyclicStructureError()); + }, + reportInaccessibleThisError() { + markError(() => oldTracker.reportInaccessibleThisError()); + }, + reportInaccessibleUniqueSymbolError() { + markError(() => oldTracker.reportInaccessibleUniqueSymbolError()); + }, + reportLikelyUnsafeImportRequiredError(specifier) { + markError(() => oldTracker.reportLikelyUnsafeImportRequiredError(specifier)); + }, + reportNonSerializableProperty(name) { + markError(() => oldTracker.reportNonSerializableProperty(name)); + }, + reportPrivateInBaseOfClassExpression(propertyName) { + markError(() => oldTracker.reportPrivateInBaseOfClassExpression(propertyName)); + }, + trackSymbol(sym, decl, meaning) { + (trackedSymbols ?? (trackedSymbols = [])).push([sym, decl, meaning]); + return false; + }, + moduleResolverHost: context.tracker.moduleResolverHost + }, context.tracker.moduleResolverHost); + return { + startRecoveryScope, + finalizeBoundary, + markError, + hadError: () => hadError + }; + function markError(unreportedError) { + hadError = true; + if (unreportedError) { + (unreportedErrors ?? (unreportedErrors = [])).push(unreportedError); + } + } + function startRecoveryScope() { + const trackedSymbolsTop = (trackedSymbols == null ? void 0 : trackedSymbols.length) ?? 0; + const unreportedErrorsTop = (unreportedErrors == null ? void 0 : unreportedErrors.length) ?? 0; + return () => { + hadError = false; + if (trackedSymbols) { + trackedSymbols.length = trackedSymbolsTop; + } + if (unreportedErrors) { + unreportedErrors.length = unreportedErrorsTop; + } + }; + } + function finalizeBoundary() { + context.tracker = oldTracker; + context.trackedSymbols = oldTrackedSymbols; + context.encounteredError = oldEncounteredError; + unreportedErrors == null ? void 0 : unreportedErrors.forEach((fn) => fn()); + if (hadError) { + return false; + } + trackedSymbols == null ? void 0 : trackedSymbols.forEach( + ([symbol, enclosingDeclaration, meaning]) => context.tracker.trackSymbol( + symbol, + enclosingDeclaration, + meaning + ) + ); + return true; + } } function enterNewScope(context, declaration, expandedParams, typeParameters, originalParameters, mapper) { const cleanupContext = cloneNodeBuilderContext(context); @@ -55675,7 +56430,7 @@ function createTypeChecker(host) { return factory.createTypeParameterDeclaration(modifiers, name, constraintNode, defaultParameterNode); } function typeToTypeNodeHelperWithPossibleReusableTypeNode(type, typeNode, context) { - return typeNode && tryReuseExistingNonParameterTypeNode(context, typeNode, type) || typeToTypeNodeHelper(type, context); + return typeNode && getTypeFromTypeNode2(context, typeNode) === type && syntacticNodeBuilder.tryReuseExistingTypeNode(context, typeNode) || typeToTypeNodeHelper(type, context); } function typeParameterToDeclaration(type, context, constraint = getConstraintOfTypeParameter(type)) { const constraintNode = constraint && typeToTypeNodeHelperWithPossibleReusableTypeNode(constraint, getConstraintDeclaration(type), context); @@ -56297,41 +57052,46 @@ function createTypeChecker(host) { } return enclosingDeclaration; } + function serializeInferredTypeForDeclaration(symbol, context, type) { + if (type.flags & 8192 /* UniqueESSymbol */ && type.symbol === symbol && (!context.enclosingDeclaration || some(symbol.declarations, (d) => getSourceFileOfNode(d) === context.enclosingFile))) { + context.flags |= 1048576 /* AllowUniqueESSymbolType */; + } + const result = typeToTypeNodeHelper(type, context); + return result; + } function serializeTypeForDeclaration(context, declaration, type, symbol) { - var _a, _b; + var _a; + let result; const addUndefinedForParameter = declaration && (isParameter(declaration) || isJSDocParameterTag(declaration)) && requiresAddingImplicitUndefined(declaration, context.enclosingDeclaration); - const enclosingDeclaration = context.enclosingDeclaration; - const restoreFlags = saveRestoreFlags(context); - if (declaration && hasInferredType(declaration) && !(context.internalFlags & 2 /* NoSyntacticPrinter */)) { - syntacticNodeBuilder.serializeTypeOfDeclaration(declaration, context); - } - context.internalFlags |= 2 /* NoSyntacticPrinter */; - if (enclosingDeclaration && (!isErrorType(type) || context.internalFlags & 8 /* AllowUnresolvedNames */)) { - const declWithExistingAnnotation = declaration && getNonlocalEffectiveTypeAnnotationNode(declaration) ? declaration : getDeclarationWithTypeAnnotation(symbol); - if (declWithExistingAnnotation && !isFunctionLikeDeclaration(declWithExistingAnnotation) && !isGetAccessorDeclaration(declWithExistingAnnotation)) { - const existing = getNonlocalEffectiveTypeAnnotationNode(declWithExistingAnnotation); - const addUndefined = addUndefinedForParameter || !!(symbol.flags & 4 /* Property */ && symbol.flags & 16777216 /* Optional */ && isOptionalDeclaration(declWithExistingAnnotation) && ((_a = symbol.links) == null ? void 0 : _a.mappedType) && containsNonMissingUndefinedType(type)); - const result2 = !isTypePredicateNode(existing) && tryReuseExistingTypeNode(context, existing, type, declWithExistingAnnotation, addUndefined); - if (result2) { - restoreFlags(); - return result2; - } + const decl = declaration ?? symbol.valueDeclaration ?? getDeclarationWithTypeAnnotation(symbol) ?? ((_a = symbol.declarations) == null ? void 0 : _a[0]); + if (decl) { + if (isAccessor(decl)) { + result = syntacticNodeBuilder.serializeTypeOfAccessor(decl, symbol, context); + } else if (hasInferredType(decl) && !nodeIsSynthesized(decl) && !(getObjectFlags(type) & 196608 /* RequiresWidening */)) { + const restore = addSymbolTypeToContext(context, symbol, type); + result = syntacticNodeBuilder.serializeTypeOfDeclaration(decl, symbol, context); + restore(); } } - if (type.flags & 8192 /* UniqueESSymbol */ && type.symbol === symbol && (!context.enclosingDeclaration || some(symbol.declarations, (d) => getSourceFileOfNode(d) === getSourceFileOfNode(context.enclosingDeclaration)))) { - context.flags |= 1048576 /* AllowUniqueESSymbolType */; + if (!result) { + if (addUndefinedForParameter) { + type = getOptionalType(type); + } + result = serializeInferredTypeForDeclaration(symbol, context, type); } - const decl = declaration ?? symbol.valueDeclaration ?? ((_b = symbol.declarations) == null ? void 0 : _b[0]); - const expr = decl && isDeclarationWithPossibleInnerTypeNodeReuse(decl) ? getPossibleTypeNodeReuseExpression(decl) : void 0; - const result = expressionOrTypeToTypeNode(context, expr, type, addUndefinedForParameter); - restoreFlags(); - return result; + return result ?? factory.createKeywordTypeNode(133 /* AnyKeyword */); } function typeNodeIsEquivalentToType(annotatedDeclaration, type, typeFromTypeNode) { if (typeFromTypeNode === type) { return true; } - if (annotatedDeclaration && (isParameter(annotatedDeclaration) || isPropertySignature(annotatedDeclaration) || isPropertyDeclaration(annotatedDeclaration)) && annotatedDeclaration.questionToken) { + if (!annotatedDeclaration) { + return false; + } + if ((isPropertySignature(annotatedDeclaration) || isPropertyDeclaration(annotatedDeclaration)) && annotatedDeclaration.questionToken) { + return getTypeWithFacts(type, 524288 /* NEUndefined */) === typeFromTypeNode; + } + if (isParameter(annotatedDeclaration) && hasEffectiveQuestionToken(annotatedDeclaration)) { return getTypeWithFacts(type, 524288 /* NEUndefined */) === typeFromTypeNode; } return false; @@ -56342,37 +57102,32 @@ function createTypeChecker(host) { if (suppressAny) context.flags &= ~256 /* SuppressAnyReturnType */; let returnTypeNode; const returnType = getReturnTypeOfSignature(signature); - if (returnType && !(suppressAny && isTypeAny(returnType))) { - if (signature.declaration && !(context.internalFlags & 2 /* NoSyntacticPrinter */)) { - syntacticNodeBuilder.serializeReturnTypeForSignature(signature.declaration, context); + if (!(suppressAny && isTypeAny(returnType))) { + if (signature.declaration && !nodeIsSynthesized(signature.declaration)) { + const declarationSymbol = getSymbolOfDeclaration(signature.declaration); + const restore = addSymbolTypeToContext(context, declarationSymbol, returnType); + returnTypeNode = syntacticNodeBuilder.serializeReturnTypeForSignature(signature.declaration, declarationSymbol, context); + restore(); + } + if (!returnTypeNode) { + returnTypeNode = serializeInferredReturnTypeForSignature(context, signature, returnType); } - context.internalFlags |= 2 /* NoSyntacticPrinter */; - returnTypeNode = serializeReturnTypeForSignatureWorker(context, signature); - } else if (!suppressAny) { + } + if (!returnTypeNode && !suppressAny) { returnTypeNode = factory.createKeywordTypeNode(133 /* AnyKeyword */); } restoreFlags(); return returnTypeNode; } - function serializeReturnTypeForSignatureWorker(context, signature) { + function serializeInferredReturnTypeForSignature(context, signature, returnType) { + const oldSuppressReportInferenceFallback = context.suppressReportInferenceFallback; + context.suppressReportInferenceFallback = true; const typePredicate = getTypePredicateOfSignature(signature); - const type = getReturnTypeOfSignature(signature); - if (context.enclosingDeclaration && (!isErrorType(type) || context.internalFlags & 8 /* AllowUnresolvedNames */) && signature.declaration && !nodeIsSynthesized(signature.declaration)) { - const annotation = getNonlocalEffectiveReturnTypeAnnotationNode(signature.declaration); - if (annotation) { - const result = tryReuseExistingTypeNode(context, annotation, type, context.enclosingDeclaration); - if (result) { - return result; - } - } - } - if (typePredicate) { - return typePredicateToTypePredicateNodeHelper(typePredicate, context); - } - const expr = signature.declaration && getPossibleTypeNodeReuseExpression(signature.declaration); - return expressionOrTypeToTypeNode(context, expr, type); + const returnTypeNode = typePredicate ? typePredicateToTypePredicateNodeHelper(context.mapper ? instantiateTypePredicate(typePredicate, context.mapper) : typePredicate, context) : typeToTypeNodeHelper(returnType, context); + context.suppressReportInferenceFallback = oldSuppressReportInferenceFallback; + return returnTypeNode; } - function trackExistingEntityName(node, context) { + function trackExistingEntityName(node, context, enclosingDeclaration = context.enclosingDeclaration) { let introducesError = false; const leftmost = getFirstIdentifier(node); if (isInJSFile(node) && (isExportsIdentifier(leftmost) || isModuleExportsAccessExpression(leftmost.parent) || isQualifiedName(leftmost.parent) && isModuleIdentifier(leftmost.parent.left) && isExportsIdentifier(leftmost.parent.right))) { @@ -56423,7 +57178,7 @@ function createTypeChecker(host) { if ( // Check for unusable parameters symbols symAtLocation === unknownSymbol || // If the symbol is not found, but was not found in the original scope either we probably have an error, don't reuse the node - symAtLocation === void 0 && sym !== void 0 || // If the symbol is found both in declaration scope and in current scope then it shoudl point to the same reference + symAtLocation === void 0 && sym !== void 0 || // If the symbol is found both in declaration scope and in current scope then it should point to the same reference symAtLocation && sym && !getSymbolIfSameReference(getExportSymbolOfValueSymbolIfExported(symAtLocation), sym) ) { if (symAtLocation !== unknownSymbol) { @@ -56444,7 +57199,7 @@ function createTypeChecker(host) { if (!(sym.flags & 262144 /* TypeParameter */) && // Type parameters are visible in the current context if they are are resolvable !isDeclarationName(node) && isSymbolAccessible( sym, - context.enclosingDeclaration, + enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ false @@ -56452,7 +57207,7 @@ function createTypeChecker(host) { context.tracker.reportInferenceFallback(node); introducesError = true; } else { - context.tracker.trackSymbol(sym, context.enclosingDeclaration, meaning); + context.tracker.trackSymbol(sym, enclosingDeclaration, meaning); } return { introducesError, node: attachSymbolToLeftmostIdentifier(node) }; } @@ -56496,6 +57251,15 @@ function createTypeChecker(host) { return symbolToTypeNode(resolvedSymbol, context, meaning, typeArguments); } function canReuseTypeNode(context, existing) { + const type = getTypeFromTypeNode2( + context, + existing, + /*noMappedTypes*/ + true + ); + if (!type) { + return false; + } if (isInJSFile(existing)) { if (isLiteralImportTypeNode(existing)) { void getTypeFromImportTypeNode(existing); @@ -56505,29 +57269,16 @@ function createTypeChecker(host) { !(length(existing.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol)))); } } - if (isThisTypeNode(existing)) { - if (context.mapper === void 0) return true; - const type = getTypeFromTypeNode2( - context, - existing, - /*noMappedTypes*/ - true - ); - return !!type; - } if (isTypeReferenceNode(existing)) { if (isConstTypeReference(existing)) return false; - const type = getTypeFromTypeReference(existing); const symbol = getNodeLinks(existing).resolvedSymbol; if (!symbol) return false; if (symbol.flags & 262144 /* TypeParameter */) { - const type2 = getDeclaredTypeOfSymbol(symbol); - if (context.mapper && getMappedType(type2, context.mapper) !== type2) { - return false; - } + const declaredType = getDeclaredTypeOfSymbol(symbol); + return !(context.mapper && getMappedType(declaredType, context.mapper) !== declaredType); } if (isInJSDoc(existing)) { - return existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) && !getIntendedTypeFromJSDocTypeReference(existing) && symbol.flags & 788968 /* Type */; + return existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) && !getIntendedTypeFromJSDocTypeReference(existing) && !!(symbol.flags & 788968 /* Type */); } } if (isTypeOperatorNode(existing) && existing.operator === 158 /* UniqueKeyword */ && existing.type.kind === 155 /* SymbolKeyword */) { @@ -56536,511 +57287,15 @@ function createTypeChecker(host) { } return true; } - function serializeExistingTypeNode(context, typeNode) { + function serializeExistingTypeNode(context, typeNode, addUndefined) { const type = getTypeFromTypeNode2(context, typeNode); - return typeToTypeNodeHelper(type, context); - } - function tryReuseExistingTypeNodeHelper(context, existing) { - if (cancellationToken && cancellationToken.throwIfCancellationRequested) { - cancellationToken.throwIfCancellationRequested(); - } - let hadError = false; - const { finalizeBoundary, startRecoveryScope } = createRecoveryBoundary(); - const transformed = visitNode(existing, visitExistingNodeTreeSymbols, isTypeNode); - if (!finalizeBoundary()) { - return void 0; - } - context.approximateLength += existing.end - existing.pos; - return transformed; - function visitExistingNodeTreeSymbols(node) { - if (hadError) return node; - const recover = startRecoveryScope(); - const onExitNewScope = isNewScopeNode(node) ? onEnterNewScope(node) : void 0; - const result = visitExistingNodeTreeSymbolsWorker(node); - onExitNewScope == null ? void 0 : onExitNewScope(); - if (hadError) { - if (isTypeNode(node) && !isTypePredicateNode(node)) { - recover(); - return serializeExistingTypeNode(context, node); - } - return node; - } - return result ? setTextRange2(context, result, node) : void 0; - } - function createRecoveryBoundary() { - let trackedSymbols; - let unreportedErrors; - const oldTracker = context.tracker; - const oldTrackedSymbols = context.trackedSymbols; - context.trackedSymbols = void 0; - const oldEncounteredError = context.encounteredError; - context.tracker = new SymbolTrackerImpl(context, { - ...oldTracker.inner, - reportCyclicStructureError() { - markError(() => oldTracker.reportCyclicStructureError()); - }, - reportInaccessibleThisError() { - markError(() => oldTracker.reportInaccessibleThisError()); - }, - reportInaccessibleUniqueSymbolError() { - markError(() => oldTracker.reportInaccessibleUniqueSymbolError()); - }, - reportLikelyUnsafeImportRequiredError(specifier) { - markError(() => oldTracker.reportLikelyUnsafeImportRequiredError(specifier)); - }, - reportNonSerializableProperty(name) { - markError(() => oldTracker.reportNonSerializableProperty(name)); - }, - trackSymbol(sym, decl, meaning) { - (trackedSymbols ?? (trackedSymbols = [])).push([sym, decl, meaning]); - return false; - }, - moduleResolverHost: context.tracker.moduleResolverHost - }, context.tracker.moduleResolverHost); - return { - startRecoveryScope: startRecoveryScope2, - finalizeBoundary: finalizeBoundary2 - }; - function markError(unreportedError) { - hadError = true; - (unreportedErrors ?? (unreportedErrors = [])).push(unreportedError); - } - function startRecoveryScope2() { - const trackedSymbolsTop = (trackedSymbols == null ? void 0 : trackedSymbols.length) ?? 0; - const unreportedErrorsTop = (unreportedErrors == null ? void 0 : unreportedErrors.length) ?? 0; - return () => { - hadError = false; - if (trackedSymbols) { - trackedSymbols.length = trackedSymbolsTop; - } - if (unreportedErrors) { - unreportedErrors.length = unreportedErrorsTop; - } - }; - } - function finalizeBoundary2() { - context.tracker = oldTracker; - context.trackedSymbols = oldTrackedSymbols; - context.encounteredError = oldEncounteredError; - unreportedErrors == null ? void 0 : unreportedErrors.forEach((fn) => fn()); - if (hadError) { - return false; - } - trackedSymbols == null ? void 0 : trackedSymbols.forEach( - ([symbol, enclosingDeclaration, meaning]) => context.tracker.trackSymbol( - symbol, - enclosingDeclaration, - meaning - ) - ); - return true; - } - } - function onEnterNewScope(node) { - return enterNewScope(context, node, getParametersInScope(node), getTypeParametersInScope(node)); - } - function tryVisitSimpleTypeNode(node) { - const innerNode = skipTypeParentheses(node); - switch (innerNode.kind) { - case 183 /* TypeReference */: - return tryVisitTypeReference(innerNode); - case 186 /* TypeQuery */: - return tryVisitTypeQuery(innerNode); - case 199 /* IndexedAccessType */: - return tryVisitIndexedAccess(innerNode); - case 198 /* TypeOperator */: - const typeOperatorNode = innerNode; - if (typeOperatorNode.operator === 143 /* KeyOfKeyword */) { - return tryVisitKeyOf(typeOperatorNode); - } - } - return visitNode(node, visitExistingNodeTreeSymbols, isTypeNode); - } - function tryVisitIndexedAccess(node) { - const resultObjectType = tryVisitSimpleTypeNode(node.objectType); - if (resultObjectType === void 0) { - return void 0; - } - return factory.updateIndexedAccessTypeNode(node, resultObjectType, visitNode(node.indexType, visitExistingNodeTreeSymbols, isTypeNode)); - } - function tryVisitKeyOf(node) { - Debug.assertEqual(node.operator, 143 /* KeyOfKeyword */); - const type = tryVisitSimpleTypeNode(node.type); - if (type === void 0) { - return void 0; - } - return factory.updateTypeOperatorNode(node, type); - } - function tryVisitTypeQuery(node) { - const { introducesError, node: exprName } = trackExistingEntityName(node.exprName, context); - if (!introducesError) { - return factory.updateTypeQueryNode( - node, - exprName, - visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode) - ); - } - const serializedName = serializeTypeName( - context, - node.exprName, - /*isTypeOf*/ - true - ); - if (serializedName) { - return setTextRange2(context, serializedName, node.exprName); - } - } - function tryVisitTypeReference(node) { - if (canReuseTypeNode(context, node)) { - const { introducesError, node: newName } = trackExistingEntityName(node.typeName, context); - const typeArguments = visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode); - if (!introducesError) { - const updated = factory.updateTypeReferenceNode( - node, - newName, - typeArguments - ); - return setTextRange2(context, updated, node); - } else { - const serializedName = serializeTypeName( - context, - node.typeName, - /*isTypeOf*/ - false, - typeArguments - ); - if (serializedName) { - return setTextRange2(context, serializedName, node.typeName); - } - } - } - } - function visitExistingNodeTreeSymbolsWorker(node) { - if (isJSDocTypeExpression(node)) { - return visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode); - } - if (isJSDocAllType(node) || node.kind === 319 /* JSDocNamepathType */) { - return factory.createKeywordTypeNode(133 /* AnyKeyword */); - } - if (isJSDocUnknownType(node)) { - return factory.createKeywordTypeNode(159 /* UnknownKeyword */); - } - if (isJSDocNullableType(node)) { - return factory.createUnionTypeNode([visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode), factory.createLiteralTypeNode(factory.createNull())]); - } - if (isJSDocOptionalType(node)) { - return factory.createUnionTypeNode([visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode), factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); - } - if (isJSDocNonNullableType(node)) { - return visitNode(node.type, visitExistingNodeTreeSymbols); - } - if (isJSDocVariadicType(node)) { - return factory.createArrayTypeNode(visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode)); - } - if (isJSDocTypeLiteral(node)) { - return factory.createTypeLiteralNode(map(node.jsDocPropertyTags, (t) => { - const name = visitNode(isIdentifier(t.name) ? t.name : t.name.right, visitExistingNodeTreeSymbols, isIdentifier); - const typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode2(context, node), name.escapedText); - const overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode2(context, t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : void 0; - return factory.createPropertySignature( - /*modifiers*/ - void 0, - name, - t.isBracketed || t.typeExpression && isJSDocOptionalType(t.typeExpression.type) ? factory.createToken(58 /* QuestionToken */) : void 0, - overrideTypeNode || t.typeExpression && visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */) - ); - })); - } - if (isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "") { - return setOriginalNode(factory.createKeywordTypeNode(133 /* AnyKeyword */), node); - } - if ((isExpressionWithTypeArguments(node) || isTypeReferenceNode(node)) && isJSDocIndexSignature(node)) { - return factory.createTypeLiteralNode([factory.createIndexSignature( - /*modifiers*/ - void 0, - [factory.createParameterDeclaration( - /*modifiers*/ - void 0, - /*dotDotDotToken*/ - void 0, - "x", - /*questionToken*/ - void 0, - visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols, isTypeNode) - )], - visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols, isTypeNode) - )]); - } - if (isJSDocFunctionType(node)) { - if (isJSDocConstructSignature(node)) { - let newTypeNode; - return factory.createConstructorTypeNode( - /*modifiers*/ - void 0, - visitNodes2(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration), - mapDefined(node.parameters, (p, i) => p.name && isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode = p.type, void 0) : factory.createParameterDeclaration( - /*modifiers*/ - void 0, - getEffectiveDotDotDotForParameter(p), - setTextRange2(context, factory.createIdentifier(getNameForJSDocFunctionParameter(p, i)), p), - factory.cloneNode(p.questionToken), - visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), - /*initializer*/ - void 0 - )), - visitNode(newTypeNode || node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */) - ); - } else { - return factory.createFunctionTypeNode( - visitNodes2(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration), - map(node.parameters, (p, i) => factory.createParameterDeclaration( - /*modifiers*/ - void 0, - getEffectiveDotDotDotForParameter(p), - setTextRange2(context, factory.createIdentifier(getNameForJSDocFunctionParameter(p, i)), p), - factory.cloneNode(p.questionToken), - visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), - /*initializer*/ - void 0 - )), - visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */) - ); - } - } - if (isThisTypeNode(node)) { - if (canReuseTypeNode(context, node)) { - return node; - } - hadError = true; - return node; - } - if (isTypeParameterDeclaration(node)) { - return factory.updateTypeParameterDeclaration( - node, - visitNodes2(node.modifiers, visitExistingNodeTreeSymbols, isModifier), - setTextRange2(context, typeParameterToName(getDeclaredTypeOfSymbol(getSymbolOfDeclaration(node)), context), node), - visitNode(node.constraint, visitExistingNodeTreeSymbols, isTypeNode), - visitNode(node.default, visitExistingNodeTreeSymbols, isTypeNode) - ); - } - if (isIndexedAccessTypeNode(node)) { - const result = tryVisitIndexedAccess(node); - if (!result) { - hadError = true; - return node; - } - return result; - } - if (isTypeReferenceNode(node)) { - const result = tryVisitTypeReference(node); - if (result) { - return result; - } - hadError = true; - return node; - } - if (isLiteralImportTypeNode(node)) { - const nodeSymbol = getNodeLinks(node).resolvedSymbol; - if (isInJSDoc(node) && nodeSymbol && // The import type resolved using jsdoc fallback logic - (!node.isTypeOf && !(nodeSymbol.flags & 788968 /* Type */) || // The import type had type arguments autofilled by js fallback logic - !(length(node.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol))))) { - return setTextRange2(context, typeToTypeNodeHelper(getTypeFromTypeNode2(context, node), context), node); - } - return factory.updateImportTypeNode( - node, - factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), - visitNode(node.attributes, visitExistingNodeTreeSymbols, isImportAttributes), - visitNode(node.qualifier, visitExistingNodeTreeSymbols, isEntityName), - visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode), - node.isTypeOf - ); - } - if (isNamedDeclaration(node) && node.name.kind === 167 /* ComputedPropertyName */ && !isLateBindableName(node.name)) { - if (!hasDynamicName(node)) { - return visitEachChild2(node, visitExistingNodeTreeSymbols); - } - if (!(context.internalFlags & 8 /* AllowUnresolvedNames */ && isEntityNameExpression(node.name.expression) && checkComputedPropertyName(node.name).flags & 1 /* Any */)) { - return void 0; - } - } - if (isFunctionLike(node) && !node.type || isPropertyDeclaration(node) && !node.type && !node.initializer || isPropertySignature(node) && !node.type && !node.initializer || isParameter(node) && !node.type && !node.initializer) { - let visited = visitEachChild2(node, visitExistingNodeTreeSymbols); - if (visited === node) { - visited = setTextRange2(context, factory.cloneNode(node), node); - } - visited.type = factory.createKeywordTypeNode(133 /* AnyKeyword */); - if (isParameter(node)) { - visited.modifiers = void 0; - } - return visited; - } - if (isTypeQueryNode(node)) { - const result = tryVisitTypeQuery(node); - if (!result) { - hadError = true; - return node; - } - return result; - } - if (isComputedPropertyName(node) && isEntityNameExpression(node.expression)) { - const { node: result, introducesError } = trackExistingEntityName(node.expression, context); - if (!introducesError) { - return factory.updateComputedPropertyName(node, result); - } else { - const type = getWidenedType(getRegularTypeOfExpression(node.expression)); - const computedPropertyNameType = typeToTypeNodeHelper(type, context); - let literal; - if (isLiteralTypeNode(computedPropertyNameType)) { - literal = computedPropertyNameType.literal; - } else { - const evaluated = evaluateEntityNameExpression(node.expression); - const literalNode = typeof evaluated.value === "string" ? factory.createStringLiteral( - evaluated.value, - /*isSingleQuote*/ - void 0 - ) : typeof evaluated.value === "number" ? factory.createNumericLiteral( - evaluated.value, - /*numericLiteralFlags*/ - 0 - ) : void 0; - if (!literalNode) { - if (isImportTypeNode(computedPropertyNameType)) { - trackComputedName(node.expression, context.enclosingDeclaration, context); - } - return node; - } - literal = literalNode; - } - if (literal.kind === 11 /* StringLiteral */ && isIdentifierText(literal.text, getEmitScriptTarget(compilerOptions))) { - return factory.createIdentifier(literal.text); - } - if (literal.kind === 9 /* NumericLiteral */ && !literal.text.startsWith("-")) { - return literal; - } - return factory.updateComputedPropertyName(node, literal); - } - } - if (isTypePredicateNode(node)) { - let parameterName; - if (isIdentifier(node.parameterName)) { - const { node: result, introducesError } = trackExistingEntityName(node.parameterName, context); - hadError = hadError || introducesError; - parameterName = result; - } else { - parameterName = factory.cloneNode(node.parameterName); - } - return factory.updateTypePredicateNode(node, factory.cloneNode(node.assertsModifier), parameterName, visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode)); - } - if (isTupleTypeNode(node) || isTypeLiteralNode(node) || isMappedTypeNode(node)) { - const visited = visitEachChild2(node, visitExistingNodeTreeSymbols); - const clone2 = setTextRange2(context, visited === node ? factory.cloneNode(node) : visited, node); - const flags = getEmitFlags(clone2); - setEmitFlags(clone2, flags | (context.flags & 1024 /* MultilineObjectLiterals */ && isTypeLiteralNode(node) ? 0 : 1 /* SingleLine */)); - return clone2; - } - if (isStringLiteral(node) && !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */) && !node.singleQuote) { - const clone2 = factory.cloneNode(node); - clone2.singleQuote = true; - return clone2; - } - if (isConditionalTypeNode(node)) { - const checkType = visitNode(node.checkType, visitExistingNodeTreeSymbols, isTypeNode); - const disposeScope = onEnterNewScope(node); - const extendType = visitNode(node.extendsType, visitExistingNodeTreeSymbols, isTypeNode); - const trueType2 = visitNode(node.trueType, visitExistingNodeTreeSymbols, isTypeNode); - disposeScope(); - const falseType2 = visitNode(node.falseType, visitExistingNodeTreeSymbols, isTypeNode); - return factory.updateConditionalTypeNode( - node, - checkType, - extendType, - trueType2, - falseType2 - ); - } - if (isTypeOperatorNode(node)) { - if (node.operator === 158 /* UniqueKeyword */ && node.type.kind === 155 /* SymbolKeyword */) { - if (!canReuseTypeNode(context, node)) { - hadError = true; - return node; - } - } else if (node.operator === 143 /* KeyOfKeyword */) { - const result = tryVisitKeyOf(node); - if (!result) { - hadError = true; - return node; - } - return result; - } - } - return visitEachChild2(node, visitExistingNodeTreeSymbols); - function visitEachChild2(node2, visitor) { - const nonlocalNode = !context.enclosingFile || context.enclosingFile !== getSourceFileOfNode(node2); - return visitEachChild( - node2, - visitor, - /*context*/ - void 0, - nonlocalNode ? visitNodesWithoutCopyingPositions : void 0 - ); - } - function visitNodesWithoutCopyingPositions(nodes, visitor, test, start, count) { - let result = visitNodes2(nodes, visitor, test, start, count); - if (result) { - if (result.pos !== -1 || result.end !== -1) { - if (result === nodes) { - result = factory.createNodeArray(nodes.slice(), nodes.hasTrailingComma); - } - setTextRangePosEnd(result, -1, -1); - } - } - return result; - } - function getEffectiveDotDotDotForParameter(p) { - return p.dotDotDotToken || (p.type && isJSDocVariadicType(p.type) ? factory.createToken(26 /* DotDotDotToken */) : void 0); - } - function getNameForJSDocFunctionParameter(p, index) { - return p.name && isIdentifier(p.name) && p.name.escapedText === "this" ? "this" : getEffectiveDotDotDotForParameter(p) ? `args` : `arg${index}`; - } - function rewriteModuleSpecifier(parent2, lit) { - if (context.bundled || context.enclosingFile !== getSourceFileOfNode(lit)) { - let name = lit.text; - const nodeSymbol = getNodeLinks(node).resolvedSymbol; - const meaning = parent2.isTypeOf ? 111551 /* Value */ : 788968 /* Type */; - const parentSymbol = nodeSymbol && isSymbolAccessible( - nodeSymbol, - context.enclosingDeclaration, - meaning, - /*shouldComputeAliasesToMakeVisible*/ - false - ).accessibility === 0 /* Accessible */ && lookupSymbolChain( - nodeSymbol, - context, - meaning, - /*yieldModuleSymbol*/ - true - )[0]; - if (parentSymbol && isExternalModuleSymbol(parentSymbol)) { - name = getSpecifierForModuleSymbol(parentSymbol, context); - } else { - const targetFile = getExternalModuleFileFromDeclaration(parent2); - if (targetFile) { - name = getSpecifierForModuleSymbol(targetFile.symbol, context); - } - } - if (name.includes("/node_modules/")) { - context.encounteredError = true; - if (context.tracker.reportLikelyUnsafeImportRequiredError) { - context.tracker.reportLikelyUnsafeImportRequiredError(name); - } - } - if (name !== lit.text) { - return setOriginalNode(factory.createStringLiteral(name), lit); - } - } - return visitNode(lit, visitExistingNodeTreeSymbols, isStringLiteral); + if (addUndefined && !someType(type, (t) => !!(t.flags & 32768 /* Undefined */)) && canReuseTypeNode(context, typeNode)) { + const clone2 = syntacticNodeBuilder.tryReuseExistingTypeNode(context, typeNode); + if (clone2) { + return factory.createUnionTypeNode([clone2, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); } } + return typeToTypeNodeHelper(type, context); } function symbolTableToDeclarationStatements(symbolTable, context) { var _a; @@ -57292,7 +57547,9 @@ function createTypeChecker(host) { const skipMembershipCheck = !isPrivate; if (skipMembershipCheck || !!length(symbol.declarations) && some(symbol.declarations, (d) => !!findAncestor(d, (n) => n === enclosingDeclaration))) { const scopeCleanup = cloneNodeBuilderContext(context); + context.tracker.pushErrorFallbackNode(find(symbol.declarations, (d) => getSourceFileOfNode(d) === context.enclosingFile)); serializeSymbolWorker(symbol, isPrivate, propertyAsAlias); + context.tracker.popErrorFallbackNode(); scopeCleanup(); } } @@ -57515,13 +57772,7 @@ function createTypeChecker(host) { context.flags |= 8388608 /* InTypeAlias */; const oldEnclosingDecl = context.enclosingDeclaration; context.enclosingDeclaration = jsdocAliasDecl; - const typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && tryReuseExistingNonParameterTypeNode( - context, - jsdocAliasDecl.typeExpression.type, - aliasType, - /*host*/ - void 0 - ) || typeToTypeNodeHelper(aliasType, context); + const typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression && isJSDocTypeExpression(jsdocAliasDecl.typeExpression) && syntacticNodeBuilder.tryReuseExistingTypeNode(context, jsdocAliasDecl.typeExpression.type) || typeToTypeNodeHelper(aliasType, context); addResult( setSyntheticLeadingComments( factory.createTypeAliasDeclaration( @@ -57754,7 +58005,7 @@ function createTypeChecker(host) { } return cleanup(factory.createExpressionWithTypeArguments( expr, - map(e.typeArguments, (a) => tryReuseExistingNonParameterTypeNode(context, a, getTypeFromTypeNode2(context, a)) || typeToTypeNodeHelper(getTypeFromTypeNode2(context, a), context)) + map(e.typeArguments, (a) => syntacticNodeBuilder.tryReuseExistingTypeNode(context, a) || typeToTypeNodeHelper(getTypeFromTypeNode2(context, a), context)) )); function cleanup(result2) { context.enclosingDeclaration = oldEnclosing; @@ -57950,6 +58201,7 @@ function createTypeChecker(host) { ); break; } + // else fall through and treat commonjs require just like import= case 271 /* ImportEqualsDeclaration */: if (target.escapedName === "export=" /* ExportEquals */ && some(target.declarations, (d) => isSourceFile(d) && isJsonSourceFile(d))) { serializeMaybeAliasAssignment(symbol); @@ -58240,7 +58492,7 @@ function createTypeChecker(host) { } function makeSerializePropertySymbol(createProperty2, methodKind, useAccessors) { return function serializePropertySymbol(p, isStatic2, baseType) { - var _a2, _b, _c, _d, _e; + var _a2, _b, _c, _d, _e, _f; const modifierFlags = getDeclarationModifierFlagsFromSymbol(p); const isPrivate = !!(modifierFlags & 2 /* Private */); if (isStatic2 && p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */)) { @@ -58270,6 +58522,7 @@ function createTypeChecker(host) { }); Debug.assert(!!setter); const paramSymbol = isFunctionLikeDeclaration(setter) ? getSignatureFromDeclaration(setter).parameters[0] : void 0; + const setterDeclaration = (_b = p.declarations) == null ? void 0 : _b.find(isSetAccessor); result.push(setTextRange2( context, factory.createSetAccessorDeclaration( @@ -58283,39 +58536,28 @@ function createTypeChecker(host) { paramSymbol ? parameterToParameterDeclarationName(paramSymbol, getEffectiveParameterDeclaration(paramSymbol), context) : "value", /*questionToken*/ void 0, - isPrivate ? void 0 : serializeTypeForDeclaration( - context, - /*declaration*/ - void 0, - getWriteTypeOfSymbol(p), - p - ) + isPrivate ? void 0 : serializeTypeForDeclaration(context, setterDeclaration, getWriteTypeOfSymbol(p), p) )], /*body*/ void 0 ), - ((_b = p.declarations) == null ? void 0 : _b.find(isSetAccessor)) || firstPropertyLikeDecl + setterDeclaration ?? firstPropertyLikeDecl )); } if (p.flags & 32768 /* GetAccessor */) { const isPrivate2 = modifierFlags & 2 /* Private */; + const getterDeclaration = (_c = p.declarations) == null ? void 0 : _c.find(isGetAccessor); result.push(setTextRange2( context, factory.createGetAccessorDeclaration( factory.createModifiersFromModifierFlags(flag), name, [], - isPrivate2 ? void 0 : serializeTypeForDeclaration( - context, - /*declaration*/ - void 0, - getTypeOfSymbol(p), - p - ), + isPrivate2 ? void 0 : serializeTypeForDeclaration(context, getterDeclaration, getTypeOfSymbol(p), p), /*body*/ void 0 ), - ((_c = p.declarations) == null ? void 0 : _c.find(isGetAccessor)) || firstPropertyLikeDecl + getterDeclaration ?? firstPropertyLikeDecl )); } return result; @@ -58326,19 +58568,13 @@ function createTypeChecker(host) { factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 8 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? factory.createToken(58 /* QuestionToken */) : void 0, - isPrivate ? void 0 : serializeTypeForDeclaration( - context, - /*declaration*/ - void 0, - getWriteTypeOfSymbol(p), - p - ), + isPrivate ? void 0 : serializeTypeForDeclaration(context, (_d = p.declarations) == null ? void 0 : _d.find(isSetAccessorDeclaration), getWriteTypeOfSymbol(p), p), // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357 // interface members can't have initializers, however class members _can_ /*initializer*/ void 0 ), - ((_d = p.declarations) == null ? void 0 : _d.find(or(isPropertyDeclaration, isVariableDeclaration))) || firstPropertyLikeDecl + ((_e = p.declarations) == null ? void 0 : _e.find(or(isPropertyDeclaration, isVariableDeclaration))) || firstPropertyLikeDecl ); } if (p.flags & (8192 /* Method */ | 16 /* Function */)) { @@ -58356,7 +58592,7 @@ function createTypeChecker(host) { /*initializer*/ void 0 ), - ((_e = p.declarations) == null ? void 0 : _e.find(isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0] + ((_f = p.declarations) == null ? void 0 : _f.find(isFunctionLikeDeclaration)) || signatures[0] && signatures[0].declaration || p.declarations && p.declarations[0] ); } const results2 = []; @@ -58399,7 +58635,7 @@ function createTypeChecker(host) { return []; } if (baseSigs.length === signatures.length) { - let failed = false; + let failed2 = false; for (let i = 0; i < baseSigs.length; i++) { if (!compareSignaturesIdentical( signatures[i], @@ -58412,11 +58648,11 @@ function createTypeChecker(host) { true, compareTypesIdentical )) { - failed = true; + failed2 = true; break; } } - if (!failed) { + if (!failed2) { return []; } } @@ -58722,6 +58958,7 @@ function createTypeChecker(host) { if (isBindingPattern(node.name) && !node.name.elements.length) { return false; } + // falls through case 267 /* ModuleDeclaration */: case 263 /* ClassDeclaration */: case 264 /* InterfaceDeclaration */: @@ -58746,6 +58983,8 @@ function createTypeChecker(host) { if (hasEffectiveModifier(node, 2 /* Private */ | 4 /* Protected */)) { return false; } + // Public properties/methods are visible if its parents are visible, so: + // falls through case 176 /* Constructor */: case 180 /* ConstructSignature */: case 179 /* CallSignature */: @@ -58763,14 +59002,20 @@ function createTypeChecker(host) { case 196 /* ParenthesizedType */: case 202 /* NamedTupleMember */: return isDeclarationVisible(node.parent); + // Default binding, import specifier and namespace import is visible + // only on demand so by default it is not visible case 273 /* ImportClause */: case 274 /* NamespaceImport */: case 276 /* ImportSpecifier */: return false; + // Type parameters are always visible case 168 /* TypeParameter */: + // Source file and namespace export are always visible + // falls through case 307 /* SourceFile */: case 270 /* NamespaceExportDeclaration */: return true; + // Export assignments do not create name bindings outside the module case 277 /* ExportAssignment */: return false; default: @@ -59580,7 +59825,7 @@ function createTypeChecker(host) { /*reportErrors*/ false ) : unknownType; - return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, 0 /* Normal */, contextualType))); + return addOptionality(getWidenedLiteralTypeForInitializer(element, checkDeclarationInitializer(element, 0 /* Normal */, contextualType))); } if (isBindingPattern(element.name)) { return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors2); @@ -59614,7 +59859,6 @@ function createTypeChecker(host) { const flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0); const symbol = createSymbol(flags, text); symbol.links.type = getTypeFromBindingElement(e, includePatternInType, reportErrors2); - symbol.links.bindingElement = e; members.set(symbol.escapedName, symbol); }); const result = createAnonymousType( @@ -59859,7 +60103,7 @@ function createTypeChecker(host) { const getter = getDeclarationOfKind(symbol, 177 /* GetAccessor */); const setter = getDeclarationOfKind(symbol, 178 /* SetAccessor */); const accessor = tryCast(getDeclarationOfKind(symbol, 172 /* PropertyDeclaration */), isAutoAccessorPropertyDeclaration); - let type = getter && isInJSFile(getter) && getTypeForDeclarationFromJSDocComment(getter) || getAnnotatedAccessorType(getter) || getAnnotatedAccessorType(setter) || getAnnotatedAccessorType(accessor) || getter && getter.body && getReturnTypeFromBody(getter) || accessor && accessor.initializer && getWidenedTypeForVariableLikeDeclaration( + let type = getter && isInJSFile(getter) && getTypeForDeclarationFromJSDocComment(getter) || getAnnotatedAccessorType(getter) || getAnnotatedAccessorType(setter) || getAnnotatedAccessorType(accessor) || getter && getter.body && getReturnTypeFromBody(getter) || accessor && getWidenedTypeForVariableLikeDeclaration( accessor, /*reportErrors*/ true @@ -60715,11 +60959,20 @@ function createTypeChecker(host) { return type; } function isLateBindableName(node) { + return isLateBindableAST(node) && isTypeUsableAsPropertyName(isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(node.argumentExpression)); + } + function isLateBindableIndexSignature(node) { + return isLateBindableAST(node) && isTypeUsableAsIndexSignature(isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(node.argumentExpression)); + } + function isLateBindableAST(node) { if (!isComputedPropertyName(node) && !isElementAccessExpression(node)) { return false; } const expr = isComputedPropertyName(node) ? node.expression : node.argumentExpression; - return isEntityNameExpression(expr) && isTypeUsableAsPropertyName(isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(expr)); + return isEntityNameExpression(expr); + } + function isTypeUsableAsIndexSignature(type) { + return isTypeAssignableTo(type, stringNumberSymbolType); } function isLateBoundName(name) { return name.charCodeAt(0) === 95 /* _ */ && name.charCodeAt(1) === 95 /* _ */ && name.charCodeAt(2) === 64 /* at */; @@ -60728,6 +60981,10 @@ function createTypeChecker(host) { const name = getNameOfDeclaration(node); return !!name && isLateBindableName(name); } + function hasLateBindableIndexSignature(node) { + const name = getNameOfDeclaration(node); + return !!name && isLateBindableIndexSignature(name); + } function hasBindableName(node) { return !hasDynamicName(node) || hasLateBindableName(node); } @@ -60781,6 +61038,24 @@ function createTypeChecker(host) { } return links.resolvedSymbol; } + function lateBindIndexSignature(parent2, earlySymbols, lateSymbols, decl) { + let indexSymbol = lateSymbols.get("__index" /* Index */); + if (!indexSymbol) { + const early = earlySymbols == null ? void 0 : earlySymbols.get("__index" /* Index */); + if (!early) { + indexSymbol = createSymbol(0 /* None */, "__index" /* Index */, 4096 /* Late */); + } else { + indexSymbol = cloneSymbol(early); + indexSymbol.links.checkFlags |= 4096 /* Late */; + } + lateSymbols.set("__index" /* Index */, indexSymbol); + } + if (!indexSymbol.declarations) { + indexSymbol.declarations = [decl]; + } else if (!decl.symbol.isReplaceableByMethod) { + indexSymbol.declarations.push(decl); + } + } function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) { const links = getSymbolLinks(symbol); if (!links[resolutionKind]) { @@ -60795,6 +61070,8 @@ function createTypeChecker(host) { if (isStatic2 === hasStaticModifier(member)) { if (hasLateBindableName(member)) { lateBindMember(symbol, earlySymbols, lateSymbols, member); + } else if (hasLateBindableIndexSignature(member)) { + lateBindIndexSignature(symbol, earlySymbols, lateSymbols, member); } } } @@ -60925,7 +61202,7 @@ function createTypeChecker(host) { resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments); } function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) { - const sig = new Signature14(checker, flags); + const sig = new Signature13(checker, flags); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -61252,8 +61529,13 @@ function createTypeChecker(host) { if (left.typeParameters && right.typeParameters) { paramMapper = createTypeMapper(right.typeParameters, left.typeParameters); } + let flags = (left.flags | right.flags) & (167 /* PropagatingFlags */ & ~1 /* HasRestParameter */); const declaration = left.declaration; const params = combineUnionParameters(left, right, paramMapper); + const lastParam = lastOrUndefined(params); + if (lastParam && getCheckFlags(lastParam) & 32768 /* RestParameter */) { + flags |= 1 /* HasRestParameter */; + } const thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter, paramMapper); const minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); const result = createSignature( @@ -61266,7 +61548,7 @@ function createTypeChecker(host) { /*resolvedTypePredicate*/ void 0, minArgCount, - (left.flags | right.flags) & 167 /* PropagatingFlags */ + flags ); result.compositeKind = 1048576 /* Union */; result.compositeSignatures = concatenate(left.compositeKind !== 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); @@ -61439,7 +61721,7 @@ function createTypeChecker(host) { } const indexSymbol = getIndexSymbolFromSymbolTable(members); if (indexSymbol) { - indexInfos = getIndexInfosOfIndexSymbol(indexSymbol); + indexInfos = getIndexInfosOfIndexSymbol(indexSymbol, arrayFrom(members.values())); } else { if (baseConstructorIndexInfo) { indexInfos = append(indexInfos, baseConstructorIndexInfo); @@ -63058,7 +63340,7 @@ function createTypeChecker(host) { return signature.isolatedSignatureType; } function getIndexSymbol(symbol) { - return symbol.members ? getIndexSymbolFromSymbolTable(symbol.members) : void 0; + return symbol.members ? getIndexSymbolFromSymbolTable(getMembersOfSymbol(symbol)) : void 0; } function getIndexSymbolFromSymbolTable(symbolTable) { return symbolTable.get("__index" /* Index */); @@ -63068,23 +63350,61 @@ function createTypeChecker(host) { } function getIndexInfosOfSymbol(symbol) { const indexSymbol = getIndexSymbol(symbol); - return indexSymbol ? getIndexInfosOfIndexSymbol(indexSymbol) : emptyArray; + return indexSymbol ? getIndexInfosOfIndexSymbol(indexSymbol, arrayFrom(getMembersOfSymbol(symbol).values())) : emptyArray; } - function getIndexInfosOfIndexSymbol(indexSymbol) { + function getIndexInfosOfIndexSymbol(indexSymbol, siblingSymbols = indexSymbol.parent ? arrayFrom(getMembersOfSymbol(indexSymbol.parent).values()) : void 0) { if (indexSymbol.declarations) { const indexInfos = []; + let hasComputedNumberProperty = false; + let readonlyComputedNumberProperty = true; + let hasComputedSymbolProperty = false; + let readonlyComputedSymbolProperty = true; + let hasComputedStringProperty = false; + let readonlyComputedStringProperty = true; + const computedPropertySymbols = []; for (const declaration of indexSymbol.declarations) { - if (declaration.parameters.length === 1) { - const parameter = declaration.parameters[0]; - if (parameter.type) { - forEachType(getTypeFromTypeNode(parameter.type), (keyType) => { - if (isValidIndexKeyType(keyType) && !findIndexInfo(indexInfos, keyType)) { - indexInfos.push(createIndexInfo(keyType, declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, hasEffectiveModifier(declaration, 8 /* Readonly */), declaration)); + if (isIndexSignatureDeclaration(declaration)) { + if (declaration.parameters.length === 1) { + const parameter = declaration.parameters[0]; + if (parameter.type) { + forEachType(getTypeFromTypeNode(parameter.type), (keyType) => { + if (isValidIndexKeyType(keyType) && !findIndexInfo(indexInfos, keyType)) { + indexInfos.push(createIndexInfo(keyType, declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, hasEffectiveModifier(declaration, 8 /* Readonly */), declaration)); + } + }); + } + } + } else if (hasLateBindableIndexSignature(declaration)) { + const declName = isBinaryExpression(declaration) ? declaration.left : declaration.name; + const keyType = isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName); + if (findIndexInfo(indexInfos, keyType)) { + continue; + } + if (isTypeAssignableTo(keyType, stringNumberSymbolType)) { + if (isTypeAssignableTo(keyType, numberType)) { + hasComputedNumberProperty = true; + if (!hasEffectiveReadonlyModifier(declaration)) { + readonlyComputedNumberProperty = false; } - }); + } else if (isTypeAssignableTo(keyType, esSymbolType)) { + hasComputedSymbolProperty = true; + if (!hasEffectiveReadonlyModifier(declaration)) { + readonlyComputedSymbolProperty = false; + } + } else { + hasComputedStringProperty = true; + if (!hasEffectiveReadonlyModifier(declaration)) { + readonlyComputedStringProperty = false; + } + } + computedPropertySymbols.push(declaration.symbol); } } } + const allPropertySymbols = concatenate(computedPropertySymbols, filter(siblingSymbols, (s) => s !== indexSymbol)); + if (hasComputedStringProperty && !findIndexInfo(indexInfos, stringType)) indexInfos.push(getObjectLiteralIndexInfo(readonlyComputedStringProperty, 0, allPropertySymbols, stringType)); + if (hasComputedNumberProperty && !findIndexInfo(indexInfos, numberType)) indexInfos.push(getObjectLiteralIndexInfo(readonlyComputedNumberProperty, 0, allPropertySymbols, numberType)); + if (hasComputedSymbolProperty && !findIndexInfo(indexInfos, esSymbolType)) indexInfos.push(getObjectLiteralIndexInfo(readonlyComputedSymbolProperty, 0, allPropertySymbols, esSymbolType)); return indexInfos; } return emptyArray; @@ -65928,7 +66248,7 @@ function createTypeChecker(host) { const links = getNodeLinks(node); if (!links.resolvedType) { const aliasSymbol = getAliasSymbolForTypeNode(node); - if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) { + if (!node.symbol || getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) { links.resolvedType = emptyTypeLiteralType; } else { let type = createObjectType(16 /* Anonymous */, node.symbol); @@ -66320,6 +66640,9 @@ function createTypeChecker(host) { return getTypeFromTemplateTypeNode(node); case 205 /* ImportType */: return getTypeFromImportTypeNode(node); + // This function assumes that an identifier, qualified name, or property access expression is a type expression + // Callers should first ensure this by calling `isPartOfTypeNode` + // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s. case 80 /* Identifier */: case 166 /* QualifiedName */: case 211 /* PropertyAccessExpression */: @@ -66567,6 +66890,7 @@ function createTypeChecker(host) { return !!tp.isThisType; case 80 /* Identifier */: return !tp.isThisType && isPartOfTypeNode(node2) && maybeTypeParameterReference(node2) && getTypeFromTypeNodeWorker(node2) === tp; + // use worker because we're looking for === equality case 186 /* TypeQuery */: const entityName = node2.exprName; const firstIdentifier = getFirstIdentifier(entityName); @@ -66986,6 +67310,7 @@ function createTypeChecker(host) { if (!isConstAssertion(node)) { break; } + // fallthrough case 294 /* JsxExpression */: case 217 /* ParenthesizedExpression */: return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer); @@ -68081,7 +68406,7 @@ function createTypeChecker(host) { const [sourceType, targetType] = getTypeNamesForErrorDisplay(source2, target2); let generalizedSource = source2; let generalizedSourceType = sourceType; - if (isLiteralType(source2) && !typeCouldHaveTopLevelSingletonTypes(target2)) { + if (!(target2.flags & 131072 /* Never */) && isLiteralType(source2) && !typeCouldHaveTopLevelSingletonTypes(target2)) { generalizedSource = getBaseTypeOfLiteralType(source2); Debug.assert(!isTypeAssignableTo(generalizedSource, target2), "generalized source shouldn't be assignable"); generalizedSourceType = getTypeNameForErrorDisplay(generalizedSource); @@ -71113,7 +71438,7 @@ function createTypeChecker(host) { case 219 /* ArrowFunction */: if (noImplicitAny && !declaration.name) { if (wideningKind === 3 /* GeneratorYield */) { - error2(declaration, Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString); + error2(declaration, Diagnostics.Generator_implicitly_has_yield_type_0_Consider_supplying_a_return_type_annotation, typeAsString); } else { error2(declaration, Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); } @@ -71131,11 +71456,37 @@ function createTypeChecker(host) { } errorOrSuggestion(noImplicitAny, declaration, diagnostic, declarationNameToString(getNameOfDeclaration(declaration)), typeAsString); } + function shouldReportErrorsFromWideningWithContextualSignature(declaration, wideningKind) { + const signature = getContextualSignatureForFunctionLikeDeclaration(declaration); + if (!signature) { + return true; + } + let returnType = getReturnTypeOfSignature(signature); + const flags = getFunctionFlags(declaration); + switch (wideningKind) { + case 1 /* FunctionReturn */: + if (flags & 1 /* Generator */) { + returnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, !!(flags & 2 /* Async */)) ?? returnType; + } else if (flags & 2 /* Async */) { + returnType = getAwaitedTypeNoAlias(returnType) ?? returnType; + } + return isGenericType(returnType); + case 3 /* GeneratorYield */: + const yieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, !!(flags & 2 /* Async */)); + return !!yieldType && isGenericType(yieldType); + case 2 /* GeneratorNext */: + const nextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, !!(flags & 2 /* Async */)); + return !!nextType && isGenericType(nextType); + } + return false; + } function reportErrorsFromWidening(declaration, type, wideningKind) { addLazyDiagnostic(() => { - if (noImplicitAny && getObjectFlags(type) & 65536 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) { - if (!reportWideningErrorsInType(type)) { - reportImplicitAny(declaration, type, wideningKind); + if (noImplicitAny && getObjectFlags(type) & 65536 /* ContainsWideningType */) { + if (!wideningKind || isFunctionLikeDeclaration(declaration) && shouldReportErrorsFromWideningWithContextualSignature(declaration, wideningKind)) { + if (!reportWideningErrorsInType(type)) { + reportImplicitAny(declaration, type, wideningKind); + } } } }); @@ -72305,6 +72656,7 @@ function createTypeChecker(host) { if (isCallExpression(node.parent)) { return Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function; } + // falls through default: if (node.parent.kind === 304 /* ShorthandPropertyAssignment */) { return Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer; @@ -72338,6 +72690,7 @@ function createTypeChecker(host) { const symbol = getResolvedSymbol(node); return symbol !== unknownSymbol ? `${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}|${getSymbolId(symbol)}` : void 0; } + // falls through case 110 /* ThisKeyword */: return `0|${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}`; case 235 /* NonNullExpression */: @@ -73891,6 +74244,9 @@ function createTypeChecker(host) { break; case 28 /* CommaToken */: return narrowType(type, expr.right, assumeTrue); + // Ordinarily we won't see && and || expressions in control flow analysis because the Binder breaks those + // expressions down to individual conditional control flows. However, we may encounter them when analyzing + // aliased conditional expressions. case 56 /* AmpersandAmpersandToken */: return assumeTrue ? narrowType( narrowType( @@ -74334,6 +74690,7 @@ function createTypeChecker(host) { } } } + // falls through case 110 /* ThisKeyword */: case 108 /* SuperKeyword */: case 211 /* PropertyAccessExpression */: @@ -74394,6 +74751,12 @@ function createTypeChecker(host) { function getControlFlowContainer(node) { return findAncestor(node.parent, (node2) => isFunctionLike(node2) && !getImmediatelyInvokedFunctionExpression(node2) || node2.kind === 268 /* ModuleBlock */ || node2.kind === 307 /* SourceFile */ || node2.kind === 172 /* PropertyDeclaration */); } + function isSymbolAssignedDefinitely(symbol) { + if (symbol.lastAssignmentPos !== void 0) { + return symbol.lastAssignmentPos < 0; + } + return isSymbolAssigned(symbol) && symbol.lastAssignmentPos !== void 0 && symbol.lastAssignmentPos < 0; + } function isSymbolAssigned(symbol) { return !isPastLastAssignment( symbol, @@ -74413,7 +74776,7 @@ function createTypeChecker(host) { markNodeAssignments(parent2); } } - return !symbol.lastAssignmentPos || location && symbol.lastAssignmentPos < location.pos; + return !symbol.lastAssignmentPos || location && Math.abs(symbol.lastAssignmentPos) < location.pos; } function isSomeSymbolAssigned(rootDeclaration) { Debug.assert(isVariableDeclaration(rootDeclaration) || isParameter(rootDeclaration)); @@ -74434,12 +74797,19 @@ function createTypeChecker(host) { function markNodeAssignments(node) { switch (node.kind) { case 80 /* Identifier */: - if (isAssignmentTarget(node)) { + const assigmentTarget = getAssignmentTargetKind(node); + if (assigmentTarget !== 0 /* None */) { const symbol = getResolvedSymbol(node); - if (isParameterOrMutableLocalVariable(symbol) && symbol.lastAssignmentPos !== Number.MAX_VALUE) { - const referencingFunction = findAncestor(node, isFunctionOrSourceFile); - const declaringFunction = findAncestor(symbol.valueDeclaration, isFunctionOrSourceFile); - symbol.lastAssignmentPos = referencingFunction === declaringFunction ? extendAssignmentPosition(node, symbol.valueDeclaration) : Number.MAX_VALUE; + const hasDefiniteAssignment = assigmentTarget === 1 /* Definite */ || symbol.lastAssignmentPos !== void 0 && symbol.lastAssignmentPos < 0; + if (isParameterOrMutableLocalVariable(symbol)) { + if (symbol.lastAssignmentPos === void 0 || Math.abs(symbol.lastAssignmentPos) !== Number.MAX_VALUE) { + const referencingFunction = findAncestor(node, isFunctionOrSourceFile); + const declaringFunction = findAncestor(symbol.valueDeclaration, isFunctionOrSourceFile); + symbol.lastAssignmentPos = referencingFunction === declaringFunction ? extendAssignmentPosition(node, symbol.valueDeclaration) : Number.MAX_VALUE; + } + if (hasDefiniteAssignment && symbol.lastAssignmentPos > 0) { + symbol.lastAssignmentPos *= -1; + } } } return; @@ -74456,7 +74826,8 @@ function createTypeChecker(host) { true ); if (symbol && isParameterOrMutableLocalVariable(symbol)) { - symbol.lastAssignmentPos = Number.MAX_VALUE; + const sign = symbol.lastAssignmentPos !== void 0 && symbol.lastAssignmentPos < 0 ? -1 : 1; + symbol.lastAssignmentPos = sign * Number.MAX_VALUE; } } return; @@ -74689,7 +75060,7 @@ function createTypeChecker(host) { } function markJsxAliasReferenced(node) { if (!getJsxNamespaceContainerForImplicitImport(node)) { - const jsxFactoryRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? Diagnostics.Cannot_find_name_0 : void 0; + const jsxFactoryRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? Diagnostics.This_JSX_tag_requires_0_to_be_in_scope_but_it_could_not_be_found : void 0; const jsxFactoryNamespace = getJsxNamespace(node); const jsxFactoryLocation = isJsxOpeningLikeElement(node) ? node.tagName : node; let jsxFactorySym; @@ -74697,7 +75068,7 @@ function createTypeChecker(host) { jsxFactorySym = resolveName( jsxFactoryLocation, jsxFactoryNamespace, - 111551 /* Value */, + compilerOptions.jsx === 1 /* Preserve */ ? 111551 /* Value */ & ~384 /* Enum */ : 111551 /* Value */, jsxFactoryRefErr, /*isUse*/ true @@ -74716,7 +75087,7 @@ function createTypeChecker(host) { resolveName( jsxFactoryLocation, localJsxNamespace, - 111551 /* Value */, + compilerOptions.jsx === 1 /* Preserve */ ? 111551 /* Value */ & ~384 /* Enum */ : 111551 /* Value */, jsxFactoryRefErr, /*isUse*/ true @@ -75040,6 +75411,7 @@ function createTypeChecker(host) { } const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol); let declaration = localOrExportSymbol.valueDeclaration; + const immediateDeclaration = declaration; if (declaration && declaration.kind === 208 /* BindingElement */ && contains(contextualBindingPatterns, declaration.parent) && findAncestor(node, (parent2) => parent2 === declaration.parent)) { return nonInferrableAnyType; } @@ -75085,7 +75457,8 @@ function createTypeChecker(host) { while (flowContainer !== declarationContainer && (flowContainer.kind === 218 /* FunctionExpression */ || flowContainer.kind === 219 /* ArrowFunction */ || isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) && (isConstantVariable(localOrExportSymbol) && type !== autoArrayType || isParameterOrMutableLocalVariable(localOrExportSymbol) && isPastLastAssignment(localOrExportSymbol, node))) { flowContainer = getControlFlowContainer(flowContainer); } - const assumeInitialized = isParameter2 || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === 281 /* ExportSpecifier */) || node.parent.kind === 235 /* NonNullExpression */ || declaration.kind === 260 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 33554432 /* Ambient */; + const isNeverInitialized = immediateDeclaration && isVariableDeclaration(immediateDeclaration) && !immediateDeclaration.initializer && !immediateDeclaration.exclamationToken && isMutableLocalVariableDeclaration(immediateDeclaration) && !isSymbolAssignedDefinitely(symbol); + const assumeInitialized = isParameter2 || isAlias || isOuterVariable && !isNeverInitialized || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === 281 /* ExportSpecifier */) || node.parent.kind === 235 /* NonNullExpression */ || declaration.kind === 260 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 33554432 /* Ambient */; const initialType = isAutomaticTypeInNonNull ? undefinedType : assumeInitialized ? isParameter2 ? removeOptionalityFromDeclaredType(type, declaration) : type : typeIsAutomatic ? undefinedType : getOptionalType(type); const flowType = isAutomaticTypeInNonNull ? getNonNullableType(getFlowTypeOfReference(node, type, initialType, flowContainer)) : getFlowTypeOfReference(node, type, initialType, flowContainer); if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) { @@ -75990,46 +76363,108 @@ function createTypeChecker(host) { function isCircularMappedProperty(symbol) { return !!(getCheckFlags(symbol) & 262144 /* Mapped */ && !symbol.links.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0); } + function isExcludedMappedPropertyName(constraint, propertyNameType) { + if (constraint.flags & 16777216 /* Conditional */) { + const type = constraint; + return !!(getReducedType(getTrueTypeFromConditionalType(type)).flags & 131072 /* Never */) && getActualTypeVariable(getFalseTypeFromConditionalType(type)) === getActualTypeVariable(type.checkType) && isTypeAssignableTo(propertyNameType, type.extendsType); + } + if (constraint.flags & 2097152 /* Intersection */) { + return some(constraint.types, (t) => isExcludedMappedPropertyName(t, propertyNameType)); + } + return false; + } function getTypeOfPropertyOfContextualType(type, name, nameType) { return mapType( type, (t) => { - var _a; - if (isGenericMappedType(t) && getMappedTypeNameTypeKind(t) !== 2 /* Remapping */) { - const constraint = getConstraintTypeFromMappedType(t); - const constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint; - const propertyNameType = nameType || getStringLiteralType(unescapeLeadingUnderscores(name)); - if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) { - return substituteIndexedMappedType(t, propertyNameType); - } - } else if (t.flags & 3670016 /* StructuredType */) { - const prop = getPropertyOfType(t, name); - if (prop) { - return isCircularMappedProperty(prop) ? void 0 : removeMissingType(getTypeOfSymbol(prop), !!(prop.flags & 16777216 /* Optional */)); + if (t.flags & 2097152 /* Intersection */) { + let types; + let indexInfoCandidates; + let ignoreIndexInfos = false; + for (const constituentType of t.types) { + if (!(constituentType.flags & 524288 /* Object */)) { + continue; + } + if (isGenericMappedType(constituentType) && getMappedTypeNameTypeKind(constituentType) !== 2 /* Remapping */) { + const substitutedType = getIndexedMappedTypeSubstitutedTypeOfContextualType(constituentType, name, nameType); + types = appendContextualPropertyTypeConstituent(types, substitutedType); + continue; + } + const propertyType = getTypeOfConcretePropertyOfContextualType(constituentType, name); + if (!propertyType) { + if (!ignoreIndexInfos) { + indexInfoCandidates = append(indexInfoCandidates, constituentType); + } + continue; + } + ignoreIndexInfos = true; + indexInfoCandidates = void 0; + types = appendContextualPropertyTypeConstituent(types, propertyType); } - if (isTupleType(t) && isNumericLiteralName(name) && +name >= 0) { - const restType = getElementTypeOfSliceOfTupleType( - t, - t.target.fixedLength, - /*endSkipCount*/ - 0, - /*writing*/ - false, - /*noReductions*/ - true - ); - if (restType) { - return restType; + if (indexInfoCandidates) { + for (const candidate of indexInfoCandidates) { + const indexInfoType = getTypeFromIndexInfosOfContextualType(candidate, name, nameType); + types = appendContextualPropertyTypeConstituent(types, indexInfoType); } } - return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), nameType || getStringLiteralType(unescapeLeadingUnderscores(name)))) == null ? void 0 : _a.type; + if (!types) { + return; + } + if (types.length === 1) { + return types[0]; + } + return getIntersectionType(types); } - return void 0; + if (!(t.flags & 524288 /* Object */)) { + return; + } + return isGenericMappedType(t) && getMappedTypeNameTypeKind(t) !== 2 /* Remapping */ ? getIndexedMappedTypeSubstitutedTypeOfContextualType(t, name, nameType) : getTypeOfConcretePropertyOfContextualType(t, name) ?? getTypeFromIndexInfosOfContextualType(t, name, nameType); }, /*noReductions*/ true ); } + function appendContextualPropertyTypeConstituent(types, type) { + return type ? append(types, type.flags & 1 /* Any */ ? unknownType : type) : types; + } + function getIndexedMappedTypeSubstitutedTypeOfContextualType(type, name, nameType) { + const propertyNameType = nameType || getStringLiteralType(unescapeLeadingUnderscores(name)); + const constraint = getConstraintTypeFromMappedType(type); + if (type.nameType && isExcludedMappedPropertyName(type.nameType, propertyNameType) || isExcludedMappedPropertyName(constraint, propertyNameType)) { + return; + } + const constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint; + if (!isTypeAssignableTo(propertyNameType, constraintOfConstraint)) { + return; + } + return substituteIndexedMappedType(type, propertyNameType); + } + function getTypeOfConcretePropertyOfContextualType(type, name) { + const prop = getPropertyOfType(type, name); + if (!prop || isCircularMappedProperty(prop)) { + return; + } + return removeMissingType(getTypeOfSymbol(prop), !!(prop.flags & 16777216 /* Optional */)); + } + function getTypeFromIndexInfosOfContextualType(type, name, nameType) { + var _a; + if (isTupleType(type) && isNumericLiteralName(name) && +name >= 0) { + const restType = getElementTypeOfSliceOfTupleType( + type, + type.target.fixedLength, + /*endSkipCount*/ + 0, + /*writing*/ + false, + /*noReductions*/ + true + ); + if (restType) { + return restType; + } + } + return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(type), nameType || getStringLiteralType(unescapeLeadingUnderscores(name)))) == null ? void 0 : _a.type; + } function getContextualTypeForObjectLiteralMethod(node, contextFlags) { Debug.assert(isObjectLiteralMethod(node)); if (node.flags & 67108864 /* InWithStatement */) { @@ -76442,7 +76877,7 @@ function createTypeChecker(host) { return getContextualTypeForArgumentAtIndex(node, 0); } function getEffectiveFirstArgumentForJsxSignature(signature, node) { - return getJsxReferenceKind(node) !== 0 /* Component */ ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); + return isJsxOpeningFragment(node) || getJsxReferenceKind(node) !== 0 /* Component */ ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node); } function getJsxPropsTypeFromCallSignature(sig, context) { let propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType); @@ -76473,6 +76908,7 @@ function createTypeChecker(host) { return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } function getStaticTypeOfReferencedJsxConstructor(context) { + if (isJsxOpeningFragment(context)) return getJSXFragmentType(context); if (isJsxIntrinsicTagName(context.tagName)) { const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context); const fakeSignature = createSignatureForJSXIntrinsic(context, result); @@ -76572,13 +77008,14 @@ function createTypeChecker(host) { const paramName = leftName === rightName ? leftName : !leftName ? rightName : !rightName ? leftName : void 0; const paramSymbol = createSymbol( 1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), - paramName || `arg${i}` + paramName || `arg${i}`, + isRestParam ? 32768 /* RestParameter */ : isOptional ? 16384 /* OptionalParameter */ : 0 ); paramSymbol.links.type = isRestParam ? createArrayType(unionParamType) : unionParamType; params[i] = paramSymbol; } if (needsExtraRestElement) { - const restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args"); + const restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args", 32768 /* RestParameter */); restParamSymbol.links.type = createArrayType(getTypeAtPosition(shorter, longestCount)); if (shorter === right) { restParamSymbol.links.type = instantiateType(restParamSymbol.links.type, mapper); @@ -76593,8 +77030,13 @@ function createTypeChecker(host) { if (left.typeParameters && right.typeParameters) { paramMapper = createTypeMapper(right.typeParameters, left.typeParameters); } + let flags = (left.flags | right.flags) & (167 /* PropagatingFlags */ & ~1 /* HasRestParameter */); const declaration = left.declaration; const params = combineIntersectionParameters(left, right, paramMapper); + const lastParam = lastOrUndefined(params); + if (lastParam && getCheckFlags(lastParam) & 32768 /* RestParameter */) { + flags |= 1 /* HasRestParameter */; + } const thisParam = combineIntersectionThisParam(left.thisParameter, right.thisParameter, paramMapper); const minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); const result = createSignature( @@ -76607,7 +77049,7 @@ function createTypeChecker(host) { /*resolvedTypePredicate*/ void 0, minArgCount, - (left.flags | right.flags) & 167 /* PropagatingFlags */ + flags ); result.compositeKind = 2097152 /* Intersection */; result.compositeSignatures = concatenate(left.compositeKind === 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]); @@ -76726,7 +77168,7 @@ function createTypeChecker(host) { return globalRegExpType; } function checkSpreadExpression(node, checkMode) { - if (languageVersion < 2 /* SpreadElements */) { + if (languageVersion < LanguageFeatureMinimumTarget.SpreadElements) { checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */); } const arrayOrIterableType = checkExpression(node.expression, checkMode); @@ -76760,7 +77202,7 @@ function createTypeChecker(host) { for (let i = 0; i < elementCount; i++) { const e = elements[i]; if (e.kind === 230 /* SpreadElement */) { - if (languageVersion < 2 /* SpreadElements */) { + if (languageVersion < LanguageFeatureMinimumTarget.SpreadElements) { checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */); } const spreadType = checkExpression(e.expression, checkMode, forceTuple); @@ -76879,7 +77321,7 @@ function createTypeChecker(host) { const firstDecl = (_a = symbol.declarations) == null ? void 0 : _a[0]; return isKnownSymbol(symbol) || firstDecl && isNamedDeclaration(firstDecl) && isComputedPropertyName(firstDecl.name) && isTypeAssignableToKind(checkComputedPropertyName(firstDecl.name), 4096 /* ESSymbol */); } - function getObjectLiteralIndexInfo(node, offset, properties, keyType) { + function getObjectLiteralIndexInfo(isReadonly, offset, properties, keyType) { const propTypes = []; for (let i = offset; i < properties.length; i++) { const prop = properties[i]; @@ -76888,7 +77330,7 @@ function createTypeChecker(host) { } } const unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType; - return createIndexInfo(keyType, unionType, isConstContext(node)); + return createIndexInfo(keyType, unionType, isReadonly); } function getImmediateAliasedSymbol(symbol) { Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here."); @@ -76985,7 +77427,7 @@ function createTypeChecker(host) { addIntraExpressionInferenceSite(inferenceContext, inferenceNode, type); } } else if (memberDecl.kind === 305 /* SpreadAssignment */) { - if (languageVersion < 2 /* ObjectAssign */) { + if (languageVersion < LanguageFeatureMinimumTarget.ObjectAssign) { checkExternalEmitHelpers(memberDecl, 2 /* Assign */); } if (propertiesArray.length > 0) { @@ -77051,9 +77493,10 @@ function createTypeChecker(host) { return createObjectLiteralType(); function createObjectLiteralType() { const indexInfos = []; - if (hasComputedStringProperty) indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, stringType)); - if (hasComputedNumberProperty) indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, numberType)); - if (hasComputedSymbolProperty) indexInfos.push(getObjectLiteralIndexInfo(node, offset, propertiesArray, esSymbolType)); + const isReadonly = isConstContext(node); + if (hasComputedStringProperty) indexInfos.push(getObjectLiteralIndexInfo(isReadonly, offset, propertiesArray, stringType)); + if (hasComputedNumberProperty) indexInfos.push(getObjectLiteralIndexInfo(isReadonly, offset, propertiesArray, numberType)); + if (hasComputedSymbolProperty) indexInfos.push(getObjectLiteralIndexInfo(isReadonly, offset, propertiesArray, esSymbolType)); const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, indexInfos); result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */; if (isJSObjectLiteral) { @@ -77102,7 +77545,8 @@ function createTypeChecker(host) { ); } checkJsxChildren(node); - return getJsxElementTypeAt(node) || anyType; + const jsxElementType = getJsxElementTypeAt(node); + return isErrorType(jsxElementType) ? anyType : jsxElementType; } function isHyphenatedJsxName(name) { return name.includes("-"); @@ -77114,8 +77558,6 @@ function createTypeChecker(host) { return node.initializer ? checkExpressionForMutableLocation(node.initializer, checkMode) : trueType; } function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode = 0 /* Normal */) { - const attributes = openingLikeElement.attributes; - const contextualType = getContextualType2(attributes, 0 /* None */); const allAttributesTable = strictNullChecks ? createSymbolTable() : void 0; let attributesTable = createSymbolTable(); let spread = emptyJsxObjectType; @@ -77124,96 +77566,105 @@ function createTypeChecker(host) { let explicitlySpecifyChildrenAttribute = false; let objectFlags = 2048 /* JsxAttributes */; const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); - for (const attributeDecl of attributes.properties) { - const member = attributeDecl.symbol; - if (isJsxAttribute(attributeDecl)) { - const exprType = checkJsxAttribute(attributeDecl, checkMode); - objectFlags |= getObjectFlags(exprType) & 458752 /* PropagatingFlags */; - const attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName); - attributeSymbol.declarations = member.declarations; - attributeSymbol.parent = member.parent; - if (member.valueDeclaration) { - attributeSymbol.valueDeclaration = member.valueDeclaration; - } - attributeSymbol.links.type = exprType; - attributeSymbol.links.target = member; - attributesTable.set(attributeSymbol.escapedName, attributeSymbol); - allAttributesTable == null ? void 0 : allAttributesTable.set(attributeSymbol.escapedName, attributeSymbol); - if (getEscapedTextOfJsxAttributeName(attributeDecl.name) === jsxChildrenPropertyName) { - explicitlySpecifyChildrenAttribute = true; - } - if (contextualType) { - const prop = getPropertyOfType(contextualType, member.escapedName); - if (prop && prop.declarations && isDeprecatedSymbol(prop) && isIdentifier(attributeDecl.name)) { - addDeprecatedSuggestion(attributeDecl.name, prop.declarations, attributeDecl.name.escapedText); + const isJsxOpenFragment = isJsxOpeningFragment(openingLikeElement); + let attributesSymbol; + let attributeParent = openingLikeElement; + if (!isJsxOpenFragment) { + const attributes = openingLikeElement.attributes; + attributesSymbol = attributes.symbol; + attributeParent = attributes; + const contextualType = getContextualType2(attributes, 0 /* None */); + for (const attributeDecl of attributes.properties) { + const member = attributeDecl.symbol; + if (isJsxAttribute(attributeDecl)) { + const exprType = checkJsxAttribute(attributeDecl, checkMode); + objectFlags |= getObjectFlags(exprType) & 458752 /* PropagatingFlags */; + const attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName); + attributeSymbol.declarations = member.declarations; + attributeSymbol.parent = member.parent; + if (member.valueDeclaration) { + attributeSymbol.valueDeclaration = member.valueDeclaration; + } + attributeSymbol.links.type = exprType; + attributeSymbol.links.target = member; + attributesTable.set(attributeSymbol.escapedName, attributeSymbol); + allAttributesTable == null ? void 0 : allAttributesTable.set(attributeSymbol.escapedName, attributeSymbol); + if (getEscapedTextOfJsxAttributeName(attributeDecl.name) === jsxChildrenPropertyName) { + explicitlySpecifyChildrenAttribute = true; + } + if (contextualType) { + const prop = getPropertyOfType(contextualType, member.escapedName); + if (prop && prop.declarations && isDeprecatedSymbol(prop) && isIdentifier(attributeDecl.name)) { + addDeprecatedSuggestion(attributeDecl.name, prop.declarations, attributeDecl.name.escapedText); + } + } + if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && isContextSensitive(attributeDecl)) { + const inferenceContext = getInferenceContext(attributes); + Debug.assert(inferenceContext); + const inferenceNode = attributeDecl.initializer.expression; + addIntraExpressionInferenceSite(inferenceContext, inferenceNode, exprType); + } + } else { + Debug.assert(attributeDecl.kind === 293 /* JsxSpreadAttribute */); + if (attributesTable.size > 0) { + spread = getSpreadType( + spread, + createJsxAttributesTypeHelper(), + attributes.symbol, + objectFlags, + /*readonly*/ + false + ); + attributesTable = createSymbolTable(); + } + const exprType = getReducedType(checkExpression(attributeDecl.expression, checkMode & 2 /* Inferential */)); + if (isTypeAny(exprType)) { + hasSpreadAnyType = true; + } + if (isValidSpreadType(exprType)) { + spread = getSpreadType( + spread, + exprType, + attributes.symbol, + objectFlags, + /*readonly*/ + false + ); + if (allAttributesTable) { + checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl); + } + } else { + error2(attributeDecl.expression, Diagnostics.Spread_types_may_only_be_created_from_object_types); + typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } } - if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && isContextSensitive(attributeDecl)) { - const inferenceContext = getInferenceContext(attributes); - Debug.assert(inferenceContext); - const inferenceNode = attributeDecl.initializer.expression; - addIntraExpressionInferenceSite(inferenceContext, inferenceNode, exprType); - } - } else { - Debug.assert(attributeDecl.kind === 293 /* JsxSpreadAttribute */); + } + if (!hasSpreadAnyType) { if (attributesTable.size > 0) { spread = getSpreadType( spread, - createJsxAttributesType(), - attributes.symbol, - objectFlags, - /*readonly*/ - false - ); - attributesTable = createSymbolTable(); - } - const exprType = getReducedType(checkExpression(attributeDecl.expression, checkMode & 2 /* Inferential */)); - if (isTypeAny(exprType)) { - hasSpreadAnyType = true; - } - if (isValidSpreadType(exprType)) { - spread = getSpreadType( - spread, - exprType, + createJsxAttributesTypeHelper(), attributes.symbol, objectFlags, /*readonly*/ false ); - if (allAttributesTable) { - checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl); - } - } else { - error2(attributeDecl.expression, Diagnostics.Spread_types_may_only_be_created_from_object_types); - typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; } } } - if (!hasSpreadAnyType) { - if (attributesTable.size > 0) { - spread = getSpreadType( - spread, - createJsxAttributesType(), - attributes.symbol, - objectFlags, - /*readonly*/ - false - ); - } - } - const parent2 = openingLikeElement.parent.kind === 284 /* JsxElement */ ? openingLikeElement.parent : void 0; - if (parent2 && parent2.openingElement === openingLikeElement && getSemanticJsxChildren(parent2.children).length > 0) { + const parent2 = openingLikeElement.parent; + if ((isJsxElement(parent2) && parent2.openingElement === openingLikeElement || isJsxFragment(parent2) && parent2.openingFragment === openingLikeElement) && getSemanticJsxChildren(parent2.children).length > 0) { const childrenTypes = checkJsxChildren(parent2, checkMode); if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") { if (explicitlySpecifyChildrenAttribute) { - error2(attributes, Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, unescapeLeadingUnderscores(jsxChildrenPropertyName)); + error2(attributeParent, Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, unescapeLeadingUnderscores(jsxChildrenPropertyName)); } - const contextualType2 = getApparentTypeOfContextualType( + const contextualType = isJsxOpeningElement(openingLikeElement) ? getApparentTypeOfContextualType( openingLikeElement.attributes, /*contextFlags*/ void 0 - ); - const childrenContextualType = contextualType2 && getTypeOfPropertyOfContextualType(contextualType2, jsxChildrenPropertyName); + ) : void 0; + const childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName); const childrenPropSymbol = createSymbol(4 /* Property */, jsxChildrenPropertyName); childrenPropSymbol.links.type = childrenTypes.length === 1 ? childrenTypes[0] : childrenContextualType && someType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : createArrayType(getUnionType(childrenTypes)); childrenPropSymbol.valueDeclaration = factory.createPropertySignature( @@ -77225,14 +77676,14 @@ function createTypeChecker(host) { /*type*/ void 0 ); - setParent(childrenPropSymbol.valueDeclaration, attributes); + setParent(childrenPropSymbol.valueDeclaration, attributeParent); childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol; const childPropMap = createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); spread = getSpreadType( spread, - createAnonymousType(attributes.symbol, childPropMap, emptyArray, emptyArray, emptyArray), - attributes.symbol, + createAnonymousType(attributesSymbol, childPropMap, emptyArray, emptyArray, emptyArray), + attributesSymbol, objectFlags, /*readonly*/ false @@ -77245,14 +77696,17 @@ function createTypeChecker(host) { if (typeToIntersect && spread !== emptyJsxObjectType) { return getIntersectionType([typeToIntersect, spread]); } - return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread); - function createJsxAttributesType() { + return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesTypeHelper() : spread); + function createJsxAttributesTypeHelper() { objectFlags |= 8192 /* FreshLiteral */; - const result = createAnonymousType(attributes.symbol, attributesTable, emptyArray, emptyArray, emptyArray); - result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */; - return result; + return createJsxAttributesType(objectFlags, attributesSymbol, attributesTable); } } + function createJsxAttributesType(objectFlags, attributesSymbol, attributesTable) { + const result = createAnonymousType(attributesSymbol, attributesTable, emptyArray, emptyArray, emptyArray); + result.objectFlags |= objectFlags | 8192 /* FreshLiteral */ | 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */; + return result; + } function checkJsxChildren(node, checkMode) { const childrenTypes = []; for (const child of node.children) { @@ -77334,7 +77788,7 @@ function createTypeChecker(host) { return void 0; } const isClassic = getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */; - const errorMessage = isClassic ? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option : Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations; + const errorMessage = isClassic ? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option : Diagnostics.This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_for_the_appropriate_package_installed; const specifier = getJSXRuntimeImportSpecifier(file, runtimeImportSpecifier); const mod = resolveExternalModule(specifier || location, runtimeImportSpecifier, errorMessage, location); const result = mod && mod !== unknownSymbol ? getMergedSymbol(resolveSymbol(mod)) : void 0; @@ -77558,10 +78012,10 @@ function createTypeChecker(host) { } checkJsxPreconditions(node); markJsxAliasReferenced(node); + const sig = getResolvedSignature(node); + checkDeprecatedSignature(sig, node); if (isNodeOpeningLikeElement) { const jsxOpeningLikeNode = node; - const sig = getResolvedSignature(jsxOpeningLikeNode); - checkDeprecatedSignature(sig, node); const elementTypeConstraint = getJsxElementTypeTypeAt(jsxOpeningLikeNode); if (elementTypeConstraint !== void 0) { const tagName = jsxOpeningLikeNode.tagName; @@ -77962,7 +78416,7 @@ function createTypeChecker(host) { const isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType; let prop; if (isPrivateIdentifier(right)) { - if (languageVersion < 9 /* PrivateNamesAndClassStaticBlocks */ || languageVersion < 99 /* ClassAndClassElementDecorators */ || !useDefineForClassFields) { + if (languageVersion < LanguageFeatureMinimumTarget.PrivateNamesAndClassStaticBlocks || languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators || !useDefineForClassFields) { if (assignmentKind !== 0 /* None */) { checkExternalEmitHelpers(node, 1048576 /* ClassPrivateFieldSet */); } @@ -78585,6 +79039,7 @@ function createTypeChecker(host) { return !!(t.flags & (16384 /* Void */ | 32768 /* Undefined */ | 2 /* Unknown */ | 1 /* Any */)); } function hasCorrectArity(node, args, signature, signatureHelpTrailingComma = false) { + if (isJsxOpeningFragment(node)) return true; let argCount; let callIsIncomplete = false; let effectiveParameterCount = getParameterCount(signature); @@ -78858,9 +79313,9 @@ function createTypeChecker(host) { } return 2 /* Mixed */; } - function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors2, containingMessageChain, errorOutputContainer) { + function checkApplicableSignatureForJsxCallLikeElement(node, signature, relation, checkMode, reportErrors2, containingMessageChain, errorOutputContainer) { const paramType = getEffectiveFirstArgumentForJsxSignature(signature, node); - const attributesType = checkExpressionWithContextualType( + const attributesType = isJsxOpeningFragment(node) ? createJsxAttributesTypeFromAttributesProperty(node) : checkExpressionWithContextualType( node.attributes, paramType, /*inferenceContext*/ @@ -78872,8 +79327,8 @@ function createTypeChecker(host) { checkAttributesType, paramType, relation, - reportErrors2 ? node.tagName : void 0, - node.attributes, + reportErrors2 ? isJsxOpeningFragment(node) ? node : node.tagName : void 0, + isJsxOpeningFragment(node) ? void 0 : node.attributes, /*headMessage*/ void 0, containingMessageChain, @@ -78944,10 +79399,11 @@ function createTypeChecker(host) { return true; } if (reportErrors2) { - const diag2 = createDiagnosticForNode(node.tagName, Diagnostics.Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3, entityNameToString(node.tagName), absoluteMinArgCount, entityNameToString(factory2), maxParamCount); - const tagNameDeclaration = (_a = getSymbolAtLocation(node.tagName)) == null ? void 0 : _a.valueDeclaration; + const tagName = node.tagName; + const diag2 = createDiagnosticForNode(tagName, Diagnostics.Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3, entityNameToString(tagName), absoluteMinArgCount, entityNameToString(factory2), maxParamCount); + const tagNameDeclaration = (_a = getSymbolAtLocation(tagName)) == null ? void 0 : _a.valueDeclaration; if (tagNameDeclaration) { - addRelatedInfo(diag2, createDiagnosticForNode(tagNameDeclaration, Diagnostics._0_is_declared_here, entityNameToString(node.tagName))); + addRelatedInfo(diag2, createDiagnosticForNode(tagNameDeclaration, Diagnostics._0_is_declared_here, entityNameToString(tagName))); } if (errorOutputContainer && errorOutputContainer.skipLogging) { (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag2); @@ -78965,8 +79421,8 @@ function createTypeChecker(host) { } function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors2, containingMessageChain, inferenceContext) { const errorOutputContainer = { errors: void 0, skipLogging: true }; - if (isJsxOpeningLikeElement(node)) { - if (!checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors2, containingMessageChain, errorOutputContainer)) { + if (isJsxCallLike(node)) { + if (!checkApplicableSignatureForJsxCallLikeElement(node, signature, relation, checkMode, reportErrors2, containingMessageChain, errorOutputContainer)) { Debug.assert(!reportErrors2 || !!errorOutputContainer.errors, "jsx should have errors when reporting errors"); return errorOutputContainer.errors || emptyArray; } @@ -79066,6 +79522,9 @@ function createTypeChecker(host) { return result; } function getEffectiveCallArguments(node) { + if (isJsxOpeningFragment(node)) { + return [createSyntheticExpression(node, emptyFreshJsxObjectType)]; + } if (node.kind === 215 /* TaggedTemplateExpression */) { const template = node.template; const args2 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())]; @@ -79350,25 +79809,32 @@ function createTypeChecker(host) { const isTaggedTemplate = node.kind === 215 /* TaggedTemplateExpression */; const isDecorator2 = node.kind === 170 /* Decorator */; const isJsxOpeningOrSelfClosingElement = isJsxOpeningLikeElement(node); + const isJsxOpenFragment = isJsxOpeningFragment(node); const isInstanceof = node.kind === 226 /* BinaryExpression */; const reportErrors2 = !isInferencePartiallyBlocked && !candidatesOutArray; + let candidatesForArgumentError; + let candidateForArgumentArityError; + let candidateForTypeArgumentError; + let result; + let argCheckMode = 0 /* Normal */; + let candidates = []; let typeArguments; - if (!isDecorator2 && !isInstanceof && !isSuperCall(node)) { + if (!isDecorator2 && !isInstanceof && !isSuperCall(node) && !isJsxOpenFragment) { typeArguments = node.typeArguments; if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 108 /* SuperKeyword */) { forEach(typeArguments, checkSourceElement); } } - const candidates = candidatesOutArray || []; + candidates = candidatesOutArray || []; reorderCandidates(signatures, candidates, callChainFlags); - Debug.assert(candidates.length, "Revert #54442 and add a testcase with whatever triggered this"); + if (!isJsxOpenFragment) { + Debug.assert(candidates.length, "Revert #54442 and add a testcase with whatever triggered this"); + } const args = getEffectiveCallArguments(node); const isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters; - let argCheckMode = !isDecorator2 && !isSingleNonGenericCandidate && some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */; - let candidatesForArgumentError; - let candidateForArgumentArityError; - let candidateForTypeArgumentError; - let result; + if (!isDecorator2 && !isSingleNonGenericCandidate && some(args, isContextSensitive)) { + argCheckMode = 4 /* SkipContextSensitive */; + } const signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 213 /* CallExpression */ && node.arguments.hasTrailingComma; if (candidates.length > 1) { result = chooseOverload(candidates, subtypeRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma); @@ -79488,7 +79954,7 @@ function createTypeChecker(host) { true, headMessage ); - } else { + } else if (!isJsxOpenFragment) { const signaturesWithCorrectTypeArgumentArity = filter(signatures, (s) => hasCorrectTypeArgumentArity(s, typeArguments)); if (signaturesWithCorrectTypeArgumentArity.length === 0) { diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments, headMessage)); @@ -79498,12 +79964,12 @@ function createTypeChecker(host) { } } return result; - function addImplementationSuccessElaboration(failed, diagnostic) { + function addImplementationSuccessElaboration(failed2, diagnostic) { var _a, _b; const oldCandidatesForArgumentError = candidatesForArgumentError; const oldCandidateForArgumentArityError = candidateForArgumentArityError; const oldCandidateForTypeArgumentError = candidateForTypeArgumentError; - const failedSignatureDeclarations = ((_b = (_a = failed.declaration) == null ? void 0 : _a.symbol) == null ? void 0 : _b.declarations) || emptyArray; + const failedSignatureDeclarations = ((_b = (_a = failed2.declaration) == null ? void 0 : _a.symbol) == null ? void 0 : _b.declarations) || emptyArray; const isOverload2 = failedSignatureDeclarations.length > 1; const implDecl = isOverload2 ? find(failedSignatureDeclarations, (d) => isFunctionLikeDeclaration(d) && nodeIsPresent(d.body)) : void 0; if (implDecl) { @@ -80136,24 +80602,53 @@ function createTypeChecker(host) { 0 /* None */ ); } + function getJSXFragmentType(node) { + const sourceFileLinks = getNodeLinks(getSourceFileOfNode(node)); + if (sourceFileLinks.jsxFragmentType !== void 0) return sourceFileLinks.jsxFragmentType; + const jsxFragmentFactoryName = getJsxNamespace(node); + if (jsxFragmentFactoryName === "null") return sourceFileLinks.jsxFragmentType = anyType; + const jsxFactoryRefErr = diagnostics ? Diagnostics.Using_JSX_fragments_requires_fragment_factory_0_to_be_in_scope_but_it_could_not_be_found : void 0; + const jsxFactorySymbol = getJsxNamespaceContainerForImplicitImport(node) ?? resolveName( + node, + jsxFragmentFactoryName, + compilerOptions.jsx === 1 /* Preserve */ ? 111551 /* Value */ & ~384 /* Enum */ : 111551 /* Value */, + /*nameNotFoundMessage*/ + jsxFactoryRefErr, + /*isUse*/ + true + ); + if (jsxFactorySymbol === void 0) return sourceFileLinks.jsxFragmentType = errorType; + if (jsxFactorySymbol.escapedName === ReactNames.Fragment) return sourceFileLinks.jsxFragmentType = getTypeOfSymbol(jsxFactorySymbol); + const resolvedAlias = (jsxFactorySymbol.flags & 2097152 /* Alias */) === 0 ? jsxFactorySymbol : resolveAlias(jsxFactorySymbol); + const reactExports = jsxFactorySymbol && getExportsOfSymbol(resolvedAlias); + const typeSymbol = reactExports && getSymbol2(reactExports, ReactNames.Fragment, 2 /* BlockScopedVariable */); + const type = typeSymbol && getTypeOfSymbol(typeSymbol); + return sourceFileLinks.jsxFragmentType = type === void 0 ? errorType : type; + } function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) { - if (isJsxIntrinsicTagName(node.tagName)) { - const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); - const fakeSignature = createSignatureForJSXIntrinsic(node, result); - checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType( - node.attributes, - getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), - /*inferenceContext*/ - void 0, - 0 /* Normal */ - ), result, node.tagName, node.attributes); - if (length(node.typeArguments)) { - forEach(node.typeArguments, checkSourceElement); - diagnostics.add(createDiagnosticForNodeArray(getSourceFileOfNode(node), node.typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, 0, length(node.typeArguments))); + const isJsxOpenFragment = isJsxOpeningFragment(node); + let exprTypes; + if (!isJsxOpenFragment) { + if (isJsxIntrinsicTagName(node.tagName)) { + const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node); + const fakeSignature = createSignatureForJSXIntrinsic(node, result); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType( + node.attributes, + getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), + /*inferenceContext*/ + void 0, + 0 /* Normal */ + ), result, node.tagName, node.attributes); + if (length(node.typeArguments)) { + forEach(node.typeArguments, checkSourceElement); + diagnostics.add(createDiagnosticForNodeArray(getSourceFileOfNode(node), node.typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, 0, length(node.typeArguments))); + } + return fakeSignature; } - return fakeSignature; + exprTypes = checkExpression(node.tagName); + } else { + exprTypes = getJSXFragmentType(node); } - const exprTypes = checkExpression(node.tagName); const apparentType = getApparentType(exprTypes); if (isErrorType(apparentType)) { return resolveErrorCall(node); @@ -80169,7 +80664,11 @@ function createTypeChecker(host) { return resolveUntypedCall(node); } if (signatures.length === 0) { - error2(node.tagName, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(node.tagName)); + if (isJsxOpenFragment) { + error2(node, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(node)); + } else { + error2(node.tagName, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(node.tagName)); + } return resolveErrorCall(node); } return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */); @@ -80211,6 +80710,7 @@ function createTypeChecker(host) { return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode); case 170 /* Decorator */: return resolveDecorator(node, candidatesOutArray, checkMode); + case 289 /* JsxOpeningFragment */: case 286 /* JsxOpeningElement */: case 285 /* JsxSelfClosingElement */: return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode); @@ -80579,7 +81079,7 @@ function createTypeChecker(host) { } function checkTaggedTemplateExpression(node) { if (!checkGrammarTaggedTemplateChain(node)) checkGrammarTypeArguments(node, node.typeArguments); - if (languageVersion < 2 /* TaggedTemplates */) { + if (languageVersion < LanguageFeatureMinimumTarget.TaggedTemplates) { checkExternalEmitHelpers(node, 262144 /* MakeTemplateObject */); } const signature = getResolvedSignature(node); @@ -80698,9 +81198,17 @@ function createTypeChecker(host) { if (exprType === silentNeverType || isErrorType(exprType) || !some(typeArguments)) { return exprType; } + const links = getNodeLinks(node); + if (!links.instantiationExpressionTypes) { + links.instantiationExpressionTypes = /* @__PURE__ */ new Map(); + } + if (links.instantiationExpressionTypes.has(exprType.id)) { + return links.instantiationExpressionTypes.get(exprType.id); + } let hasSomeApplicableSignature = false; let nonApplicableType; const result = getInstantiatedType(exprType); + links.instantiationExpressionTypes.set(exprType.id, result); const errorType2 = hasSomeApplicableSignature ? nonApplicableType : exprType; if (errorType2) { diagnostics.add(createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Type_0_has_no_signatures_for_which_the_type_argument_list_is_applicable, typeToString(errorType2))); @@ -81755,7 +82263,7 @@ function createTypeChecker(host) { }); } function checkIfExpressionRefinesParameter(func, expr, param, initType) { - const antecedent = expr.flowNode || expr.parent.kind === 253 /* ReturnStatement */ && expr.parent.flowNode || createFlowNode( + const antecedent = canHaveFlowNode(expr) && expr.flowNode || expr.parent.kind === 253 /* ReturnStatement */ && expr.parent.flowNode || createFlowNode( 2 /* Start */, /*node*/ void 0, @@ -82074,6 +82582,7 @@ function createTypeChecker(host) { hasError = true; break; } + // fallthrough case 7 /* ES2022 */: case 99 /* ESNext */: case 200 /* Preserve */: @@ -82081,6 +82590,7 @@ function createTypeChecker(host) { if (languageVersion >= 4 /* ES2017 */) { break; } + // fallthrough default: span ?? (span = getSpanOfTokenAtPosition(sourceFile, node.pos)); const message = isAwaitExpression(node) ? Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_nodenext_or_preserve_and_the_target_option_is_set_to_es2017_or_higher : Diagnostics.Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_nodenext_or_preserve_and_the_target_option_is_set_to_es2017_or_higher; @@ -82289,7 +82799,7 @@ function createTypeChecker(host) { return silentNeverType; } if (isPrivateIdentifier(left)) { - if (languageVersion < 9 /* PrivateNamesAndClassStaticBlocks */ || languageVersion < 99 /* ClassAndClassElementDecorators */ || !useDefineForClassFields) { + if (languageVersion < LanguageFeatureMinimumTarget.PrivateNamesAndClassStaticBlocks || languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators || !useDefineForClassFields) { checkExternalEmitHelpers(left, 2097152 /* ClassPrivateFieldIn */); } if (!getNodeLinks(left).resolvedSymbol && getContainingClass(left)) { @@ -82350,7 +82860,7 @@ function createTypeChecker(host) { if (propertyIndex < properties.length - 1) { error2(property, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } else { - if (languageVersion < 5 /* ObjectSpreadRest */) { + if (languageVersion < LanguageFeatureMinimumTarget.ObjectSpreadRest) { checkExternalEmitHelpers(property, 4 /* Rest */); } const nonRestNames = []; @@ -82371,7 +82881,7 @@ function createTypeChecker(host) { } function checkArrayLiteralAssignment(node, sourceType, checkMode) { const elements = node.elements; - if (languageVersion < 2 /* DestructuringAssignment */ && compilerOptions.downlevelIteration) { + if (languageVersion < LanguageFeatureMinimumTarget.DestructuringAssignment && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } const possiblyOutOfBoundsType = checkIteratedTypeOrElementType(65 /* Destructuring */ | 128 /* PossiblyOutOfBounds */, sourceType, undefinedType, node) || errorType; @@ -82498,9 +83008,13 @@ function createTypeChecker(host) { return true; } return false; + // Some forms listed here for clarity case 222 /* VoidExpression */: + // Explicit opt-out case 216 /* TypeAssertionExpression */: + // Not SEF, but can produce useful type warnings case 234 /* AsExpression */: + // Not SEF, but can produce useful type warnings default: return false; } @@ -83141,10 +83655,10 @@ function createTypeChecker(host) { } const isAsync = (functionFlags & 2 /* Async */) !== 0; if (node.asteriskToken) { - if (isAsync && languageVersion < 5 /* AsyncGenerators */) { + if (isAsync && languageVersion < LanguageFeatureMinimumTarget.AsyncGenerators) { checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */); } - if (!isAsync && languageVersion < 2 /* Generators */ && compilerOptions.downlevelIteration) { + if (!isAsync && languageVersion < LanguageFeatureMinimumTarget.Generators && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 256 /* Values */); } } @@ -83375,7 +83889,7 @@ function createTypeChecker(host) { return createTupleType(elementTypes, elementFlags, type.target.readonly); } function widenTypeInferredFromInitializer(declaration, type) { - const widened = getCombinedNodeFlagsCached(declaration) & 6 /* Constant */ || isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type); + const widened = getWidenedLiteralTypeForInitializer(declaration, type); if (isInJSFile(declaration)) { if (isEmptyLiteralType(widened)) { reportImplicitAny(declaration, anyType); @@ -83387,6 +83901,9 @@ function createTypeChecker(host) { } return widened; } + function getWidenedLiteralTypeForInitializer(declaration, type) { + return getCombinedNodeFlagsCached(declaration) & 6 /* Constant */ || isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type); + } function isLiteralOfContextualType(candidateType, contextualType) { if (contextualType) { if (contextualType.flags & 3145728 /* UnionOrIntersection */) { @@ -83746,6 +84263,7 @@ function createTypeChecker(host) { if (node.expression.kind === 102 /* ImportKeyword */) { return checkImportCallExpression(node); } + // falls through case 214 /* NewExpression */: return checkCallExpression(node, checkMode); case 215 /* TaggedTemplateExpression */: @@ -83834,7 +84352,7 @@ function createTypeChecker(host) { const modifiers = getTypeParameterModifiers(typeParameter) & (8192 /* In */ | 16384 /* Out */); if (modifiers) { const symbol = getSymbolOfDeclaration(node.parent); - if (isTypeAliasDeclaration(node.parent) && !(getObjectFlags(getDeclaredTypeOfSymbol(symbol)) & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */))) { + if (isTypeAliasDeclaration(node.parent) && !(getObjectFlags(getDeclaredTypeOfSymbol(symbol)) & (16 /* Anonymous */ | 32 /* Mapped */))) { error2(node, Diagnostics.Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types); } else if (modifiers === 8192 /* In */ || modifiers === 16384 /* Out */) { (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.CheckTypes, "checkTypeParameterDeferred", { parent: getTypeId(getDeclaredTypeOfSymbol(symbol)), id: getTypeId(typeParameter) }); @@ -83973,13 +84491,13 @@ function createTypeChecker(host) { } const functionFlags = getFunctionFlags(node); if (!(functionFlags & 4 /* Invalid */)) { - if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 5 /* AsyncGenerators */) { + if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < LanguageFeatureMinimumTarget.AsyncGenerators) { checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */); } - if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* AsyncFunctions */) { + if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < LanguageFeatureMinimumTarget.AsyncFunctions) { checkExternalEmitHelpers(node, 64 /* Awaiter */); } - if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* Generators */) { + if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < LanguageFeatureMinimumTarget.Generators) { checkExternalEmitHelpers(node, 128 /* Generator */); } } @@ -84115,6 +84633,7 @@ function createTypeChecker(host) { if (useDefineForClassFields) { break; } + // fall through case "prototype": const message = Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1; const className = getNameOfSymbolAsWritten(getSymbolOfDeclaration(node)); @@ -84161,15 +84680,17 @@ function createTypeChecker(host) { if (indexSymbol == null ? void 0 : indexSymbol.declarations) { const indexSignatureMap = /* @__PURE__ */ new Map(); for (const declaration of indexSymbol.declarations) { - if (declaration.parameters.length === 1 && declaration.parameters[0].type) { - forEachType(getTypeFromTypeNode(declaration.parameters[0].type), (type) => { - const entry = indexSignatureMap.get(getTypeId(type)); - if (entry) { - entry.declarations.push(declaration); - } else { - indexSignatureMap.set(getTypeId(type), { type, declarations: [declaration] }); - } - }); + if (isIndexSignatureDeclaration(declaration)) { + if (declaration.parameters.length === 1 && declaration.parameters[0].type) { + forEachType(getTypeFromTypeNode(declaration.parameters[0].type), (type) => { + const entry = indexSignatureMap.get(getTypeId(type)); + if (entry) { + entry.declarations.push(declaration); + } else { + indexSignatureMap.set(getTypeId(type), { type, declarations: [declaration] }); + } + }); + } } } indexSignatureMap.forEach((entry) => { @@ -84211,7 +84732,7 @@ function createTypeChecker(host) { } function setNodeLinksForPrivateIdentifierScope(node) { if (isPrivateIdentifier(node.name)) { - if (languageVersion < 9 /* PrivateNamesAndClassStaticBlocks */ || languageVersion < 99 /* ClassAndClassElementDecorators */ || !useDefineForClassFields) { + if (languageVersion < LanguageFeatureMinimumTarget.PrivateNamesAndClassStaticBlocks || languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators || !useDefineForClassFields) { for (let lexicalScope = getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = getEnclosingBlockScopeContainer(lexicalScope)) { getNodeLinks(lexicalScope).flags |= 1048576 /* ContainsClassWithPrivateIdentifiers */; } @@ -84858,6 +85379,8 @@ function createTypeChecker(host) { switch (d.kind) { case 264 /* InterfaceDeclaration */: case 265 /* TypeAliasDeclaration */: + // A jsdoc typedef and callback are, by definition, type aliases. + // falls through case 346 /* JSDocTypedefTag */: case 338 /* JSDocCallbackTag */: case 340 /* JSDocEnumTag */: @@ -84878,6 +85401,8 @@ function createTypeChecker(host) { return 1 /* ExportValue */; } d = expression; + // The below options all declare an Alias, which is allowed to merge with other values within the importing module. + // falls through case 271 /* ImportEqualsDeclaration */: case 274 /* NamespaceImport */: case 273 /* ImportClause */: @@ -84891,6 +85416,7 @@ function createTypeChecker(host) { case 208 /* BindingElement */: case 262 /* FunctionDeclaration */: case 276 /* ImportSpecifier */: + // https://github.com/Microsoft/TypeScript/pull/7591 case 80 /* Identifier */: return 1 /* ExportValue */; case 173 /* MethodSignature */: @@ -85239,6 +85765,7 @@ function createTypeChecker(host) { headMessage = Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1; break; } + // falls through case 169 /* Parameter */: headMessage = Diagnostics.Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any; break; @@ -85345,7 +85872,7 @@ function createTypeChecker(host) { if (node.kind === 169 /* Parameter */) { checkExternalEmitHelpers(firstDecorator, 32 /* Param */); } - } else if (languageVersion < 99 /* ClassAndClassElementDecorators */) { + } else if (languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators) { checkExternalEmitHelpers(firstDecorator, 8 /* ESDecorateAndRunInitializers */); if (isClassDeclaration(node)) { if (!node.name) { @@ -86011,7 +86538,7 @@ function createTypeChecker(host) { potentialUnusedRenamedBindingElementsInTypes.push(node); return; } - if (isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < 5 /* ObjectSpreadRest */) { + if (isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < LanguageFeatureMinimumTarget.ObjectSpreadRest) { checkExternalEmitHelpers(node, 4 /* Rest */); } if (node.propertyName && node.propertyName.kind === 167 /* ComputedPropertyName */) { @@ -86047,7 +86574,7 @@ function createTypeChecker(host) { } } if (isBindingPattern(node.name)) { - if (node.name.kind === 207 /* ArrayBindingPattern */ && languageVersion < 2 /* BindingPatterns */ && compilerOptions.downlevelIteration) { + if (node.name.kind === 207 /* ArrayBindingPattern */ && languageVersion < LanguageFeatureMinimumTarget.BindingPatterns && compilerOptions.downlevelIteration) { checkExternalEmitHelpers(node, 512 /* Read */); } forEach(node.name.elements, checkSourceElement); @@ -86201,7 +86728,7 @@ function createTypeChecker(host) { } function checkVariableDeclarationList(node) { const blockScopeKind = getCombinedNodeFlags(node) & 7 /* BlockScoped */; - if ((blockScopeKind === 4 /* Using */ || blockScopeKind === 6 /* AwaitUsing */) && languageVersion < 99 /* UsingAndAwaitUsing */) { + if ((blockScopeKind === 4 /* Using */ || blockScopeKind === 6 /* AwaitUsing */) && languageVersion < LanguageFeatureMinimumTarget.UsingAndAwaitUsing) { checkExternalEmitHelpers(node, 16777216 /* AddDisposableResourceAndDisposeResources */); } forEach(node.declarations, checkSourceElement); @@ -86415,11 +86942,11 @@ function createTypeChecker(host) { grammarErrorOnNode(node.awaitModifier, Diagnostics.for_await_loops_cannot_be_used_inside_a_class_static_block); } else { const functionFlags = getFunctionFlags(container); - if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 5 /* ForAwaitOf */) { + if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < LanguageFeatureMinimumTarget.ForAwaitOf) { checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */); } } - } else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ForOf */) { + } else if (compilerOptions.downlevelIteration && languageVersion < LanguageFeatureMinimumTarget.ForOf) { checkExternalEmitHelpers(node, 256 /* ForOfIncludes */); } if (node.initializer.kind === 261 /* VariableDeclarationList */) { @@ -86652,7 +87179,7 @@ function createTypeChecker(host) { return anyIterationTypes; } if (!(type.flags & 1048576 /* Union */)) { - const errorOutputContainer = errorNode ? { errors: void 0 } : void 0; + const errorOutputContainer = errorNode ? { errors: void 0, skipLogging: true } : void 0; const iterationTypes2 = getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer); if (iterationTypes2 === noIterationTypes) { if (errorNode) { @@ -86820,11 +87347,27 @@ function createTypeChecker(host) { if (isTypeAny(methodType)) { return noCache ? anyIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes); } - const signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : void 0; - if (!some(signatures)) { + const allSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : void 0; + const validSignatures = filter(allSignatures, (sig) => getMinArgumentCount(sig) === 0); + if (!some(validSignatures)) { + if (errorNode && some(allSignatures)) { + checkTypeAssignableTo( + type, + resolver.getGlobalIterableType( + /*reportErrors*/ + true + ), + errorNode, + /*headMessage*/ + void 0, + /*containingMessageChain*/ + void 0, + errorOutputContainer + ); + } return noCache ? noIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes); } - const iteratorType = getIntersectionType(map(signatures, getReturnTypeOfSignature)); + const iteratorType = getIntersectionType(map(validSignatures, getReturnTypeOfSignature)); const iterationTypes = getIterationTypesOfIteratorWorker(iteratorType, resolver, errorNode, errorOutputContainer, noCache) ?? noIterationTypes; return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes); } @@ -87460,12 +88003,12 @@ function createTypeChecker(host) { return true; } function getFirstTransformableStaticClassElement(node) { - const willTransformStaticElementsOfDecoratedClass = !legacyDecorators && languageVersion < 99 /* ClassAndClassElementDecorators */ && classOrConstructorParameterIsDecorated( + const willTransformStaticElementsOfDecoratedClass = !legacyDecorators && languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators && classOrConstructorParameterIsDecorated( /*useLegacyDecorators*/ false, node ); - const willTransformPrivateElementsOrClassStaticBlocks = languageVersion < 9 /* PrivateNamesAndClassStaticBlocks */ || languageVersion < 99 /* ClassAndClassElementDecorators */; + const willTransformPrivateElementsOrClassStaticBlocks = languageVersion < LanguageFeatureMinimumTarget.PrivateNamesAndClassStaticBlocks || languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators; const willTransformInitializers = !emitStandardClassFields; if (willTransformStaticElementsOfDecoratedClass || willTransformPrivateElementsOrClassStaticBlocks) { for (const member of node.members) { @@ -87492,7 +88035,7 @@ function createTypeChecker(host) { if (node.name) return; const parent2 = walkUpOuterExpressions(node); if (!isNamedEvaluationSource(parent2)) return; - const willTransformESDecorators = !legacyDecorators && languageVersion < 99 /* ClassAndClassElementDecorators */; + const willTransformESDecorators = !legacyDecorators && languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators; let location; if (willTransformESDecorators && classOrConstructorParameterIsDecorated( /*useLegacyDecorators*/ @@ -87552,7 +88095,7 @@ function createTypeChecker(host) { const baseTypeNode = getEffectiveBaseTypeNode(node); if (baseTypeNode) { forEach(baseTypeNode.typeArguments, checkSourceElement); - if (languageVersion < 2 /* Classes */) { + if (languageVersion < LanguageFeatureMinimumTarget.Classes) { checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */); } const extendsNode = getClassExtendsHeritageElement(node); @@ -88058,6 +88601,9 @@ function createTypeChecker(host) { } function checkInterfaceDeclaration(node) { if (!checkGrammarModifiers(node)) checkGrammarInterfaceDeclaration(node); + if (!allowBlockDeclarations(node.parent)) { + grammarErrorOnNode(node, Diagnostics._0_declarations_can_only_be_declared_inside_a_block, "interface"); + } checkTypeParameters(node.typeParameters); addLazyDiagnostic(() => { checkTypeNameIsReserved(node.name, Diagnostics.Interface_name_cannot_be_0); @@ -88092,6 +88638,9 @@ function createTypeChecker(host) { function checkTypeAliasDeclaration(node) { checkGrammarModifiers(node); checkTypeNameIsReserved(node.name, Diagnostics.Type_alias_name_cannot_be_0); + if (!allowBlockDeclarations(node.parent)) { + grammarErrorOnNode(node, Diagnostics._0_declarations_can_only_be_declared_inside_a_block, "type"); + } checkExportsOnMergedDeclarations(node); checkTypeParameters(node.typeParameters); if (node.type.kind === 141 /* IntrinsicKeyword */) { @@ -88460,6 +89009,7 @@ function createTypeChecker(host) { break; case 271 /* ImportEqualsDeclaration */: if (isInternalModuleImportEqualsDeclaration(node)) break; + // falls through case 272 /* ImportDeclaration */: grammarErrorOnFirstToken(node, Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module); break; @@ -88472,6 +89022,7 @@ function createTypeChecker(host) { } break; } + // falls through case 263 /* ClassDeclaration */: case 266 /* EnumDeclaration */: case 262 /* FunctionDeclaration */: @@ -88735,6 +89286,7 @@ function createTypeChecker(host) { grammarErrorOnFirstToken(node, Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { + let resolvedModule; const importClause = node.importClause; if (importClause && !checkGrammarImportClause(importClause)) { if (importClause.name) { @@ -88747,18 +89299,27 @@ function createTypeChecker(host) { checkExternalEmitHelpers(node, 65536 /* ImportStar */); } } else { - const moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier); - if (moduleExisted) { + resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier); + if (resolvedModule) { forEach(importClause.namedBindings.elements, checkImportBinding); } } } + if (isOnlyImportableAsDefault(node.moduleSpecifier, resolvedModule) && !hasTypeJsonImportAttribute(node)) { + error2(node.moduleSpecifier, Diagnostics.Importing_a_JSON_file_into_an_ECMAScript_module_requires_a_type_Colon_json_import_attribute_when_module_is_set_to_0, ModuleKind[moduleKind]); + } } else if (noUncheckedSideEffectImports && !importClause) { void resolveExternalModuleName(node, node.moduleSpecifier); } } checkImportAttributes(node); } + function hasTypeJsonImportAttribute(node) { + return !!node.attributes && node.attributes.elements.some((attr) => { + var _a; + return getTextOfIdentifierOrLiteral(attr.name) === "type" && ((_a = tryCast(attr.value, isStringLiteralLike)) == null ? void 0 : _a.text) === "json"; + }); + } function checkImportEqualsDeclaration(node) { if (checkGrammarModuleElementContext(node, isInJSFile(node) ? Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module : Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) { return; @@ -89148,6 +89709,7 @@ function createTypeChecker(host) { return checkJSDocPropertyTag(node); case 317 /* JSDocFunctionType */: checkJSDocFunctionType(node); + // falls through case 315 /* JSDocNonNullableType */: case 314 /* JSDocNullableType */: case 312 /* JSDocAllType */: @@ -89571,6 +90133,7 @@ function createTypeChecker(host) { switch (location.kind) { case 307 /* SourceFile */: if (!isExternalModule(location)) break; + // falls through case 267 /* ModuleDeclaration */: copyLocallyVisibleExportSymbols(getSymbolOfDeclaration(location).exports, meaning & 2623475 /* ModuleMember */); break; @@ -89582,6 +90145,9 @@ function createTypeChecker(host) { if (className) { copySymbol(location.symbol, meaning); } + // this fall-through is necessary because we would like to handle + // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration. + // falls through case 263 /* ClassDeclaration */: case 264 /* InterfaceDeclaration */: if (!isStaticSymbol) { @@ -89690,6 +90256,7 @@ function createTypeChecker(host) { if (isPropertyAccessExpression(entityName.parent) && getLeftmostAccessExpression(entityName.parent) === entityName) { return void 0; } + // falls through case 4 /* ThisProperty */: case 2 /* ModuleExports */: return getSymbolOfDeclaration(entityName.parent.parent); @@ -89869,7 +90436,7 @@ function createTypeChecker(host) { } else if (isJSDocMemberName(name)) { return resolveJSDocMemberName(name); } - } else if (isTypeReferenceIdentifier(name)) { + } else if (isEntityName(name) && isTypeReferenceIdentifier(name)) { const meaning = name.parent.kind === 183 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */; const symbol = resolveEntityName( name, @@ -89983,6 +90550,7 @@ function createTypeChecker(host) { if (!isThisInTypeQuery(node)) { return getSymbolOfNameOrPropertyAccessExpression(node); } + // falls through case 110 /* ThisKeyword */: const container = getThisContainer( node, @@ -90000,6 +90568,7 @@ function createTypeChecker(host) { if (isInExpressionContext(node)) { return checkExpression(node).symbol; } + // falls through case 197 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; case 108 /* SuperKeyword */: @@ -90022,6 +90591,7 @@ function createTypeChecker(host) { if (isCallExpression(parent2) && isBindableObjectDefinePropertyCall(parent2) && parent2.arguments[1] === node) { return getSymbolOfDeclaration(parent2); } + // falls through case 9 /* NumericLiteral */: const objectType = isElementAccessExpression(parent2) ? parent2.argumentExpression === node ? getTypeOfExpression(parent2.expression) : void 0 : isLiteralTypeNode(parent2) && isIndexedAccessTypeNode(grandParent) ? getTypeFromTypeNode(grandParent.objectType) : void 0; return objectType && getPropertyOfType(objectType, escapeLeadingUnderscores(node.text)); @@ -90051,6 +90621,7 @@ function createTypeChecker(host) { const symbol = getIntrinsicTagSymbol(node.parent); return symbol === unknownSymbol ? void 0 : symbol; } + // falls through default: return void 0; } @@ -90456,7 +91027,7 @@ function createTypeChecker(host) { const typeNode = getNonlocalEffectiveTypeAnnotationNode(parameter); if (!typeNode) return false; const type = getTypeFromTypeNode(typeNode); - return containsUndefinedType(type); + return isErrorType(type) || containsUndefinedType(type); } function requiresAddingImplicitUndefined(parameter, enclosingDeclaration) { return (isRequiredInitializedParameter(parameter, enclosingDeclaration) || isOptionalUninitializedParameterProperty(parameter)) && !declaredParameterTypeContainsUndefined(parameter); @@ -90743,16 +91314,12 @@ function createTypeChecker(host) { } } function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, internalFlags, tracker) { - const declaration = getParseTreeNode(declarationIn, isVariableLikeOrAccessor); + const declaration = getParseTreeNode(declarationIn, hasInferredType); if (!declaration) { return factory.createToken(133 /* AnyKeyword */); } const symbol = getSymbolOfDeclaration(declaration); - const type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : errorType; - return nodeBuilder.serializeTypeForDeclaration(declaration, type, symbol, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker); - } - function isDeclarationWithPossibleInnerTypeNodeReuse(declaration) { - return isFunctionLike(declaration) || isExportAssignment(declaration) || isVariableLike(declaration); + return nodeBuilder.serializeTypeForDeclaration(declaration, symbol, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker); } function getAllAccessorDeclarationsForDeclaration(accessor) { accessor = getParseTreeNode(accessor, isGetOrSetAccessorDeclaration); @@ -90769,52 +91336,19 @@ function createTypeChecker(host) { getAccessor }; } - function getPossibleTypeNodeReuseExpression(declaration) { - return isFunctionLike(declaration) && !isSetAccessor(declaration) ? getSingleReturnExpression(declaration) : isExportAssignment(declaration) ? declaration.expression : !!declaration.initializer ? declaration.initializer : isParameter(declaration) && isSetAccessor(declaration.parent) ? getSingleReturnExpression(getAllAccessorDeclarationsForDeclaration(declaration.parent).getAccessor) : void 0; - } - function getSingleReturnExpression(declaration) { - let candidateExpr; - if (declaration && !nodeIsMissing(declaration.body)) { - if (getFunctionFlags(declaration) & 3 /* AsyncGenerator */) return void 0; - const body = declaration.body; - if (body && isBlock(body)) { - forEachReturnStatement(body, (s) => { - if (!candidateExpr) { - candidateExpr = s.expression; - } else { - candidateExpr = void 0; - return true; - } - }); - } else { - candidateExpr = body; - } - } - return candidateExpr; - } function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, internalFlags, tracker) { const signatureDeclaration = getParseTreeNode(signatureDeclarationIn, isFunctionLike); if (!signatureDeclaration) { return factory.createToken(133 /* AnyKeyword */); } - return nodeBuilder.serializeReturnTypeForSignature(getSignatureFromDeclaration(signatureDeclaration), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker); + return nodeBuilder.serializeReturnTypeForSignature(signatureDeclaration, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker); } function createTypeOfExpression(exprIn, enclosingDeclaration, flags, internalFlags, tracker) { const expr = getParseTreeNode(exprIn, isExpression); if (!expr) { return factory.createToken(133 /* AnyKeyword */); } - const type = getWidenedType(getRegularTypeOfExpression(expr)); - return nodeBuilder.expressionOrTypeToTypeNode( - expr, - type, - /*addUndefined*/ - void 0, - enclosingDeclaration, - flags | 1024 /* MultilineObjectLiterals */, - internalFlags, - tracker - ); + return nodeBuilder.serializeTypeForExpression(expr, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker); } function hasGlobalName(name) { return globals.has(escapeLeadingUnderscores(name)); @@ -90965,22 +91499,6 @@ function createTypeChecker(host) { } return void 0; } - function getNonlocalEffectiveReturnTypeAnnotationNode(node) { - const direct = getEffectiveReturnTypeNode(node); - if (direct) { - return direct; - } - if (node.kind === 177 /* GetAccessor */) { - const other = getAllAccessorDeclarationsForDeclaration(node).setAccessor; - if (other) { - const param = getSetAccessorValueParameter(other); - if (param) { - return getEffectiveTypeAnnotationNode(param); - } - } - } - return void 0; - } function createResolver() { return { getReferencedExportContainer, @@ -91059,7 +91577,29 @@ function createTypeChecker(host) { return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, internalFlags, tracker); }, isImportRequiredByAugmentation, - isDefinitelyReferenceToGlobalSymbolObject + isDefinitelyReferenceToGlobalSymbolObject, + createLateBoundIndexSignatures: (cls, enclosing, flags, internalFlags, tracker) => { + const sym = cls.symbol; + const staticInfos = getIndexInfosOfType(getTypeOfSymbol(sym)); + const instanceIndexSymbol = getIndexSymbol(sym); + const instanceInfos = instanceIndexSymbol && getIndexInfosOfIndexSymbol(instanceIndexSymbol, arrayFrom(getMembersOfSymbol(sym).values())); + let result; + for (const infoList of [staticInfos, instanceInfos]) { + if (!length(infoList)) continue; + result || (result = []); + for (const info of infoList) { + if (info.declaration) continue; + const node = nodeBuilder.indexInfoToIndexSignatureDeclaration(info, enclosing, flags, internalFlags, tracker); + if (node && infoList === staticInfos) { + (node.modifiers || (node.modifiers = factory.createNodeArray())).unshift(factory.createModifier(126 /* StaticKeyword */)); + } + if (node) { + result.push(node); + } + } + } + return result; + } }; function isImportRequiredByAugmentation(node) { const file = getSourceFileOfNode(node); @@ -91362,6 +91902,8 @@ function createTypeChecker(host) { return ["__propKey"]; case 16777216 /* AddDisposableResourceAndDisposeResources */: return ["__addDisposableResource", "__disposeResources"]; + case 33554432 /* RewriteRelativeImportExtension */: + return ["__rewriteRelativeImportExtension"]; default: return Debug.fail("Unrecognized helper"); } @@ -92145,6 +92687,7 @@ function createTypeChecker(host) { ); break; } + // fallthrough case 7 /* ES2022 */: case 99 /* ESNext */: case 200 /* Preserve */: @@ -92152,6 +92695,7 @@ function createTypeChecker(host) { if (languageVersion >= 4 /* ES2017 */) { break; } + // fallthrough default: diagnostics.add( createDiagnosticForNode(forInOrOfStatement.awaitModifier, Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_nodenext_or_preserve_and_the_target_option_is_set_to_es2017_or_higher) @@ -92509,7 +93053,7 @@ function createTypeChecker(host) { } return false; } - function allowLetAndConstDeclarations(parent2) { + function allowBlockDeclarations(parent2) { switch (parent2.kind) { case 245 /* IfStatement */: case 246 /* DoStatement */: @@ -92520,12 +93064,12 @@ function createTypeChecker(host) { case 250 /* ForOfStatement */: return false; case 256 /* LabeledStatement */: - return allowLetAndConstDeclarations(parent2.parent); + return allowBlockDeclarations(parent2.parent); } return true; } function checkGrammarForDisallowedBlockScopedVariableStatement(node) { - if (!allowLetAndConstDeclarations(node.parent)) { + if (!allowBlockDeclarations(node.parent)) { const blockScopeKind = getCombinedNodeFlagsCached(node.declarationList) & 7 /* BlockScoped */; if (blockScopeKind) { const keyword = blockScopeKind === 1 /* Let */ ? "let" : blockScopeKind === 2 /* Const */ ? "const" : blockScopeKind === 4 /* Using */ ? "using" : blockScopeKind === 6 /* AwaitUsing */ ? "await using" : Debug.fail("Unknown BlockScope flag"); @@ -92924,6 +93468,10 @@ var JsxNames; JsxNames2.IntrinsicClassAttributes = "IntrinsicClassAttributes"; JsxNames2.LibraryManagedAttributes = "LibraryManagedAttributes"; })(JsxNames || (JsxNames = {})); +var ReactNames; +((ReactNames2) => { + ReactNames2.Fragment = "Fragment"; +})(ReactNames || (ReactNames = {})); function getIterationTypesKeyFromIterationTypeKind(typeKind) { switch (typeKind) { case 0 /* Yield */: @@ -92949,7 +93497,7 @@ function createBasicNodeBuilderModuleSpecifierResolutionHost(host) { var _a; return (_a = host.getPackageJsonInfoCache) == null ? void 0 : _a.call(host); }, - useCaseSensitiveFileNames: maybeBind(host, host.useCaseSensitiveFileNames), + useCaseSensitiveFileNames: () => host.useCaseSensitiveFileNames(), redirectTargetsMap: host.redirectTargetsMap, getProjectReferenceRedirect: (fileName) => host.getProjectReferenceRedirect(fileName), isSourceOfProjectReferenceRedirect: (fileName) => host.isSourceOfProjectReferenceRedirect(fileName), @@ -92957,7 +93505,8 @@ function createBasicNodeBuilderModuleSpecifierResolutionHost(host) { getFileIncludeReasons: () => host.getFileIncludeReasons(), readFile: host.readFile ? (fileName) => host.readFile(fileName) : void 0, getDefaultResolutionModeForFile: (file) => host.getDefaultResolutionModeForFile(file), - getModeForResolutionAtIndex: (file, index) => host.getModeForResolutionAtIndex(file, index) + getModeForResolutionAtIndex: (file, index) => host.getModeForResolutionAtIndex(file, index), + getGlobalTypingsCacheLocation: maybeBind(host, host.getGlobalTypingsCacheLocation) }; } var SymbolTrackerImpl = class _SymbolTrackerImpl { @@ -93046,10 +93595,19 @@ var SymbolTrackerImpl = class _SymbolTrackerImpl { } reportInferenceFallback(node) { var _a; - if ((_a = this.inner) == null ? void 0 : _a.reportInferenceFallback) { + if (((_a = this.inner) == null ? void 0 : _a.reportInferenceFallback) && !this.context.suppressReportInferenceFallback) { + this.onDiagnosticReported(); this.inner.reportInferenceFallback(node); } } + pushErrorFallbackNode(node) { + var _a, _b; + return (_b = (_a = this.inner) == null ? void 0 : _a.pushErrorFallbackNode) == null ? void 0 : _b.call(_a, node); + } + popErrorFallbackNode() { + var _a, _b; + return (_b = (_a = this.inner) == null ? void 0 : _a.popErrorFallbackNode) == null ? void 0 : _b.call(_a); + } }; // src/compiler/visitorPublic.ts @@ -94328,13 +94886,13 @@ var visitEachChildTable = { ); }, // Transformation nodes - [354 /* PartiallyEmittedExpression */]: function visitEachChildOfPartiallyEmittedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { + [355 /* PartiallyEmittedExpression */]: function visitEachChildOfPartiallyEmittedExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) { return context.factory.updatePartiallyEmittedExpression( node, Debug.checkDefined(nodeVisitor(node.expression, visitor, isExpression)) ); }, - [355 /* CommaListExpression */]: function visitEachChildOfCommaListExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { + [356 /* CommaListExpression */]: function visitEachChildOfCommaListExpression(node, visitor, context, nodesVisitor, _nodeVisitor, _tokenVisitor) { return context.factory.updateCommaListExpression( node, nodesVisitor(node.elements, visitor, isExpression) @@ -95289,9 +95847,9 @@ function getDecoratorsOfParameters(node) { } return decorators; } -function getAllDecoratorsOfClass(node) { +function getAllDecoratorsOfClass(node, useLegacyDecorators) { const decorators = getDecorators(node); - const parameters = getDecoratorsOfParameters(getFirstConstructorWithBody(node)); + const parameters = useLegacyDecorators ? getDecoratorsOfParameters(getFirstConstructorWithBody(node)) : void 0; if (!some(decorators) && !some(parameters)) { return void 0; } @@ -95305,18 +95863,27 @@ function getAllDecoratorsOfClassElement(member, parent2, useLegacyDecorators) { case 177 /* GetAccessor */: case 178 /* SetAccessor */: if (!useLegacyDecorators) { - return getAllDecoratorsOfMethod(member); + return getAllDecoratorsOfMethod( + member, + /*useLegacyDecorators*/ + false + ); } - return getAllDecoratorsOfAccessors(member, parent2); + return getAllDecoratorsOfAccessors( + member, + parent2, + /*useLegacyDecorators*/ + true + ); case 174 /* MethodDeclaration */: - return getAllDecoratorsOfMethod(member); + return getAllDecoratorsOfMethod(member, useLegacyDecorators); case 172 /* PropertyDeclaration */: return getAllDecoratorsOfProperty(member); default: return void 0; } } -function getAllDecoratorsOfAccessors(accessor, parent2) { +function getAllDecoratorsOfAccessors(accessor, parent2, useLegacyDecorators) { if (!accessor.body) { return void 0; } @@ -95326,7 +95893,7 @@ function getAllDecoratorsOfAccessors(accessor, parent2) { return void 0; } const decorators = getDecorators(firstAccessorWithDecorators); - const parameters = getDecoratorsOfParameters(setAccessor); + const parameters = useLegacyDecorators ? getDecoratorsOfParameters(setAccessor) : void 0; if (!some(decorators) && !some(parameters)) { return void 0; } @@ -95337,12 +95904,12 @@ function getAllDecoratorsOfAccessors(accessor, parent2) { setDecorators: setAccessor && getDecorators(setAccessor) }; } -function getAllDecoratorsOfMethod(method) { +function getAllDecoratorsOfMethod(method, useLegacyDecorators) { if (!method.body) { return void 0; } const decorators = getDecorators(method); - const parameters = getDecoratorsOfParameters(method); + const parameters = useLegacyDecorators ? getDecoratorsOfParameters(method) : void 0; if (!some(decorators) && !some(parameters)) { return void 0; } @@ -95387,6 +95954,13 @@ function isSimpleParameter(node) { function isSimpleParameterList(nodes) { return every(nodes, isSimpleParameter); } +function rewriteModuleSpecifier(node, compilerOptions) { + if (!node || !isStringLiteral(node) || !shouldRewriteModuleSpecifier(node.text, compilerOptions)) { + return node; + } + const updatedText = changeExtension(node.text, getOutputExtension(node.text, compilerOptions)); + return updatedText !== node.text ? setOriginalNode(setTextRange(factory.createStringLiteral(updatedText, node.singleQuote), node), node) : node; +} // src/compiler/transformers/destructuring.ts var FlattenLevel = /* @__PURE__ */ ((FlattenLevel2) => { @@ -96210,7 +96784,7 @@ function transformTypeScript(context) { let currentNamespaceContainerName; let currentLexicalScope; let currentScopeFirstDeclarationsOfName; - let enabledSubstitutions; + let enabledSubstitutions = 0 /* None */; let applicableSubstitutions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { @@ -96440,6 +97014,8 @@ function transformTypeScript(context) { case 148 /* ReadonlyKeyword */: case 103 /* InKeyword */: case 147 /* OutKeyword */: + // TypeScript accessibility and readonly modifiers are elided + // falls through case 188 /* ArrayType */: case 189 /* TupleType */: case 190 /* OptionalType */: @@ -96468,6 +97044,8 @@ function transformTypeScript(context) { case 199 /* IndexedAccessType */: case 200 /* MappedType */: case 201 /* LiteralType */: + // TypeScript type nodes are elided. + // falls through case 181 /* IndexSignature */: return void 0; case 265 /* TypeAliasDeclaration */: @@ -97711,7 +98289,14 @@ function transformTypeScript(context) { return void 0; } if (!node.exportClause || isNamespaceExport(node.exportClause)) { - return node; + return factory2.updateExportDeclaration( + node, + node.modifiers, + node.isTypeOnly, + node.exportClause, + node.moduleSpecifier, + node.attributes + ); } const allowEmpty = !!compilerOptions.verbatimModuleSyntax; const exportClause = visitNode( @@ -97750,8 +98335,10 @@ function transformTypeScript(context) { return void 0; } if (isExternalModuleImportEqualsDeclaration(node)) { - const isReferenced = shouldEmitAliasDeclaration(node); - return isReferenced ? visitEachChild(node, visitor, context) : void 0; + if (!shouldEmitAliasDeclaration(node)) { + return void 0; + } + return visitEachChild(node, visitor, context); } if (!shouldEmitImportEqualsDeclaration(node)) { return void 0; @@ -98018,7 +98605,7 @@ function transformClassFields(context) { const previousOnEmitNode = context.onEmitNode; context.onEmitNode = onEmitNode; let shouldTransformPrivateStaticElementsInFile = false; - let enabledSubstitutions; + let enabledSubstitutions = 0 /* None */; let classAliases; let pendingExpressions; let pendingStatements; @@ -98150,7 +98737,7 @@ function transformClassFields(context) { /*discarded*/ true ); - case 355 /* CommaListExpression */: + case 356 /* CommaListExpression */: return visitCommaListExpression( node, /*discarded*/ @@ -100090,6 +100677,7 @@ function transformClassFields(context) { if (isArrowFunction(original) || getEmitFlags(node) & 524288 /* AsyncFunctionBody */) { break; } + // falls through case 262 /* FunctionDeclaration */: case 176 /* Constructor */: case 177 /* GetAccessor */: @@ -100365,6 +100953,7 @@ function createRuntimeTypeSerializer(context) { case 197 /* ThisType */: case 205 /* ImportType */: break; + // handle JSDoc types from an invalid parse case 312 /* JSDocAllType */: case 313 /* JSDocUnknownType */: case 317 /* JSDocFunctionType */: @@ -100964,7 +101553,11 @@ function transformLegacyDecorators(context) { } } function generateConstructorDecorationExpression(node) { - const allDecorators = getAllDecoratorsOfClass(node); + const allDecorators = getAllDecoratorsOfClass( + node, + /*useLegacyDecorators*/ + true + ); const decoratorExpressions = transformAllDecoratorsOfDeclaration(allDecorators); if (!decoratorExpressions) { return void 0; @@ -101210,6 +101803,7 @@ function transformESDecorators(context) { return Debug.fail("Not supported outside of a class. Use 'classElementVisitor' instead."); case 169 /* Parameter */: return visitParameterDeclaration(node); + // Support NamedEvaluation to ensure the correct class name for class expressions. case 226 /* BinaryExpression */: return visitBinaryExpression( node, @@ -101230,7 +101824,7 @@ function transformESDecorators(context) { return visitForStatement(node); case 244 /* ExpressionStatement */: return visitExpressionStatement(node); - case 355 /* CommaListExpression */: + case 356 /* CommaListExpression */: return visitCommaListExpression( node, /*discarded*/ @@ -101242,7 +101836,7 @@ function transformESDecorators(context) { /*discarded*/ false ); - case 354 /* PartiallyEmittedExpression */: + case 355 /* PartiallyEmittedExpression */: return visitPartiallyEmittedExpression( node, /*discarded*/ @@ -101266,6 +101860,7 @@ function transformESDecorators(context) { case 167 /* ComputedPropertyName */: return visitComputedPropertyName(node); case 174 /* MethodDeclaration */: + // object literal methods and accessors case 178 /* SetAccessor */: case 177 /* GetAccessor */: case 218 /* FunctionExpression */: @@ -101328,7 +101923,7 @@ function transformESDecorators(context) { /*discarded*/ true ); - case 355 /* CommaListExpression */: + case 356 /* CommaListExpression */: return visitCommaListExpression( node, /*discarded*/ @@ -101474,7 +102069,11 @@ function transformESDecorators(context) { let syntheticConstructor; let heritageClauses; let shouldTransformPrivateStaticElementsInClass = false; - const classDecorators = transformAllDecoratorsOfDeclaration(getAllDecoratorsOfClass(node)); + const classDecorators = transformAllDecoratorsOfDeclaration(getAllDecoratorsOfClass( + node, + /*useLegacyDecorators*/ + false + )); if (classDecorators) { classInfo2.classDecoratorsName = factory2.createUniqueName("_classDecorators", 16 /* Optimistic */ | 32 /* FileLevel */); classInfo2.classDescriptorName = factory2.createUniqueName("_classDescriptor", 16 /* Optimistic */ | 32 /* FileLevel */); @@ -102947,7 +103546,7 @@ function transformES2017(context) { const resolver = context.getEmitResolver(); const compilerOptions = context.getCompilerOptions(); const languageVersion = getEmitScriptTarget(compilerOptions); - let enabledSubstitutions; + let enabledSubstitutions = 0 /* None */; let enclosingSuperContainerFlags = 0; let enclosingFunctionParameterNames; let capturedSuperProperties; @@ -103822,7 +104421,7 @@ function transformES2018(context) { const previousOnSubstituteNode = context.onSubstituteNode; context.onSubstituteNode = onSubstituteNode; let exportedVariableStatement = false; - let enabledSubstitutions; + let enabledSubstitutions = 0 /* None */; let enclosingFunctionFlags; let parametersWithPrecedingObjectRestOrSpread; let enclosingSuperContainerFlags = 0; @@ -103910,7 +104509,7 @@ function transformES2018(context) { return visitObjectLiteralExpression(node); case 226 /* BinaryExpression */: return visitBinaryExpression(node, expressionResultIsUnused2); - case 355 /* CommaListExpression */: + case 356 /* CommaListExpression */: return visitCommaListExpression(node, expressionResultIsUnused2); case 299 /* CatchClause */: return visitCatchClause(node); @@ -106957,7 +107556,7 @@ function transformES2015(context) { ); } let convertedLoopState; - let enabledSubstitutions; + let enabledSubstitutions = 0 /* None */; return chainBundle(context, transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -107050,6 +107649,7 @@ function transformES2015(context) { switch (node.kind) { case 126 /* StaticKeyword */: return void 0; + // elide static keyword case 263 /* ClassDeclaration */: return visitClassDeclaration(node); case 231 /* ClassExpression */: @@ -107128,7 +107728,7 @@ function transformES2015(context) { return visitParenthesizedExpression(node, expressionResultIsUnused2); case 226 /* BinaryExpression */: return visitBinaryExpression(node, expressionResultIsUnused2); - case 355 /* CommaListExpression */: + case 356 /* CommaListExpression */: return visitCommaListExpression(node, expressionResultIsUnused2); case 15 /* NoSubstitutionTemplateLiteral */: case 16 /* TemplateHead */: @@ -107512,12 +108112,14 @@ function transformES2015(context) { return false; } switch (node.kind) { + // stop at function boundaries case 219 /* ArrowFunction */: case 218 /* FunctionExpression */: case 262 /* FunctionDeclaration */: case 176 /* Constructor */: case 175 /* ClassStaticBlockDeclaration */: return false; + // only step into computed property names for class and object literal elements case 177 /* GetAccessor */: case 178 /* SetAccessor */: case 174 /* MethodDeclaration */: @@ -107726,12 +108328,14 @@ function transformES2015(context) { return factory2.createPartiallyEmittedExpression(node.right, node); } switch (node.kind) { + // stop at function boundaries case 219 /* ArrowFunction */: case 218 /* FunctionExpression */: case 262 /* FunctionDeclaration */: case 176 /* Constructor */: case 175 /* ClassStaticBlockDeclaration */: return node; + // only step into computed property names for class and object literal elements case 177 /* GetAccessor */: case 178 /* SetAccessor */: case 174 /* MethodDeclaration */: @@ -107777,12 +108381,14 @@ function transformES2015(context) { ); } switch (node.kind) { + // stop at function boundaries case 219 /* ArrowFunction */: case 218 /* FunctionExpression */: case 262 /* FunctionDeclaration */: case 176 /* Constructor */: case 175 /* ClassStaticBlockDeclaration */: return node; + // only step into computed property names for class and object literal elements case 177 /* GetAccessor */: case 178 /* SetAccessor */: case 174 /* MethodDeclaration */: @@ -110414,7 +111020,7 @@ function transformGenerators(context) { switch (node.kind) { case 226 /* BinaryExpression */: return visitBinaryExpression(node); - case 355 /* CommaListExpression */: + case 356 /* CommaListExpression */: return visitCommaListExpression(node); case 227 /* ConditionalExpression */: return visitConditionalExpression(node); @@ -112310,6 +112916,7 @@ function transformModule(context) { const moduleInfoMap = []; let currentSourceFile; let currentModuleInfo; + let importsAndRequiresToRewriteOrShim; const noSubstitution = []; let needUMDDynamicImportHelper; return chainBundle(context, transformSourceFile); @@ -112320,6 +112927,20 @@ function transformModule(context) { currentSourceFile = node; currentModuleInfo = collectExternalModuleInfo(context, node); moduleInfoMap[getOriginalNodeId(node)] = currentModuleInfo; + if (compilerOptions.rewriteRelativeImportExtensions) { + forEachDynamicImportOrRequireCall( + node, + /*includeTypeSpaceImports*/ + false, + /*requireStringLiteralLikeArgument*/ + false, + (node2) => { + if (!isStringLiteralLike(node2.arguments[0]) || shouldRewriteModuleSpecifier(node2.arguments[0].text, compilerOptions)) { + importsAndRequiresToRewriteOrShim = append(importsAndRequiresToRewriteOrShim, node2); + } + } + ); + } const transformModule2 = getTransformModuleDelegate(moduleKind); const updated = transformModule2(node); currentSourceFile = void 0; @@ -112791,7 +113412,7 @@ function transformModule(context) { } } function visitorWorker(node, valueIsDiscarded) { - if (!(node.transformFlags & (8388608 /* ContainsDynamicImport */ | 4096 /* ContainsDestructuringAssignment */ | 268435456 /* ContainsUpdateExpressionForIdentifier */))) { + if (!(node.transformFlags & (8388608 /* ContainsDynamicImport */ | 4096 /* ContainsDestructuringAssignment */ | 268435456 /* ContainsUpdateExpressionForIdentifier */)) && !(importsAndRequiresToRewriteOrShim == null ? void 0 : importsAndRequiresToRewriteOrShim.length)) { return node; } switch (node.kind) { @@ -112805,11 +113426,17 @@ function transformModule(context) { return visitExpressionStatement(node); case 217 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, valueIsDiscarded); - case 354 /* PartiallyEmittedExpression */: + case 355 /* PartiallyEmittedExpression */: return visitPartiallyEmittedExpression(node, valueIsDiscarded); case 213 /* CallExpression */: + const needsRewrite = node === firstOrUndefined(importsAndRequiresToRewriteOrShim); + if (needsRewrite) { + importsAndRequiresToRewriteOrShim.shift(); + } if (isImportCall(node) && host.shouldTransformImportCall(currentSourceFile)) { - return visitImportCallExpression(node); + return visitImportCallExpression(node, needsRewrite); + } else if (needsRewrite) { + return shimOrRewriteImportOrRequireCall(node); } break; case 226 /* BinaryExpression */: @@ -113101,13 +113728,27 @@ function transformModule(context) { } return visitEachChild(node, visitor, context); } - function visitImportCallExpression(node) { + function shimOrRewriteImportOrRequireCall(node) { + return factory2.updateCallExpression( + node, + node.expression, + /*typeArguments*/ + void 0, + visitNodes2(node.arguments, (arg) => { + if (arg === node.arguments[0]) { + return isStringLiteralLike(arg) ? rewriteModuleSpecifier(arg, compilerOptions) : emitHelpers().createRewriteRelativeImportExtensionsHelper(arg); + } + return visitor(arg); + }, isExpression) + ); + } + function visitImportCallExpression(node, rewriteOrShim) { if (moduleKind === 0 /* None */ && languageVersion >= 7 /* ES2020 */) { return visitEachChild(node, visitor, context); } const externalModuleName = getExternalModuleNameLiteral(factory2, node, currentSourceFile, host, resolver, compilerOptions); const firstArgument = visitNode(firstOrUndefined(node.arguments), visitor, isExpression); - const argument = externalModuleName && (!firstArgument || !isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument; + const argument = externalModuleName && (!firstArgument || !isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument && rewriteOrShim ? isStringLiteral(firstArgument) ? rewriteModuleSpecifier(firstArgument, compilerOptions) : emitHelpers().createRewriteRelativeImportExtensionsHelper(firstArgument) : firstArgument; const containsLexicalThis = !!(node.transformFlags & 16384 /* ContainsLexicalThis */); switch (compilerOptions.module) { case 2 /* AMD */: @@ -113438,7 +114079,7 @@ function transformModule(context) { const moduleName = getExternalModuleNameLiteral(factory2, importNode, currentSourceFile, host, resolver, compilerOptions); const args = []; if (moduleName) { - args.push(moduleName); + args.push(rewriteModuleSpecifier(moduleName, compilerOptions)); } return factory2.createCallExpression( factory2.createIdentifier("require"), @@ -114565,6 +115206,7 @@ function transformSystemModule(context) { if (!entry.importClause) { break; } + // falls through case 271 /* ImportEqualsDeclaration */: Debug.assert(importVariableName !== void 0); statements.push( @@ -115199,7 +115841,7 @@ function transformSystemModule(context) { return visitExpressionStatement(node); case 217 /* ParenthesizedExpression */: return visitParenthesizedExpression(node, valueIsDiscarded); - case 354 /* PartiallyEmittedExpression */: + case 355 /* PartiallyEmittedExpression */: return visitPartiallyEmittedExpression(node, valueIsDiscarded); case 226 /* BinaryExpression */: if (isDestructuringAssignment(node)) { @@ -115532,6 +116174,8 @@ function transformECMAScriptModule(context) { context.onSubstituteNode = onSubstituteNode; context.enableEmitNotification(307 /* SourceFile */); context.enableSubstitution(80 /* Identifier */); + const noSubstitution = /* @__PURE__ */ new Set(); + let importsAndRequiresToRewriteOrShim; let helperNameSubstitutions; let currentSourceFile; let importRequireStatements; @@ -115543,7 +116187,22 @@ function transformECMAScriptModule(context) { if (isExternalModule(node) || getIsolatedModules(compilerOptions)) { currentSourceFile = node; importRequireStatements = void 0; + if (compilerOptions.rewriteRelativeImportExtensions && (currentSourceFile.flags & 4194304 /* PossiblyContainsDynamicImport */ || isInJSFile(node))) { + forEachDynamicImportOrRequireCall( + node, + /*includeTypeSpaceImports*/ + false, + /*requireStringLiteralLikeArgument*/ + false, + (node2) => { + if (!isStringLiteralLike(node2.arguments[0]) || shouldRewriteModuleSpecifier(node2.arguments[0].text, compilerOptions)) { + importsAndRequiresToRewriteOrShim = append(importsAndRequiresToRewriteOrShim, node2); + } + } + ); + } let result = updateExternalModule(node); + addEmitHelpers(result, context.readEmitHelpers()); currentSourceFile = void 0; if (importRequireStatements) { result = factory2.updateSourceFile( @@ -115566,7 +116225,7 @@ function transformECMAScriptModule(context) { if (externalHelpersImportDeclaration) { const statements = []; const statementOffset = factory2.copyPrologue(node.statements, statements); - append(statements, externalHelpersImportDeclaration); + addRange(statements, visitArray([externalHelpersImportDeclaration], visitor, isStatement)); addRange(statements, visitNodes2(node.statements, visitor, isStatement, statementOffset)); return factory2.updateSourceFile( node, @@ -115585,14 +116244,52 @@ function transformECMAScriptModule(context) { case 278 /* ExportDeclaration */: const exportDecl = node; return visitExportDeclaration(exportDecl); + case 272 /* ImportDeclaration */: + return visitImportDeclaration(node); + case 213 /* CallExpression */: + if (node === (importsAndRequiresToRewriteOrShim == null ? void 0 : importsAndRequiresToRewriteOrShim[0])) { + return visitImportOrRequireCall(importsAndRequiresToRewriteOrShim.shift()); + } + break; + default: + if ((importsAndRequiresToRewriteOrShim == null ? void 0 : importsAndRequiresToRewriteOrShim.length) && rangeContainsRange(node, importsAndRequiresToRewriteOrShim[0])) { + return visitEachChild(node, visitor, context); + } } return node; } + function visitImportDeclaration(node) { + if (!compilerOptions.rewriteRelativeImportExtensions) { + return node; + } + const updatedModuleSpecifier = rewriteModuleSpecifier(node.moduleSpecifier, compilerOptions); + if (updatedModuleSpecifier === node.moduleSpecifier) { + return node; + } + return factory2.updateImportDeclaration( + node, + node.modifiers, + node.importClause, + updatedModuleSpecifier, + node.attributes + ); + } + function visitImportOrRequireCall(node) { + return factory2.updateCallExpression( + node, + node.expression, + node.typeArguments, + [ + isStringLiteralLike(node.arguments[0]) ? rewriteModuleSpecifier(node.arguments[0], compilerOptions) : emitHelpers().createRewriteRelativeImportExtensionsHelper(node.arguments[0]), + ...node.arguments.slice(1) + ] + ); + } function createRequireCall2(importNode) { const moduleName = getExternalModuleNameLiteral(factory2, importNode, Debug.checkDefined(currentSourceFile), host, resolver, compilerOptions); const args = []; if (moduleName) { - args.push(moduleName); + args.push(rewriteModuleSpecifier(moduleName, compilerOptions)); } if (getEmitModuleKind(compilerOptions) === 200 /* Preserve */) { return factory2.createCallExpression( @@ -115737,11 +116434,16 @@ function transformECMAScriptModule(context) { return node; } function visitExportDeclaration(node) { - if (compilerOptions.module !== void 0 && compilerOptions.module > 5 /* ES2015 */) { - return node; - } - if (!node.exportClause || !isNamespaceExport(node.exportClause) || !node.moduleSpecifier) { - return node; + const updatedModuleSpecifier = rewriteModuleSpecifier(node.moduleSpecifier, compilerOptions); + if (compilerOptions.module !== void 0 && compilerOptions.module > 5 /* ES2015 */ || !node.exportClause || !isNamespaceExport(node.exportClause) || !node.moduleSpecifier) { + return !node.moduleSpecifier || updatedModuleSpecifier === node.moduleSpecifier ? node : factory2.updateExportDeclaration( + node, + node.modifiers, + node.isTypeOnly, + node.exportClause, + updatedModuleSpecifier, + node.attributes + ); } const oldIdentifier = node.exportClause.name; const synthName = factory2.getGeneratedNameForNode(oldIdentifier); @@ -115757,7 +116459,7 @@ function transformECMAScriptModule(context) { synthName ) ), - node.moduleSpecifier, + updatedModuleSpecifier, node.attributes ); setOriginalNode(importDecl, node.exportClause); @@ -115781,7 +116483,9 @@ function transformECMAScriptModule(context) { if ((isExternalModule(node) || getIsolatedModules(compilerOptions)) && compilerOptions.importHelpers) { helperNameSubstitutions = /* @__PURE__ */ new Map(); } + currentSourceFile = node; previousOnEmitNode(hint, node, emitCallback); + currentSourceFile = void 0; helperNameSubstitutions = void 0; } else { previousOnEmitNode(hint, node, emitCallback); @@ -115789,18 +116493,29 @@ function transformECMAScriptModule(context) { } function onSubstituteNode(hint, node) { node = previousOnSubstituteNode(hint, node); - if (helperNameSubstitutions && isIdentifier(node) && getEmitFlags(node) & 8192 /* HelperName */) { + if (node.id && noSubstitution.has(node.id)) { + return node; + } + if (isIdentifier(node) && getEmitFlags(node) & 8192 /* HelperName */) { return substituteHelperName(node); } return node; } function substituteHelperName(node) { - const name = idText(node); - let substitution = helperNameSubstitutions.get(name); - if (!substitution) { - helperNameSubstitutions.set(name, substitution = factory2.createUniqueName(name, 16 /* Optimistic */ | 32 /* FileLevel */)); + const externalHelpersModuleName = currentSourceFile && getExternalHelpersModuleName(currentSourceFile); + if (externalHelpersModuleName) { + noSubstitution.add(getNodeId(node)); + return factory2.createPropertyAccessExpression(externalHelpersModuleName, node); } - return substitution; + if (helperNameSubstitutions) { + const name = idText(node); + let substitution = helperNameSubstitutions.get(name); + if (!substitution) { + helperNameSubstitutions.set(name, substitution = factory2.createUniqueName(name, 16 /* Optimistic */ | 32 /* FileLevel */)); + } + return substitution; + } + return node; } } @@ -116150,8 +116865,8 @@ function createGetIsolatedDeclarationErrors(resolver) { [219 /* ArrowFunction */]: Diagnostics.Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations, [174 /* MethodDeclaration */]: Diagnostics.Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations, [180 /* ConstructSignature */]: Diagnostics.Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations, - [177 /* GetAccessor */]: Diagnostics.At_least_one_accessor_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations, - [178 /* SetAccessor */]: Diagnostics.At_least_one_accessor_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations, + [177 /* GetAccessor */]: Diagnostics.At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations, + [178 /* SetAccessor */]: Diagnostics.At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations, [169 /* Parameter */]: Diagnostics.Parameter_must_have_an_explicit_type_annotation_with_isolatedDeclarations, [260 /* VariableDeclaration */]: Diagnostics.Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations, [172 /* PropertyDeclaration */]: Diagnostics.Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations, @@ -116280,7 +116995,7 @@ function createGetIsolatedDeclarationErrors(resolver) { if (!addUndefined && node.initializer) { return createExpressionError(node.initializer); } - const message = addUndefined ? Diagnostics.Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_it_s_type_This_is_not_supported_with_isolatedDeclarations : errorByDeclarationKind[node.kind]; + const message = addUndefined ? Diagnostics.Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_its_type_This_is_not_supported_with_isolatedDeclarations : errorByDeclarationKind[node.kind]; const diag2 = createDiagnosticForNode(node, message); const targetStr = getTextOfNode( node.name, @@ -116358,6 +117073,7 @@ function transformDeclarations(context) { let suppressNewDiagnosticContexts; const { factory: factory2 } = context; const host = context.getEmitHost(); + let restoreFallbackNode = () => void 0; const symbolTracker = { trackSymbol, reportInaccessibleThisError, @@ -116369,7 +117085,19 @@ function transformDeclarations(context) { moduleResolverHost: host, reportNonlocalAugmentation, reportNonSerializableProperty, - reportInferenceFallback + reportInferenceFallback, + pushErrorFallbackNode(node) { + const currentFallback = errorFallbackNode; + const currentRestore = restoreFallbackNode; + restoreFallbackNode = () => { + restoreFallbackNode = currentRestore; + errorFallbackNode = currentFallback; + }; + errorFallbackNode = node; + }, + popErrorFallbackNode() { + restoreFallbackNode(); + } }; let errorNameNode; let errorFallbackNode; @@ -116706,7 +117434,7 @@ function transformDeclarations(context) { ); } } - function ensureParameter(p, modifierMask, type) { + function ensureParameter(p, modifierMask) { let oldDiag; if (!suppressNewDiagnosticContexts) { oldDiag = getSymbolAccessibilityDiagnostic; @@ -116720,7 +117448,6 @@ function transformDeclarations(context) { resolver.isOptionalParameter(p) ? p.questionToken || factory2.createToken(58 /* QuestionToken */) : void 0, ensureType( p, - type || p.type, /*ignorePrivate*/ true ), @@ -116745,44 +117472,34 @@ function transformDeclarations(context) { } return void 0; } - function ensureType(node, type, ignorePrivate) { + function ensureType(node, ignorePrivate) { if (!ignorePrivate && hasEffectiveModifier(node, 2 /* Private */)) { return; } if (shouldPrintWithInitializer(node)) { return; } - const shouldAddImplicitUndefined = node.kind === 169 /* Parameter */ && resolver.requiresAddingImplicitUndefined(node, enclosingDeclaration); - if (type && !shouldAddImplicitUndefined) { - return visitNode(type, visitDeclarationSubtree, isTypeNode); + if (!isExportAssignment(node) && !isBindingElement(node) && node.type && (!isParameter(node) || !resolver.requiresAddingImplicitUndefined(node, enclosingDeclaration))) { + return visitNode(node.type, visitDeclarationSubtree, isTypeNode); } + const oldErrorNameNode = errorNameNode; errorNameNode = node.name; let oldDiag; if (!suppressNewDiagnosticContexts) { oldDiag = getSymbolAccessibilityDiagnostic; - getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(node); + if (canProduceDiagnostics(node)) { + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(node); + } } let typeNode; - switch (node.kind) { - case 169 /* Parameter */: - case 171 /* PropertySignature */: - case 172 /* PropertyDeclaration */: - case 208 /* BindingElement */: - case 260 /* VariableDeclaration */: - typeNode = resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker); - break; - case 262 /* FunctionDeclaration */: - case 180 /* ConstructSignature */: - case 173 /* MethodSignature */: - case 174 /* MethodDeclaration */: - case 177 /* GetAccessor */: - case 179 /* CallSignature */: - typeNode = resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker); - break; - default: - Debug.assertNever(node); + if (hasInferredType(node)) { + typeNode = resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker); + } else if (isFunctionLike(node)) { + typeNode = resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker); + } else { + Debug.assertNever(node); } - errorNameNode = void 0; + errorNameNode = oldErrorNameNode; if (!suppressNewDiagnosticContexts) { getSymbolAccessibilityDiagnostic = oldDiag; } @@ -116798,6 +117515,7 @@ function transformDeclarations(context) { case 265 /* TypeAliasDeclaration */: case 266 /* EnumDeclaration */: return !resolver.isDeclarationVisible(node); + // The following should be doing their own visibility checks based on filtering their members case 260 /* VariableDeclaration */: return !getBindingNameVisible(node); case 271 /* ImportEqualsDeclaration */: @@ -116851,13 +117569,7 @@ function transformDeclarations(context) { if (!isPrivate) { const valueParameter = getSetAccessorValueParameter(input); if (valueParameter) { - const accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, getAllAccessorDeclarations(isObjectLiteralExpression(input.parent) ? input.parent.properties : input.parent.members, input)); - newValueParameter = ensureParameter( - valueParameter, - /*modifierMask*/ - void 0, - accessorType - ); + newValueParameter = ensureParameter(valueParameter); } } if (!newValueParameter) { @@ -116889,7 +117601,7 @@ function transformDeclarations(context) { } return setCommentRange(updated, getCommentRange(original)); } - function rewriteModuleSpecifier(parent2, input) { + function rewriteModuleSpecifier2(parent2, input) { if (!input) return void 0; resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent2.kind !== 267 /* ModuleDeclaration */ && parent2.kind !== 205 /* ImportType */; if (isStringLiteralLike(input)) { @@ -116911,7 +117623,7 @@ function transformDeclarations(context) { decl.modifiers, decl.isTypeOnly, decl.name, - factory2.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)) + factory2.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier2(decl, specifier)) ); } else { const oldDiag = getSymbolAccessibilityDiagnostic; @@ -116927,7 +117639,7 @@ function transformDeclarations(context) { decl, decl.modifiers, decl.importClause, - rewriteModuleSpecifier(decl, decl.moduleSpecifier), + rewriteModuleSpecifier2(decl, decl.moduleSpecifier), tryGetResolutionModeOverride(decl.attributes) ); } @@ -116943,7 +117655,7 @@ function transformDeclarations(context) { /*namedBindings*/ void 0 ), - rewriteModuleSpecifier(decl, decl.moduleSpecifier), + rewriteModuleSpecifier2(decl, decl.moduleSpecifier), tryGetResolutionModeOverride(decl.attributes) ); } @@ -116961,7 +117673,7 @@ function transformDeclarations(context) { visibleDefaultBinding, namedBindings ), - rewriteModuleSpecifier(decl, decl.moduleSpecifier), + rewriteModuleSpecifier2(decl, decl.moduleSpecifier), tryGetResolutionModeOverride(decl.attributes) ) : void 0; } @@ -116976,7 +117688,7 @@ function transformDeclarations(context) { visibleDefaultBinding, bindingList && bindingList.length ? factory2.updateNamedImports(decl.importClause.namedBindings, bindingList) : void 0 ), - rewriteModuleSpecifier(decl, decl.moduleSpecifier), + rewriteModuleSpecifier2(decl, decl.moduleSpecifier), tryGetResolutionModeOverride(decl.attributes) ); } @@ -116989,7 +117701,7 @@ function transformDeclarations(context) { decl.modifiers, /*importClause*/ void 0, - rewriteModuleSpecifier(decl, decl.moduleSpecifier), + rewriteModuleSpecifier2(decl, decl.moduleSpecifier), tryGetResolutionModeOverride(decl.attributes) ); } @@ -117108,7 +117820,7 @@ function transformDeclarations(context) { input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), - ensureType(input, input.type) + ensureType(input) )); case 176 /* Constructor */: { const ctor = factory2.createConstructorDeclaration( @@ -117135,7 +117847,7 @@ function transformDeclarations(context) { input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), - ensureType(input, input.type), + ensureType(input), /*body*/ void 0 ); @@ -117148,13 +117860,12 @@ function transformDeclarations(context) { void 0 ); } - const accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, getAllAccessorDeclarations(isObjectLiteralExpression(input.parent) ? input.parent.properties : input.parent.members, input)); return cleanup(factory2.updateGetAccessorDeclaration( input, ensureModifiers(input), input.name, updateAccessorParamsList(input, hasEffectiveModifier(input, 2 /* Private */)), - ensureType(input, accessorType), + ensureType(input), /*body*/ void 0 )); @@ -117187,7 +117898,7 @@ function transformDeclarations(context) { ensureModifiers(input), input.name, input.questionToken, - ensureType(input, input.type), + ensureType(input), ensureNoInitializer(input) )); case 171 /* PropertySignature */: @@ -117202,7 +117913,7 @@ function transformDeclarations(context) { ensureModifiers(input), input.name, input.questionToken, - ensureType(input, input.type) + ensureType(input) )); case 173 /* MethodSignature */: { if (isPrivateIdentifier(input.name)) { @@ -117218,7 +117929,7 @@ function transformDeclarations(context) { input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), - ensureType(input, input.type) + ensureType(input) )); } case 179 /* CallSignature */: { @@ -117227,7 +117938,7 @@ function transformDeclarations(context) { input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), - ensureType(input, input.type) + ensureType(input) ) ); } @@ -117250,7 +117961,7 @@ function transformDeclarations(context) { input.name, /*exclamationToken*/ void 0, - ensureType(input, input.type), + ensureType(input), ensureNoInitializer(input) )); } @@ -117303,7 +118014,7 @@ function transformDeclarations(context) { if (!isLiteralImportTypeNode(input)) return cleanup(input); return cleanup(factory2.updateImportTypeNode( input, - factory2.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), + factory2.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier2(input, input.argument.literal)), input.attributes, input.qualifier, visitNodes2(input.typeArguments, visitDeclarationSubtree, isTypeNode), @@ -117356,7 +118067,7 @@ function transformDeclarations(context) { input.modifiers, input.isTypeOnly, input.exportClause, - rewriteModuleSpecifier(input, input.moduleSpecifier), + rewriteModuleSpecifier2(input, input.moduleSpecifier), tryGetResolutionModeOverride(input.attributes) ); } @@ -117374,11 +118085,12 @@ function transformDeclarations(context) { errorNode: input }); errorFallbackNode = input; + const type = ensureType(input); const varDecl = factory2.createVariableDeclaration( newId, /*exclamationToken*/ void 0, - resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker), + type, /*initializer*/ void 0 ); @@ -117475,7 +118187,7 @@ function transformDeclarations(context) { input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), - ensureType(input, input.type), + ensureType(input), /*body*/ void 0 )); @@ -117606,7 +118318,7 @@ function transformDeclarations(context) { return cleanup(updateModuleDeclarationAndKeyword( input, mods, - isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, + isExternalModuleAugmentation(input) ? rewriteModuleSpecifier2(input, input.name) : input.name, body )); } else { @@ -117643,7 +118355,7 @@ function transformDeclarations(context) { ensureModifiers(param), param.name, param.questionToken, - ensureType(param, param.type), + ensureType(param), ensureNoInitializer(param) ), param @@ -117664,11 +118376,7 @@ function transformDeclarations(context) { elem.name, /*questionOrExclamationToken*/ void 0, - ensureType( - elem, - /*type*/ - void 0 - ), + ensureType(elem), /*initializer*/ void 0 )); @@ -117692,7 +118400,8 @@ function transformDeclarations(context) { void 0 ) ] : void 0; - const memberNodes = concatenate(concatenate(privateIdentifier, parameterProperties), visitNodes2(input.members, visitDeclarationSubtree, isClassElement)); + const lateIndexes = resolver.createLateBoundIndexSignatures(input, enclosingDeclaration, declarationEmitNodeBuilderFlags, declarationEmitInternalNodeBuilderFlags, symbolTracker); + const memberNodes = concatenate(concatenate(concatenate(privateIdentifier, lateIndexes), parameterProperties), visitNodes2(input.members, visitDeclarationSubtree, isClassElement)); const members = factory2.createNodeArray(memberNodes); const extendsClause = getEffectiveBaseTypeNode(input); if (extendsClause && !isEntityNameExpression(extendsClause.expression) && extendsClause.expression.kind !== 106 /* NullKeyword */) { @@ -117818,11 +118527,7 @@ function transformDeclarations(context) { e.name, /*exclamationToken*/ void 0, - ensureType( - e, - /*type*/ - void 0 - ), + ensureType(e), /*initializer*/ void 0 ); @@ -117872,18 +118577,6 @@ function transformDeclarations(context) { } return maskModifierFlags(node, mask2, additions); } - function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) { - let accessorType = getTypeAnnotationFromAccessor(node); - if (!accessorType && node !== accessors.firstAccessor) { - accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor); - getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(accessors.firstAccessor); - } - if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) { - accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor); - getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor); - } - return accessorType; - } function transformHeritageClauses(nodes) { return factory2.createNodeArray(filter( map(nodes, (clause) => factory2.updateHeritageClause( @@ -117919,11 +118612,6 @@ function maskModifierFlags(node, modifierMask = 131071 /* All */ ^ 1 /* Public * } return flags; } -function getTypeAnnotationFromAccessor(accessor) { - if (accessor) { - return accessor.kind === 177 /* GetAccessor */ ? accessor.type : accessor.parameters.length > 0 ? accessor.parameters[0].type : void 0; - } -} function canHaveLiteralInitializer(node) { switch (node.kind) { case 172 /* PropertyDeclaration */: @@ -118079,7 +118767,7 @@ function noEmitNotification(hint, node, callback) { } function transformNodes(resolver, host, factory2, options, nodes, transformers, allowDtsFiles) { var _a, _b; - const enabledSyntaxKindFeatures = new Array(357 /* Count */); + const enabledSyntaxKindFeatures = new Array(358 /* Count */); let lexicalEnvironmentVariableDeclarations; let lexicalEnvironmentFunctionDeclarations; let lexicalEnvironmentStatements; @@ -119008,7 +119696,8 @@ var notImplementedResolver = { isBindingCapturedByNode: notImplemented, getDeclarationStatementsForSourceFile: notImplemented, isImportRequiredByAugmentation: notImplemented, - isDefinitelyReferenceToGlobalSymbolObject: notImplemented + isDefinitelyReferenceToGlobalSymbolObject: notImplemented, + createLateBoundIndexSignatures: notImplemented }; var createPrinterWithDefaults = /* @__PURE__ */ memoize(() => createPrinter({})); var createPrinterWithRemoveComments = /* @__PURE__ */ memoize(() => createPrinter({ removeComments: true })); @@ -119293,6 +119982,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { if (onEmitNode !== noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) { return pipelineEmitWithNotification; } + // falls through case 1 /* Substitution */: if (substituteNode !== noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node) || node) !== node) { if (currentParenthesizerRule) { @@ -119300,14 +119990,17 @@ function createPrinter(printerOptions = {}, handlers = {}) { } return pipelineEmitWithSubstitution; } + // falls through case 2 /* Comments */: if (shouldEmitComments(node)) { return pipelineEmitWithComments; } + // falls through case 3 /* SourceMaps */: if (shouldEmitSourceMaps(node)) { return pipelineEmitWithSourceMaps; } + // falls through case 4 /* Emit */: return pipelineEmitWithHint; default: @@ -119359,6 +120052,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } if (hint === 4 /* Unspecified */) { switch (node.kind) { + // Pseudo-literals case 16 /* TemplateHead */: case 17 /* TemplateMiddle */: case 18 /* TemplateTail */: @@ -119367,20 +120061,26 @@ function createPrinter(printerOptions = {}, handlers = {}) { /*jsxAttributeEscape*/ false ); + // Identifiers case 80 /* Identifier */: return emitIdentifier(node); + // PrivateIdentifiers case 81 /* PrivateIdentifier */: return emitPrivateIdentifier(node); + // Parse tree nodes + // Names case 166 /* QualifiedName */: return emitQualifiedName(node); case 167 /* ComputedPropertyName */: return emitComputedPropertyName(node); + // Signature elements case 168 /* TypeParameter */: return emitTypeParameter(node); case 169 /* Parameter */: return emitParameter(node); case 170 /* Decorator */: return emitDecorator(node); + // Type members case 171 /* PropertySignature */: return emitPropertySignature(node); case 172 /* PropertyDeclaration */: @@ -119402,6 +120102,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitConstructSignature(node); case 181 /* IndexSignature */: return emitIndexSignature(node); + // Types case 182 /* TypePredicate */: return emitTypePredicate(node); case 183 /* TypeReference */: @@ -119420,6 +120121,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitTupleType(node); case 190 /* OptionalType */: return emitOptionalType(node); + // SyntaxKind.RestType is handled below case 192 /* UnionType */: return emitUnionType(node); case 193 /* IntersectionType */: @@ -119450,16 +120152,19 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitTemplateTypeSpan(node); case 205 /* ImportType */: return emitImportTypeNode(node); + // Binding patterns case 206 /* ObjectBindingPattern */: return emitObjectBindingPattern(node); case 207 /* ArrayBindingPattern */: return emitArrayBindingPattern(node); case 208 /* BindingElement */: return emitBindingElement(node); + // Misc case 239 /* TemplateSpan */: return emitTemplateSpan(node); case 240 /* SemicolonClassElement */: return emitSemicolonClassElement(); + // Statements case 241 /* Block */: return emitBlock(node); case 243 /* VariableStatement */: @@ -119501,6 +120206,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitTryStatement(node); case 259 /* DebuggerStatement */: return emitDebuggerStatement(node); + // Declarations case 260 /* VariableDeclaration */: return emitVariableDeclaration(node); case 261 /* VariableDeclarationList */: @@ -119551,8 +120257,10 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitImportAttribute(node); case 282 /* MissingDeclaration */: return; + // Module references case 283 /* ExternalModuleReference */: return emitExternalModuleReference(node); + // JSX (non-expression) case 12 /* JsxText */: return emitJsxText(node); case 286 /* JsxOpeningElement */: @@ -119571,6 +120279,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitJsxExpression(node); case 295 /* JsxNamespacedName */: return emitJsxNamespacedName(node); + // Clauses case 296 /* CaseClause */: return emitCaseClause(node); case 297 /* DefaultClause */: @@ -119579,18 +120288,22 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitHeritageClause(node); case 299 /* CatchClause */: return emitCatchClause(node); + // Property assignments case 303 /* PropertyAssignment */: return emitPropertyAssignment(node); case 304 /* ShorthandPropertyAssignment */: return emitShorthandPropertyAssignment(node); case 305 /* SpreadAssignment */: return emitSpreadAssignment(node); + // Enum case 306 /* EnumMember */: return emitEnumMember(node); + // Top-level nodes case 307 /* SourceFile */: return emitSourceFile(node); case 308 /* Bundle */: return Debug.fail("Bundles should be printed using printBundle"); + // JSDoc nodes (only used in codefixes currently) case 309 /* JSDocTypeExpression */: return emitJSDocTypeExpression(node); case 310 /* JSDocNameReference */: @@ -119628,6 +120341,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { case 330 /* JSDocAuthorTag */: case 331 /* JSDocDeprecatedTag */: return; + // SyntaxKind.JSDocClassTag (see JSDocTag, above) case 333 /* JSDocPublicTag */: case 334 /* JSDocPrivateTag */: case 335 /* JSDocProtectedTag */: @@ -119637,6 +120351,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitJSDocCallbackTag(node); case 339 /* JSDocOverloadTag */: return emitJSDocOverloadTag(node); + // SyntaxKind.JSDocEnumTag (see below) case 341 /* JSDocParameterTag */: case 348 /* JSDocPropertyTag */: return emitJSDocPropertyLikeTag(node); @@ -119655,7 +120370,10 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitJSDocSeeTag(node); case 351 /* JSDocImportTag */: return emitJSDocImportTag(node); + // SyntaxKind.JSDocPropertyTag (see JSDocParameterTag, above) + // Transformation nodes case 353 /* NotEmittedStatement */: + case 354 /* NotEmittedTypeElement */: return; } if (isExpression(node)) { @@ -119673,6 +120391,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } if (hint === 1 /* Expression */) { switch (node.kind) { + // Literals case 9 /* NumericLiteral */: case 10 /* BigIntLiteral */: return emitNumericOrBigIntLiteral(node); @@ -119684,10 +120403,12 @@ function createPrinter(printerOptions = {}, handlers = {}) { /*jsxAttributeEscape*/ false ); + // Identifiers case 80 /* Identifier */: return emitIdentifier(node); case 81 /* PrivateIdentifier */: return emitPrivateIdentifier(node); + // Expressions case 209 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); case 210 /* ObjectLiteralExpression */: @@ -119750,21 +120471,24 @@ function createPrinter(printerOptions = {}, handlers = {}) { return Debug.fail("SyntheticExpression should never be printed."); case 282 /* MissingDeclaration */: return; + // JSX case 284 /* JsxElement */: return emitJsxElement(node); case 285 /* JsxSelfClosingElement */: return emitJsxSelfClosingElement(node); case 288 /* JsxFragment */: return emitJsxFragment(node); + // Synthesized list case 352 /* SyntaxList */: return Debug.fail("SyntaxList should not be printed"); + // Transformation nodes case 353 /* NotEmittedStatement */: return; - case 354 /* PartiallyEmittedExpression */: + case 355 /* PartiallyEmittedExpression */: return emitPartiallyEmittedExpression(node); - case 355 /* CommaListExpression */: + case 356 /* CommaListExpression */: return emitCommaList(node); - case 356 /* SyntheticReferenceExpression */: + case 357 /* SyntheticReferenceExpression */: return Debug.fail("SyntheticReferenceExpression should not be printed"); } } @@ -120855,15 +121579,88 @@ function createPrinter(printerOptions = {}, handlers = {}) { return false; } function parenthesizeExpressionForNoAsi(node) { - if (!commentsDisabled && isPartiallyEmittedExpression(node) && willEmitLeadingNewLine(node)) { - const parseNode = getParseTreeNode(node); - if (parseNode && isParenthesizedExpression(parseNode)) { - const parens = factory.createParenthesizedExpression(node.expression); - setOriginalNode(parens, node); - setTextRange(parens, parseNode); - return parens; + if (!commentsDisabled) { + switch (node.kind) { + case 355 /* PartiallyEmittedExpression */: + if (willEmitLeadingNewLine(node)) { + const parseNode = getParseTreeNode(node); + if (parseNode && isParenthesizedExpression(parseNode)) { + const parens = factory.createParenthesizedExpression(node.expression); + setOriginalNode(parens, node); + setTextRange(parens, parseNode); + return parens; + } + return factory.createParenthesizedExpression(node); + } + return factory.updatePartiallyEmittedExpression( + node, + parenthesizeExpressionForNoAsi(node.expression) + ); + case 211 /* PropertyAccessExpression */: + return factory.updatePropertyAccessExpression( + node, + parenthesizeExpressionForNoAsi(node.expression), + node.name + ); + case 212 /* ElementAccessExpression */: + return factory.updateElementAccessExpression( + node, + parenthesizeExpressionForNoAsi(node.expression), + node.argumentExpression + ); + case 213 /* CallExpression */: + return factory.updateCallExpression( + node, + parenthesizeExpressionForNoAsi(node.expression), + node.typeArguments, + node.arguments + ); + case 215 /* TaggedTemplateExpression */: + return factory.updateTaggedTemplateExpression( + node, + parenthesizeExpressionForNoAsi(node.tag), + node.typeArguments, + node.template + ); + case 225 /* PostfixUnaryExpression */: + return factory.updatePostfixUnaryExpression( + node, + parenthesizeExpressionForNoAsi(node.operand) + ); + case 226 /* BinaryExpression */: + return factory.updateBinaryExpression( + node, + parenthesizeExpressionForNoAsi(node.left), + node.operatorToken, + node.right + ); + case 227 /* ConditionalExpression */: + return factory.updateConditionalExpression( + node, + parenthesizeExpressionForNoAsi(node.condition), + node.questionToken, + node.whenTrue, + node.colonToken, + node.whenFalse + ); + case 234 /* AsExpression */: + return factory.updateAsExpression( + node, + parenthesizeExpressionForNoAsi(node.expression), + node.type + ); + case 238 /* SatisfiesExpression */: + return factory.updateSatisfiesExpression( + node, + parenthesizeExpressionForNoAsi(node.expression), + node.type + ); + case 235 /* NonNullExpression */: + return factory.updateNonNullExpression( + node, + parenthesizeExpressionForNoAsi(node.expression) + ); } - return factory.createParenthesizedExpression(node); } return node; } @@ -123921,7 +124718,7 @@ function resolveTripleslashReference(moduleName, containingFile) { } function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) { let commonPathComponents; - const failed = forEach(fileNames, (sourceFile) => { + const failed2 = forEach(fileNames, (sourceFile) => { const sourcePathComponents = getNormalizedPathComponents(sourceFile, currentDirectory); sourcePathComponents.pop(); if (!commonPathComponents) { @@ -123942,7 +124739,7 @@ function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, ge commonPathComponents.length = sourcePathComponents.length; } }); - if (failed) { + if (failed2) { return ""; } if (!commonPathComponents) { @@ -124458,15 +125255,22 @@ function forEachProjectReference(projectReferences, resolvedProjectReferences, c const result = cbRef(projectReferences2, parent2); if (result) return result; } - return forEach(resolvedProjectReferences2, (resolvedRef, index) => { - if (resolvedRef && (seenResolvedRefs == null ? void 0 : seenResolvedRefs.has(resolvedRef.sourceFile.path))) { - return void 0; + let skipChildren; + return forEach( + resolvedProjectReferences2, + (resolvedRef, index) => { + if (resolvedRef && (seenResolvedRefs == null ? void 0 : seenResolvedRefs.has(resolvedRef.sourceFile.path))) { + (skipChildren ?? (skipChildren = /* @__PURE__ */ new Set())).add(resolvedRef); + return void 0; + } + const result = cbResolvedRef(resolvedRef, parent2, index); + if (result || !resolvedRef) return result; + (seenResolvedRefs || (seenResolvedRefs = /* @__PURE__ */ new Set())).add(resolvedRef.sourceFile.path); } - const result = cbResolvedRef(resolvedRef, parent2, index); - if (result || !resolvedRef) return result; - (seenResolvedRefs || (seenResolvedRefs = /* @__PURE__ */ new Set())).add(resolvedRef.sourceFile.path); - return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef); - }); + ) || forEach( + resolvedProjectReferences2, + (resolvedRef) => resolvedRef && !(skipChildren == null ? void 0 : skipChildren.has(resolvedRef)) ? worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef) : void 0 + ); } } var inferredTypesContainingFile = "__inferred type names__.ts"; @@ -124564,7 +125368,13 @@ function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, if (oldResolvedRef.commandLine.options.configFile !== newParsedCommandLine.options.configFile) return false; if (!arrayIsEqualTo(oldResolvedRef.commandLine.fileNames, newParsedCommandLine.fileNames)) return false; (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef); - return !forEach(oldResolvedRef.references, (childResolvedRef, index) => !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index])); + return !forEach( + oldResolvedRef.references, + (childResolvedRef, index) => !resolvedProjectReferenceUptoDate( + childResolvedRef, + oldResolvedRef.commandLine.projectReferences[index] + ) + ); } const refPath = resolveProjectReferencePath(oldRef); return !getParsedCommandLine(refPath); @@ -124839,7 +125649,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config const packageIdToSourceFile = /* @__PURE__ */ new Map(); let sourceFileToPackageName = /* @__PURE__ */ new Map(); let redirectTargetsMap = createMultiMap(); - let usesUriStyleNodeCoreModules = false; + let usesUriStyleNodeCoreModules; const filesByName = /* @__PURE__ */ new Map(); let missingFileNames = /* @__PURE__ */ new Map(); const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? /* @__PURE__ */ new Map() : void 0; @@ -125084,7 +125894,8 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config getCanonicalFileName, getFileIncludeReasons: () => fileReasons, structureIsReused, - writeFile: writeFile2 + writeFile: writeFile2, + getGlobalTypingsCacheLocation: maybeBind(host, host.getGlobalTypingsCacheLocation) }; onProgramCreateComplete(); verifyCompilerOptions(); @@ -125159,7 +125970,11 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config return (_a2 = resolvedTypeReferenceDirectiveNames == null ? void 0 : resolvedTypeReferenceDirectiveNames.get(file.path)) == null ? void 0 : _a2.get(typeDirectiveName, mode); } function getResolvedTypeReferenceDirectiveFromTypeReferenceDirective(typeRef, sourceFile) { - return getResolvedTypeReferenceDirective(sourceFile, typeRef.fileName, typeRef.resolutionMode || sourceFile.impliedNodeFormat); + return getResolvedTypeReferenceDirective( + sourceFile, + typeRef.fileName, + getModeForTypeReferenceDirectiveInFile(typeRef, sourceFile) + ); } function forEachResolvedModule(callback, file) { forEachResolution(resolvedModules, callback, file); @@ -125546,10 +126361,11 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config const moduleNames = getModuleNames(newSourceFile); const resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile); (resolvedModulesProcessing ?? (resolvedModulesProcessing = /* @__PURE__ */ new Map())).set(newSourceFile.path, resolutions); + const optionsForFile = getCompilerOptionsForFile(newSourceFile); const resolutionsChanged = hasChangesInResolutions( moduleNames, resolutions, - (name) => oldProgram.getResolvedModule(newSourceFile, name.text, getModeForUsageLocation2(newSourceFile, name)), + (name) => oldProgram.getResolvedModule(newSourceFile, name.text, getModeForUsageLocationWorker(newSourceFile, name, optionsForFile)), moduleResolutionIsEqualTo ); if (resolutionsChanged) structureIsReused = 1 /* SafeModules */; @@ -125559,7 +126375,11 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config const typeReferenceResolutionsChanged = hasChangesInResolutions( typesReferenceDirectives, typeReferenceResolutions, - (name) => oldProgram.getResolvedTypeReferenceDirective(newSourceFile, getTypeReferenceResolutionName(name), getModeForFileReference(name, newSourceFile.impliedNodeFormat)), + (name) => oldProgram.getResolvedTypeReferenceDirective( + newSourceFile, + getTypeReferenceResolutionName(name), + getModeForTypeReferenceDirectiveInFile(name, newSourceFile) + ), typeDirectiveIsEqualTo ); if (typeReferenceResolutionsChanged) structureIsReused = 1 /* SafeModules */; @@ -125650,7 +126470,8 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config getFileIncludeReasons: program.getFileIncludeReasons, createHash: maybeBind(host, host.createHash), getModuleResolutionCache: () => program.getModuleResolutionCache(), - trace: maybeBind(host, host.trace) + trace: maybeBind(host, host.trace), + getGlobalTypingsCacheLocation: program.getGlobalTypingsCacheLocation }; } function writeFile2(fileName, text, writeByteOrderMark, onError, sourceFiles, data) { @@ -125947,6 +126768,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config diagnostics.push(createDiagnosticForNode2(node, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?")); return "skip"; } + // falls through case 173 /* MethodSignature */: case 176 /* Constructor */: case 177 /* GetAccessor */: @@ -126078,6 +126900,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config diagnostics.push(createDiagnosticForNodeArray2(nodes, Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files)); return "skip"; } + // falls through case 243 /* VariableStatement */: if (nodes === parent2.modifiers) { checkModifiers(parent2.modifiers, parent2.kind === 243 /* VariableStatement */); @@ -126120,6 +126943,8 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config if (isConstValid) { continue; } + // to report error, + // falls through case 125 /* PublicKeyword */: case 123 /* PrivateKeyword */: case 124 /* ProtectedKeyword */: @@ -126131,6 +126956,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config case 147 /* OutKeyword */: diagnostics.push(createDiagnosticForNode2(modifier, Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, tokenToString(modifier.kind))); break; + // These are all legal modifiers. case 126 /* StaticKeyword */: case 95 /* ExportKeyword */: case 90 /* DefaultKeyword */: @@ -126244,7 +127070,21 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config ); } if (file.flags & 4194304 /* PossiblyContainsDynamicImport */ || isJavaScriptFile) { - collectDynamicImportOrRequireOrJsDocImportCalls(file); + forEachDynamicImportOrRequireCall( + file, + /*includeTypeSpaceImports*/ + true, + /*requireStringLiteralLikeArgument*/ + true, + (node, moduleSpecifier) => { + setParentRecursive( + node, + /*incremental*/ + false + ); + imports = append(imports, moduleSpecifier); + } + ); } file.imports = imports || emptyArray; file.moduleAugmentations = moduleAugmentations || emptyArray; @@ -126261,7 +127101,11 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config ); imports = append(imports, moduleNameExpr); if (!usesUriStyleNodeCoreModules && currentNodeModulesDepth === 0 && !file.isDeclarationFile) { - usesUriStyleNodeCoreModules = startsWith(moduleNameExpr.text, "node:"); + if (startsWith(moduleNameExpr.text, "node:") && !exclusivelyPrefixedNodeCoreModules.has(moduleNameExpr.text)) { + usesUriStyleNodeCoreModules = true; + } else if (usesUriStyleNodeCoreModules === void 0 && unprefixedNodeCoreModules.has(moduleNameExpr.text)) { + usesUriStyleNodeCoreModules = false; + } } } } else if (isModuleDeclaration(node)) { @@ -126288,63 +127132,6 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } } } - function collectDynamicImportOrRequireOrJsDocImportCalls(file2) { - const r = /import|require/g; - while (r.exec(file2.text) !== null) { - const node = getNodeAtPosition(file2, r.lastIndex); - if (isJavaScriptFile && isRequireCall( - node, - /*requireStringLiteralLikeArgument*/ - true - )) { - setParentRecursive( - node, - /*incremental*/ - false - ); - imports = append(imports, node.arguments[0]); - } else if (isImportCall(node) && node.arguments.length >= 1 && isStringLiteralLike(node.arguments[0])) { - setParentRecursive( - node, - /*incremental*/ - false - ); - imports = append(imports, node.arguments[0]); - } else if (isLiteralImportTypeNode(node)) { - setParentRecursive( - node, - /*incremental*/ - false - ); - imports = append(imports, node.argument.literal); - } else if (isJavaScriptFile && isJSDocImportTag(node)) { - const moduleNameExpr = getExternalModuleName(node); - if (moduleNameExpr && isStringLiteral(moduleNameExpr) && moduleNameExpr.text) { - setParentRecursive( - node, - /*incremental*/ - false - ); - imports = append(imports, moduleNameExpr); - } - } - } - } - function getNodeAtPosition(sourceFile, position) { - let current = sourceFile; - const getContainingChild = (child) => { - if (child.pos <= position && (position < child.end || position === child.end && child.kind === 1 /* EndOfFileToken */)) { - return child; - } - }; - while (true) { - const child = isJavaScriptFile && hasJSDocNodes(current) && forEach(current.jsDoc, getContainingChild) || forEachChild(current, getContainingChild); - if (!child) { - return current; - } - current = child; - } - } } function getLibFileFromReference(ref) { var _a2; @@ -126710,8 +127497,8 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config const ref = file.typeReferenceDirectives[index]; const resolvedTypeReferenceDirective = resolutions[index]; const fileName = ref.fileName; - resolutionsInFile.set(fileName, getModeForFileReference(ref, file.impliedNodeFormat), resolvedTypeReferenceDirective); - const mode = ref.resolutionMode || getDefaultResolutionModeForFile2(file); + const mode = getModeForTypeReferenceDirectiveInFile(ref, file); + resolutionsInFile.set(fileName, mode, resolvedTypeReferenceDirective); processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: 5 /* TypeReferenceDirective */, file: file.path, index }); } } @@ -126988,11 +127775,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } } const outputFile = options.outFile; - if (options.tsBuildInfoFile) { - if (!canEmitTsBuildInfo(options)) { - createDiagnosticForOptionName(Diagnostics.Option_tsBuildInfoFile_cannot_be_specified_without_specifying_option_incremental_or_composite_or_if_not_running_tsc_b, "tsBuildInfoFile"); - } - } else if (options.incremental && !outputFile && !options.configFilePath) { + if (!options.tsBuildInfoFile && options.incremental && !outputFile && !options.configFilePath) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified)); } verifyDeprecatedCompilerOptions(); @@ -127173,7 +127956,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config createDiagnosticForOptionName(Diagnostics.Option_verbatimModuleSyntax_cannot_be_used_when_module_is_set_to_UMD_AMD_or_System, "verbatimModuleSyntax"); } } - if (options.allowImportingTsExtensions && !(options.noEmit || options.emitDeclarationOnly)) { + if (options.allowImportingTsExtensions && !(options.noEmit || options.emitDeclarationOnly || options.rewriteRelativeImportExtensions)) { createOptionValueDiagnostic("allowImportingTsExtensions", Diagnostics.Option_allowImportingTsExtensions_can_only_be_used_when_either_noEmit_or_emitDeclarationOnly_is_set); } const moduleResolution = getEmitModuleResolutionKind(options); @@ -127500,7 +128283,11 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config case 1 /* SourceFromProjectReference */: case 2 /* OutputFromProjectReference */: const referencedResolvedRef = Debug.checkDefined(resolvedProjectReferences == null ? void 0 : resolvedProjectReferences[reason.index]); - const referenceInfo = forEachProjectReference(projectReferences, resolvedProjectReferences, (resolvedRef, parent2, index2) => resolvedRef === referencedResolvedRef ? { sourceFile: (parent2 == null ? void 0 : parent2.sourceFile) || options.configFile, index: index2 } : void 0); + const referenceInfo = forEachProjectReference( + projectReferences, + resolvedProjectReferences, + (resolvedRef, parent2, index2) => resolvedRef === referencedResolvedRef ? { sourceFile: (parent2 == null ? void 0 : parent2.sourceFile) || options.configFile, index: index2 } : void 0 + ); if (!referenceInfo) return void 0; const { sourceFile, index } = referenceInfo; const referencesSyntax = forEachTsConfigPropArray(sourceFile, "references", (property) => isArrayLiteralExpression(property.initializer) ? property.initializer : void 0); @@ -127535,27 +128322,31 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config } function verifyProjectReferences() { const buildInfoPath = !options.suppressOutputPathCheck ? getTsBuildInfoEmitOutputFilePath(options) : void 0; - forEachProjectReference(projectReferences, resolvedProjectReferences, (resolvedRef, parent2, index) => { - const ref = (parent2 ? parent2.commandLine.projectReferences : projectReferences)[index]; - const parentFile = parent2 && parent2.sourceFile; - verifyDeprecatedProjectReference(ref, parentFile, index); - if (!resolvedRef) { - createDiagnosticForReference(parentFile, index, Diagnostics.File_0_not_found, ref.path); - return; - } - const options2 = resolvedRef.commandLine.options; - if (!options2.composite || options2.noEmit) { - const inputs = parent2 ? parent2.commandLine.fileNames : rootNames; - if (inputs.length) { - if (!options2.composite) createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); - if (options2.noEmit) createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_may_not_disable_emit, ref.path); + forEachProjectReference( + projectReferences, + resolvedProjectReferences, + (resolvedRef, parent2, index) => { + const ref = (parent2 ? parent2.commandLine.projectReferences : projectReferences)[index]; + const parentFile = parent2 && parent2.sourceFile; + verifyDeprecatedProjectReference(ref, parentFile, index); + if (!resolvedRef) { + createDiagnosticForReference(parentFile, index, Diagnostics.File_0_not_found, ref.path); + return; + } + const options2 = resolvedRef.commandLine.options; + if (!options2.composite || options2.noEmit) { + const inputs = parent2 ? parent2.commandLine.fileNames : rootNames; + if (inputs.length) { + if (!options2.composite) createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path); + if (options2.noEmit) createDiagnosticForReference(parentFile, index, Diagnostics.Referenced_project_0_may_not_disable_emit, ref.path); + } + } + if (!parent2 && buildInfoPath && buildInfoPath === getTsBuildInfoEmitOutputFilePath(options2)) { + createDiagnosticForReference(parentFile, index, Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path); + hasEmitBlockingDiagnostics.set(toPath3(buildInfoPath), true); } } - if (!parent2 && buildInfoPath && buildInfoPath === getTsBuildInfoEmitOutputFilePath(options2)) { - createDiagnosticForReference(parentFile, index, Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path); - hasEmitBlockingDiagnostics.set(toPath3(buildInfoPath), true); - } - }); + ); } function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, ...args) { let needCompilerDiagnostic = true; @@ -127751,6 +128542,9 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config function shouldTransformImportCall(sourceFile) { return shouldTransformImportCallWorker(sourceFile, getCompilerOptionsForFile(sourceFile)); } + function getModeForTypeReferenceDirectiveInFile(ref, sourceFile) { + return ref.resolutionMode || getDefaultResolutionModeForFile2(sourceFile); + } } function shouldTransformImportCallWorker(sourceFile, options) { const moduleKind = getEmitModuleKind(options); @@ -130008,6 +130802,9 @@ function canWatchDirectoryOrFile(pathComponents2, length2) { const perceivedOsRootLength = perceivedOsRootLengthForWatching(pathComponents2, length2); return length2 > perceivedOsRootLength + 1; } +function canWatchDirectoryOrFilePath(path) { + return canWatchDirectoryOrFile(getPathComponents(path)); +} function canWatchAtTypes(atTypes) { return canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(getDirectoryPath(atTypes)); } @@ -130019,12 +130816,12 @@ function isInDirectoryPath(dirComponents, fileOrDirComponents) { return true; } function canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(fileOrDirPath) { - return canWatchDirectoryOrFile(getPathComponents(fileOrDirPath)); + return canWatchDirectoryOrFilePath(fileOrDirPath); } function canWatchAffectingLocation(filePath) { return canWatchAffectedPackageJsonOrNodeModulesOfAtTypes(filePath); } -function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath, rootDir, rootPath, rootPathComponents, getCurrentDirectory, preferNonRecursiveWatch) { +function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath, rootDir, rootPath, rootPathComponents, isRootWatchable, getCurrentDirectory, preferNonRecursiveWatch) { const failedLookupPathComponents = getPathComponents(failedLookupLocationPath); failedLookupLocation = isRootedDiskPath(failedLookupLocation) ? normalizePath(failedLookupLocation) : getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory()); const failedLookupComponents = getPathComponents(failedLookupLocation); @@ -130033,7 +130830,7 @@ function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLoo const nodeModulesIndex = failedLookupPathComponents.indexOf("node_modules"); if (nodeModulesIndex !== -1 && nodeModulesIndex + 1 <= perceivedOsRootLength + 1) return void 0; const lastNodeModulesIndex = failedLookupPathComponents.lastIndexOf("node_modules"); - if (isInDirectoryPath(rootPathComponents, failedLookupPathComponents)) { + if (isRootWatchable && isInDirectoryPath(rootPathComponents, failedLookupPathComponents)) { if (failedLookupPathComponents.length > rootPathComponents.length + 1) { return getDirectoryOfFailedLookupWatch( failedLookupComponents, @@ -130105,9 +130902,9 @@ function getDirectoryOfFailedLookupWatch(dirComponents, dirPathComponents, lengt packageDirPath: packageDirLength !== void 0 ? getPathFromPathComponents(dirPathComponents, packageDirLength) : void 0 }; } -function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath, rootPath, rootPathComponents, getCurrentDirectory, preferNonRecursiveWatch, filterCustomPath) { +function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath, rootPath, rootPathComponents, isRootWatchable, getCurrentDirectory, preferNonRecursiveWatch, filterCustomPath) { const typeRootPathComponents = getPathComponents(typeRootPath); - if (isInDirectoryPath(rootPathComponents, typeRootPathComponents)) { + if (isRootWatchable && isInDirectoryPath(rootPathComponents, typeRootPathComponents)) { return rootPath; } typeRoot = isRootedDiskPath(typeRoot) ? normalizePath(typeRoot) : getNormalizedAbsolutePath(typeRoot, getCurrentDirectory()); @@ -130148,10 +130945,10 @@ function createModuleResolutionLoaderUsingGlobalCache(containingFile, redirected function resolveModuleNameUsingGlobalCache(resolutionHost, moduleResolutionCache, moduleName, containingFile, compilerOptions, redirectedReference, mode) { const host = getModuleResolutionHost(resolutionHost); const primaryResult = resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode); - if (!resolutionHost.getGlobalCache) { + if (!resolutionHost.getGlobalTypingsCacheLocation) { return primaryResult; } - const globalCache = resolutionHost.getGlobalCache(); + const globalCache = resolutionHost.getGlobalTypingsCacheLocation(); if (globalCache !== void 0 && !isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && extensionIsTS(primaryResult.resolvedModule.extension))) { const { resolvedModule, failedLookupLocations, affectingLocations, resolutionDiagnostics } = loadModuleFromGlobalCache( Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), @@ -130215,6 +131012,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW const rootDir = getRootDirectoryOfResolutionCache(rootDirForResolution, getCurrentDirectory); const rootPath = resolutionHost.toPath(rootDir); const rootPathComponents = getPathComponents(rootPath); + const isRootWatchable = canWatchDirectoryOrFile(rootPathComponents); const isSymlinkCache = /* @__PURE__ */ new Map(); const packageDirWatchers = /* @__PURE__ */ new Map(); const dirPathToSymlinkPackageRefCount = /* @__PURE__ */ new Map(); @@ -130626,6 +131424,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW rootDir, rootPath, rootPathComponents, + isRootWatchable, getCurrentDirectory, resolutionHost.preferNonRecursiveWatch ); @@ -130814,6 +131613,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW rootDir, rootPath, rootPathComponents, + isRootWatchable, getCurrentDirectory, resolutionHost.preferNonRecursiveWatch ); @@ -130957,6 +131757,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW return false; } (failedLookupChecks || (failedLookupChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); + (startsWithPathChecks || (startsWithPathChecks = /* @__PURE__ */ new Set())).add(fileOrDirectoryPath); const packagePath = parseNodeModuleFromPath( fileOrDirectoryPath, /*isFolder*/ @@ -131038,6 +131839,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW resolutionHost.toPath(typeRoot), rootPath, rootPathComponents, + isRootWatchable, getCurrentDirectory, resolutionHost.preferNonRecursiveWatch, (dirPath2) => directoryWatchesOfFailedLookups.has(dirPath2) || dirPathToSymlinkPackageRefCount.has(dirPath2) @@ -131593,6 +132395,7 @@ function getSourceFileVersionAsHashFromText(host, text) { if (pos && text.charCodeAt(pos - 1) === 13 /* carriageReturn */) { pos--; } + // falls through case 13 /* carriageReturn */: break; default: @@ -131794,6 +132597,7 @@ function createWatchProgram(host) { let updateLevel; let missingFilesMap; let watchedWildcardDirectories; + let staleWatches = /* @__PURE__ */ new Map([[void 0, void 0]]); let timerToUpdateProgram; let timerToInvalidateFailedLookupResolutions; let parsedConfigs; @@ -131882,8 +132686,6 @@ function createWatchProgram(host) { const customHasInvalidLibResolutions = host.resolveLibrary ? maybeBind(host, host.hasInvalidatedLibResolutions) || returnTrue : returnFalse; builderProgram = readBuilderProgram(compilerOptions, compilerHost); synchronizeProgram(); - watchConfigFileWildCardDirectories(); - if (configFileName) updateExtendedConfigFilesWatches(toPath3(configFileName), compilerOptions, watchOptions, WatchType.ExtendedConfigFile); return configFileName ? { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close, getResolutionCache } : { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames, close, getResolutionCache }; function close() { clearInvalidateResolutionsOfFailedLookupLocations(); @@ -131986,6 +132788,16 @@ function createWatchProgram(host) { compilerHost.directoryExists = originalDirectoryExists; compilerHost.createDirectory = originalCreateDirectory; compilerHost.writeFile = originalWriteFile; + staleWatches == null ? void 0 : staleWatches.forEach((configFile, configPath) => { + if (!configPath) { + watchConfigFileWildCardDirectories(); + if (configFileName) updateExtendedConfigFilesWatches(toPath3(configFileName), compilerOptions, watchOptions, WatchType.ExtendedConfigFile); + } else { + const config = parsedConfigs == null ? void 0 : parsedConfigs.get(configPath); + if (config) watchReferencedProject(configFile, configPath, config); + } + }); + staleWatches = void 0; return builderProgram; } function createNewProgram(hasInvalidatedResolutions, hasInvalidatedLibResolutions) { @@ -132178,7 +132990,13 @@ function createWatchProgram(host) { Debug.assert(configFileName); updateLevel = 0 /* Update */; rootFileNames = getFileNamesFromConfigSpecs(compilerOptions.configFile.configFileSpecs, getNormalizedAbsolutePath(getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost, extraFileExtensions); - if (updateErrorForNoInputFiles(rootFileNames, getNormalizedAbsolutePath(configFileName, currentDirectory), compilerOptions.configFile.configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) { + if (updateErrorForNoInputFiles( + rootFileNames, + getNormalizedAbsolutePath(configFileName, currentDirectory), + compilerOptions.configFile.configFileSpecs, + configFileParsingDiagnostics, + canConfigFileJsonReportNoInputFiles + )) { hasChangedConfigFileParsingErrors = true; } synchronizeProgram(); @@ -132192,9 +133010,8 @@ function createWatchProgram(host) { } parseConfigFile2(); hasChangedCompilerOptions = true; + (staleWatches ?? (staleWatches = /* @__PURE__ */ new Map())).set(void 0, void 0); synchronizeProgram(); - watchConfigFileWildCardDirectories(); - updateExtendedConfigFilesWatches(toPath3(configFileName), compilerOptions, watchOptions, WatchType.ExtendedConfigFile); } function parseConfigFile2() { Debug.assert(configFileName); @@ -132246,7 +133063,7 @@ function createWatchProgram(host) { } else { (parsedConfigs || (parsedConfigs = /* @__PURE__ */ new Map())).set(configPath, config = { parsedCommandLine }); } - watchReferencedProject(configFileName2, configPath, config); + (staleWatches ?? (staleWatches = /* @__PURE__ */ new Map())).set(configPath, configFileName2); return parsedCommandLine; } function getParsedCommandLineFromConfigFileHost(configFileName2) { @@ -133130,6 +133947,7 @@ function createBuildOrUpdateInvalidedProject(state, project, projectPath, projec queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, Debug.checkDefined(buildResult)); step++; break; + // Should never be done case 3 /* Done */: default: assertType(step); @@ -133165,7 +133983,13 @@ function getNextInvalidatedProjectCreateInfo(state, buildOrder, reportQueue) { watchPackageJsonFiles(state, project, projectPath, config); } else if (updateLevel === 1 /* RootNamesAndUpdate */) { config.fileNames = getFileNamesFromConfigSpecs(config.options.configFile.configFileSpecs, getDirectoryPath(project), config.options, state.parseConfigFileHost); - updateErrorForNoInputFiles(config.fileNames, project, config.options.configFile.configFileSpecs, config.errors, canJsonReportNoInputFiles(config.raw)); + updateErrorForNoInputFiles( + config.fileNames, + project, + config.options.configFile.configFileSpecs, + config.errors, + canJsonReportNoInputFiles(config.raw) + ); watchInputFiles(state, project, projectPath, config); watchPackageJsonFiles(state, project, projectPath, config); } @@ -133346,11 +134170,7 @@ function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, } function getUpToDateStatusWorker(state, project, resolvedPath) { var _a, _b, _c, _d, _e; - if (!project.fileNames.length && !canJsonReportNoInputFiles(project.raw)) { - return { - type: 16 /* ContainerOnly */ - }; - } + if (isSolutionConfig(project)) return { type: 16 /* ContainerOnly */ }; let referenceStatuses; const force = !!state.options.force; if (project.projectReferences) { @@ -133670,6 +134490,7 @@ function queueReferencingProjects(state, project, projectPath, projectIndex, con status.type = 2 /* UpToDateWithUpstreamTypes */; break; } + // falls through case 15 /* UpToDateWithInputFileText */: case 2 /* UpToDateWithUpstreamTypes */: if (!(buildResult & 2 /* DeclarationOutputUnchanged */)) { @@ -134187,6 +135008,8 @@ function reportUpToDateStatus(state, configFileName, status) { relName(state, configFileName) ); case 16 /* ContainerOnly */: + // Don't report status on "solution" projects + // falls through case 13 /* ComputingUpstream */: break; default: @@ -134259,7 +135082,7 @@ function shouldBePretty(sys2, options) { return options.pretty; } function getOptionsForHelp(commandLine) { - return !!commandLine.options.all ? toSorted(optionDeclarations, (a, b) => compareStringsCaseInsensitive(a.name, b.name)) : filter(optionDeclarations.slice(), (v) => !!v.showInSimplifiedHelpView); + return !!commandLine.options.all ? toSorted(optionDeclarations.concat(tscBuildOption), (a, b) => compareStringsCaseInsensitive(a.name, b.name)) : filter(optionDeclarations.concat(tscBuildOption), (v) => !!v.showInSimplifiedHelpView); } function printVersion(sys2) { sys2.write(getDiagnosticText(Diagnostics.Version_0, version) + sys2.newLine); @@ -134583,7 +135406,7 @@ function printAllHelp(sys2, compilerOptions, buildOptions, watchOptions) { output = [...output, ...generateSectionOptionsOutput( sys2, getDiagnosticText(Diagnostics.BUILD_OPTIONS), - buildOptions, + filter(buildOptions, (option) => option !== tscBuildOption), /*subCategory*/ false, formatMessage(Diagnostics.Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_trigger_building_composite_projects_which_you_can_learn_more_about_at_0, "https://aka.ms/tsc-composite-builds") @@ -134597,7 +135420,7 @@ function printBuildHelp(sys2, buildOptions) { output = [...output, ...generateSectionOptionsOutput( sys2, getDiagnosticText(Diagnostics.BUILD_OPTIONS), - buildOptions, + filter(buildOptions, (option) => option !== tscBuildOption), /*subCategory*/ false, formatMessage(Diagnostics.Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_trigger_building_composite_projects_which_you_can_learn_more_about_at_0, "https://aka.ms/tsc-composite-builds") @@ -134634,10 +135457,6 @@ function printHelp(sys2, commandLine) { } function executeCommandLineWorker(sys2, cb, commandLine) { let reportDiagnostic = createDiagnosticReporter(sys2); - if (commandLine.options.build) { - reportDiagnostic(createCompilerDiagnostic(Diagnostics.Option_build_must_be_the_first_command_line_argument)); - return sys2.exit(1 /* DiagnosticsPresent_OutputsSkipped */); - } let configFileName; if (commandLine.options.locale) { validateLocaleAndSetLanguage(commandLine.options.locale, sys2, commandLine.errors); @@ -134783,16 +135602,16 @@ function executeCommandLineWorker(sys2, cb, commandLine) { } } } -function isBuild(commandLineArgs) { +function isBuildCommand(commandLineArgs) { if (commandLineArgs.length > 0 && commandLineArgs[0].charCodeAt(0) === 45 /* minus */) { const firstOption = commandLineArgs[0].slice(commandLineArgs[0].charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); - return firstOption === "build" || firstOption === "b"; + return firstOption === tscBuildOption.name || firstOption === tscBuildOption.shortName; } return false; } function executeCommandLine(system, cb, commandLineArgs) { - if (isBuild(commandLineArgs)) { - const { buildOptions, watchOptions, projects, errors } = parseBuildCommand(commandLineArgs.slice(1)); + if (isBuildCommand(commandLineArgs)) { + const { buildOptions, watchOptions, projects, errors } = parseBuildCommand(commandLineArgs); if (buildOptions.generateCpuProfile && system.enableCPUProfiler) { system.enableCPUProfiler(buildOptions.generateCpuProfile, () => performBuild( system, @@ -135304,39 +136123,518 @@ function writeConfigFile(sys2, reportDiagnostic, options, fileNames) { } // src/compiler/expressionToTypeNode.ts +function syntacticResult(type, reportFallback = true) { + return { type, reportFallback }; +} +var notImplemented2 = syntacticResult( + /*type*/ + void 0, + /*reportFallback*/ + false +); +var alreadyReported = syntacticResult( + /*type*/ + void 0, + /*reportFallback*/ + false +); +var failed = syntacticResult( + /*type*/ + void 0, + /*reportFallback*/ + true +); function createSyntacticTypeNodeBuilder(options, resolver) { const strictNullChecks = getStrictOptionValue(options, "strictNullChecks"); return { - typeFromExpression, serializeTypeOfDeclaration, serializeReturnTypeForSignature, - serializeTypeOfExpression + serializeTypeOfExpression, + serializeTypeOfAccessor, + tryReuseExistingTypeNode(context, existing) { + if (!resolver.canReuseTypeNode(context, existing)) { + return void 0; + } + return tryReuseExistingTypeNode(context, existing); + } }; - function serializeExistingTypeAnnotation(type, addUndefined) { - return type !== void 0 && (!addUndefined || type && canAddUndefined(type)) ? true : void 0; + function reuseNode(context, node, range = node) { + return node === void 0 ? void 0 : resolver.markNodeReuse(context, node.flags & 16 /* Synthesized */ ? node : factory.cloneNode(node), range ?? node); + } + function tryReuseExistingTypeNode(context, existing) { + const { finalizeBoundary, startRecoveryScope, hadError, markError } = resolver.createRecoveryBoundary(context); + const transformed = visitNode(existing, visitExistingNodeTreeSymbols, isTypeNode); + if (!finalizeBoundary()) { + return void 0; + } + context.approximateLength += existing.end - existing.pos; + return transformed; + function visitExistingNodeTreeSymbols(node) { + if (hadError()) return node; + const recover = startRecoveryScope(); + const onExitNewScope = isNewScopeNode(node) ? resolver.enterNewScope(context, node) : void 0; + const result = visitExistingNodeTreeSymbolsWorker(node); + onExitNewScope == null ? void 0 : onExitNewScope(); + if (hadError()) { + if (isTypeNode(node) && !isTypePredicateNode(node)) { + recover(); + return resolver.serializeExistingTypeNode(context, node); + } + return node; + } + return result ? resolver.markNodeReuse(context, result, node) : void 0; + } + function tryVisitSimpleTypeNode(node) { + const innerNode = skipTypeParentheses(node); + switch (innerNode.kind) { + case 183 /* TypeReference */: + return tryVisitTypeReference(innerNode); + case 186 /* TypeQuery */: + return tryVisitTypeQuery(innerNode); + case 199 /* IndexedAccessType */: + return tryVisitIndexedAccess(innerNode); + case 198 /* TypeOperator */: + const typeOperatorNode = innerNode; + if (typeOperatorNode.operator === 143 /* KeyOfKeyword */) { + return tryVisitKeyOf(typeOperatorNode); + } + } + return visitNode(node, visitExistingNodeTreeSymbols, isTypeNode); + } + function tryVisitIndexedAccess(node) { + const resultObjectType = tryVisitSimpleTypeNode(node.objectType); + if (resultObjectType === void 0) { + return void 0; + } + return factory.updateIndexedAccessTypeNode(node, resultObjectType, visitNode(node.indexType, visitExistingNodeTreeSymbols, isTypeNode)); + } + function tryVisitKeyOf(node) { + Debug.assertEqual(node.operator, 143 /* KeyOfKeyword */); + const type = tryVisitSimpleTypeNode(node.type); + if (type === void 0) { + return void 0; + } + return factory.updateTypeOperatorNode(node, type); + } + function tryVisitTypeQuery(node) { + const { introducesError, node: exprName } = resolver.trackExistingEntityName(context, node.exprName); + if (!introducesError) { + return factory.updateTypeQueryNode( + node, + exprName, + visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode) + ); + } + const serializedName = resolver.serializeTypeName( + context, + node.exprName, + /*isTypeOf*/ + true + ); + if (serializedName) { + return resolver.markNodeReuse(context, serializedName, node.exprName); + } + } + function tryVisitTypeReference(node) { + if (resolver.canReuseTypeNode(context, node)) { + const { introducesError, node: newName } = resolver.trackExistingEntityName(context, node.typeName); + const typeArguments = visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode); + if (!introducesError) { + const updated = factory.updateTypeReferenceNode( + node, + newName, + typeArguments + ); + return resolver.markNodeReuse(context, updated, node); + } else { + const serializedName = resolver.serializeTypeName( + context, + node.typeName, + /*isTypeOf*/ + false, + typeArguments + ); + if (serializedName) { + return resolver.markNodeReuse(context, serializedName, node.typeName); + } + } + } + } + function visitExistingNodeTreeSymbolsWorker(node) { + var _a; + if (isJSDocTypeExpression(node)) { + return visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode); + } + if (isJSDocAllType(node) || node.kind === 319 /* JSDocNamepathType */) { + return factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + if (isJSDocUnknownType(node)) { + return factory.createKeywordTypeNode(159 /* UnknownKeyword */); + } + if (isJSDocNullableType(node)) { + return factory.createUnionTypeNode([visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode), factory.createLiteralTypeNode(factory.createNull())]); + } + if (isJSDocOptionalType(node)) { + return factory.createUnionTypeNode([visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode), factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); + } + if (isJSDocNonNullableType(node)) { + return visitNode(node.type, visitExistingNodeTreeSymbols); + } + if (isJSDocVariadicType(node)) { + return factory.createArrayTypeNode(visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode)); + } + if (isJSDocTypeLiteral(node)) { + return factory.createTypeLiteralNode(map(node.jsDocPropertyTags, (t) => { + const name = visitNode(isIdentifier(t.name) ? t.name : t.name.right, visitExistingNodeTreeSymbols, isIdentifier); + const overrideTypeNode = resolver.getJsDocPropertyOverride(context, node, t); + return factory.createPropertySignature( + /*modifiers*/ + void 0, + name, + t.isBracketed || t.typeExpression && isJSDocOptionalType(t.typeExpression.type) ? factory.createToken(58 /* QuestionToken */) : void 0, + overrideTypeNode || t.typeExpression && visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */) + ); + })); + } + if (isTypeReferenceNode(node) && isIdentifier(node.typeName) && node.typeName.escapedText === "") { + return setOriginalNode(factory.createKeywordTypeNode(133 /* AnyKeyword */), node); + } + if ((isExpressionWithTypeArguments(node) || isTypeReferenceNode(node)) && isJSDocIndexSignature(node)) { + return factory.createTypeLiteralNode([factory.createIndexSignature( + /*modifiers*/ + void 0, + [factory.createParameterDeclaration( + /*modifiers*/ + void 0, + /*dotDotDotToken*/ + void 0, + "x", + /*questionToken*/ + void 0, + visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols, isTypeNode) + )], + visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols, isTypeNode) + )]); + } + if (isJSDocFunctionType(node)) { + if (isJSDocConstructSignature(node)) { + let newTypeNode; + return factory.createConstructorTypeNode( + /*modifiers*/ + void 0, + visitNodes2(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration), + mapDefined(node.parameters, (p, i) => p.name && isIdentifier(p.name) && p.name.escapedText === "new" ? (newTypeNode = p.type, void 0) : factory.createParameterDeclaration( + /*modifiers*/ + void 0, + getEffectiveDotDotDotForParameter(p), + resolver.markNodeReuse(context, factory.createIdentifier(getNameForJSDocFunctionParameter(p, i)), p), + factory.cloneNode(p.questionToken), + visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), + /*initializer*/ + void 0 + )), + visitNode(newTypeNode || node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */) + ); + } else { + return factory.createFunctionTypeNode( + visitNodes2(node.typeParameters, visitExistingNodeTreeSymbols, isTypeParameterDeclaration), + map(node.parameters, (p, i) => factory.createParameterDeclaration( + /*modifiers*/ + void 0, + getEffectiveDotDotDotForParameter(p), + resolver.markNodeReuse(context, factory.createIdentifier(getNameForJSDocFunctionParameter(p, i)), p), + factory.cloneNode(p.questionToken), + visitNode(p.type, visitExistingNodeTreeSymbols, isTypeNode), + /*initializer*/ + void 0 + )), + visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode) || factory.createKeywordTypeNode(133 /* AnyKeyword */) + ); + } + } + if (isThisTypeNode(node)) { + if (resolver.canReuseTypeNode(context, node)) { + return node; + } + markError(); + return node; + } + if (isTypeParameterDeclaration(node)) { + const { node: newName } = resolver.trackExistingEntityName(context, node.name); + return factory.updateTypeParameterDeclaration( + node, + visitNodes2(node.modifiers, visitExistingNodeTreeSymbols, isModifier), + // resolver.markNodeReuse(context, typeParameterToName(getDeclaredTypeOfSymbol(getSymbolOfDeclaration(node)), context), node), + newName, + visitNode(node.constraint, visitExistingNodeTreeSymbols, isTypeNode), + visitNode(node.default, visitExistingNodeTreeSymbols, isTypeNode) + ); + } + if (isIndexedAccessTypeNode(node)) { + const result = tryVisitIndexedAccess(node); + if (!result) { + markError(); + return node; + } + return result; + } + if (isTypeReferenceNode(node)) { + const result = tryVisitTypeReference(node); + if (result) { + return result; + } + markError(); + return node; + } + if (isLiteralImportTypeNode(node)) { + if (((_a = node.attributes) == null ? void 0 : _a.token) === 132 /* AssertKeyword */) { + markError(); + return node; + } + if (!resolver.canReuseTypeNode(context, node)) { + return resolver.serializeExistingTypeNode(context, node); + } + return factory.updateImportTypeNode( + node, + factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier2(node, node.argument.literal)), + visitNode(node.attributes, visitExistingNodeTreeSymbols, isImportAttributes), + visitNode(node.qualifier, visitExistingNodeTreeSymbols, isEntityName), + visitNodes2(node.typeArguments, visitExistingNodeTreeSymbols, isTypeNode), + node.isTypeOf + ); + } + if (isNamedDeclaration(node) && node.name.kind === 167 /* ComputedPropertyName */ && !resolver.hasLateBindableName(node)) { + if (!hasDynamicName(node)) { + return visitEachChild2(node, visitExistingNodeTreeSymbols); + } + if (resolver.shouldRemoveDeclaration(context, node)) { + return void 0; + } + } + if (isFunctionLike(node) && !node.type || isPropertyDeclaration(node) && !node.type && !node.initializer || isPropertySignature(node) && !node.type && !node.initializer || isParameter(node) && !node.type && !node.initializer) { + let visited = visitEachChild2(node, visitExistingNodeTreeSymbols); + if (visited === node) { + visited = resolver.markNodeReuse(context, factory.cloneNode(node), node); + } + visited.type = factory.createKeywordTypeNode(133 /* AnyKeyword */); + if (isParameter(node)) { + visited.modifiers = void 0; + } + return visited; + } + if (isTypeQueryNode(node)) { + const result = tryVisitTypeQuery(node); + if (!result) { + markError(); + return node; + } + return result; + } + if (isComputedPropertyName(node) && isEntityNameExpression(node.expression)) { + const { node: result, introducesError } = resolver.trackExistingEntityName(context, node.expression); + if (!introducesError) { + return factory.updateComputedPropertyName(node, result); + } else { + const computedPropertyNameType = resolver.serializeTypeOfExpression(context, node.expression); + let literal; + if (isLiteralTypeNode(computedPropertyNameType)) { + literal = computedPropertyNameType.literal; + } else { + const evaluated = resolver.evaluateEntityNameExpression(node.expression); + const literalNode = typeof evaluated.value === "string" ? factory.createStringLiteral( + evaluated.value, + /*isSingleQuote*/ + void 0 + ) : typeof evaluated.value === "number" ? factory.createNumericLiteral( + evaluated.value, + /*numericLiteralFlags*/ + 0 + ) : void 0; + if (!literalNode) { + if (isImportTypeNode(computedPropertyNameType)) { + resolver.trackComputedName(context, node.expression); + } + return node; + } + literal = literalNode; + } + if (literal.kind === 11 /* StringLiteral */ && isIdentifierText(literal.text, getEmitScriptTarget(options))) { + return factory.createIdentifier(literal.text); + } + if (literal.kind === 9 /* NumericLiteral */ && !literal.text.startsWith("-")) { + return literal; + } + return factory.updateComputedPropertyName(node, literal); + } + } + if (isTypePredicateNode(node)) { + let parameterName; + if (isIdentifier(node.parameterName)) { + const { node: result, introducesError } = resolver.trackExistingEntityName(context, node.parameterName); + if (introducesError) markError(); + parameterName = result; + } else { + parameterName = factory.cloneNode(node.parameterName); + } + return factory.updateTypePredicateNode(node, factory.cloneNode(node.assertsModifier), parameterName, visitNode(node.type, visitExistingNodeTreeSymbols, isTypeNode)); + } + if (isTupleTypeNode(node) || isTypeLiteralNode(node) || isMappedTypeNode(node)) { + const visited = visitEachChild2(node, visitExistingNodeTreeSymbols); + const clone2 = resolver.markNodeReuse(context, visited === node ? factory.cloneNode(node) : visited, node); + const flags = getEmitFlags(clone2); + setEmitFlags(clone2, flags | (context.flags & 1024 /* MultilineObjectLiterals */ && isTypeLiteralNode(node) ? 0 : 1 /* SingleLine */)); + return clone2; + } + if (isStringLiteral(node) && !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */) && !node.singleQuote) { + const clone2 = factory.cloneNode(node); + clone2.singleQuote = true; + return clone2; + } + if (isConditionalTypeNode(node)) { + const checkType = visitNode(node.checkType, visitExistingNodeTreeSymbols, isTypeNode); + const disposeScope = resolver.enterNewScope(context, node); + const extendType = visitNode(node.extendsType, visitExistingNodeTreeSymbols, isTypeNode); + const trueType = visitNode(node.trueType, visitExistingNodeTreeSymbols, isTypeNode); + disposeScope(); + const falseType = visitNode(node.falseType, visitExistingNodeTreeSymbols, isTypeNode); + return factory.updateConditionalTypeNode( + node, + checkType, + extendType, + trueType, + falseType + ); + } + if (isTypeOperatorNode(node)) { + if (node.operator === 158 /* UniqueKeyword */ && node.type.kind === 155 /* SymbolKeyword */) { + if (!resolver.canReuseTypeNode(context, node)) { + markError(); + return node; + } + } else if (node.operator === 143 /* KeyOfKeyword */) { + const result = tryVisitKeyOf(node); + if (!result) { + markError(); + return node; + } + return result; + } + } + return visitEachChild2(node, visitExistingNodeTreeSymbols); + function visitEachChild2(node2, visitor) { + const nonlocalNode = !context.enclosingFile || context.enclosingFile !== getSourceFileOfNode(node2); + return visitEachChild( + node2, + visitor, + /*context*/ + void 0, + nonlocalNode ? visitNodesWithoutCopyingPositions : void 0 + ); + } + function visitNodesWithoutCopyingPositions(nodes, visitor, test, start, count) { + let result = visitNodes2(nodes, visitor, test, start, count); + if (result) { + if (result.pos !== -1 || result.end !== -1) { + if (result === nodes) { + result = factory.createNodeArray(nodes.slice(), nodes.hasTrailingComma); + } + setTextRangePosEnd(result, -1, -1); + } + } + return result; + } + function getEffectiveDotDotDotForParameter(p) { + return p.dotDotDotToken || (p.type && isJSDocVariadicType(p.type) ? factory.createToken(26 /* DotDotDotToken */) : void 0); + } + function getNameForJSDocFunctionParameter(p, index) { + return p.name && isIdentifier(p.name) && p.name.escapedText === "this" ? "this" : getEffectiveDotDotDotForParameter(p) ? `args` : `arg${index}`; + } + function rewriteModuleSpecifier2(parent2, lit) { + const newName = resolver.getModuleSpecifierOverride(context, parent2, lit); + if (newName) { + return setOriginalNode(factory.createStringLiteral(newName), lit); + } + return visitNode(lit, visitExistingNodeTreeSymbols, isStringLiteral); + } + } + } + function serializeExistingTypeNode(typeNode, context, addUndefined) { + if (!typeNode) return void 0; + let result; + if ((!addUndefined || canAddUndefined(typeNode)) && resolver.canReuseTypeNode(context, typeNode)) { + result = tryReuseExistingTypeNode(context, typeNode); + if (result !== void 0) { + result = addUndefinedIfNeeded( + result, + addUndefined, + /*owner*/ + void 0, + context + ); + } + } + return result; + } + function serializeTypeAnnotationOfDeclaration(declaredType, context, node, symbol, requiresAddingUndefined, useFallback = requiresAddingUndefined !== void 0) { + if (!declaredType) return void 0; + if (!resolver.canReuseTypeNodeAnnotation(context, node, declaredType, symbol, requiresAddingUndefined)) { + if (!requiresAddingUndefined || !resolver.canReuseTypeNodeAnnotation( + context, + node, + declaredType, + symbol, + /*requiresAddingUndefined*/ + false + )) { + return void 0; + } + } + let result; + if (!requiresAddingUndefined || canAddUndefined(declaredType)) { + result = serializeExistingTypeNode(declaredType, context, requiresAddingUndefined); + } + if (result !== void 0 || !useFallback) { + return result; + } + context.tracker.reportInferenceFallback(node); + return resolver.serializeExistingTypeNode(context, declaredType, requiresAddingUndefined) ?? factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + function serializeExistingTypeNodeWithFallback(typeNode, context, addUndefined, targetNode) { + if (!typeNode) return void 0; + const result = serializeExistingTypeNode(typeNode, context, addUndefined); + if (result !== void 0) { + return result; + } + context.tracker.reportInferenceFallback(targetNode ?? typeNode); + return resolver.serializeExistingTypeNode(context, typeNode, addUndefined) ?? factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + function serializeTypeOfAccessor(accessor, symbol, context) { + return typeFromAccessor(accessor, symbol, context) ?? inferAccessorType(accessor, resolver.getAllAccessorDeclarations(accessor), context, symbol); } function serializeTypeOfExpression(expr, context, addUndefined, preserveLiterals) { - return typeFromExpression( + const result = typeFromExpression( expr, context, /*isConstContext*/ false, addUndefined, preserveLiterals - ) ?? inferExpressionType(expr, context); + ); + return result.type !== void 0 ? result.type : inferExpressionType(expr, context, result.reportFallback); } - function serializeTypeOfDeclaration(node, context) { + function serializeTypeOfDeclaration(node, symbol, context) { switch (node.kind) { - case 171 /* PropertySignature */: - return serializeExistingTypeAnnotation(getEffectiveTypeAnnotationNode(node)); case 169 /* Parameter */: - return typeFromParameter(node, context); + case 341 /* JSDocParameterTag */: + return typeFromParameter(node, symbol, context); case 260 /* VariableDeclaration */: - return typeFromVariable(node, context); + return typeFromVariable(node, symbol, context); + case 171 /* PropertySignature */: + case 348 /* JSDocPropertyTag */: case 172 /* PropertyDeclaration */: - return typeFromProperty(node, context); + return typeFromProperty(node, symbol, context); case 208 /* BindingElement */: - return inferTypeOfDeclaration(node, context); + return inferTypeOfDeclaration(node, symbol, context); case 277 /* ExportAssignment */: return serializeTypeOfExpression( node.expression, @@ -135349,17 +136647,39 @@ function createSyntacticTypeNodeBuilder(options, resolver) { case 211 /* PropertyAccessExpression */: case 212 /* ElementAccessExpression */: case 226 /* BinaryExpression */: - return serializeExistingTypeAnnotation(getEffectiveTypeAnnotationNode(node)) || inferTypeOfDeclaration(node, context); + return typeFromExpandoProperty(node, symbol, context); case 303 /* PropertyAssignment */: - return typeFromExpression(node.initializer, context) || inferTypeOfDeclaration(node, context); + case 304 /* ShorthandPropertyAssignment */: + return typeFromPropertyAssignment(node, symbol, context); default: Debug.assertNever(node, `Node needs to be an inferrable node, found ${Debug.formatSyntaxKind(node.kind)}`); } } - function serializeReturnTypeForSignature(node, context) { + function typeFromPropertyAssignment(node, symbol, context) { + const typeAnnotation = getEffectiveTypeAnnotationNode(node); + let result; + if (typeAnnotation && resolver.canReuseTypeNodeAnnotation(context, node, typeAnnotation, symbol)) { + result = serializeExistingTypeNode(typeAnnotation, context); + } + if (!result && node.kind === 303 /* PropertyAssignment */) { + const initializer = node.initializer; + const type = isJSDocTypeAssertion(initializer) ? getJSDocTypeAssertionType(initializer) : initializer.kind === 234 /* AsExpression */ || initializer.kind === 216 /* TypeAssertionExpression */ ? initializer.type : void 0; + if (type && !isConstTypeReference(type)) { + result = serializeExistingTypeNode(type, context); + } + } + return result ?? inferTypeOfDeclaration( + node, + symbol, + context, + /*reportFallback*/ + false + ); + } + function serializeReturnTypeForSignature(node, symbol, context) { switch (node.kind) { case 177 /* GetAccessor */: - return typeFromAccessor(node, context); + return serializeTypeOfAccessor(node, symbol, context); case 174 /* MethodDeclaration */: case 262 /* FunctionDeclaration */: case 180 /* ConstructSignature */: @@ -135374,45 +136694,50 @@ function createSyntacticTypeNodeBuilder(options, resolver) { case 219 /* ArrowFunction */: case 317 /* JSDocFunctionType */: case 323 /* JSDocSignature */: - return createReturnFromSignature(node, context); + return createReturnFromSignature(node, symbol, context); default: Debug.assertNever(node, `Node needs to be an inferrable node, found ${Debug.formatSyntaxKind(node.kind)}`); } } - function getTypeAnnotationFromAccessor2(accessor) { + function getTypeAnnotationFromAccessor(accessor) { if (accessor) { - return accessor.kind === 177 /* GetAccessor */ ? getEffectiveReturnTypeNode(accessor) : accessor.parameters.length > 0 ? getEffectiveTypeAnnotationNode(accessor.parameters[0]) : void 0; + return accessor.kind === 177 /* GetAccessor */ ? isInJSFile(accessor) && getJSDocType(accessor) || getEffectiveReturnTypeNode(accessor) : getEffectiveSetAccessorTypeAnnotationNode(accessor); } } function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) { - let accessorType = getTypeAnnotationFromAccessor2(node); + let accessorType = getTypeAnnotationFromAccessor(node); if (!accessorType && node !== accessors.firstAccessor) { - accessorType = getTypeAnnotationFromAccessor2(accessors.firstAccessor); + accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor); } if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) { - accessorType = getTypeAnnotationFromAccessor2(accessors.secondAccessor); + accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor); } return accessorType; } - function typeFromAccessor(node, context) { + function typeFromAccessor(node, symbol, context) { const accessorDeclarations = resolver.getAllAccessorDeclarations(node); const accessorType = getTypeAnnotationFromAllAccessorDeclarations(node, accessorDeclarations); - if (accessorType) { - return serializeExistingTypeAnnotation(accessorType); + if (accessorType && !isTypePredicateNode(accessorType)) { + return withNewScope(context, node, () => serializeTypeAnnotationOfDeclaration(accessorType, context, node, symbol) ?? inferTypeOfDeclaration(node, symbol, context)); } if (accessorDeclarations.getAccessor) { - return createReturnFromSignature(accessorDeclarations.getAccessor, context); + return withNewScope(context, accessorDeclarations.getAccessor, () => createReturnFromSignature( + accessorDeclarations.getAccessor, + /*symbol*/ + void 0, + context + )); } - return false; + return void 0; } - function typeFromVariable(node, context) { + function typeFromVariable(node, symbol, context) { + var _a; const declaredType = getEffectiveTypeAnnotationNode(node); + let resultType = failed; if (declaredType) { - return serializeExistingTypeAnnotation(declaredType); - } - let resultType; - if (node.initializer) { - if (!resolver.isExpandoFunctionDeclaration(node)) { + resultType = syntacticResult(serializeTypeAnnotationOfDeclaration(declaredType, context, node, symbol)); + } else if (node.initializer && (((_a = symbol.declarations) == null ? void 0 : _a.length) === 1 || countWhere(symbol.declarations, isVariableDeclaration) === 1)) { + if (!resolver.isExpandoFunctionDeclaration(node) && !isContextuallyTyped(node)) { resultType = typeFromExpression( node.initializer, context, @@ -135424,71 +136749,119 @@ function createSyntacticTypeNodeBuilder(options, resolver) { ); } } - return resultType ?? inferTypeOfDeclaration(node, context); + return resultType.type !== void 0 ? resultType.type : inferTypeOfDeclaration(node, symbol, context, resultType.reportFallback); } - function typeFromParameter(node, context) { + function typeFromParameter(node, symbol, context) { const parent2 = node.parent; if (parent2.kind === 178 /* SetAccessor */) { - return typeFromAccessor(parent2, context); + return serializeTypeOfAccessor( + parent2, + /*symbol*/ + void 0, + context + ); } const declaredType = getEffectiveTypeAnnotationNode(node); - const addUndefined = resolver.requiresAddingImplicitUndefined(node, context.enclosingDeclaration); - let resultType; + const addUndefined = resolver.requiresAddingImplicitUndefined(node, symbol, context.enclosingDeclaration); + let resultType = failed; if (declaredType) { - resultType = serializeExistingTypeAnnotation(declaredType, addUndefined); + resultType = syntacticResult(serializeTypeAnnotationOfDeclaration(declaredType, context, node, symbol, addUndefined)); + } else if (isParameter(node) && node.initializer && isIdentifier(node.name) && !isContextuallyTyped(node)) { + resultType = typeFromExpression( + node.initializer, + context, + /*isConstContext*/ + void 0, + addUndefined + ); + } + return resultType.type !== void 0 ? resultType.type : inferTypeOfDeclaration(node, symbol, context, resultType.reportFallback); + } + function typeFromExpandoProperty(node, symbol, context) { + const declaredType = getEffectiveTypeAnnotationNode(node); + let result; + if (declaredType) { + result = serializeTypeAnnotationOfDeclaration(declaredType, context, node, symbol); + } + const oldSuppressReportInferenceFallback = context.suppressReportInferenceFallback; + context.suppressReportInferenceFallback = true; + const resultType = result ?? inferTypeOfDeclaration( + node, + symbol, + context, + /*reportFallback*/ + false + ); + context.suppressReportInferenceFallback = oldSuppressReportInferenceFallback; + return resultType; + } + function typeFromProperty(node, symbol, context) { + const declaredType = getEffectiveTypeAnnotationNode(node); + const requiresAddingUndefined = resolver.requiresAddingImplicitUndefined(node, symbol, context.enclosingDeclaration); + let resultType = failed; + if (declaredType) { + resultType = syntacticResult(serializeTypeAnnotationOfDeclaration(declaredType, context, node, symbol, requiresAddingUndefined)); } else { - if (node.initializer && isIdentifier(node.name)) { + const initializer = isPropertyDeclaration(node) ? node.initializer : void 0; + if (initializer && !isContextuallyTyped(node)) { + const isReadonly = isDeclarationReadonly(node); resultType = typeFromExpression( - node.initializer, + initializer, context, /*isConstContext*/ void 0, - addUndefined + requiresAddingUndefined, + isReadonly ); } } - return resultType ?? inferTypeOfDeclaration(node, context); + return resultType.type !== void 0 ? resultType.type : inferTypeOfDeclaration(node, symbol, context, resultType.reportFallback); } - function typeFromProperty(node, context) { - const declaredType = getEffectiveTypeAnnotationNode(node); - if (declaredType) { - return serializeExistingTypeAnnotation(declaredType); + function inferTypeOfDeclaration(node, symbol, context, reportFallback = true) { + if (reportFallback) { + context.tracker.reportInferenceFallback(node); } - let resultType; - if (node.initializer) { - const isReadonly = isDeclarationReadonly(node); - resultType = typeFromExpression( - node.initializer, - context, - /*isConstContext*/ - void 0, - /*requiresAddingUndefined*/ - void 0, - isReadonly - ); + if (context.noInferenceFallback === true) { + return factory.createKeywordTypeNode(133 /* AnyKeyword */); } - return resultType ?? inferTypeOfDeclaration(node, context); + return resolver.serializeTypeOfDeclaration(context, node, symbol); } - function inferTypeOfDeclaration(node, context) { - context.tracker.reportInferenceFallback(node); - return false; - } - function inferExpressionType(node, context) { - context.tracker.reportInferenceFallback(node); - return false; + function inferExpressionType(node, context, reportFallback = true, requiresAddingUndefined) { + Debug.assert(!requiresAddingUndefined); + if (reportFallback) { + context.tracker.reportInferenceFallback(node); + } + if (context.noInferenceFallback === true) { + return factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + return resolver.serializeTypeOfExpression(context, node) ?? factory.createKeywordTypeNode(133 /* AnyKeyword */); } - function inferReturnTypeOfSignatureSignature(node, context) { - context.tracker.reportInferenceFallback(node); - return false; + function inferReturnTypeOfSignatureSignature(node, context, reportFallback) { + if (reportFallback) { + context.tracker.reportInferenceFallback(node); + } + if (context.noInferenceFallback === true) { + return factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + return resolver.serializeReturnTypeForSignature(context, node) ?? factory.createKeywordTypeNode(133 /* AnyKeyword */); } - function inferAccessorType(node, allAccessors, context) { + function inferAccessorType(node, allAccessors, context, symbol, reportFallback = true) { if (node.kind === 177 /* GetAccessor */) { - return createReturnFromSignature(node, context); + return createReturnFromSignature(node, symbol, context, reportFallback); } else { - context.tracker.reportInferenceFallback(node); - return false; + if (reportFallback) { + context.tracker.reportInferenceFallback(node); + } + const result = allAccessors.getAccessor && createReturnFromSignature(allAccessors.getAccessor, symbol, context, reportFallback); + return result ?? resolver.serializeTypeOfDeclaration(context, node, symbol) ?? factory.createKeywordTypeNode(133 /* AnyKeyword */); } } + function withNewScope(context, node, fn) { + const cleanup = resolver.enterNewScope(context, node); + const result = fn(); + cleanup(); + return result; + } function typeFromTypeAssertion(expression, type, context, requiresAddingUndefined) { if (isConstTypeReference(type)) { return typeFromExpression( @@ -135499,10 +136872,7 @@ function createSyntacticTypeNodeBuilder(options, resolver) { requiresAddingUndefined ); } - if (requiresAddingUndefined && !canAddUndefined(type)) { - context.tracker.reportInferenceFallback(type); - } - return serializeExistingTypeAnnotation(type); + return syntacticResult(serializeExistingTypeNodeWithFallback(type, context, requiresAddingUndefined)); } function typeFromExpression(node, context, isConstContext = false, requiresAddingUndefined = false, preserveLiterals = false) { switch (node.kind) { @@ -135513,14 +136883,19 @@ function createSyntacticTypeNodeBuilder(options, resolver) { return typeFromExpression(node.expression, context, isConstContext, requiresAddingUndefined); case 80 /* Identifier */: if (resolver.isUndefinedIdentifierExpression(node)) { - return true; + return syntacticResult(createUndefinedTypeNode()); } break; case 106 /* NullKeyword */: - return true; + if (strictNullChecks) { + return syntacticResult(addUndefinedIfNeeded(factory.createLiteralTypeNode(factory.createNull()), requiresAddingUndefined, node, context)); + } else { + return syntacticResult(factory.createKeywordTypeNode(133 /* AnyKeyword */)); + } case 219 /* ArrowFunction */: case 218 /* FunctionExpression */: - return typeFromFunctionLikeExpression(node, context); + Debug.type(node); + return withNewScope(context, node, () => typeFromFunctionLikeExpression(node, context)); case 216 /* TypeAssertionExpression */: case 234 /* AsExpression */: const asExpression = node; @@ -135528,43 +136903,73 @@ function createSyntacticTypeNodeBuilder(options, resolver) { case 224 /* PrefixUnaryExpression */: const unaryExpression = node; if (isPrimitiveLiteralValue(unaryExpression)) { - if (unaryExpression.operand.kind === 10 /* BigIntLiteral */) { - return typeFromPrimitiveLiteral(); - } - if (unaryExpression.operand.kind === 9 /* NumericLiteral */) { - return typeFromPrimitiveLiteral(); - } + return typeFromPrimitiveLiteral( + unaryExpression.operator === 40 /* PlusToken */ ? unaryExpression.operand : unaryExpression, + unaryExpression.operand.kind === 10 /* BigIntLiteral */ ? 163 /* BigIntKeyword */ : 150 /* NumberKeyword */, + context, + isConstContext || preserveLiterals, + requiresAddingUndefined + ); } break; - case 9 /* NumericLiteral */: - return typeFromPrimitiveLiteral(); + case 209 /* ArrayLiteralExpression */: + return typeFromArrayLiteral(node, context, isConstContext, requiresAddingUndefined); + case 210 /* ObjectLiteralExpression */: + return typeFromObjectLiteral(node, context, isConstContext, requiresAddingUndefined); + case 231 /* ClassExpression */: + return syntacticResult(inferExpressionType( + node, + context, + /*reportFallback*/ + true, + requiresAddingUndefined + )); case 228 /* TemplateExpression */: if (!isConstContext && !preserveLiterals) { - return true; + return syntacticResult(factory.createKeywordTypeNode(154 /* StringKeyword */)); } break; - case 15 /* NoSubstitutionTemplateLiteral */: - case 11 /* StringLiteral */: - return typeFromPrimitiveLiteral(); - case 10 /* BigIntLiteral */: - return typeFromPrimitiveLiteral(); - case 112 /* TrueKeyword */: - case 97 /* FalseKeyword */: - return typeFromPrimitiveLiteral(); - case 209 /* ArrayLiteralExpression */: - return typeFromArrayLiteral(node, context, isConstContext); - case 210 /* ObjectLiteralExpression */: - return typeFromObjectLiteral(node, context, isConstContext); - case 231 /* ClassExpression */: - return inferExpressionType(node, context); + default: + let typeKind; + let primitiveNode = node; + switch (node.kind) { + case 9 /* NumericLiteral */: + typeKind = 150 /* NumberKeyword */; + break; + case 15 /* NoSubstitutionTemplateLiteral */: + primitiveNode = factory.createStringLiteral(node.text); + typeKind = 154 /* StringKeyword */; + break; + case 11 /* StringLiteral */: + typeKind = 154 /* StringKeyword */; + break; + case 10 /* BigIntLiteral */: + typeKind = 163 /* BigIntKeyword */; + break; + case 112 /* TrueKeyword */: + case 97 /* FalseKeyword */: + typeKind = 136 /* BooleanKeyword */; + break; + } + if (typeKind) { + return typeFromPrimitiveLiteral(primitiveNode, typeKind, context, isConstContext || preserveLiterals, requiresAddingUndefined); + } } - return void 0; + return failed; } function typeFromFunctionLikeExpression(fnNode, context) { - const returnType = serializeExistingTypeAnnotation(fnNode.type) ?? createReturnFromSignature(fnNode, context); - const typeParameters = reuseTypeParameters(fnNode.typeParameters); - const parameters = fnNode.parameters.every((p) => ensureParameter(p, context)); - return returnType && typeParameters && parameters; + const oldNoInferenceFallback = context.noInferenceFallback; + context.noInferenceFallback = true; + createReturnFromSignature( + fnNode, + /*symbol*/ + void 0, + context + ); + reuseTypeParameters(fnNode.typeParameters, context); + fnNode.parameters.map((p) => ensureParameter(p, context)); + context.noInferenceFallback = oldNoInferenceFallback; + return notImplemented2; } function canGetTypeFromArrayLiteral(arrayLiteral, context, isConstContext) { if (!isConstContext) { @@ -135579,18 +136984,38 @@ function createSyntacticTypeNodeBuilder(options, resolver) { } return true; } - function typeFromArrayLiteral(arrayLiteral, context, isConstContext) { + function typeFromArrayLiteral(arrayLiteral, context, isConstContext, requiresAddingUndefined) { if (!canGetTypeFromArrayLiteral(arrayLiteral, context, isConstContext)) { - return false; + if (requiresAddingUndefined || isDeclaration(walkUpParenthesizedExpressions(arrayLiteral).parent)) { + return alreadyReported; + } + return syntacticResult(inferExpressionType( + arrayLiteral, + context, + /*reportFallback*/ + false, + requiresAddingUndefined + )); } - let canInferArray = true; + const oldNoInferenceFallback = context.noInferenceFallback; + context.noInferenceFallback = true; + const elementTypesInfo = []; for (const element of arrayLiteral.elements) { Debug.assert(element.kind !== 230 /* SpreadElement */); - if (element.kind !== 232 /* OmittedExpression */) { - canInferArray = (typeFromExpression(element, context, isConstContext) ?? inferExpressionType(element, context)) && canInferArray; + if (element.kind === 232 /* OmittedExpression */) { + elementTypesInfo.push( + createUndefinedTypeNode() + ); + } else { + const expressionType = typeFromExpression(element, context, isConstContext); + const elementType = expressionType.type !== void 0 ? expressionType.type : inferExpressionType(element, context, expressionType.reportFallback); + elementTypesInfo.push(elementType); } } - return true; + const tupleType = factory.createTupleTypeNode(elementTypesInfo); + tupleType.emitNode = { flags: 1, autoGenerate: void 0, internalFlags: 0 }; + context.noInferenceFallback = oldNoInferenceFallback; + return notImplemented2; } function canGetTypeFromObjectLiteral(objectLiteral, context) { let result = true; @@ -135621,64 +137046,214 @@ function createSyntacticTypeNodeBuilder(options, resolver) { } return result; } - function typeFromObjectLiteral(objectLiteral, context, isConstContext) { - if (!canGetTypeFromObjectLiteral(objectLiteral, context)) return false; - let canInferObjectLiteral = true; + function typeFromObjectLiteral(objectLiteral, context, isConstContext, requiresAddingUndefined) { + if (!canGetTypeFromObjectLiteral(objectLiteral, context)) { + if (requiresAddingUndefined || isDeclaration(walkUpParenthesizedExpressions(objectLiteral).parent)) { + return alreadyReported; + } + return syntacticResult(inferExpressionType( + objectLiteral, + context, + /*reportFallback*/ + false, + requiresAddingUndefined + )); + } + const oldNoInferenceFallback = context.noInferenceFallback; + context.noInferenceFallback = true; + const properties = []; + const oldFlags = context.flags; + context.flags |= 4194304 /* InObjectTypeLiteral */; for (const prop of objectLiteral.properties) { Debug.assert(!isShorthandPropertyAssignment(prop) && !isSpreadAssignment(prop)); const name = prop.name; + let newProp; switch (prop.kind) { case 174 /* MethodDeclaration */: - canInferObjectLiteral = !!typeFromObjectLiteralMethod(prop, name, context) && canInferObjectLiteral; + newProp = withNewScope(context, prop, () => typeFromObjectLiteralMethod(prop, name, context, isConstContext)); break; case 303 /* PropertyAssignment */: - canInferObjectLiteral = !!typeFromObjectLiteralPropertyAssignment(prop, name, context, isConstContext) && canInferObjectLiteral; + newProp = typeFromObjectLiteralPropertyAssignment(prop, name, context, isConstContext); break; case 178 /* SetAccessor */: case 177 /* GetAccessor */: - canInferObjectLiteral = !!typeFromObjectLiteralAccessor(prop, name, context) && canInferObjectLiteral; + newProp = typeFromObjectLiteralAccessor(prop, name, context); break; } + if (newProp) { + setCommentRange(newProp, prop); + properties.push(newProp); + } } - return canInferObjectLiteral; + context.flags = oldFlags; + const typeNode = factory.createTypeLiteralNode(properties); + if (!(context.flags & 1024 /* MultilineObjectLiterals */)) { + setEmitFlags(typeNode, 1 /* SingleLine */); + } + context.noInferenceFallback = oldNoInferenceFallback; + return notImplemented2; } function typeFromObjectLiteralPropertyAssignment(prop, name, context, isConstContext) { - return typeFromExpression(prop.initializer, context, isConstContext) ?? inferTypeOfDeclaration(prop, context); + const modifiers = isConstContext ? [factory.createModifier(148 /* ReadonlyKeyword */)] : []; + const expressionResult = typeFromExpression(prop.initializer, context, isConstContext); + const typeNode = expressionResult.type !== void 0 ? expressionResult.type : inferTypeOfDeclaration( + prop, + /*symbol*/ + void 0, + context, + expressionResult.reportFallback + ); + return factory.createPropertySignature( + modifiers, + reuseNode(context, name), + /*questionToken*/ + void 0, + typeNode + ); } function ensureParameter(p, context) { - return typeFromParameter(p, context); + return factory.updateParameterDeclaration( + p, + [], + reuseNode(context, p.dotDotDotToken), + resolver.serializeNameOfParameter(context, p), + resolver.isOptionalParameter(p) ? factory.createToken(58 /* QuestionToken */) : void 0, + typeFromParameter( + p, + /*symbol*/ + void 0, + context + ), + // Ignore private param props, since this type is going straight back into a param + /*initializer*/ + void 0 + ); } - function reuseTypeParameters(typeParameters) { - return (typeParameters == null ? void 0 : typeParameters.every( - (tp) => serializeExistingTypeAnnotation(tp.constraint) && serializeExistingTypeAnnotation(tp.default) - )) ?? true; + function reuseTypeParameters(typeParameters, context) { + return typeParameters == null ? void 0 : typeParameters.map( + (tp) => { + var _a; + return factory.updateTypeParameterDeclaration( + tp, + (_a = tp.modifiers) == null ? void 0 : _a.map((m) => reuseNode(context, m)), + reuseNode(context, tp.name), + serializeExistingTypeNodeWithFallback(tp.constraint, context), + serializeExistingTypeNodeWithFallback(tp.default, context) + ); + } + ); } - function typeFromObjectLiteralMethod(method, name, context) { - const returnType = createReturnFromSignature(method, context); - const typeParameters = reuseTypeParameters(method.typeParameters); - const parameters = method.parameters.every((p) => ensureParameter(p, context)); - return returnType && typeParameters && parameters; + function typeFromObjectLiteralMethod(method, name, context, isConstContext) { + const returnType = createReturnFromSignature( + method, + /*symbol*/ + void 0, + context + ); + const typeParameters = reuseTypeParameters(method.typeParameters, context); + const parameters = method.parameters.map((p) => ensureParameter(p, context)); + if (isConstContext) { + return factory.createPropertySignature( + [factory.createModifier(148 /* ReadonlyKeyword */)], + reuseNode(context, name), + reuseNode(context, method.questionToken), + factory.createFunctionTypeNode( + typeParameters, + parameters, + returnType + ) + ); + } else { + if (isIdentifier(name) && name.escapedText === "new") { + name = factory.createStringLiteral("new"); + } + return factory.createMethodSignature( + [], + reuseNode(context, name), + reuseNode(context, method.questionToken), + typeParameters, + parameters, + returnType + ); + } } function typeFromObjectLiteralAccessor(accessor, name, context) { const allAccessors = resolver.getAllAccessorDeclarations(accessor); - const getAccessorType = allAccessors.getAccessor && getTypeAnnotationFromAccessor2(allAccessors.getAccessor); - const setAccessorType = allAccessors.setAccessor && getTypeAnnotationFromAccessor2(allAccessors.setAccessor); + const getAccessorType = allAccessors.getAccessor && getTypeAnnotationFromAccessor(allAccessors.getAccessor); + const setAccessorType = allAccessors.setAccessor && getTypeAnnotationFromAccessor(allAccessors.setAccessor); if (getAccessorType !== void 0 && setAccessorType !== void 0) { - const parameters = accessor.parameters.every((p) => ensureParameter(p, context)); - if (isGetAccessor(accessor)) { - return parameters && serializeExistingTypeAnnotation(getAccessorType); - } else { - return parameters; - } + return withNewScope(context, accessor, () => { + const parameters = accessor.parameters.map((p) => ensureParameter(p, context)); + if (isGetAccessor(accessor)) { + return factory.updateGetAccessorDeclaration( + accessor, + [], + reuseNode(context, name), + parameters, + serializeExistingTypeNodeWithFallback(getAccessorType, context), + /*body*/ + void 0 + ); + } else { + return factory.updateSetAccessorDeclaration( + accessor, + [], + reuseNode(context, name), + parameters, + /*body*/ + void 0 + ); + } + }); } else if (allAccessors.firstAccessor === accessor) { - const foundType = getAccessorType ?? setAccessorType; - const propertyType = foundType ? serializeExistingTypeAnnotation(foundType) : inferAccessorType(accessor, allAccessors, context); - return propertyType; + const foundType = getAccessorType ? withNewScope(context, allAccessors.getAccessor, () => serializeExistingTypeNodeWithFallback(getAccessorType, context)) : setAccessorType ? withNewScope(context, allAccessors.setAccessor, () => serializeExistingTypeNodeWithFallback(setAccessorType, context)) : void 0; + const propertyType = foundType ?? inferAccessorType( + accessor, + allAccessors, + context, + /*symbol*/ + void 0 + ); + const propertySignature = factory.createPropertySignature( + allAccessors.setAccessor === void 0 ? [factory.createModifier(148 /* ReadonlyKeyword */)] : [], + reuseNode(context, name), + /*questionToken*/ + void 0, + propertyType + ); + return propertySignature; } - return false; } - function typeFromPrimitiveLiteral() { - return true; + function createUndefinedTypeNode() { + if (strictNullChecks) { + return factory.createKeywordTypeNode(157 /* UndefinedKeyword */); + } else { + return factory.createKeywordTypeNode(133 /* AnyKeyword */); + } + } + function typeFromPrimitiveLiteral(node, baseType, context, preserveLiterals, requiresAddingUndefined) { + let result; + if (preserveLiterals) { + if (node.kind === 224 /* PrefixUnaryExpression */ && node.operator === 40 /* PlusToken */) { + result = factory.createLiteralTypeNode(reuseNode(context, node.operand)); + } + result = factory.createLiteralTypeNode(reuseNode(context, node)); + } else { + result = factory.createKeywordTypeNode(baseType); + } + return syntacticResult(addUndefinedIfNeeded(result, requiresAddingUndefined, node, context)); + } + function addUndefinedIfNeeded(node, addUndefined, owner, context) { + const parentDeclaration = owner && walkUpParenthesizedExpressions(owner).parent; + const optionalDeclaration = parentDeclaration && isDeclaration(parentDeclaration) && isOptionalDeclaration(parentDeclaration); + if (!strictNullChecks || !(addUndefined || optionalDeclaration)) return node; + if (!canAddUndefined(node)) { + context.tracker.reportInferenceFallback(node); + } + if (isUnionTypeNode(node)) { + return factory.createUnionTypeNode([...node.types, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); + } + return factory.createUnionTypeNode([node, factory.createKeywordTypeNode(157 /* UndefinedKeyword */)]); } function canAddUndefined(node) { if (!strictNullChecks) return true; @@ -135693,24 +137268,28 @@ function createSyntacticTypeNodeBuilder(options, resolver) { } return false; } - function createReturnFromSignature(fn, context) { - let returnType; - const returnTypeNode = getEffectiveReturnTypeNode(fn); + function createReturnFromSignature(fn, symbol, context, reportFallback = true) { + let returnType = failed; + const returnTypeNode = isJSDocConstructSignature(fn) ? getEffectiveTypeAnnotationNode(fn.parameters[0]) : getEffectiveReturnTypeNode(fn); if (returnTypeNode) { - returnType = serializeExistingTypeAnnotation(returnTypeNode); - } - if (!returnType && isValueSignatureDeclaration(fn)) { + returnType = syntacticResult(serializeTypeAnnotationOfDeclaration(returnTypeNode, context, fn, symbol)); + } else if (isValueSignatureDeclaration(fn)) { returnType = typeFromSingleReturnExpression(fn, context); } - return returnType ?? inferReturnTypeOfSignatureSignature(fn, context); + return returnType.type !== void 0 ? returnType.type : inferReturnTypeOfSignatureSignature(fn, context, reportFallback && returnType.reportFallback && !returnTypeNode); } function typeFromSingleReturnExpression(declaration, context) { let candidateExpr; if (declaration && !nodeIsMissing(declaration.body)) { - if (getFunctionFlags(declaration) & 3 /* AsyncGenerator */) return void 0; + const flags = getFunctionFlags(declaration); + if (flags & 3 /* AsyncGenerator */) return failed; const body = declaration.body; if (body && isBlock(body)) { forEachReturnStatement(body, (s) => { + if (s.parent !== body) { + candidateExpr = void 0; + return true; + } if (!candidateExpr) { candidateExpr = s.expression; } else { @@ -135723,9 +137302,21 @@ function createSyntacticTypeNodeBuilder(options, resolver) { } } if (candidateExpr) { - return typeFromExpression(candidateExpr, context); + if (isContextuallyTyped(candidateExpr)) { + const type = isJSDocTypeAssertion(candidateExpr) ? getJSDocTypeAssertionType(candidateExpr) : isAsExpression(candidateExpr) || isTypeAssertionExpression(candidateExpr) ? candidateExpr.type : void 0; + if (type && !isConstTypeReference(type)) { + return syntacticResult(serializeExistingTypeNode(type, context)); + } + } else { + return typeFromExpression(candidateExpr, context); + } } - return void 0; + return failed; + } + function isContextuallyTyped(node) { + return findAncestor(node.parent, (n) => { + return isCallExpression(n) || !isFunctionLikeDeclaration(n) && !!getEffectiveTypeAnnotationNode(n) || isJsxElement(n) || isJsxExpression(n); + }); } } @@ -135737,8 +137328,6 @@ __export(ts_JsTyping_exports, { isTypingUpToDate: () => isTypingUpToDate, loadSafeList: () => loadSafeList, loadTypesMap: () => loadTypesMap, - nodeCoreModuleList: () => nodeCoreModuleList, - nodeCoreModules: () => nodeCoreModules, nonRelativeModuleNameForTypingCache: () => nonRelativeModuleNameForTypingCache, renderPackageNameValidationFailure: () => renderPackageNameValidationFailure, validatePackageName: () => validatePackageName @@ -135787,58 +137376,6 @@ function isTypingUpToDate(cachedTyping, availableTypingVersions) { const availableVersion = new Version(getProperty(availableTypingVersions, `ts${versionMajorMinor}`) || getProperty(availableTypingVersions, "latest")); return availableVersion.compareTo(cachedTyping.version) <= 0; } -var unprefixedNodeCoreModuleList = [ - "assert", - "assert/strict", - "async_hooks", - "buffer", - "child_process", - "cluster", - "console", - "constants", - "crypto", - "dgram", - "diagnostics_channel", - "dns", - "dns/promises", - "domain", - "events", - "fs", - "fs/promises", - "http", - "https", - "http2", - "inspector", - "module", - "net", - "os", - "path", - "perf_hooks", - "process", - "punycode", - "querystring", - "readline", - "repl", - "stream", - "stream/promises", - "string_decoder", - "timers", - "timers/promises", - "tls", - "trace_events", - "tty", - "url", - "util", - "util/types", - "v8", - "vm", - "wasi", - "worker_threads", - "zlib" -]; -var prefixedNodeCoreModuleList = unprefixedNodeCoreModuleList.map((name) => `node:${name}`); -var nodeCoreModuleList = [...unprefixedNodeCoreModuleList, ...prefixedNodeCoreModuleList]; -var nodeCoreModules = new Set(nodeCoreModuleList); function nonRelativeModuleNameForTypingCache(moduleName) { return nodeCoreModules.has(moduleName) ? "node" : moduleName; } @@ -136073,6 +137610,7 @@ function renderPackageNameValidationFailureWorker(typing, result, name, isScopeN return `'${typing}':: ${kind} name '${name}' contains non URI safe characters`; case 0 /* Ok */: return Debug.fail(); + // Shouldn't have called this. default: Debug.assertNever(result); } @@ -136449,6 +137987,7 @@ function getMeaningFromDeclaration(node) { case 277 /* ExportAssignment */: case 278 /* ExportDeclaration */: return 7 /* All */; + // An external module can be a Value case 307 /* SourceFile */: return 4 /* Namespace */ | 1 /* Value */; } @@ -136757,6 +138296,7 @@ function getNodeKind(node) { return isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; case 4 /* ThisProperty */: return "property" /* memberVariableElement */; + // property case 5 /* Property */: return isFunctionExpression(right) ? "method" /* memberFunctionElement */ : "property" /* memberVariableElement */; case 6 /* Prototype */: @@ -136794,9 +138334,6 @@ function getLineStartPositionForPosition(position, sourceFile) { const line = sourceFile.getLineAndCharacterOfPosition(position).line; return lineStarts[line]; } -function rangeContainsRange(r1, r2) { - return startEndContainsRange(r1.pos, r1.end, r2); -} function rangeContainsRangeExclusive(r1, r2) { return rangeContainsPositionExclusive(r1, r2.pos) && rangeContainsPositionExclusive(r1, r2.end); } @@ -136806,9 +138343,6 @@ function rangeContainsPosition(r, pos) { function rangeContainsPositionExclusive(r, pos) { return r.pos < pos && pos < r.end; } -function startEndContainsRange(start, end, range) { - return start <= range.pos && end >= range.end; -} function rangeContainsStartEnd(range, start, end) { return range.pos <= start && range.end >= end; } @@ -136850,6 +138384,7 @@ function isCompletedNode(n, sourceFile) { if (!n.arguments) { return true; } + // falls through case 213 /* CallExpression */: case 217 /* ParenthesizedExpression */: case 196 /* ParenthesizedType */: @@ -137578,16 +139113,19 @@ function getPossibleTypeArgumentsInfo(tokenIn, sourceFile) { token = findPrecedingMatchingToken(token, 23 /* OpenBracketToken */, sourceFile); if (!token) return void 0; break; + // Valid tokens in a type name. Skip. case 28 /* CommaToken */: nTypeArguments++; break; case 39 /* EqualsGreaterThanToken */: + // falls through case 80 /* Identifier */: case 11 /* StringLiteral */: case 9 /* NumericLiteral */: case 10 /* BigIntLiteral */: case 112 /* TrueKeyword */: case 97 /* FalseKeyword */: + // falls through case 114 /* TypeOfKeyword */: case 96 /* ExtendsKeyword */: case 143 /* KeyOfKeyword */: @@ -137824,7 +139362,7 @@ function createModuleSpecifierResolutionHost(program, host) { fileExists: (fileName) => program.fileExists(fileName), getCurrentDirectory: () => host.getCurrentDirectory(), readFile: maybeBind(host, host.readFile), - useCaseSensitiveFileNames: maybeBind(host, host.useCaseSensitiveFileNames), + useCaseSensitiveFileNames: maybeBind(host, host.useCaseSensitiveFileNames) || program.useCaseSensitiveFileNames, getSymlinkCache: maybeBind(host, host.getSymlinkCache) || program.getSymlinkCache, getModuleSpecifierCache: maybeBind(host, host.getModuleSpecifierCache), getPackageJsonInfoCache: () => { @@ -138676,28 +140214,33 @@ function tryAndIgnoreErrors(cb) { function tryIOAndConsumeErrors(host, toApply, ...args) { return tryAndIgnoreErrors(() => toApply && toApply.apply(host, args)); } -function findPackageJsons(startDirectory, host, stopDirectory) { +function findPackageJsons(startDirectory, host) { const paths = []; - forEachAncestorDirectory(startDirectory, (ancestor) => { - if (ancestor === stopDirectory) { - return true; - } - const currentConfigPath = combinePaths(ancestor, "package.json"); - if (tryFileExists(host, currentConfigPath)) { - paths.push(currentConfigPath); + forEachAncestorDirectoryStoppingAtGlobalCache( + host, + startDirectory, + (ancestor) => { + const currentConfigPath = combinePaths(ancestor, "package.json"); + if (tryFileExists(host, currentConfigPath)) { + paths.push(currentConfigPath); + } } - }); + ); return paths; } function findPackageJson(directory, host) { let packageJson; - forEachAncestorDirectory(directory, (ancestor) => { - if (ancestor === "node_modules") return true; - packageJson = findConfigFile(ancestor, (f) => tryFileExists(host, f), "package.json"); - if (packageJson) { - return true; + forEachAncestorDirectoryStoppingAtGlobalCache( + host, + directory, + (ancestor) => { + if (ancestor === "node_modules") return true; + packageJson = findConfigFile(ancestor, (f) => tryFileExists(host, f), "package.json"); + if (packageJson) { + return true; + } } - }); + ); return packageJson; } function getPackageJsonsVisibleToFile(fileName, host) { @@ -138705,15 +140248,19 @@ function getPackageJsonsVisibleToFile(fileName, host) { return []; } const packageJsons = []; - forEachAncestorDirectory(getDirectoryPath(fileName), (ancestor) => { - const packageJsonFileName = combinePaths(ancestor, "package.json"); - if (host.fileExists(packageJsonFileName)) { - const info = createPackageJsonInfo(packageJsonFileName, host); - if (info) { - packageJsons.push(info); + forEachAncestorDirectoryStoppingAtGlobalCache( + host, + getDirectoryPath(fileName), + (ancestor) => { + const packageJsonFileName = combinePaths(ancestor, "package.json"); + if (host.fileExists(packageJsonFileName)) { + const info = createPackageJsonInfo(packageJsonFileName, host); + if (info) { + packageJsons.push(info); + } } } - }); + ); return packageJsons; } function createPackageJsonInfo(fileName, host) { @@ -138842,7 +140389,7 @@ function createPackageJsonImportFilter(fromFile, preferences, host) { return moduleSpecifierIsCoveredByPackageJson(moduleSpecifier); } function isAllowedCoreNodeModulesImport(moduleSpecifier) { - if (isFullSourceFile(fromFile) && isSourceFileJS(fromFile) && ts_JsTyping_exports.nodeCoreModules.has(moduleSpecifier)) { + if (isFullSourceFile(fromFile) && isSourceFileJS(fromFile) && nodeCoreModules.has(moduleSpecifier)) { if (usesNodeCoreModules === void 0) { usesNodeCoreModules = consumesNodeCoreModules(fromFile); } @@ -138879,7 +140426,7 @@ function createPackageJsonImportFilter(fromFile, preferences, host) { } } function consumesNodeCoreModules(sourceFile) { - return some(sourceFile.imports, ({ text }) => ts_JsTyping_exports.nodeCoreModules.has(text)); + return some(sourceFile.imports, ({ text }) => nodeCoreModules.has(text)); } function isInsideNodeModules(fileOrDirectory) { return contains(getPathComponents(fileOrDirectory), "node_modules"); @@ -138953,7 +140500,13 @@ function getDefaultLikeExportNameFromDeclaration(symbol) { if (isExportSpecifier(d) && d.symbol.flags === 2097152 /* Alias */) { return (_b = tryCast(d.propertyName, isIdentifier)) == null ? void 0 : _b.text; } - return (_c = tryCast(getNameOfDeclaration(d), isIdentifier)) == null ? void 0 : _c.text; + const name = (_c = tryCast(getNameOfDeclaration(d), isIdentifier)) == null ? void 0 : _c.text; + if (name) { + return name; + } + if (symbol.parent && !isExternalModuleSymbol(symbol.parent)) { + return symbol.parent.getName(); + } }); } function getSymbolParentOrFail(symbol) { @@ -139015,11 +140568,16 @@ function isDeprecatedDeclaration(decl) { return !!(getCombinedNodeFlagsAlwaysIncludeJSDoc(decl) & 65536 /* Deprecated */); } function shouldUseUriStyleNodeCoreModules(file, program) { - const decisionFromFile = firstDefined(file.imports, (node) => { - if (ts_JsTyping_exports.nodeCoreModules.has(node.text)) { - return startsWith(node.text, "node:"); + let decisionFromFile; + for (const node of file.imports) { + if (nodeCoreModules.has(node.text) && !exclusivelyPrefixedNodeCoreModules.has(node.text)) { + if (startsWith(node.text, "node:")) { + return true; + } else { + decisionFromFile = false; + } } - }); + } return decisionFromFile ?? program.usesUriStyleNodeCoreModules; } function getNewLineKind(newLineCharacter) { @@ -139179,6 +140737,7 @@ var ExportKind = /* @__PURE__ */ ((ExportKind3) => { ExportKind3[ExportKind3["Default"] = 1] = "Default"; ExportKind3[ExportKind3["ExportEquals"] = 2] = "ExportEquals"; ExportKind3[ExportKind3["UMD"] = 3] = "UMD"; + ExportKind3[ExportKind3["Module"] = 4] = "Module"; return ExportKind3; })(ExportKind || {}); function createCacheableExportInfoMap(host) { @@ -139369,38 +140928,57 @@ function createCacheableExportInfoMap(host) { return !packageDeepestNodeModulesPath || startsWith(info.moduleFileName, packageDeepestNodeModulesPath); } } -function isImportableFile(program, from, to, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) { +function isImportable(program, fromFile, toFile, toModule, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) { var _a; - if (from === to) return false; - const cachedResult = moduleSpecifierCache == null ? void 0 : moduleSpecifierCache.get(from.path, to.path, preferences, {}); + if (!toFile) { + let useNodePrefix; + const moduleName = stripQuotes(toModule.name); + if (nodeCoreModules.has(moduleName) && (useNodePrefix = shouldUseUriStyleNodeCoreModules(fromFile, program)) !== void 0) { + return useNodePrefix === startsWith(moduleName, "node:"); + } + return !packageJsonFilter || packageJsonFilter.allowsImportingAmbientModule(toModule, moduleSpecifierResolutionHost) || fileContainsPackageImport(fromFile, moduleName); + } + Debug.assertIsDefined(toFile); + if (fromFile === toFile) return false; + const cachedResult = moduleSpecifierCache == null ? void 0 : moduleSpecifierCache.get(fromFile.path, toFile.path, preferences, {}); if ((cachedResult == null ? void 0 : cachedResult.isBlockedByPackageJsonDependencies) !== void 0) { - return !cachedResult.isBlockedByPackageJsonDependencies || !!cachedResult.packageName && fileContainsPackageImport(from, cachedResult.packageName); + return !cachedResult.isBlockedByPackageJsonDependencies || !!cachedResult.packageName && fileContainsPackageImport(fromFile, cachedResult.packageName); } const getCanonicalFileName = hostGetCanonicalFileName(moduleSpecifierResolutionHost); const globalTypingsCache = (_a = moduleSpecifierResolutionHost.getGlobalTypingsCacheLocation) == null ? void 0 : _a.call(moduleSpecifierResolutionHost); const hasImportablePath = !!ts_moduleSpecifiers_exports.forEachFileNameOfModule( - from.fileName, - to.fileName, + fromFile.fileName, + toFile.fileName, moduleSpecifierResolutionHost, /*preferSymlinks*/ false, (toPath3) => { - const toFile = program.getSourceFile(toPath3); - return (toFile === to || !toFile) && isImportablePath(from.fileName, toPath3, getCanonicalFileName, globalTypingsCache); + const file = program.getSourceFile(toPath3); + return (file === toFile || !file) && isImportablePath( + fromFile.fileName, + toPath3, + getCanonicalFileName, + globalTypingsCache, + moduleSpecifierResolutionHost + ); } ); if (packageJsonFilter) { - const importInfo = hasImportablePath ? packageJsonFilter.getSourceFileInfo(to, moduleSpecifierResolutionHost) : void 0; - moduleSpecifierCache == null ? void 0 : moduleSpecifierCache.setBlockedByPackageJsonDependencies(from.path, to.path, preferences, {}, importInfo == null ? void 0 : importInfo.packageName, !(importInfo == null ? void 0 : importInfo.importable)); - return !!(importInfo == null ? void 0 : importInfo.importable) || !!(importInfo == null ? void 0 : importInfo.packageName) && fileContainsPackageImport(from, importInfo.packageName); + const importInfo = hasImportablePath ? packageJsonFilter.getSourceFileInfo(toFile, moduleSpecifierResolutionHost) : void 0; + moduleSpecifierCache == null ? void 0 : moduleSpecifierCache.setBlockedByPackageJsonDependencies(fromFile.path, toFile.path, preferences, {}, importInfo == null ? void 0 : importInfo.packageName, !(importInfo == null ? void 0 : importInfo.importable)); + return !!(importInfo == null ? void 0 : importInfo.importable) || hasImportablePath && !!(importInfo == null ? void 0 : importInfo.packageName) && fileContainsPackageImport(fromFile, importInfo.packageName); } return hasImportablePath; } function fileContainsPackageImport(sourceFile, packageName) { return sourceFile.imports && sourceFile.imports.some((i) => i.text === packageName || i.text.startsWith(packageName + "/")); } -function isImportablePath(fromPath, toPath3, getCanonicalFileName, globalCachePath) { - const toNodeModules = forEachAncestorDirectory(toPath3, (ancestor) => getBaseFileName(ancestor) === "node_modules" ? ancestor : void 0); +function isImportablePath(fromPath, toPath3, getCanonicalFileName, globalCachePath, host) { + const toNodeModules = forEachAncestorDirectoryStoppingAtGlobalCache( + host, + toPath3, + (ancestor) => getBaseFileName(ancestor) === "node_modules" ? ancestor : void 0 + ); const toNodeModulesParent = toNodeModules && getDirectoryPath(getCanonicalFileName(toNodeModules)); return toNodeModulesParent === void 0 || startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) || !!globalCachePath && startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent); } @@ -139471,13 +141049,17 @@ function getIsExcluded(excludePatterns, host) { if (excludePatterns.some((p) => p.test(fileName))) return true; if ((realpathsWithSymlinks == null ? void 0 : realpathsWithSymlinks.size) && pathContainsNodeModules(fileName)) { let dir = getDirectoryPath(fileName); - return forEachAncestorDirectory(getDirectoryPath(path), (dirPath) => { - const symlinks = realpathsWithSymlinks.get(ensureTrailingDirectorySeparator(dirPath)); - if (symlinks) { - return symlinks.some((s) => excludePatterns.some((p) => p.test(fileName.replace(dir, s)))); + return forEachAncestorDirectoryStoppingAtGlobalCache( + host, + getDirectoryPath(path), + (dirPath) => { + const symlinks = realpathsWithSymlinks.get(ensureTrailingDirectorySeparator(dirPath)); + if (symlinks) { + return symlinks.some((s) => excludePatterns.some((p) => p.test(fileName.replace(dir, s)))); + } + dir = getDirectoryPath(dir); } - dir = getDirectoryPath(dir); - }) ?? false; + ) ?? false; } return false; }; @@ -139516,7 +141098,7 @@ function getExportInfoMap(importingFile, host, program, preferences, cancellatio true, (moduleSymbol, moduleFile, program2, isFromPackageJson) => { if (++moduleCount % 100 === 0) cancellationToken == null ? void 0 : cancellationToken.throwIfCancellationRequested(); - const seenExports = /* @__PURE__ */ new Map(); + const seenExports = /* @__PURE__ */ new Set(); const checker = program2.getTypeChecker(); const defaultInfo = getDefaultLikeExportInfo(moduleSymbol, checker); if (defaultInfo && isImportableSymbol(defaultInfo.symbol, checker)) { @@ -139556,7 +141138,11 @@ function getExportInfoMap(importingFile, host, program, preferences, cancellatio } function getDefaultLikeExportInfo(moduleSymbol, checker) { const exportEquals = checker.resolveExternalModuleSymbol(moduleSymbol); - if (exportEquals !== moduleSymbol) return { symbol: exportEquals, exportKind: 2 /* ExportEquals */ }; + if (exportEquals !== moduleSymbol) { + const defaultExport2 = checker.tryGetMemberInModuleExports("default" /* Default */, exportEquals); + if (defaultExport2) return { symbol: defaultExport2, exportKind: 1 /* Default */ }; + return { symbol: exportEquals, exportKind: 2 /* ExportEquals */ }; + } const defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); if (defaultExport) return { symbol: defaultExport, exportKind: 1 /* Default */ }; } @@ -139574,7 +141160,7 @@ function getNamesForExportedSymbol(defaultExport, checker, scriptTarget) { function forEachNameOfDefaultExport(defaultExport, checker, scriptTarget, cb) { let chain; let current = defaultExport; - const seen = /* @__PURE__ */ new Map(); + const seen = /* @__PURE__ */ new Set(); while (current) { const fromDeclaration = getDefaultLikeExportNameFromDeclaration(current); if (fromDeclaration) { @@ -139847,6 +141433,7 @@ function canFollow(keyword1, keyword2) { case 126 /* StaticKeyword */: case 129 /* AccessorKeyword */: return true; + // Allow things like "public get", "public constructor" and "public static". default: return false; } @@ -140657,6 +142244,7 @@ var DocumentHighlights; if (statement.kind === 251 /* ContinueStatement */) { return false; } + // falls through case 248 /* ForStatement */: case 249 /* ForInStatement */: case 250 /* ForOfStatement */: @@ -140702,6 +142290,7 @@ var DocumentHighlights; return [...nodes, container]; } return nodes; + // Syntactically invalid positions that the parser might produce anyway default: return void 0; } @@ -142281,8 +143870,10 @@ function isFixablePromiseArgument(arg, checker) { if (functionFlags & 1 /* Generator */) { return false; } + // falls through case 219 /* ArrowFunction */: visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true); + // falls through case 106 /* NullKeyword */: return true; case 80 /* Identifier */: @@ -142955,6 +144546,7 @@ function addChildrenRecursively(node) { Debug.assertNever(special); } } + // falls through default: if (hasJSDocNodes(node)) { forEach(node.jsDoc, (jsDoc) => { @@ -143117,6 +144709,7 @@ function isSynthesized(node) { return !!(node.flags & 16 /* Synthesized */); } function isOwnChild(n, parent2) { + if (n.parent === void 0) return false; const par = isModuleBlock(n.parent) ? n.parent.parent : n.parent; return par === parent2.node || contains(parent2.additionalNodes, par); } @@ -143401,6 +144994,7 @@ __export(ts_refactor_exports, { getStatementsToMove: () => getStatementsToMove, getUsageInfo: () => getUsageInfo, inferFunctionReturnType: () => ts_refactor_inferFunctionReturnType_exports, + isInImport: () => isInImport, isRefactorErrorInfo: () => isRefactorErrorInfo, refactorKindBeginsWith: () => refactorKindBeginsWith, registerRefactor: () => registerRefactor @@ -143547,6 +145141,7 @@ function changeExport(exportingSourceFile, { wasDefault, exportNode, exportName changes.replaceNode(exportingSourceFile, exportNode, factory.createExportDefault(Debug.checkDefined(decl.initializer, "Initializer was previously known to be present"))); break; } + // falls through case 266 /* EnumDeclaration */: case 265 /* TypeAliasDeclaration */: case 267 /* ModuleDeclaration */: @@ -144031,7 +145626,7 @@ function flattenTypeLiteralNodeReference(checker, selection) { } if (isIntersectionTypeNode(selection)) { const result = []; - const seen = /* @__PURE__ */ new Map(); + const seen = /* @__PURE__ */ new Set(); for (const type of selection.types) { const flattenedTypeMembers = flattenTypeLiteralNodeReference(checker, type); if (!flattenedTypeMembers || !flattenedTypeMembers.every((type2) => type2.name && addToSeen(seen, getNameFromPropertyName(type2.name)))) { @@ -144653,6 +146248,7 @@ function getNamesToExportInCommonJS(decl) { case 262 /* FunctionDeclaration */: case 263 /* ClassDeclaration */: return [decl.name.text]; + // TODO: GH#18217 case 243 /* VariableStatement */: return mapDefined(decl.declarationList.declarations, (d) => isIdentifier(d.name) ? d.name.text : void 0); case 267 /* ModuleDeclaration */: @@ -144834,23 +146430,22 @@ function getUsageInfo(oldFile, toMove, checker, existingTargetLocals = /* @__PUR const unusedImportsFromOldFile = /* @__PURE__ */ new Set(); for (const statement of toMove) { forEachReference(statement, checker, enclosingRange, (symbol, isValidTypeOnlyUseSite) => { - if (!symbol.declarations || isGlobalType(checker, symbol)) { + if (!symbol.declarations) { return; } if (existingTargetLocals.has(skipAlias(symbol, checker))) { unusedImportsFromOldFile.add(symbol); return; } - for (const decl of symbol.declarations) { - if (isInImport(decl)) { - const prevIsTypeOnly = oldImportsNeededByTargetFile.get(symbol); - oldImportsNeededByTargetFile.set(symbol, [ - prevIsTypeOnly === void 0 ? isValidTypeOnlyUseSite : prevIsTypeOnly && isValidTypeOnlyUseSite, - tryCast(decl, (d) => isImportSpecifier(d) || isImportClause(d) || isNamespaceImport(d) || isImportEqualsDeclaration(d) || isBindingElement(d) || isVariableDeclaration(d)) - ]); - } else if (isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile && !movedSymbols.has(symbol)) { - targetFileImportsFromOldFile.set(symbol, isValidTypeOnlyUseSite); - } + const importedDeclaration = find(symbol.declarations, isInImport); + if (importedDeclaration) { + const prevIsTypeOnly = oldImportsNeededByTargetFile.get(symbol); + oldImportsNeededByTargetFile.set(symbol, [ + prevIsTypeOnly === void 0 ? isValidTypeOnlyUseSite : prevIsTypeOnly && isValidTypeOnlyUseSite, + tryCast(importedDeclaration, (d) => isImportSpecifier(d) || isImportClause(d) || isNamespaceImport(d) || isImportEqualsDeclaration(d) || isBindingElement(d) || isVariableDeclaration(d)) + ]); + } else if (!movedSymbols.has(symbol) && every(symbol.declarations, (decl) => isTopLevelDeclaration(decl) && sourceFileOfTopLevelDeclaration(decl) === oldFile)) { + targetFileImportsFromOldFile.set(symbol, isValidTypeOnlyUseSite); } }); } @@ -144884,16 +146479,6 @@ function getUsageInfo(oldFile, toMove, checker, existingTargetLocals = /* @__PUR return !!jsxNamespaceSymbol2 && some(jsxNamespaceSymbol2.declarations, isInImport) ? jsxNamespaceSymbol2 : void 0; } } -function isGlobalType(checker, symbol) { - return !!checker.resolveName( - symbol.name, - /*location*/ - void 0, - 788968 /* Type */, - /*excludeGlobals*/ - false - ); -} function makeUniqueFilename(proposedFilename, extension, inDirectory, host) { let newFilename = proposedFilename; for (let i = 1; ; i++) { @@ -145112,6 +146697,9 @@ function addTargetFileImports(oldFile, importsToCopy, targetFileImportsFromOldFi const targetSymbol = skipAlias(symbol, checker); if (checker.isUnknownSymbol(targetSymbol)) { importAdder.addVerbatimImport(Debug.checkDefined(declaration ?? findAncestor((_a = symbol.declarations) == null ? void 0 : _a[0], isAnyImportOrRequireStatement))); + } else if (targetSymbol.parent === void 0) { + Debug.assert(declaration !== void 0, "expected module symbol to have a declaration"); + importAdder.addImportForModuleSymbol(symbol, isValidTypeOnlyUseSite, declaration); } else { importAdder.addImportFromExportedSymbol(targetSymbol, isValidTypeOnlyUseSite, declaration); } @@ -146115,6 +147703,7 @@ function entryToFunctionCall(entry) { const functionReference = entry.node; const parent2 = functionReference.parent; switch (parent2.kind) { + // foo(...) or super(...) or new Foo(...) case 213 /* CallExpression */: case 214 /* NewExpression */: const callOrNewExpression = tryCast(parent2, isCallOrNewExpression); @@ -146122,6 +147711,7 @@ function entryToFunctionCall(entry) { return callOrNewExpression; } break; + // x.foo(...) case 211 /* PropertyAccessExpression */: const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { @@ -146131,6 +147721,7 @@ function entryToFunctionCall(entry) { } } break; + // x["foo"](...) case 212 /* ElementAccessExpression */: const elementAccessExpression = tryCast(parent2, isElementAccessExpression); if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { @@ -146149,12 +147740,14 @@ function entryToAccessExpression(entry) { const reference = entry.node; const parent2 = reference.parent; switch (parent2.kind) { + // `C.foo` case 211 /* PropertyAccessExpression */: const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); if (propertyAccessExpression && propertyAccessExpression.expression === reference) { return propertyAccessExpression; } break; + // `C["foo"]` case 212 /* ElementAccessExpression */: const elementAccessExpression = tryCast(parent2, isElementAccessExpression); if (elementAccessExpression && elementAccessExpression.expression === reference) { @@ -147247,11 +148840,13 @@ function getRangeToExtract2(sourceFile, span, invoked = true) { forEachChild(n, check); } }); + // falls through case 263 /* ClassDeclaration */: case 262 /* FunctionDeclaration */: if (isSourceFile(node2.parent) && node2.parent.externalModuleIndicator === void 0) { (errors2 || (errors2 = [])).push(createDiagnosticForNode(node2, Messages.functionWillNotBeVisibleInTheNewScope)); } + // falls through case 231 /* ClassExpression */: case 218 /* FunctionExpression */: case 174 /* MethodDeclaration */: @@ -149078,6 +150673,7 @@ var SymbolObject = class { if (context) { if (isGetAccessor(context)) { if (!this.contextualGetAccessorDocumentationComment) { + this.contextualGetAccessorDocumentationComment = emptyArray; this.contextualGetAccessorDocumentationComment = getDocumentationComment(filter(this.declarations, isGetAccessor), checker); } if (length(this.contextualGetAccessorDocumentationComment)) { @@ -149086,6 +150682,7 @@ var SymbolObject = class { } if (isSetAccessor(context)) { if (!this.contextualSetAccessorDocumentationComment) { + this.contextualSetAccessorDocumentationComment = emptyArray; this.contextualSetAccessorDocumentationComment = getDocumentationComment(filter(this.declarations, isSetAccessor), checker); } if (length(this.contextualSetAccessorDocumentationComment)) { @@ -149106,6 +150703,7 @@ var SymbolObject = class { if (context) { if (isGetAccessor(context)) { if (!this.contextualGetAccessorTags) { + this.contextualGetAccessorTags = emptyArray; this.contextualGetAccessorTags = getJsDocTagsOfDeclarations(filter(this.declarations, isGetAccessor), checker); } if (length(this.contextualGetAccessorTags)) { @@ -149114,6 +150712,7 @@ var SymbolObject = class { } if (isSetAccessor(context)) { if (!this.contextualSetAccessorTags) { + this.contextualSetAccessorTags = emptyArray; this.contextualSetAccessorTags = getJsDocTagsOfDeclarations(filter(this.declarations, isSetAccessor), checker); } if (length(this.contextualSetAccessorTags)) { @@ -149426,6 +151025,7 @@ var SourceFileObject = class extends NodeObject { if (!hasSyntacticModifier(node, 31 /* ParameterPropertyModifier */)) { break; } + // falls through case 260 /* VariableDeclaration */: case 208 /* BindingElement */: { const decl = node; @@ -149437,6 +151037,7 @@ var SourceFileObject = class extends NodeObject { visit(decl.initializer); } } + // falls through case 306 /* EnumMember */: case 172 /* PropertyDeclaration */: case 171 /* PropertySignature */: @@ -149471,6 +151072,7 @@ var SourceFileObject = class extends NodeObject { if (getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } + // falls through default: forEachChild(node, visit); } @@ -149718,7 +151320,8 @@ var invalidOperationsInSyntacticMode = [ "getNavigateToItems", "getRenameInfo", "findRenameLocations", - "getApplicableRefactors" + "getApplicableRefactors", + "preparePasteEditsForFile" ]; function createLanguageService(host, documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory(), host.jsDocParsingMode), syntaxOnlyOrLanguageServiceMode) { var _a; @@ -149834,7 +151437,8 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h resolveLibrary: maybeBind(host, host.resolveLibrary), useSourceOfProjectReferenceRedirect: maybeBind(host, host.useSourceOfProjectReferenceRedirect), getParsedCommandLine, - jsDocParsingMode: host.jsDocParsingMode + jsDocParsingMode: host.jsDocParsingMode, + getGlobalTypingsCacheLocation: maybeBind(host, host.getGlobalTypingsCacheLocation) }; const originalGetSourceFile = compilerHost.getSourceFile; const { getSourceFileWithCache } = changeCompilerHostLikeToUseCache( @@ -150210,6 +151814,14 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h tags }; } + function preparePasteEditsForFile(fileName, copiedTextRange) { + synchronizeHostData(); + return ts_preparePasteEdits_exports.preparePasteEdits( + getValidSourceFile(fileName), + copiedTextRange, + program.getTypeChecker() + ); + } function getPasteEdits(args, formatOptions) { synchronizeHostData(); return ts_PasteEdits_exports.pasteEditsProvider( @@ -150358,6 +151970,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h case 197 /* ThisType */: case 80 /* Identifier */: break; + // Cant create the text span default: return void 0; } @@ -150463,22 +152076,22 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h } return []; } - function getCodeFixesAtPosition(fileName, start, end, errorCodes67, formatOptions, preferences = emptyOptions) { + function getCodeFixesAtPosition(fileName, start, end, errorCodes68, formatOptions, preferences = emptyOptions) { synchronizeHostData(); const sourceFile = getValidSourceFile(fileName); const span = createTextSpanFromBounds(start, end); const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host); - return flatMap(deduplicate(errorCodes67, equateValues, compareValues), (errorCode) => { + return flatMap(deduplicate(errorCodes68, equateValues, compareValues), (errorCode) => { cancellationToken.throwIfCancellationRequested(); return ts_codefix_exports.getFixes({ errorCode, sourceFile, span, program, host, cancellationToken, formatContext, preferences }); }); } - function getCombinedCodeFix(scope, fixId55, formatOptions, preferences = emptyOptions) { + function getCombinedCodeFix(scope, fixId56, formatOptions, preferences = emptyOptions) { synchronizeHostData(); Debug.assert(scope.type === "file"); const sourceFile = getValidSourceFile(scope.fileName); const formatContext = ts_formatting_exports.getFormatContext(formatOptions, host); - return ts_codefix_exports.getAllFixes({ fixId: fixId55, sourceFile, program, host, cancellationToken, formatContext, preferences }); + return ts_codefix_exports.getAllFixes({ fixId: fixId56, sourceFile, program, host, cancellationToken, formatContext, preferences }); } function organizeImports2(args, formatOptions, preferences = emptyOptions) { synchronizeHostData(); @@ -151011,6 +152624,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h uncommentSelection, provideInlayHints: provideInlayHints2, getSupportedCodeFixes, + preparePasteEditsForFile, getPasteEdits, mapCode: mapCode2 }; @@ -151075,6 +152689,7 @@ function getContainingObjectLiteralElementWorker(node) { if (node.parent.kind === 167 /* ComputedPropertyName */) { return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : void 0; } + // falls through case 80 /* Identifier */: return isObjectLiteralElement(node.parent) && (node.parent.parent.kind === 210 /* ObjectLiteralExpression */ || node.parent.parent.kind === 292 /* JsxAttributes */) && node.parent.name === node ? node.parent : void 0; } @@ -151229,6 +152844,7 @@ function spanInSourceFileAtLocation(sourceFile, position) { if (isFunctionBlock(node)) { return spanInFunctionBlock(node); } + // falls through case 268 /* ModuleBlock */: return spanInBlock(node); case 299 /* CatchClause */: @@ -151277,6 +152893,7 @@ function spanInSourceFileAtLocation(sourceFile, position) { if (getModuleInstanceState(node) !== 1 /* Instantiated */) { return void 0; } + // falls through case 263 /* ClassDeclaration */: case 266 /* EnumDeclaration */: case 306 /* EnumMember */: @@ -151289,9 +152906,11 @@ function spanInSourceFileAtLocation(sourceFile, position) { case 206 /* ObjectBindingPattern */: case 207 /* ArrayBindingPattern */: return spanInBindingPattern(node); + // No breakpoint in interface, type alias case 264 /* InterfaceDeclaration */: case 265 /* TypeAliasDeclaration */: return void 0; + // Tokens: case 27 /* SemicolonToken */: case 1 /* EndOfFileToken */: return spanInNodeIfStartsOnSameLine(findPrecedingToken(node.pos, sourceFile)); @@ -151312,6 +152931,7 @@ function spanInSourceFileAtLocation(sourceFile, position) { case 32 /* GreaterThanToken */: case 30 /* LessThanToken */: return spanInGreaterThanOrLessThanToken(node); + // Keywords: case 117 /* WhileKeyword */: return spanInWhileKeyword(node); case 93 /* ElseKeyword */: @@ -151462,10 +153082,13 @@ function spanInSourceFileAtLocation(sourceFile, position) { if (getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return void 0; } + // Set on parent if on same line otherwise on first statement + // falls through case 247 /* WhileStatement */: case 245 /* IfStatement */: case 249 /* ForInStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); + // Set span on previous token if it starts on same line otherwise on the first statement of the block case 248 /* ForStatement */: case 250 /* ForOfStatement */: return spanInNodeIfStartsOnSameLine(findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); @@ -151531,6 +153154,7 @@ function spanInSourceFileAtLocation(sourceFile, position) { if (getModuleInstanceState(node2.parent.parent) !== 1 /* Instantiated */) { return void 0; } + // falls through case 266 /* EnumDeclaration */: case 263 /* ClassDeclaration */: return textSpan(node2); @@ -151538,6 +153162,7 @@ function spanInSourceFileAtLocation(sourceFile, position) { if (isFunctionBlock(node2.parent)) { return textSpan(node2); } + // falls through case 299 /* CatchClause */: return spanInNode(lastOrUndefined(node2.parent.statements)); case 269 /* CaseBlock */: @@ -151550,6 +153175,7 @@ function spanInSourceFileAtLocation(sourceFile, position) { case 206 /* ObjectBindingPattern */: const bindingPattern = node2.parent; return spanInNode(lastOrUndefined(bindingPattern.elements) || bindingPattern); + // Default to parent node default: if (isArrayLiteralOrObjectLiteralDestructuringPattern(node2.parent)) { const objectLiteral = node2.parent; @@ -151599,6 +153225,7 @@ function spanInSourceFileAtLocation(sourceFile, position) { case 214 /* NewExpression */: case 217 /* ParenthesizedExpression */: return spanInPreviousNode(node2); + // Default to parent node default: return spanInNode(node2.parent); } @@ -152132,8 +153759,10 @@ __export(ts_codefix_exports, { setJsonCompilerOptionValue: () => setJsonCompilerOptionValue, setJsonCompilerOptionValues: () => setJsonCompilerOptionValues, tryGetAutoImportableReferenceFromTypeNode: () => tryGetAutoImportableReferenceFromTypeNode, + typeNodeToAutoImportableTypeNode: () => typeNodeToAutoImportableTypeNode, typePredicateToAutoImportableTypeNode: () => typePredicateToAutoImportableTypeNode, - typeToAutoImportableTypeNode: () => typeToAutoImportableTypeNode + typeToAutoImportableTypeNode: () => typeToAutoImportableTypeNode, + typeToMinimizedReferenceType: () => typeToMinimizedReferenceType }); // src/services/codeFixProvider.ts @@ -152150,14 +153779,14 @@ function createCodeFixActionWithoutFixAll(fixName8, changes, description3) { void 0 ); } -function createCodeFixAction(fixName8, changes, description3, fixId55, fixAllDescription, command) { - return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId55, diagnosticToString(fixAllDescription), command); +function createCodeFixAction(fixName8, changes, description3, fixId56, fixAllDescription, command) { + return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId56, diagnosticToString(fixAllDescription), command); } -function createCodeFixActionMaybeFixAll(fixName8, changes, description3, fixId55, fixAllDescription, command) { - return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId55, fixAllDescription && diagnosticToString(fixAllDescription), command); +function createCodeFixActionMaybeFixAll(fixName8, changes, description3, fixId56, fixAllDescription, command) { + return createCodeFixActionWorker(fixName8, diagnosticToString(description3), changes, fixId56, fixAllDescription && diagnosticToString(fixAllDescription), command); } -function createCodeFixActionWorker(fixName8, description3, changes, fixId55, fixAllDescription, command) { - return { fixName: fixName8, description: description3, changes, fixId: fixId55, fixAllDescription, commands: command ? [command] : void 0 }; +function createCodeFixActionWorker(fixName8, description3, changes, fixId56, fixAllDescription, command) { + return { fixName: fixName8, description: description3, changes, fixId: fixId56, fixAllDescription, commands: command ? [command] : void 0 }; } function registerCodeFix(reg) { for (const error2 of reg.errorCodes) { @@ -152165,9 +153794,9 @@ function registerCodeFix(reg) { errorCodeToFixes.add(String(error2), reg); } if (reg.fixIds) { - for (const fixId55 of reg.fixIds) { - Debug.assert(!fixIdToRegistration.has(fixId55)); - fixIdToRegistration.set(fixId55, reg); + for (const fixId56 of reg.fixIds) { + Debug.assert(!fixIdToRegistration.has(fixId56)); + fixIdToRegistration.set(fixId56, reg); } } } @@ -152176,15 +153805,15 @@ function getSupportedErrorCodes() { return errorCodeToFixesArray ?? (errorCodeToFixesArray = arrayFrom(errorCodeToFixes.keys())); } function removeFixIdIfFixAllUnavailable(registration, diagnostics) { - const { errorCodes: errorCodes67 } = registration; + const { errorCodes: errorCodes68 } = registration; let maybeFixableDiagnostics = 0; for (const diag2 of diagnostics) { - if (contains(errorCodes67, diag2.code)) maybeFixableDiagnostics++; + if (contains(errorCodes68, diag2.code)) maybeFixableDiagnostics++; if (maybeFixableDiagnostics > 1) break; } const fixAllUnavailable = maybeFixableDiagnostics < 2; - return ({ fixId: fixId55, fixAllDescription, ...action }) => { - return fixAllUnavailable ? action : { ...action, fixId: fixId55, fixAllDescription }; + return ({ fixId: fixId56, fixAllDescription, ...action }) => { + return fixAllUnavailable ? action : { ...action, fixId: fixId56, fixAllDescription }; }; } function getFixes(context) { @@ -152201,14 +153830,14 @@ function createCombinedCodeActions(changes, commands) { function createFileTextChanges(fileName, textChanges2) { return { fileName, textChanges: textChanges2 }; } -function codeFixAll(context, errorCodes67, use) { +function codeFixAll(context, errorCodes68, use) { const commands = []; - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => eachDiagnostic(context, errorCodes67, (diag2) => use(t, diag2, commands))); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => eachDiagnostic(context, errorCodes68, (diag2) => use(t, diag2, commands))); return createCombinedCodeActions(changes, commands.length === 0 ? void 0 : commands); } -function eachDiagnostic(context, errorCodes67, cb) { +function eachDiagnostic(context, errorCodes68, cb) { for (const diag2 of getDiagnostics(context)) { - if (contains(errorCodes67, diag2.code)) { + if (contains(errorCodes68, diag2.code)) { cb(diag2); } } @@ -152722,19 +154351,99 @@ function makeChange6(changeTracker, sourceFile, pos) { changeTracker.replaceNode(sourceFile, decorator.expression, replacement); } -// src/services/codefixes/addNameToNamelessParameter.ts -var fixId7 = "addNameToNamelessParameter"; -var errorCodes7 = [Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code]; +// src/services/codefixes/addMissingResolutionModeImportAttribute.ts +var fixId7 = "addMissingResolutionModeImportAttribute"; +var errorCodes7 = [ + Diagnostics.Type_only_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute.code, + Diagnostics.Type_import_of_an_ECMAScript_module_from_a_CommonJS_module_must_have_a_resolution_mode_attribute.code +]; registerCodeFix({ errorCodes: errorCodes7, - getCodeActions: function getCodeActionsToAddNameToNamelessParameter(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange7(t, context.sourceFile, context.span.start)); - return [createCodeFixAction(fixId7, changes, Diagnostics.Add_parameter_name, fixId7, Diagnostics.Add_names_to_all_parameters_without_names)]; + getCodeActions: function getCodeActionsToAddMissingResolutionModeImportAttribute(context) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange7(t, context.sourceFile, context.span.start, context.program, context.host, context.preferences)); + return [createCodeFixAction(fixId7, changes, Diagnostics.Add_resolution_mode_import_attribute, fixId7, Diagnostics.Add_resolution_mode_import_attribute_to_all_type_only_imports_that_need_it)]; }, fixIds: [fixId7], - getAllCodeActions: (context) => codeFixAll(context, errorCodes7, (changes, diag2) => makeChange7(changes, diag2.file, diag2.start)) + getAllCodeActions: (context) => codeFixAll(context, errorCodes7, (changes, diag2) => makeChange7(changes, diag2.file, diag2.start, context.program, context.host, context.preferences)) +}); +function makeChange7(changeTracker, sourceFile, pos, program, host, preferences) { + var _a, _b, _c; + const token = getTokenAtPosition(sourceFile, pos); + const importNode = findAncestor(token, or(isImportDeclaration, isImportTypeNode)); + Debug.assert(!!importNode, "Expected position to be owned by an ImportDeclaration or ImportType."); + const useSingleQuotes = getQuotePreference(sourceFile, preferences) === 0 /* Single */; + const moduleSpecifier = tryGetModuleSpecifierFromDeclaration(importNode); + const canUseImportMode = !moduleSpecifier || ((_a = resolveModuleName( + moduleSpecifier.text, + sourceFile.fileName, + program.getCompilerOptions(), + host, + program.getModuleResolutionCache(), + /*redirectedReference*/ + void 0, + 99 /* ESNext */ + ).resolvedModule) == null ? void 0 : _a.resolvedFileName) === ((_c = (_b = program.getResolvedModuleFromModuleSpecifier( + moduleSpecifier, + sourceFile + )) == null ? void 0 : _b.resolvedModule) == null ? void 0 : _c.resolvedFileName); + const attributes = importNode.attributes ? factory.updateImportAttributes( + importNode.attributes, + factory.createNodeArray([ + ...importNode.attributes.elements, + factory.createImportAttribute( + factory.createStringLiteral("resolution-mode", useSingleQuotes), + factory.createStringLiteral(canUseImportMode ? "import" : "require", useSingleQuotes) + ) + ], importNode.attributes.elements.hasTrailingComma), + importNode.attributes.multiLine + ) : factory.createImportAttributes( + factory.createNodeArray([ + factory.createImportAttribute( + factory.createStringLiteral("resolution-mode", useSingleQuotes), + factory.createStringLiteral(canUseImportMode ? "import" : "require", useSingleQuotes) + ) + ]) + ); + if (importNode.kind === 272 /* ImportDeclaration */) { + changeTracker.replaceNode( + sourceFile, + importNode, + factory.updateImportDeclaration( + importNode, + importNode.modifiers, + importNode.importClause, + importNode.moduleSpecifier, + attributes + ) + ); + } else { + changeTracker.replaceNode( + sourceFile, + importNode, + factory.updateImportTypeNode( + importNode, + importNode.argument, + attributes, + importNode.qualifier, + importNode.typeArguments + ) + ); + } +} + +// src/services/codefixes/addNameToNamelessParameter.ts +var fixId8 = "addNameToNamelessParameter"; +var errorCodes8 = [Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code]; +registerCodeFix({ + errorCodes: errorCodes8, + getCodeActions: function getCodeActionsToAddNameToNamelessParameter(context) { + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange8(t, context.sourceFile, context.span.start)); + return [createCodeFixAction(fixId8, changes, Diagnostics.Add_parameter_name, fixId8, Diagnostics.Add_names_to_all_parameters_without_names)]; + }, + fixIds: [fixId8], + getAllCodeActions: (context) => codeFixAll(context, errorCodes8, (changes, diag2) => makeChange8(changes, diag2.file, diag2.start)) }); -function makeChange7(changeTracker, sourceFile, start) { +function makeChange8(changeTracker, sourceFile, start) { const token = getTokenAtPosition(sourceFile, start); const param = token.parent; if (!isParameter(param)) { @@ -152775,13 +154484,13 @@ function tryGetNextParam(sourceFile, param) { // src/services/codefixes/addOptionalPropertyUndefined.ts var addOptionalPropertyUndefined = "addOptionalPropertyUndefined"; -var errorCodes8 = [ +var errorCodes9 = [ Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target.code, Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code, Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_types_of_the_target_s_properties.code ]; registerCodeFix({ - errorCodes: errorCodes8, + errorCodes: errorCodes9, getCodeActions(context) { const typeChecker = context.program.getTypeChecker(); const toAdd = getPropertiesToAdd(context.sourceFile, context.span, typeChecker); @@ -152852,18 +154561,18 @@ function addUndefinedToOptionalProperty(changes, toAdd) { } // src/services/codefixes/annotateWithTypeFromJSDoc.ts -var fixId8 = "annotateWithTypeFromJSDoc"; -var errorCodes9 = [Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code]; +var fixId9 = "annotateWithTypeFromJSDoc"; +var errorCodes10 = [Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code]; registerCodeFix({ - errorCodes: errorCodes9, + errorCodes: errorCodes10, getCodeActions(context) { const decl = getDeclaration(context.sourceFile, context.span.start); if (!decl) return; 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)]; + return [createCodeFixAction(fixId9, changes, Diagnostics.Annotate_with_type_from_JSDoc, fixId9, Diagnostics.Annotate_everything_with_types_from_JSDoc)]; }, - fixIds: [fixId8], - getAllCodeActions: (context) => codeFixAll(context, errorCodes9, (changes, diag2) => { + fixIds: [fixId9], + getAllCodeActions: (context) => codeFixAll(context, errorCodes10, (changes, diag2) => { const decl = getDeclaration(diag2.file, diag2.start); if (decl) doChange8(changes, diag2.file, decl); }) @@ -153020,16 +154729,16 @@ function transformJSDocIndexSignature(node) { } // src/services/codefixes/convertFunctionToEs6Class.ts -var fixId9 = "convertFunctionToEs6Class"; -var errorCodes10 = [Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code]; +var fixId10 = "convertFunctionToEs6Class"; +var errorCodes11 = [Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code]; registerCodeFix({ - errorCodes: errorCodes10, + errorCodes: errorCodes11, getCodeActions(context) { 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)]; + return [createCodeFixAction(fixId10, changes, Diagnostics.Convert_function_to_an_ES2015_class, fixId10, Diagnostics.Convert_all_constructor_functions_to_classes)]; }, - fixIds: [fixId9], - getAllCodeActions: (context) => codeFixAll(context, errorCodes10, (changes, err) => doChange9(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())) + fixIds: [fixId10], + getAllCodeActions: (context) => codeFixAll(context, errorCodes11, (changes, err) => doChange9(changes, err.file, err.start, context.program.getTypeChecker(), context.preferences, context.program.getCompilerOptions())) }); function doChange9(changes, sourceFile, position, checker, preferences, compilerOptions) { const ctorSymbol = checker.getSymbolAtLocation(getTokenAtPosition(sourceFile, position)); @@ -153301,18 +155010,18 @@ function tryGetPropertyName(node, compilerOptions, quotePreference) { } // src/services/codefixes/convertToAsyncFunction.ts -var fixId10 = "convertToAsyncFunction"; -var errorCodes11 = [Diagnostics.This_may_be_converted_to_an_async_function.code]; +var fixId11 = "convertToAsyncFunction"; +var errorCodes12 = [Diagnostics.This_may_be_converted_to_an_async_function.code]; var codeActionSucceeded = true; registerCodeFix({ - errorCodes: errorCodes11, + errorCodes: errorCodes12, getCodeActions(context) { codeActionSucceeded = true; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker())); - return codeActionSucceeded ? [createCodeFixAction(fixId10, changes, Diagnostics.Convert_to_async_function, fixId10, Diagnostics.Convert_all_to_async_functions)] : []; + return codeActionSucceeded ? [createCodeFixAction(fixId11, changes, Diagnostics.Convert_to_async_function, fixId11, Diagnostics.Convert_all_to_async_functions)] : []; }, - fixIds: [fixId10], - getAllCodeActions: (context) => codeFixAll(context, errorCodes11, (changes, err) => convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker())) + fixIds: [fixId11], + getAllCodeActions: (context) => codeFixAll(context, errorCodes12, (changes, err) => convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker())) }); function convertToAsyncFunction(changes, sourceFile, position, checker) { const tokenAtPosition = getTokenAtPosition(sourceFile, position); @@ -154111,6 +155820,7 @@ function convertStatement(sourceFile, statement, checker, changes, identifiers, } } } + // falls through default: return false; } @@ -154210,6 +155920,8 @@ function tryChangeModuleExportsObject(object, useSitesToUnqualify) { switch (prop.kind) { case 177 /* GetAccessor */: case 178 /* SetAccessor */: + // TODO: Maybe we should handle this? See fourslash test `refactorConvertToEs6Module_export_object_shorthand.ts`. + // falls through case 304 /* ShorthandPropertyAssignment */: case 305 /* SpreadAssignment */: return void 0; @@ -154291,6 +156003,7 @@ function convertExportsDotXEquals_replaceNode(name, exported, useSitesToUnqualif return exportConst(); } } + // falls through case 219 /* ArrowFunction */: return functionExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify); case 231 /* ClassExpression */: @@ -154339,6 +156052,7 @@ function convertSingleImport(name, moduleSpecifier, checker, identifiers, target )]); } } + // falls through -- object destructuring has an interesting pattern and must be a variable declaration case 207 /* ArrayBindingPattern */: { const tmp = makeUniqueName(moduleSpecifierToValidIdentifier(moduleSpecifier.text, target), identifiers); return convertedImports([ @@ -154512,19 +156226,19 @@ function convertedImports(newImports, useSitesToUnqualify) { } // src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts -var fixId11 = "correctQualifiedNameToIndexedAccessType"; -var errorCodes12 = [Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code]; +var fixId12 = "correctQualifiedNameToIndexedAccessType"; +var errorCodes13 = [Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code]; registerCodeFix({ - errorCodes: errorCodes12, + errorCodes: errorCodes13, getCodeActions(context) { const qualifiedName = getQualifiedName(context.sourceFile, context.span.start); if (!qualifiedName) return void 0; 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)]; + return [createCodeFixAction(fixId12, changes, [Diagnostics.Rewrite_as_the_indexed_access_type_0, newText], fixId12, Diagnostics.Rewrite_all_as_indexed_access_types)]; }, - fixIds: [fixId11], - getAllCodeActions: (context) => codeFixAll(context, errorCodes12, (changes, diag2) => { + fixIds: [fixId12], + getAllCodeActions: (context) => codeFixAll(context, errorCodes13, (changes, diag2) => { const q = getQualifiedName(diag2.file, diag2.start); if (q) { doChange10(changes, diag2.file, q); @@ -154550,20 +156264,20 @@ function doChange10(changeTracker, sourceFile, qualifiedName) { } // src/services/codefixes/convertToTypeOnlyExport.ts -var errorCodes13 = [Diagnostics.Re_exporting_a_type_when_0_is_enabled_requires_using_export_type.code]; -var fixId12 = "convertToTypeOnlyExport"; +var errorCodes14 = [Diagnostics.Re_exporting_a_type_when_0_is_enabled_requires_using_export_type.code]; +var fixId13 = "convertToTypeOnlyExport"; registerCodeFix({ - errorCodes: errorCodes13, + errorCodes: errorCodes14, getCodeActions: function getCodeActionsToConvertToTypeOnlyExport(context) { const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => fixSingleExportDeclaration(t, getExportSpecifierForDiagnosticSpan(context.span, context.sourceFile), context)); if (changes.length) { - return [createCodeFixAction(fixId12, changes, Diagnostics.Convert_to_type_only_export, fixId12, Diagnostics.Convert_all_re_exported_types_to_type_only_exports)]; + return [createCodeFixAction(fixId13, changes, Diagnostics.Convert_to_type_only_export, fixId13, Diagnostics.Convert_all_re_exported_types_to_type_only_exports)]; } }, - fixIds: [fixId12], + fixIds: [fixId13], getAllCodeActions: function getAllCodeActionsToConvertToTypeOnlyExport(context) { - const fixedExportDeclarations = /* @__PURE__ */ new Map(); - return codeFixAll(context, errorCodes13, (changes, diag2) => { + const fixedExportDeclarations = /* @__PURE__ */ new Set(); + return codeFixAll(context, errorCodes14, (changes, diag2) => { const exportSpecifier = getExportSpecifierForDiagnosticSpan(diag2, context.sourceFile); if (exportSpecifier && addToSeen(fixedExportDeclarations, getNodeId(exportSpecifier.parent.parent))) { fixSingleExportDeclaration(changes, exportSpecifier, context); @@ -154622,18 +156336,18 @@ function getTypeExportSpecifiers(originExportSpecifier, context) { ); return filter(exportClause.elements, (element) => { var _a; - return element === originExportSpecifier || ((_a = findDiagnosticForNode(element, diagnostics)) == null ? void 0 : _a.code) === errorCodes13[0]; + return element === originExportSpecifier || ((_a = findDiagnosticForNode(element, diagnostics)) == null ? void 0 : _a.code) === errorCodes14[0]; }); } // src/services/codefixes/convertToTypeOnlyImport.ts -var errorCodes14 = [ +var errorCodes15 = [ Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled.code, Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled.code ]; -var fixId13 = "convertToTypeOnlyImport"; +var fixId14 = "convertToTypeOnlyImport"; registerCodeFix({ - errorCodes: errorCodes14, + errorCodes: errorCodes15, getCodeActions: function getCodeActionsToConvertToTypeOnlyImport(context) { var _a; const declaration = getDeclaration2(context.sourceFile, context.span.start); @@ -154641,15 +156355,15 @@ registerCodeFix({ const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange11(t, context.sourceFile, declaration)); const importDeclarationChanges = declaration.kind === 276 /* ImportSpecifier */ && isImportDeclaration(declaration.parent.parent.parent) && canConvertImportDeclarationForSpecifier(declaration, context.sourceFile, context.program) ? ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange11(t, context.sourceFile, declaration.parent.parent.parent)) : void 0; const mainAction = createCodeFixAction( - fixId13, + fixId14, changes, declaration.kind === 276 /* ImportSpecifier */ ? [Diagnostics.Use_type_0, ((_a = declaration.propertyName) == null ? void 0 : _a.text) ?? declaration.name.text] : Diagnostics.Use_import_type, - fixId13, + fixId14, Diagnostics.Fix_all_with_type_only_imports ); if (some(importDeclarationChanges)) { return [ - createCodeFixActionWithoutFixAll(fixId13, importDeclarationChanges, Diagnostics.Use_import_type), + createCodeFixActionWithoutFixAll(fixId14, importDeclarationChanges, Diagnostics.Use_import_type), mainAction ]; } @@ -154657,10 +156371,10 @@ registerCodeFix({ } return void 0; }, - fixIds: [fixId13], + fixIds: [fixId14], getAllCodeActions: function getAllCodeActionsToConvertToTypeOnlyImport(context) { const fixedImportDeclarations = /* @__PURE__ */ new Set(); - return codeFixAll(context, errorCodes14, (changes, diag2) => { + return codeFixAll(context, errorCodes15, (changes, diag2) => { const errorDeclaration = getDeclaration2(diag2.file, diag2.start); if ((errorDeclaration == null ? void 0 : errorDeclaration.kind) === 272 /* ImportDeclaration */ && !fixedImportDeclarations.has(errorDeclaration)) { doChange11(changes, diag2.file, errorDeclaration); @@ -154793,11 +156507,11 @@ function doChange11(changes, sourceFile, declaration) { } // src/services/codefixes/convertTypedefToType.ts -var fixId14 = "convertTypedefToType"; -var errorCodes15 = [Diagnostics.JSDoc_typedef_may_be_converted_to_TypeScript_type.code]; +var fixId15 = "convertTypedefToType"; +var errorCodes16 = [Diagnostics.JSDoc_typedef_may_be_converted_to_TypeScript_type.code]; registerCodeFix({ - fixIds: [fixId14], - errorCodes: errorCodes15, + fixIds: [fixId15], + errorCodes: errorCodes16, getCodeActions(context) { const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); const node = getTokenAtPosition( @@ -154809,10 +156523,10 @@ registerCodeFix({ if (changes.length > 0) { return [ createCodeFixAction( - fixId14, + fixId15, changes, Diagnostics.Convert_typedef_to_TypeScript_type, - fixId14, + fixId15, Diagnostics.Convert_all_typedef_to_TypeScript_types ) ]; @@ -154820,7 +156534,7 @@ registerCodeFix({ }, getAllCodeActions: (context) => codeFixAll( context, - errorCodes15, + errorCodes16, (changes, diag2) => { const newLineCharacter = getNewLineOrDefaultFromHost(context.host, context.formatContext.options); const node = getTokenAtPosition(diag2.file, diag2.start); @@ -154963,10 +156677,10 @@ function getJSDocTypedefNodes(node) { } // src/services/codefixes/convertLiteralTypeToMappedType.ts -var fixId15 = "convertLiteralTypeToMappedType"; -var errorCodes16 = [Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0.code]; +var fixId16 = "convertLiteralTypeToMappedType"; +var errorCodes17 = [Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0.code]; registerCodeFix({ - errorCodes: errorCodes16, + errorCodes: errorCodes17, getCodeActions: function getCodeActionsToConvertLiteralTypeToMappedType(context) { const { sourceFile, span } = context; const info = getInfo5(sourceFile, span.start); @@ -154975,10 +156689,10 @@ registerCodeFix({ } const { name, constraint } = 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)]; + return [createCodeFixAction(fixId16, changes, [Diagnostics.Convert_0_to_1_in_0, constraint, name], fixId16, Diagnostics.Convert_all_type_literals_to_mapped_type)]; }, - fixIds: [fixId15], - getAllCodeActions: (context) => codeFixAll(context, errorCodes16, (changes, diag2) => { + fixIds: [fixId16], + getAllCodeActions: (context) => codeFixAll(context, errorCodes17, (changes, diag2) => { const info = getInfo5(diag2.file, diag2.start); if (info) { doChange13(changes, diag2.file, info); @@ -155024,25 +156738,25 @@ function doChange13(changes, sourceFile, { container, typeNode, constraint, name } // src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts -var errorCodes17 = [ +var errorCodes18 = [ Diagnostics.Class_0_incorrectly_implements_interface_1.code, Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code ]; -var fixId16 = "fixClassIncorrectlyImplementsInterface"; +var fixId17 = "fixClassIncorrectlyImplementsInterface"; registerCodeFix({ - errorCodes: errorCodes17, + errorCodes: errorCodes18, getCodeActions(context) { const { sourceFile, span } = context; const classDeclaration = getClass(sourceFile, span.start); return mapDefined(getEffectiveImplementsTypeNodes(classDeclaration), (implementedTypeNode) => { const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences)); - return changes.length === 0 ? void 0 : createCodeFixAction(fixId16, changes, [Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId16, Diagnostics.Implement_all_unimplemented_interfaces); + return changes.length === 0 ? void 0 : createCodeFixAction(fixId17, changes, [Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId17, Diagnostics.Implement_all_unimplemented_interfaces); }); }, - fixIds: [fixId16], + fixIds: [fixId17], getAllCodeActions(context) { - const seenClassDeclarations = /* @__PURE__ */ new Map(); - return codeFixAll(context, errorCodes17, (changes, diag2) => { + const seenClassDeclarations = /* @__PURE__ */ new Set(); + return codeFixAll(context, errorCodes18, (changes, diag2) => { const classDeclaration = getClass(diag2.file, diag2.start); if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) { for (const implementedTypeNode of getEffectiveImplementsTypeNodes(classDeclaration)) { @@ -155108,7 +156822,7 @@ function getHeritageClauseSymbolTable(classDeclaration, checker) { // src/services/codefixes/importFixes.ts var importFixName = "import"; var importFixId = "fixMissingImport"; -var errorCodes18 = [ +var errorCodes19 = [ Diagnostics.Cannot_find_name_0.code, Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, @@ -155127,10 +156841,11 @@ var errorCodes18 = [ Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha.code, Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode.code, Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig.code, - Diagnostics.Cannot_find_namespace_0_Did_you_mean_1.code + Diagnostics.Cannot_find_namespace_0_Did_you_mean_1.code, + Diagnostics.This_JSX_tag_requires_0_to_be_in_scope_but_it_could_not_be_found.code ]; registerCodeFix({ - errorCodes: errorCodes18, + errorCodes: errorCodes19, getCodeActions(context) { const { errorCode, preferences, sourceFile, span, program } = context; const info = getFixInfos( @@ -155166,7 +156881,7 @@ registerCodeFix({ host, cancellationToken ); - eachDiagnostic(context, errorCodes18, (diag2) => importAdder.addImportFromDiagnostic(diag2, context)); + eachDiagnostic(context, errorCodes19, (diag2) => importAdder.addImportFromDiagnostic(diag2, context)); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, importAdder.writeFixes)); } }); @@ -155189,7 +156904,7 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre const removeExisting = /* @__PURE__ */ new Set(); const verbatimImports = /* @__PURE__ */ new Set(); const newImports = /* @__PURE__ */ new Map(); - return { addImportFromDiagnostic, addImportFromExportedSymbol, writeFixes, hasFixes, addImportForUnresolvedIdentifier, addImportForNonExistentExport, removeExistingImport, addVerbatimImport }; + return { addImportFromDiagnostic, addImportFromExportedSymbol, addImportForModuleSymbol, writeFixes, hasFixes, addImportForUnresolvedIdentifier, addImportForNonExistentExport, removeExistingImport, addVerbatimImport }; function addVerbatimImport(declaration) { verbatimImports.add(declaration); } @@ -155205,7 +156920,7 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre } function addImportFromExportedSymbol(exportedSymbol, isValidTypeOnlyUseSite, referenceImport) { var _a, _b; - const moduleSymbol = Debug.checkDefined(exportedSymbol.parent); + const moduleSymbol = Debug.checkDefined(exportedSymbol.parent, "Expected exported symbol to have module symbol as parent"); const symbolName2 = getNameForExportedSymbol(exportedSymbol, getEmitScriptTarget(compilerOptions)); const checker = program.getTypeChecker(); const symbol = checker.getMergedSymbol(skipAlias(exportedSymbol, checker)); @@ -155239,12 +156954,91 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre ); if (fix) { const localName = ((_b = tryCast(referenceImport == null ? void 0 : referenceImport.name, isIdentifier)) == null ? void 0 : _b.text) ?? symbolName2; + let addAsTypeOnly; + let propertyName; if (referenceImport && isTypeOnlyImportDeclaration(referenceImport) && (fix.kind === 3 /* AddNew */ || fix.kind === 2 /* AddToExisting */) && fix.addAsTypeOnly === 1 /* Allowed */) { - fix = { ...fix, addAsTypeOnly: 2 /* Required */ }; + addAsTypeOnly = 2 /* Required */; } + if (exportedSymbol.name !== localName) { + propertyName = exportedSymbol.name; + } + fix = { + ...fix, + ...addAsTypeOnly === void 0 ? {} : { addAsTypeOnly }, + ...propertyName === void 0 ? {} : { propertyName } + }; addImport({ fix, symbolName: localName ?? symbolName2, errorIdentifierText: void 0 }); } } + function addImportForModuleSymbol(symbolAlias, isValidTypeOnlyUseSite, referenceImport) { + var _a, _b, _c; + const checker = program.getTypeChecker(); + const moduleSymbol = checker.getAliasedSymbol(symbolAlias); + Debug.assert(moduleSymbol.flags & 1536 /* Module */, "Expected symbol to be a module"); + const moduleSpecifierResolutionHost = createModuleSpecifierResolutionHost(program, host); + const moduleSpecifierResult = ts_moduleSpecifiers_exports.getModuleSpecifiersWithCacheInfo( + moduleSymbol, + checker, + compilerOptions, + sourceFile, + moduleSpecifierResolutionHost, + preferences, + /*options*/ + void 0, + /*forAutoImport*/ + true + ); + const useRequire = shouldUseRequire(sourceFile, program); + let addAsTypeOnly = getAddAsTypeOnly( + isValidTypeOnlyUseSite, + /*isForNewImportDeclaration*/ + true, + /*symbol*/ + void 0, + symbolAlias.flags, + program.getTypeChecker(), + compilerOptions + ); + addAsTypeOnly = addAsTypeOnly === 1 /* Allowed */ && isTypeOnlyImportDeclaration(referenceImport) ? 2 /* Required */ : 1 /* Allowed */; + const importKind = isImportDeclaration(referenceImport) ? isDefaultImport(referenceImport) ? 1 /* Default */ : 2 /* Namespace */ : isImportSpecifier(referenceImport) ? 0 /* Named */ : isImportClause(referenceImport) && !!referenceImport.name ? 1 /* Default */ : 2 /* Namespace */; + const exportInfo = [{ + symbol: symbolAlias, + moduleSymbol, + moduleFileName: (_c = (_b = (_a = moduleSymbol.declarations) == null ? void 0 : _a[0]) == null ? void 0 : _b.getSourceFile()) == null ? void 0 : _c.fileName, + exportKind: 4 /* Module */, + targetFlags: symbolAlias.flags, + isFromPackageJson: false + }]; + const existingFix = getImportFixForSymbol( + sourceFile, + exportInfo, + program, + /*position*/ + void 0, + !!isValidTypeOnlyUseSite, + useRequire, + host, + preferences + ); + let fix; + if (existingFix && importKind !== 2 /* Namespace */) { + fix = { + ...existingFix, + addAsTypeOnly, + importKind + }; + } else { + fix = { + kind: 3 /* AddNew */, + moduleSpecifierKind: existingFix !== void 0 ? existingFix.moduleSpecifierKind : moduleSpecifierResult.kind, + moduleSpecifier: existingFix !== void 0 ? existingFix.moduleSpecifier : first(moduleSpecifierResult.moduleSpecifiers), + importKind, + addAsTypeOnly, + useRequire + }; + } + addImport({ fix, symbolName: symbolAlias.name, errorIdentifierText: void 0 }); + } function addImportForNonExistentExport(exportName, exportingFileName, exportKind, exportedMeanings, isImportUsageValidAsTypeOnly) { const exportingSourceFile = program.getSourceFile(exportingFileName); const useRequire = shouldUseRequire(sourceFile, program); @@ -155307,7 +157101,7 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre removeExisting.add(declaration); } function addImport(info) { - var _a, _b; + var _a, _b, _c; const { fix, symbolName: symbolName2 } = info; switch (fix.kind) { case 0 /* UseNamespace */: @@ -155317,40 +157111,40 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre importType.push(fix); break; case 2 /* AddToExisting */: { - const { importClauseOrBindingPattern, importKind, addAsTypeOnly } = fix; + const { importClauseOrBindingPattern, importKind, addAsTypeOnly, propertyName } = fix; let entry = addToExisting.get(importClauseOrBindingPattern); if (!entry) { addToExisting.set(importClauseOrBindingPattern, entry = { importClauseOrBindingPattern, defaultImport: void 0, namedImports: /* @__PURE__ */ new Map() }); } if (importKind === 0 /* Named */) { - const prevValue = entry == null ? void 0 : entry.namedImports.get(symbolName2); - entry.namedImports.set(symbolName2, reduceAddAsTypeOnlyValues(prevValue, addAsTypeOnly)); + const prevTypeOnly = (_a = entry == null ? void 0 : entry.namedImports.get(symbolName2)) == null ? void 0 : _a.addAsTypeOnly; + entry.namedImports.set(symbolName2, { addAsTypeOnly: reduceAddAsTypeOnlyValues(prevTypeOnly, addAsTypeOnly), propertyName }); } else { Debug.assert(entry.defaultImport === void 0 || entry.defaultImport.name === symbolName2, "(Add to Existing) Default import should be missing or match symbolName"); entry.defaultImport = { name: symbolName2, - addAsTypeOnly: reduceAddAsTypeOnlyValues((_a = entry.defaultImport) == null ? void 0 : _a.addAsTypeOnly, addAsTypeOnly) + addAsTypeOnly: reduceAddAsTypeOnlyValues((_b = entry.defaultImport) == null ? void 0 : _b.addAsTypeOnly, addAsTypeOnly) }; } break; } case 3 /* AddNew */: { - const { moduleSpecifier, importKind, useRequire, addAsTypeOnly } = fix; + const { moduleSpecifier, importKind, useRequire, addAsTypeOnly, propertyName } = fix; const entry = getNewImportEntry(moduleSpecifier, importKind, useRequire, addAsTypeOnly); Debug.assert(entry.useRequire === useRequire, "(Add new) Tried to add an `import` and a `require` for the same module"); switch (importKind) { case 1 /* Default */: Debug.assert(entry.defaultImport === void 0 || entry.defaultImport.name === symbolName2, "(Add new) Default import should be missing or match symbolName"); - entry.defaultImport = { name: symbolName2, addAsTypeOnly: reduceAddAsTypeOnlyValues((_b = entry.defaultImport) == null ? void 0 : _b.addAsTypeOnly, addAsTypeOnly) }; + entry.defaultImport = { name: symbolName2, addAsTypeOnly: reduceAddAsTypeOnlyValues((_c = entry.defaultImport) == null ? void 0 : _c.addAsTypeOnly, addAsTypeOnly) }; break; case 0 /* Named */: const prevValue = (entry.namedImports || (entry.namedImports = /* @__PURE__ */ new Map())).get(symbolName2); - entry.namedImports.set(symbolName2, reduceAddAsTypeOnlyValues(prevValue, addAsTypeOnly)); + entry.namedImports.set(symbolName2, [reduceAddAsTypeOnlyValues(prevValue, addAsTypeOnly), propertyName]); break; case 3 /* CommonJS */: if (compilerOptions.verbatimModuleSyntax) { const prevValue2 = (entry.namedImports || (entry.namedImports = /* @__PURE__ */ new Map())).get(symbolName2); - entry.namedImports.set(symbolName2, reduceAddAsTypeOnlyValues(prevValue2, addAsTypeOnly)); + entry.namedImports.set(symbolName2, [reduceAddAsTypeOnlyValues(prevValue2, addAsTypeOnly), propertyName]); } else { Debug.assert(entry.namespaceLikeImport === void 0 || entry.namespaceLikeImport.name === symbolName2, "Namespacelike import shoudl be missing or match symbolName"); entry.namespaceLikeImport = { importKind, name: symbolName2, addAsTypeOnly }; @@ -155411,7 +157205,7 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre function writeFixes(changeTracker, oldFileQuotePreference) { var _a, _b; let quotePreference; - if (isFullSourceFile(sourceFile) && sourceFile.imports.length === 0 && oldFileQuotePreference !== void 0) { + if (sourceFile.imports !== void 0 && sourceFile.imports.length === 0 && oldFileQuotePreference !== void 0) { quotePreference = oldFileQuotePreference; } else { quotePreference = getQuotePreference(sourceFile, preferences); @@ -155504,7 +157298,7 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre sourceFile, importClauseOrBindingPattern, defaultImport, - arrayFrom(namedImports.entries(), ([name, addAsTypeOnly]) => ({ addAsTypeOnly, name })), + arrayFrom(namedImports.entries(), ([name, { addAsTypeOnly, propertyName }]) => ({ addAsTypeOnly, propertyName, name })), importSpecifiersToRemoveWhileAdding, preferences ); @@ -155517,7 +157311,7 @@ function createImportAdderWorker(sourceFile, program, useAutoImportProvider, pre moduleSpecifier, quotePreference, defaultImport, - namedImports && arrayFrom(namedImports.entries(), ([name, addAsTypeOnly]) => ({ addAsTypeOnly, name })), + namedImports && arrayFrom(namedImports.entries(), ([name, [addAsTypeOnly, propertyName]]) => ({ addAsTypeOnly, propertyName, name })), namespaceLikeImport, compilerOptions, preferences @@ -155693,7 +157487,8 @@ function getAllExportInfoForSymbol(importingFile, symbol, symbolName2, moduleSym const moduleSourceFile = isFileExcluded && mergedModuleSymbol.declarations && getDeclarationOfKind(mergedModuleSymbol, 307 /* SourceFile */); const moduleSymbolExcluded = moduleSourceFile && isFileExcluded(moduleSourceFile); return getExportInfoMap(importingFile, host, program, preferences, cancellationToken).search(importingFile.path, preferCapitalized, (name) => name === symbolName2, (info) => { - if (getChecker(info[0].isFromPackageJson).getMergedSymbol(skipAlias(info[0].symbol, getChecker(info[0].isFromPackageJson))) === symbol && (moduleSymbolExcluded || info.some((i) => i.moduleSymbol === moduleSymbol || i.symbol.parent === moduleSymbol))) { + const checker = getChecker(info[0].isFromPackageJson); + if (checker.getMergedSymbol(skipAlias(info[0].symbol, checker)) === symbol && (moduleSymbolExcluded || info.some((i) => checker.getMergedSymbol(i.moduleSymbol) === moduleSymbol || i.symbol.parent === moduleSymbol))) { return info; } }); @@ -156122,6 +157917,8 @@ function getImportKind(importingFile, exportKind, program, forceImportKeyword) { return getExportEqualsImportKind(importingFile, program.getCompilerOptions(), !!forceImportKeyword); case 3 /* UMD */: return getUmdImportKind(importingFile, program, !!forceImportKeyword); + case 4 /* Module */: + return 2 /* Namespace */; default: return Debug.assertNever(exportKind); } @@ -156222,7 +158019,7 @@ function getExportInfos(symbolName2, isJsxTagName, currentTokenMeaning, cancella }); function addSymbol(moduleSymbol, toFile, exportedSymbol, exportKind, program2, isFromPackageJson) { const moduleSpecifierResolutionHost = getModuleSpecifierResolutionHost(isFromPackageJson); - if (toFile && isImportableFile(program2, fromFile, toFile, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache) || (!toFile && packageJsonFilter.allowsImportingAmbientModule(moduleSymbol, moduleSpecifierResolutionHost) || fileContainsPackageImport(fromFile, stripQuotes(moduleSymbol.name)))) { + if (isImportable(program2, fromFile, toFile, moduleSymbol, preferences, packageJsonFilter, moduleSpecifierResolutionHost, moduleSpecifierCache)) { const checker = program2.getTypeChecker(); originalSymbolToExportInfos.add(getUniqueSymbolId(exportedSymbol, checker).toString(), { symbol: exportedSymbol, moduleSymbol, moduleFileName: toFile == null ? void 0 : toFile.fileName, exportKind, targetFlags: skipAlias(exportedSymbol, checker).flags, isFromPackageJson }); } @@ -156417,8 +158214,7 @@ function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImpor ...namedImports.map((i) => factory.createBindingElement( /*dotDotDotToken*/ void 0, - /*propertyName*/ - void 0, + i.propertyName, i.name )) ]) @@ -156429,12 +158225,7 @@ function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImpor addElementToBindingPattern(clause, defaultImport.name, "default"); } for (const specifier of namedImports) { - addElementToBindingPattern( - clause, - specifier.name, - /*propertyName*/ - void 0 - ); + addElementToBindingPattern(clause, specifier.name, specifier.propertyName); } return; } @@ -156450,8 +158241,7 @@ function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImpor namedImports.map( (namedImport) => factory.createImportSpecifier( (!clause.isTypeOnly || promoteFromTypeOnly2) && shouldUseTypeOnly(namedImport, preferences), - /*propertyName*/ - void 0, + namedImport.propertyName === void 0 ? void 0 : factory.createIdentifier(namedImport.propertyName), factory.createIdentifier(namedImport.name) ) ), @@ -156546,8 +158336,7 @@ function getNewImports(moduleSpecifier, quotePreference, defaultImport, namedImp namedImports == null ? void 0 : namedImports.map( (namedImport) => factory.createImportSpecifier( !topLevelTypeOnly && shouldUseTypeOnly(namedImport, preferences), - /*propertyName*/ - void 0, + namedImport.propertyName === void 0 ? void 0 : factory.createIdentifier(namedImport.propertyName), factory.createIdentifier(namedImport.name) ) ), @@ -156585,11 +158374,10 @@ function getNewRequires(moduleSpecifier, quotePreference, defaultImport, namedIm const quotedModuleSpecifier = makeStringLiteral(moduleSpecifier, quotePreference); let statements; if (defaultImport || (namedImports == null ? void 0 : namedImports.length)) { - const bindingElements = (namedImports == null ? void 0 : namedImports.map(({ name }) => factory.createBindingElement( + const bindingElements = (namedImports == null ? void 0 : namedImports.map(({ name, propertyName }) => factory.createBindingElement( /*dotDotDotToken*/ void 0, - /*propertyName*/ - void 0, + propertyName, name ))) || []; if (defaultImport) { @@ -156641,8 +158429,8 @@ function getEmitModuleFormatOfFile(file, program) { } // src/services/codefixes/fixAddMissingConstraint.ts -var fixId17 = "addMissingConstraint"; -var errorCodes19 = [ +var fixId18 = "addMissingConstraint"; +var errorCodes20 = [ // We want errors this could be attached to: // Diagnostics.This_type_parameter_probably_needs_an_extends_0_constraint Diagnostics.Type_0_is_not_comparable_to_type_1.code, @@ -156655,20 +158443,20 @@ var errorCodes19 = [ Diagnostics.Type_0_does_not_satisfy_the_constraint_1.code ]; registerCodeFix({ - errorCodes: errorCodes19, + errorCodes: errorCodes20, getCodeActions(context) { const { sourceFile, span, program, preferences, host } = context; 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)); - return [createCodeFixAction(fixId17, changes, Diagnostics.Add_extends_constraint, fixId17, Diagnostics.Add_extends_constraint_to_all_type_parameters)]; + return [createCodeFixAction(fixId18, changes, Diagnostics.Add_extends_constraint, fixId18, Diagnostics.Add_extends_constraint_to_all_type_parameters)]; }, - fixIds: [fixId17], + fixIds: [fixId18], getAllCodeActions: (context) => { const { program, preferences, host } = context; - const seen = /* @__PURE__ */ new Map(); + const seen = /* @__PURE__ */ new Set(); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { - eachDiagnostic(context, errorCodes19, (diag2) => { + eachDiagnostic(context, errorCodes20, (diag2) => { const info = getInfo6(program, diag2.file, createTextSpan(diag2.start, diag2.length)); if (info) { if (addToSeen(seen, getNodeId(info.declaration))) { @@ -156750,7 +158538,7 @@ function tryGetConstraintType(checker, node) { var fixName = "fixOverrideModifier"; var fixAddOverrideId = "fixAddOverrideModifier"; var fixRemoveOverrideId = "fixRemoveOverrideModifier"; -var errorCodes20 = [ +var errorCodes21 = [ Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0.code, Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class.code, Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0.code, @@ -156814,19 +158602,19 @@ var errorCodeFixIdMap = { } }; registerCodeFix({ - errorCodes: errorCodes20, + errorCodes: errorCodes21, getCodeActions: function getCodeActionsToFixOverrideModifierIssues(context) { const { errorCode, span } = context; const info = errorCodeFixIdMap[errorCode]; if (!info) return emptyArray; - const { descriptions, fixId: fixId55, fixAllDescriptions } = info; + const { descriptions, fixId: fixId56, fixAllDescriptions } = info; const changes = ts_textChanges_exports.ChangeTracker.with(context, (changes2) => dispatchChanges(changes2, context, errorCode, span.start)); return [ - createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId55, fixAllDescriptions) + createCodeFixActionMaybeFixAll(fixName, changes, descriptions, fixId56, fixAllDescriptions) ]; }, fixIds: [fixName, fixAddOverrideId, fixRemoveOverrideId], - getAllCodeActions: (context) => codeFixAll(context, errorCodes20, (changes, diag2) => { + getAllCodeActions: (context) => codeFixAll(context, errorCodes21, (changes, diag2) => { const { code, start } = diag2; const info = errorCodeFixIdMap[code]; if (!info || info.fixId !== context.fixId) { @@ -156902,20 +158690,20 @@ function findContainerClassElementLike(sourceFile, pos) { } // src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts -var fixId18 = "fixNoPropertyAccessFromIndexSignature"; -var errorCodes21 = [ +var fixId19 = "fixNoPropertyAccessFromIndexSignature"; +var errorCodes22 = [ Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0.code ]; registerCodeFix({ - errorCodes: errorCodes21, - fixIds: [fixId18], + errorCodes: errorCodes22, + fixIds: [fixId19], getCodeActions(context) { const { sourceFile, span, preferences } = context; const property = getPropertyAccessExpression(sourceFile, span.start); 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)]; + return [createCodeFixAction(fixId19, changes, [Diagnostics.Use_element_access_for_0, property.name.text], fixId19, Diagnostics.Use_element_access_for_all_undeclared_properties)]; }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes21, (changes, diag2) => doChange14(changes, diag2.file, getPropertyAccessExpression(diag2.file, diag2.start), context.preferences)) + getAllCodeActions: (context) => codeFixAll(context, errorCodes22, (changes, diag2) => doChange14(changes, diag2.file, getPropertyAccessExpression(diag2.file, diag2.start), context.preferences)) }); function doChange14(changes, sourceFile, node, preferences) { const quotePreference = getQuotePreference(sourceFile, preferences); @@ -156931,20 +158719,20 @@ function getPropertyAccessExpression(sourceFile, pos) { } // src/services/codefixes/fixImplicitThis.ts -var fixId19 = "fixImplicitThis"; -var errorCodes22 = [Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code]; +var fixId20 = "fixImplicitThis"; +var errorCodes23 = [Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code]; registerCodeFix({ - errorCodes: errorCodes22, + errorCodes: errorCodes23, getCodeActions: function getCodeActionsToFixImplicitThis(context) { const { sourceFile, program, span } = context; let diagnostic; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => { diagnostic = doChange15(t, sourceFile, span.start, program.getTypeChecker()); }); - return diagnostic ? [createCodeFixAction(fixId19, changes, diagnostic, fixId19, Diagnostics.Fix_all_implicit_this_errors)] : emptyArray; + return diagnostic ? [createCodeFixAction(fixId20, changes, diagnostic, fixId20, Diagnostics.Fix_all_implicit_this_errors)] : emptyArray; }, - fixIds: [fixId19], - getAllCodeActions: (context) => codeFixAll(context, errorCodes22, (changes, diag2) => { + fixIds: [fixId20], + getAllCodeActions: (context) => codeFixAll(context, errorCodes23, (changes, diag2) => { doChange15(changes, diag2.file, diag2.start, context.program.getTypeChecker()); }) }); @@ -156989,25 +158777,25 @@ function doChange15(changes, sourceFile, pos, checker) { } // src/services/codefixes/fixImportNonExportedMember.ts -var fixId20 = "fixImportNonExportedMember"; -var errorCodes23 = [ +var fixId21 = "fixImportNonExportedMember"; +var errorCodes24 = [ Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported.code ]; registerCodeFix({ - errorCodes: errorCodes23, - fixIds: [fixId20], + errorCodes: errorCodes24, + fixIds: [fixId21], getCodeActions(context) { const { sourceFile, span, program } = context; const info = getInfo7(sourceFile, span.start, program); if (info === void 0) return void 0; 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)]; + return [createCodeFixAction(fixId21, changes, [Diagnostics.Export_0_from_module_1, info.exportName.node.text, info.moduleSpecifier], fixId21, Diagnostics.Export_all_referenced_locals)]; }, getAllCodeActions(context) { const { program } = context; return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { const exports2 = /* @__PURE__ */ new Map(); - eachDiagnostic(context, errorCodes23, (diag2) => { + eachDiagnostic(context, errorCodes24, (diag2) => { const info = getInfo7(diag2.file, diag2.start, program); if (info === void 0) return void 0; const { exportName, node, moduleSourceFile } = info; @@ -157147,20 +158935,20 @@ function getNodeOfSymbol(symbol) { } // src/services/codefixes/fixIncorrectNamedTupleSyntax.ts -var fixId21 = "fixIncorrectNamedTupleSyntax"; -var errorCodes24 = [ +var fixId22 = "fixIncorrectNamedTupleSyntax"; +var errorCodes25 = [ Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type.code, Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type.code ]; registerCodeFix({ - errorCodes: errorCodes24, + errorCodes: errorCodes25, getCodeActions: function getCodeActionsToFixIncorrectNamedTupleSyntax(context) { const { sourceFile, span } = context; const namedTupleMember = getNamedTupleMember(sourceFile, span.start); 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)]; + return [createCodeFixAction(fixId22, changes, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels, fixId22, Diagnostics.Move_labeled_tuple_element_modifiers_to_labels)]; }, - fixIds: [fixId21] + fixIds: [fixId22] }); function getNamedTupleMember(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); @@ -157195,8 +158983,8 @@ function doChange17(changes, sourceFile, namedTupleMember) { } // src/services/codefixes/fixSpelling.ts -var fixId22 = "fixSpelling"; -var errorCodes25 = [ +var fixId23 = "fixSpelling"; +var errorCodes26 = [ Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, Diagnostics.Cannot_find_name_0_Did_you_mean_1.code, @@ -157213,7 +159001,7 @@ var errorCodes25 = [ Diagnostics.Type_0_is_not_assignable_to_type_1.code ]; registerCodeFix({ - errorCodes: errorCodes25, + errorCodes: errorCodes26, getCodeActions(context) { const { sourceFile, errorCode } = context; const info = getInfo8(sourceFile, context.span.start, context, errorCode); @@ -157221,10 +159009,10 @@ registerCodeFix({ const { node, suggestedSymbol } = info; const target = getEmitScriptTarget(context.host.getCompilationSettings()); 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)]; + return [createCodeFixAction("spelling", changes, [Diagnostics.Change_spelling_to_0, symbolName(suggestedSymbol)], fixId23, Diagnostics.Fix_all_detected_spelling_errors)]; }, - fixIds: [fixId22], - getAllCodeActions: (context) => codeFixAll(context, errorCodes25, (changes, diag2) => { + fixIds: [fixId23], + getAllCodeActions: (context) => codeFixAll(context, errorCodes26, (changes, diag2) => { const info = getInfo8(diag2.file, diag2.start, context, diag2.code); const target = getEmitScriptTarget(context.host.getCompilationSettings()); if (info) doChange18(changes, context.sourceFile, info.node, info.suggestedSymbol, target); @@ -157313,17 +159101,17 @@ function getResolvedSourceFileFromImportDeclaration(context, importDeclaration, } // src/services/codefixes/returnValueCorrect.ts -var fixId23 = "returnValueCorrect"; +var fixId24 = "returnValueCorrect"; var fixIdAddReturnStatement = "fixAddReturnStatement"; var fixRemoveBracesFromArrowFunctionBody = "fixRemoveBracesFromArrowFunctionBody"; var fixIdWrapTheBlockWithParen = "fixWrapTheBlockWithParen"; -var errorCodes26 = [ +var errorCodes27 = [ Diagnostics.A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value.code, Diagnostics.Type_0_is_not_assignable_to_type_1.code, Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code ]; registerCodeFix({ - errorCodes: errorCodes26, + errorCodes: errorCodes27, fixIds: [fixIdAddReturnStatement, fixRemoveBracesFromArrowFunctionBody, fixIdWrapTheBlockWithParen], getCodeActions: function getCodeActionsToCorrectReturnValue(context) { const { program, sourceFile, span: { start }, errorCode } = context; @@ -157338,7 +159126,7 @@ registerCodeFix({ return [getActionForfixWrapTheBlockWithParen(context, info.declaration, info.expression)]; } }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes26, (changes, diag2) => { + getAllCodeActions: (context) => codeFixAll(context, errorCodes27, (changes, diag2) => { const info = getInfo9(context.program.getTypeChecker(), diag2.file, diag2.start, diag2.code); if (!info) return void 0; switch (context.fixId) { @@ -157537,7 +159325,7 @@ function wrapBlockWithParen(changes, sourceFile, declaration, expression) { } function getActionForfixAddReturnStatement(context, expression, statement) { const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addReturnStatement(t, context.sourceFile, expression, statement)); - return createCodeFixAction(fixId23, changes, Diagnostics.Add_a_return_statement, fixIdAddReturnStatement, Diagnostics.Add_all_missing_return_statement); + return createCodeFixAction(fixId24, changes, Diagnostics.Add_a_return_statement, fixIdAddReturnStatement, Diagnostics.Add_all_missing_return_statement); } function getActionForFixRemoveBracesFromArrowFunctionBody(context, declaration, expression, commentSource) { const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => removeBlockBodyBrace( @@ -157549,11 +159337,11 @@ function getActionForFixRemoveBracesFromArrowFunctionBody(context, declaration, /*withParen*/ false )); - return createCodeFixAction(fixId23, changes, Diagnostics.Remove_braces_from_arrow_function_body, fixRemoveBracesFromArrowFunctionBody, Diagnostics.Remove_braces_from_all_arrow_function_bodies_with_relevant_issues); + return createCodeFixAction(fixId24, changes, Diagnostics.Remove_braces_from_arrow_function_body, fixRemoveBracesFromArrowFunctionBody, Diagnostics.Remove_braces_from_all_arrow_function_bodies_with_relevant_issues); } function getActionForfixWrapTheBlockWithParen(context, declaration, expression) { const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => wrapBlockWithParen(t, context.sourceFile, declaration, expression)); - return createCodeFixAction(fixId23, changes, Diagnostics.Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal, fixIdWrapTheBlockWithParen, Diagnostics.Wrap_all_object_literal_with_parentheses); + return createCodeFixAction(fixId24, changes, Diagnostics.Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal, fixIdWrapTheBlockWithParen, Diagnostics.Wrap_all_object_literal_with_parentheses); } // src/services/codefixes/fixAddMissingMember.ts @@ -157561,7 +159349,7 @@ var fixMissingMember = "fixMissingMember"; var fixMissingProperties = "fixMissingProperties"; var fixMissingAttributes = "fixMissingAttributes"; var fixMissingFunctionDeclaration = "fixMissingFunctionDeclaration"; -var errorCodes27 = [ +var errorCodes28 = [ Diagnostics.Property_0_does_not_exist_on_type_1.code, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2.code, @@ -157571,7 +159359,7 @@ var errorCodes27 = [ Diagnostics.Cannot_find_name_0.code ]; registerCodeFix({ - errorCodes: errorCodes27, + errorCodes: errorCodes28, getCodeActions(context) { const typeChecker = context.program.getTypeChecker(); const info = getInfo10(context.sourceFile, context.span.start, context.errorCode, typeChecker, context.program); @@ -157598,21 +159386,21 @@ registerCodeFix({ }, fixIds: [fixMissingMember, fixMissingFunctionDeclaration, fixMissingProperties, fixMissingAttributes], getAllCodeActions: (context) => { - const { program, fixId: fixId55 } = context; + const { program, fixId: fixId56 } = context; const checker = program.getTypeChecker(); - const seen = /* @__PURE__ */ new Map(); + const seen = /* @__PURE__ */ new Set(); const typeDeclToMembers = /* @__PURE__ */ new Map(); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { - eachDiagnostic(context, errorCodes27, (diag2) => { + eachDiagnostic(context, errorCodes28, (diag2) => { const info = getInfo10(diag2.file, diag2.start, diag2.code, checker, context.program); if (!info || !addToSeen(seen, getNodeId(info.parentDeclaration) + "#" + (info.kind === 3 /* ObjectLiteral */ ? info.identifier : info.token.text))) { return; } - if (fixId55 === fixMissingFunctionDeclaration && (info.kind === 2 /* Function */ || info.kind === 5 /* Signature */)) { + if (fixId56 === fixMissingFunctionDeclaration && (info.kind === 2 /* Function */ || info.kind === 5 /* Signature */)) { addFunctionDeclaration(changes, context, info); - } else if (fixId55 === fixMissingProperties && info.kind === 3 /* ObjectLiteral */) { + } else if (fixId56 === fixMissingProperties && info.kind === 3 /* ObjectLiteral */) { addObjectLiteralProperties(changes, context, info); - } else if (fixId55 === fixMissingAttributes && info.kind === 4 /* JsxAttributes */) { + } else if (fixId56 === fixMissingAttributes && info.kind === 4 /* JsxAttributes */) { addJsxAttributes(changes, context, info); } else { if (info.kind === 1 /* Enum */) { @@ -157651,7 +159439,7 @@ registerCodeFix({ } }); function getInfo10(sourceFile, tokenPos, errorCode, checker, program) { - var _a; + var _a, _b, _c; const token = getTokenAtPosition(sourceFile, tokenPos); const parent2 = token.parent; if (errorCode === Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1.code) { @@ -157664,7 +159452,7 @@ function getInfo10(sourceFile, tokenPos, errorCode, checker, program) { if (!(param && isParameter(param) && isIdentifier(param.name))) return void 0; const properties = arrayFrom(checker.getUnmatchedProperties( checker.getTypeAtLocation(parent2), - checker.getParameterType(signature, argIndex), + checker.getParameterType(signature, argIndex).getNonNullableType(), /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ @@ -157674,7 +159462,7 @@ function getInfo10(sourceFile, tokenPos, errorCode, checker, program) { return { kind: 3 /* ObjectLiteral */, token: param.name, identifier: param.name.text, properties, parentDeclaration: parent2 }; } if (token.kind === 19 /* OpenBraceToken */ && isObjectLiteralExpression(parent2)) { - const targetType = checker.getContextualType(parent2) || checker.getTypeAtLocation(parent2); + const targetType = (_a = checker.getContextualType(parent2) || checker.getTypeAtLocation(parent2)) == null ? void 0 : _a.getNonNullableType(); const properties = arrayFrom(checker.getUnmatchedProperties( checker.getTypeAtLocation(parent2), targetType, @@ -157689,7 +159477,7 @@ function getInfo10(sourceFile, tokenPos, errorCode, checker, program) { } if (!isMemberName(token)) return void 0; if (isIdentifier(token) && hasInitializer(parent2) && parent2.initializer && isObjectLiteralExpression(parent2.initializer)) { - const targetType = checker.getContextualType(token) || checker.getTypeAtLocation(token); + const targetType = (_b = checker.getContextualType(token) || checker.getTypeAtLocation(token)) == null ? void 0 : _b.getNonNullableType(); const properties = arrayFrom(checker.getUnmatchedProperties( checker.getTypeAtLocation(parent2.initializer), targetType, @@ -157708,7 +159496,7 @@ function getInfo10(sourceFile, tokenPos, errorCode, checker, program) { return { kind: 4 /* JsxAttributes */, token, attributes, parentDeclaration: token.parent }; } if (isIdentifier(token)) { - const type = (_a = checker.getContextualType(token)) == null ? void 0 : _a.getNonNullableType(); + const type = (_c = checker.getContextualType(token)) == null ? void 0 : _c.getNonNullableType(); if (type && getObjectFlags(type) & 16 /* Anonymous */) { const signature = firstOrUndefined(checker.getSignaturesOfType(type, 0 /* Call */)); if (signature === void 0) return void 0; @@ -158029,8 +159817,9 @@ function tryGetValueFromType(context, checker, importAdder, quotePreference, typ } if (type.flags & 1056 /* EnumLike */) { const enumMember = type.symbol.exports ? firstOrUndefinedIterator(type.symbol.exports.values()) : type.symbol; + const symbol = type.symbol.parent && type.symbol.parent.flags & 256 /* RegularEnum */ ? type.symbol.parent : type.symbol; const name = checker.symbolToExpression( - type.symbol.parent ? type.symbol.parent : type.symbol, + symbol, 111551 /* Value */, /*enclosingDeclaration*/ void 0, @@ -158181,17 +159970,17 @@ function findScope(node) { } // src/services/codefixes/fixAddMissingNewOperator.ts -var fixId24 = "addMissingNewOperator"; -var errorCodes28 = [Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code]; +var fixId25 = "addMissingNewOperator"; +var errorCodes29 = [Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code]; registerCodeFix({ - errorCodes: errorCodes28, + errorCodes: errorCodes29, getCodeActions(context) { const { sourceFile, span } = context; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingNewOperator(t, sourceFile, span)); - return [createCodeFixAction(fixId24, changes, Diagnostics.Add_missing_new_operator_to_call, fixId24, Diagnostics.Add_missing_new_operator_to_all_calls)]; + return [createCodeFixAction(fixId25, changes, Diagnostics.Add_missing_new_operator_to_call, fixId25, Diagnostics.Add_missing_new_operator_to_all_calls)]; }, - fixIds: [fixId24], - getAllCodeActions: (context) => codeFixAll(context, errorCodes28, (changes, diag2) => addMissingNewOperator(changes, context.sourceFile, diag2)) + fixIds: [fixId25], + getAllCodeActions: (context) => codeFixAll(context, errorCodes29, (changes, diag2) => addMissingNewOperator(changes, context.sourceFile, diag2)) }); function addMissingNewOperator(changes, sourceFile, span) { const call = cast(findAncestorMatchingSpan2(sourceFile, span), isCallExpression); @@ -158210,9 +159999,9 @@ function findAncestorMatchingSpan2(sourceFile, span) { // src/services/codefixes/fixAddMissingParam.ts var addMissingParamFixId = "addMissingParam"; var addOptionalParamFixId = "addOptionalParam"; -var errorCodes29 = [Diagnostics.Expected_0_arguments_but_got_1.code]; +var errorCodes30 = [Diagnostics.Expected_0_arguments_but_got_1.code]; registerCodeFix({ - errorCodes: errorCodes29, + errorCodes: errorCodes30, fixIds: [addMissingParamFixId, addOptionalParamFixId], getCodeActions(context) { const info = getInfo11(context.sourceFile, context.program, context.span.start); @@ -158245,7 +160034,7 @@ registerCodeFix({ } return actions2; }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes29, (changes, diag2) => { + getAllCodeActions: (context) => codeFixAll(context, errorCodes30, (changes, diag2) => { const info = getInfo11(context.sourceFile, context.program, diag2.start); if (info) { const { declarations, newParameters, newOptionalParameters } = info; @@ -158448,17 +160237,19 @@ function getParameterType(importAdder, typeNode, scriptTarget) { var fixName2 = "fixCannotFindModule"; var fixIdInstallTypesPackage = "installTypesPackage"; var errorCodeCannotFindModule = Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations.code; -var errorCodes30 = [ +var errorCannotFindImplicitJsxImport = Diagnostics.This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_for_the_appropriate_package_installed.code; +var errorCodes31 = [ errorCodeCannotFindModule, - Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code + Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type.code, + errorCannotFindImplicitJsxImport ]; registerCodeFix({ - errorCodes: errorCodes30, + errorCodes: errorCodes31, getCodeActions: function getCodeActionsToFixNotFoundModule(context) { - const { host, sourceFile, span: { start } } = context; - const packageName = tryGetImportedPackageName(sourceFile, start); + const { host, sourceFile, span: { start }, errorCode } = context; + const packageName = errorCode === errorCannotFindImplicitJsxImport ? getJSXImplicitImportBase(context.program.getCompilerOptions(), sourceFile) : tryGetImportedPackageName(sourceFile, start); if (packageName === void 0) return void 0; - const typesPackageName = getTypesPackageNameToInstall(packageName, host, context.errorCode); + const typesPackageName = getTypesPackageNameToInstall(packageName, host, errorCode); return typesPackageName === void 0 ? [] : [createCodeFixAction( fixName2, /*changes*/ @@ -158471,7 +160262,7 @@ registerCodeFix({ }, fixIds: [fixIdInstallTypesPackage], getAllCodeActions: (context) => { - return codeFixAll(context, errorCodes30, (_changes, diag2, commands) => { + return codeFixAll(context, errorCodes31, (_changes, diag2, commands) => { const packageName = tryGetImportedPackageName(diag2.file, diag2.start); if (packageName === void 0) return void 0; switch (context.fixId) { @@ -158500,11 +160291,11 @@ function tryGetImportedPackageName(sourceFile, pos) { } function getTypesPackageNameToInstall(packageName, host, diagCode) { var _a; - return diagCode === errorCodeCannotFindModule ? ts_JsTyping_exports.nodeCoreModules.has(packageName) ? "@types/node" : void 0 : ((_a = host.isKnownTypesPackageName) == null ? void 0 : _a.call(host, packageName)) ? getTypesPackageName(packageName) : void 0; + return diagCode === errorCodeCannotFindModule ? nodeCoreModules.has(packageName) ? "@types/node" : void 0 : ((_a = host.isKnownTypesPackageName) == null ? void 0 : _a.call(host, packageName)) ? getTypesPackageName(packageName) : void 0; } // src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts -var errorCodes31 = [ +var errorCodes32 = [ Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code, Diagnostics.Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2.code, Diagnostics.Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_and_3_more.code, @@ -158512,18 +160303,18 @@ var errorCodes31 = [ Diagnostics.Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1.code, Diagnostics.Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_and_2_more.code ]; -var fixId25 = "fixClassDoesntImplementInheritedAbstractMember"; +var fixId26 = "fixClassDoesntImplementInheritedAbstractMember"; registerCodeFix({ - errorCodes: errorCodes31, + errorCodes: errorCodes32, getCodeActions: function getCodeActionsToFixClassNotImplementingInheritedMembers(context) { const { sourceFile, span } = context; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => addMissingMembers(getClass2(sourceFile, span.start), sourceFile, context, t, context.preferences)); - return changes.length === 0 ? void 0 : [createCodeFixAction(fixId25, changes, Diagnostics.Implement_inherited_abstract_class, fixId25, Diagnostics.Implement_all_inherited_abstract_classes)]; + return changes.length === 0 ? void 0 : [createCodeFixAction(fixId26, changes, Diagnostics.Implement_inherited_abstract_class, fixId26, Diagnostics.Implement_all_inherited_abstract_classes)]; }, - fixIds: [fixId25], + fixIds: [fixId26], getAllCodeActions: function getAllCodeActionsToFixClassDoesntImplementInheritedAbstractMember(context) { - const seenClassDeclarations = /* @__PURE__ */ new Map(); - return codeFixAll(context, errorCodes31, (changes, diag2) => { + const seenClassDeclarations = /* @__PURE__ */ new Set(); + return codeFixAll(context, errorCodes32, (changes, diag2) => { const classDeclaration = getClass2(diag2.file, diag2.start); if (addToSeen(seenClassDeclarations, getNodeId(classDeclaration))) { addMissingMembers(classDeclaration, context.sourceFile, context, changes, context.preferences); @@ -158550,23 +160341,23 @@ function symbolPointsToNonPrivateAndAbstractMember(symbol) { } // src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts -var fixId26 = "classSuperMustPrecedeThisAccess"; -var errorCodes32 = [Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code]; +var fixId27 = "classSuperMustPrecedeThisAccess"; +var errorCodes33 = [Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code]; registerCodeFix({ - errorCodes: errorCodes32, + errorCodes: errorCodes33, getCodeActions(context) { const { sourceFile, span } = context; const nodes = getNodes(sourceFile, span.start); if (!nodes) return void 0; const { constructor, superCall } = nodes; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange20(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)]; + return [createCodeFixAction(fixId27, changes, Diagnostics.Make_super_call_the_first_statement_in_the_constructor, fixId27, Diagnostics.Make_all_super_calls_the_first_statement_in_their_constructor)]; }, - fixIds: [fixId26], + fixIds: [fixId27], getAllCodeActions(context) { const { sourceFile } = context; - const seenClasses = /* @__PURE__ */ new Map(); - return codeFixAll(context, errorCodes32, (changes, diag2) => { + const seenClasses = /* @__PURE__ */ new Set(); + return codeFixAll(context, errorCodes33, (changes, diag2) => { const nodes = getNodes(diag2.file, diag2.start); if (!nodes) return; const { constructor, superCall } = nodes; @@ -158592,18 +160383,18 @@ function findSuperCall(n) { } // src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts -var fixId27 = "constructorForDerivedNeedSuperCall"; -var errorCodes33 = [Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code]; +var fixId28 = "constructorForDerivedNeedSuperCall"; +var errorCodes34 = [Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code]; registerCodeFix({ - errorCodes: errorCodes33, + errorCodes: errorCodes34, getCodeActions(context) { const { sourceFile, span } = context; const ctr = getNode(sourceFile, span.start); const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange21(t, sourceFile, ctr)); - return [createCodeFixAction(fixId27, changes, Diagnostics.Add_missing_super_call, fixId27, Diagnostics.Add_all_missing_super_calls)]; + return [createCodeFixAction(fixId28, changes, Diagnostics.Add_missing_super_call, fixId28, Diagnostics.Add_all_missing_super_calls)]; }, - fixIds: [fixId27], - getAllCodeActions: (context) => codeFixAll(context, errorCodes33, (changes, diag2) => doChange21(changes, context.sourceFile, getNode(diag2.file, diag2.start))) + fixIds: [fixId28], + getAllCodeActions: (context) => codeFixAll(context, errorCodes34, (changes, diag2) => doChange21(changes, context.sourceFile, getNode(diag2.file, diag2.start))) }); function getNode(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); @@ -158623,9 +160414,9 @@ function doChange21(changes, sourceFile, ctr) { // src/services/codefixes/fixEnableJsxFlag.ts var fixID = "fixEnableJsxFlag"; -var errorCodes34 = [Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided.code]; +var errorCodes35 = [Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided.code]; registerCodeFix({ - errorCodes: errorCodes34, + errorCodes: errorCodes35, getCodeActions: function getCodeActionsToFixEnableJsxFlag(context) { const { configFile } = context.program.getCompilerOptions(); if (configFile === void 0) { @@ -158637,7 +160428,7 @@ registerCodeFix({ ]; }, fixIds: [fixID], - getAllCodeActions: (context) => codeFixAll(context, errorCodes34, (changes) => { + getAllCodeActions: (context) => codeFixAll(context, errorCodes35, (changes) => { const { configFile } = context.program.getCompilerOptions(); if (configFile === void 0) { return void 0; @@ -158650,23 +160441,23 @@ function doChange22(changeTracker, configFile) { } // src/services/codefixes/fixNaNEquality.ts -var fixId28 = "fixNaNEquality"; -var errorCodes35 = [ +var fixId29 = "fixNaNEquality"; +var errorCodes36 = [ Diagnostics.This_condition_will_always_return_0.code ]; registerCodeFix({ - errorCodes: errorCodes35, + errorCodes: errorCodes36, getCodeActions(context) { const { sourceFile, span, program } = context; const info = getInfo12(program, sourceFile, span); if (info === void 0) return; const { suggestion, expression, arg } = info; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange23(t, sourceFile, arg, expression)); - return [createCodeFixAction(fixId28, changes, [Diagnostics.Use_0, suggestion], fixId28, Diagnostics.Use_Number_isNaN_in_all_conditions)]; + return [createCodeFixAction(fixId29, changes, [Diagnostics.Use_0, suggestion], fixId29, Diagnostics.Use_Number_isNaN_in_all_conditions)]; }, - fixIds: [fixId28], + fixIds: [fixId29], getAllCodeActions: (context) => { - return codeFixAll(context, errorCodes35, (changes, diag2) => { + return codeFixAll(context, errorCodes36, (changes, diag2) => { const info = getInfo12(context.program, diag2.file, createTextSpan(diag2.start, diag2.length)); if (info) { doChange23(changes, diag2.file, info.arg, info.expression); @@ -158746,20 +160537,20 @@ registerCodeFix({ }); // src/services/codefixes/fixPropertyAssignment.ts -var fixId29 = "fixPropertyAssignment"; -var errorCodes36 = [ +var fixId30 = "fixPropertyAssignment"; +var errorCodes37 = [ Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code ]; registerCodeFix({ - errorCodes: errorCodes36, - fixIds: [fixId29], + errorCodes: errorCodes37, + fixIds: [fixId30], getCodeActions(context) { const { sourceFile, span } = context; const property = getProperty2(sourceFile, span.start); const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange24(t, context.sourceFile, property)); - return [createCodeFixAction(fixId29, changes, [Diagnostics.Change_0_to_1, "=", ":"], fixId29, [Diagnostics.Switch_each_misused_0_to_1, "=", ":"])]; + return [createCodeFixAction(fixId30, changes, [Diagnostics.Change_0_to_1, "=", ":"], fixId30, [Diagnostics.Switch_each_misused_0_to_1, "=", ":"])]; }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes36, (changes, diag2) => doChange24(changes, diag2.file, getProperty2(diag2.file, diag2.start))) + getAllCodeActions: (context) => codeFixAll(context, errorCodes37, (changes, diag2) => doChange24(changes, diag2.file, getProperty2(diag2.file, diag2.start))) }); function doChange24(changes, sourceFile, node) { changes.replaceNode(sourceFile, node, factory.createPropertyAssignment(node.name, node.objectAssignmentInitializer)); @@ -158769,20 +160560,20 @@ function getProperty2(sourceFile, pos) { } // src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts -var fixId30 = "extendsInterfaceBecomesImplements"; -var errorCodes37 = [Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code]; +var fixId31 = "extendsInterfaceBecomesImplements"; +var errorCodes38 = [Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code]; registerCodeFix({ - errorCodes: errorCodes37, + errorCodes: errorCodes38, getCodeActions(context) { const { sourceFile } = context; const nodes = getNodes2(sourceFile, context.span.start); if (!nodes) return void 0; const { extendsToken, heritageClauses } = nodes; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChanges2(t, sourceFile, extendsToken, heritageClauses)); - return [createCodeFixAction(fixId30, changes, Diagnostics.Change_extends_to_implements, fixId30, Diagnostics.Change_all_extended_interfaces_to_implements)]; + return [createCodeFixAction(fixId31, changes, Diagnostics.Change_extends_to_implements, fixId31, Diagnostics.Change_all_extended_interfaces_to_implements)]; }, - fixIds: [fixId30], - getAllCodeActions: (context) => codeFixAll(context, errorCodes37, (changes, diag2) => { + fixIds: [fixId31], + getAllCodeActions: (context) => codeFixAll(context, errorCodes38, (changes, diag2) => { const nodes = getNodes2(diag2.file, diag2.start); if (nodes) doChanges2(changes, diag2.file, nodes.extendsToken, nodes.heritageClauses); }) @@ -158809,15 +160600,15 @@ function doChanges2(changes, sourceFile, extendsToken, heritageClauses) { } // src/services/codefixes/fixForgottenThisPropertyAccess.ts -var fixId31 = "forgottenThisPropertyAccess"; +var fixId32 = "forgottenThisPropertyAccess"; var didYouMeanStaticMemberCode = Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code; -var errorCodes38 = [ +var errorCodes39 = [ Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code, Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression.code, didYouMeanStaticMemberCode ]; registerCodeFix({ - errorCodes: errorCodes38, + errorCodes: errorCodes39, getCodeActions(context) { const { sourceFile } = context; const info = getInfo13(sourceFile, context.span.start, context.errorCode); @@ -158825,10 +160616,10 @@ registerCodeFix({ return void 0; } const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange25(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)]; + return [createCodeFixAction(fixId32, changes, [Diagnostics.Add_0_to_unresolved_variable, info.className || "this"], fixId32, Diagnostics.Add_qualifier_to_all_unresolved_variables_matching_a_member_name)]; }, - fixIds: [fixId31], - getAllCodeActions: (context) => codeFixAll(context, errorCodes38, (changes, diag2) => { + fixIds: [fixId32], + getAllCodeActions: (context) => codeFixAll(context, errorCodes39, (changes, diag2) => { const info = getInfo13(diag2.file, diag2.start, diag2.code); if (info) doChange25(changes, context.sourceFile, info); }) @@ -158847,12 +160638,12 @@ function doChange25(changes, sourceFile, { node, className }) { // src/services/codefixes/fixInvalidJsxCharacters.ts var fixIdExpression = "fixInvalidJsxCharacters_expression"; var fixIdHtmlEntity = "fixInvalidJsxCharacters_htmlEntity"; -var errorCodes39 = [ +var errorCodes40 = [ Diagnostics.Unexpected_token_Did_you_mean_or_gt.code, Diagnostics.Unexpected_token_Did_you_mean_or_rbrace.code ]; registerCodeFix({ - errorCodes: errorCodes39, + errorCodes: errorCodes40, fixIds: [fixIdExpression, fixIdHtmlEntity], getCodeActions(context) { const { sourceFile, preferences, span } = context; @@ -158878,7 +160669,7 @@ registerCodeFix({ ]; }, getAllCodeActions(context) { - return codeFixAll(context, errorCodes39, (changes, diagnostic) => doChange26(changes, context.preferences, diagnostic.file, diagnostic.start, context.fixId === fixIdHtmlEntity)); + return codeFixAll(context, errorCodes40, (changes, diagnostic) => doChange26(changes, context.preferences, diagnostic.file, diagnostic.start, context.fixId === fixIdHtmlEntity)); } }); var htmlEntity = { @@ -158900,12 +160691,12 @@ function doChange26(changes, preferences, sourceFile, start, useHtmlEntity) { // src/services/codefixes/fixUnmatchedParameter.ts var deleteUnmatchedParameter = "deleteUnmatchedParameter"; var renameUnmatchedParameter = "renameUnmatchedParameter"; -var errorCodes40 = [ +var errorCodes41 = [ Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name.code ]; registerCodeFix({ fixIds: [deleteUnmatchedParameter, renameUnmatchedParameter], - errorCodes: errorCodes40, + errorCodes: errorCodes41, getCodeActions: function getCodeActionsToFixUnmatchedParameter(context) { const { sourceFile, span } = context; const actions2 = []; @@ -158920,7 +160711,7 @@ registerCodeFix({ getAllCodeActions: function getAllCodeActionsToFixUnmatchedParameter(context) { const tagsToSignature = /* @__PURE__ */ new Map(); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { - eachDiagnostic(context, errorCodes40, ({ file, start }) => { + eachDiagnostic(context, errorCodes41, ({ file, start }) => { const info = getInfo14(file, start); if (info) { tagsToSignature.set(info.signature, append(tagsToSignature.get(info.signature), info.jsDocParameterTag)); @@ -158983,10 +160774,10 @@ function getInfo14(sourceFile, pos) { } // src/services/codefixes/fixUnreferenceableDecoratorMetadata.ts -var fixId32 = "fixUnreferenceableDecoratorMetadata"; -var errorCodes41 = [Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled.code]; +var fixId33 = "fixUnreferenceableDecoratorMetadata"; +var errorCodes42 = [Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled.code]; registerCodeFix({ - errorCodes: errorCodes41, + errorCodes: errorCodes42, getCodeActions: (context) => { const importDeclaration = getImportDeclaration(context.sourceFile, context.program, context.span.start); if (!importDeclaration) return; @@ -158994,14 +160785,14 @@ registerCodeFix({ const typeOnlyChanges = ts_textChanges_exports.ChangeTracker.with(context, (t) => doTypeOnlyImportChange(t, context.sourceFile, importDeclaration, context.program)); let actions2; if (namespaceChanges.length) { - actions2 = append(actions2, createCodeFixActionWithoutFixAll(fixId32, namespaceChanges, Diagnostics.Convert_named_imports_to_namespace_import)); + actions2 = append(actions2, createCodeFixActionWithoutFixAll(fixId33, namespaceChanges, Diagnostics.Convert_named_imports_to_namespace_import)); } if (typeOnlyChanges.length) { - actions2 = append(actions2, createCodeFixActionWithoutFixAll(fixId32, typeOnlyChanges, Diagnostics.Use_import_type)); + actions2 = append(actions2, createCodeFixActionWithoutFixAll(fixId33, typeOnlyChanges, Diagnostics.Use_import_type)); } return actions2; }, - fixIds: [fixId32] + fixIds: [fixId33] }); function getImportDeclaration(sourceFile, program, start) { const identifier = tryCast(getTokenAtPosition(sourceFile, start), isIdentifier); @@ -159038,7 +160829,7 @@ var fixIdPrefix = "unusedIdentifier_prefix"; var fixIdDelete = "unusedIdentifier_delete"; var fixIdDeleteImports = "unusedIdentifier_deleteImports"; var fixIdInfer = "unusedIdentifier_infer"; -var errorCodes42 = [ +var errorCodes43 = [ Diagnostics._0_is_declared_but_its_value_is_never_read.code, Diagnostics._0_is_declared_but_never_used.code, Diagnostics.Property_0_is_declared_but_its_value_is_never_read.code, @@ -159048,7 +160839,7 @@ var errorCodes42 = [ Diagnostics.All_type_parameters_are_unused.code ]; registerCodeFix({ - errorCodes: errorCodes42, + errorCodes: errorCodes43, getCodeActions(context) { const { errorCode, sourceFile, program, cancellationToken } = context; const checker = program.getTypeChecker(); @@ -159137,7 +160928,7 @@ registerCodeFix({ const { sourceFile, program, cancellationToken } = context; const checker = program.getTypeChecker(); const sourceFiles = program.getSourceFiles(); - return codeFixAll(context, errorCodes42, (changes, diag2) => { + return codeFixAll(context, errorCodes43, (changes, diag2) => { const token = getTokenAtPosition(sourceFile, diag2.start); switch (context.fixId) { case fixIdPrefix: @@ -159377,18 +161168,18 @@ function deleteFunctionLikeDeclaration(changes, sourceFile, node) { } // src/services/codefixes/fixUnreachableCode.ts -var fixId33 = "fixUnreachableCode"; -var errorCodes43 = [Diagnostics.Unreachable_code_detected.code]; +var fixId34 = "fixUnreachableCode"; +var errorCodes44 = [Diagnostics.Unreachable_code_detected.code]; registerCodeFix({ - errorCodes: errorCodes43, + errorCodes: errorCodes44, getCodeActions(context) { const syntacticDiagnostics = context.program.getSyntacticDiagnostics(context.sourceFile, context.cancellationToken); if (syntacticDiagnostics.length) return; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange27(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)]; + return [createCodeFixAction(fixId34, changes, Diagnostics.Remove_unreachable_code, fixId34, Diagnostics.Remove_all_unreachable_code)]; }, - fixIds: [fixId33], - getAllCodeActions: (context) => codeFixAll(context, errorCodes43, (changes, diag2) => doChange27(changes, diag2.file, diag2.start, diag2.length, diag2.code)) + fixIds: [fixId34], + getAllCodeActions: (context) => codeFixAll(context, errorCodes44, (changes, diag2) => doChange27(changes, diag2.file, diag2.start, diag2.length, diag2.code)) }); function doChange27(changes, sourceFile, start, length2, errorCode) { const token = getTokenAtPosition(sourceFile, start); @@ -159415,6 +161206,7 @@ function doChange27(changes, sourceFile, start, length2, errorCode) { } return; } + // falls through case 247 /* WhileStatement */: case 248 /* ForStatement */: changes.delete(sourceFile, container); @@ -159439,16 +161231,16 @@ function lastWhere(a, pred) { } // src/services/codefixes/fixUnusedLabel.ts -var fixId34 = "fixUnusedLabel"; -var errorCodes44 = [Diagnostics.Unused_label.code]; +var fixId35 = "fixUnusedLabel"; +var errorCodes45 = [Diagnostics.Unused_label.code]; registerCodeFix({ - errorCodes: errorCodes44, + errorCodes: errorCodes45, getCodeActions(context) { const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange28(t, context.sourceFile, context.span.start)); - return [createCodeFixAction(fixId34, changes, Diagnostics.Remove_unused_label, fixId34, Diagnostics.Remove_all_unused_labels)]; + return [createCodeFixAction(fixId35, changes, Diagnostics.Remove_unused_label, fixId35, Diagnostics.Remove_all_unused_labels)]; }, - fixIds: [fixId34], - getAllCodeActions: (context) => codeFixAll(context, errorCodes44, (changes, diag2) => doChange28(changes, diag2.file, diag2.start)) + fixIds: [fixId35], + getAllCodeActions: (context) => codeFixAll(context, errorCodes45, (changes, diag2) => doChange28(changes, diag2.file, diag2.start)) }); function doChange28(changes, sourceFile, start) { const token = getTokenAtPosition(sourceFile, start); @@ -159467,13 +161259,13 @@ function doChange28(changes, sourceFile, start) { // src/services/codefixes/fixJSDocTypes.ts var fixIdPlain = "fixJSDocTypes_plain"; var fixIdNullable = "fixJSDocTypes_nullable"; -var errorCodes45 = [ +var errorCodes46 = [ Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code, Diagnostics._0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1.code, Diagnostics._0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1.code ]; registerCodeFix({ - errorCodes: errorCodes45, + errorCodes: errorCodes46, getCodeActions(context) { const { sourceFile } = context; const checker = context.program.getTypeChecker(); @@ -159486,20 +161278,20 @@ registerCodeFix({ actions2.push(fix(type, fixIdNullable, Diagnostics.Change_all_jsdoc_style_types_to_TypeScript_and_add_undefined_to_nullable_types)); } return actions2; - function fix(type2, fixId55, fixAllDescription) { + function fix(type2, fixId56, fixAllDescription) { const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange29(t, sourceFile, typeNode, type2, checker)); - return createCodeFixAction("jdocTypes", changes, [Diagnostics.Change_0_to_1, original, checker.typeToString(type2)], fixId55, fixAllDescription); + return createCodeFixAction("jdocTypes", changes, [Diagnostics.Change_0_to_1, original, checker.typeToString(type2)], fixId56, fixAllDescription); } }, fixIds: [fixIdPlain, fixIdNullable], getAllCodeActions(context) { - const { fixId: fixId55, program, sourceFile } = context; + const { fixId: fixId56, program, sourceFile } = context; const checker = program.getTypeChecker(); - return codeFixAll(context, errorCodes45, (changes, err) => { + return codeFixAll(context, errorCodes46, (changes, err) => { const info = getInfo15(err.file, err.start, checker); if (!info) return; const { typeNode, type } = info; - const fixedType = typeNode.kind === 314 /* JSDocNullableType */ && fixId55 === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; + const fixedType = typeNode.kind === 314 /* JSDocNullableType */ && fixId56 === fixIdNullable ? checker.getNullableType(type, 32768 /* Undefined */) : type; doChange29(changes, sourceFile, typeNode, fixedType, checker); }); } @@ -159555,21 +161347,21 @@ function getType(checker, node) { } // src/services/codefixes/fixMissingCallParentheses.ts -var fixId35 = "fixMissingCallParentheses"; -var errorCodes46 = [ +var fixId36 = "fixMissingCallParentheses"; +var errorCodes47 = [ Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead.code ]; registerCodeFix({ - errorCodes: errorCodes46, - fixIds: [fixId35], + errorCodes: errorCodes47, + fixIds: [fixId36], getCodeActions(context) { const { sourceFile, span } = context; const callName = getCallName(sourceFile, span.start); if (!callName) return; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange30(t, context.sourceFile, callName)); - return [createCodeFixAction(fixId35, changes, Diagnostics.Add_missing_call_parentheses, fixId35, Diagnostics.Add_all_missing_call_parentheses)]; + return [createCodeFixAction(fixId36, changes, Diagnostics.Add_missing_call_parentheses, fixId36, Diagnostics.Add_all_missing_call_parentheses)]; }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes46, (changes, diag2) => { + getAllCodeActions: (context) => codeFixAll(context, errorCodes47, (changes, diag2) => { const callName = getCallName(diag2.file, diag2.start); if (callName) doChange30(changes, diag2.file, callName); }) @@ -159593,14 +161385,14 @@ function getCallName(sourceFile, start) { } // src/services/codefixes/fixMissingTypeAnnotationOnExports.ts -var fixId36 = "fixMissingTypeAnnotationOnExports"; +var fixId37 = "fixMissingTypeAnnotationOnExports"; var addAnnotationFix = "add-annotation"; var addInlineTypeAssertion = "add-type-assertion"; var extractExpression = "extract-expression"; -var errorCodes47 = [ +var errorCodes48 = [ Diagnostics.Function_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations.code, Diagnostics.Method_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations.code, - Diagnostics.At_least_one_accessor_must_have_an_explicit_return_type_annotation_with_isolatedDeclarations.code, + Diagnostics.At_least_one_accessor_must_have_an_explicit_type_annotation_with_isolatedDeclarations.code, Diagnostics.Variable_must_have_an_explicit_type_annotation_with_isolatedDeclarations.code, Diagnostics.Parameter_must_have_an_explicit_type_annotation_with_isolatedDeclarations.code, Diagnostics.Property_must_have_an_explicit_type_annotation_with_isolatedDeclarations.code, @@ -159616,7 +161408,7 @@ var errorCodes47 = [ Diagnostics.Default_exports_can_t_be_inferred_with_isolatedDeclarations.code, Diagnostics.Only_const_arrays_can_be_inferred_with_isolatedDeclarations.code, Diagnostics.Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations_Add_an_explicit_declaration_for_the_properties_assigned_to_this_function.code, - Diagnostics.Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_it_s_type_This_is_not_supported_with_isolatedDeclarations.code, + Diagnostics.Declaration_emit_for_this_parameter_requires_implicitly_adding_undefined_to_its_type_This_is_not_supported_with_isolatedDeclarations.code, Diagnostics.Type_containing_private_name_0_can_t_be_used_with_isolatedDeclarations.code, Diagnostics.Add_satisfies_and_a_type_assertion_to_this_expression_satisfies_T_as_T_to_make_the_type_explicit.code ]; @@ -159637,8 +161429,8 @@ var canHaveTypeAnnotation = /* @__PURE__ */ new Set([ var declarationEmitNodeBuilderFlags2 = 1024 /* MultilineObjectLiterals */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 524288 /* AllowEmptyTuple */ | 4 /* GenerateNamesForShadowedTypeParams */ | 1 /* NoTruncation */; var declarationEmitInternalNodeBuilderFlags2 = 1 /* WriteComputedProps */; registerCodeFix({ - errorCodes: errorCodes47, - fixIds: [fixId36], + errorCodes: errorCodes48, + fixIds: [fixId37], getCodeActions(context) { const fixes = []; addCodeAction(addAnnotationFix, fixes, context, 0 /* Full */, (f) => f.addTypeAnnotation(context.span)); @@ -159652,7 +161444,7 @@ registerCodeFix({ }, getAllCodeActions: (context) => { const changes = withContext(context, 0 /* Full */, (f) => { - eachDiagnostic(context, errorCodes47, (diag2) => { + eachDiagnostic(context, errorCodes48, (diag2) => { f.addTypeAnnotation(diag2); }); }); @@ -159666,7 +161458,7 @@ function addCodeAction(fixName8, fixes, context, typePrintMode, cb) { fixName8, changes.textChanges, changes.result, - fixId36, + fixId37, Diagnostics.Add_all_missing_type_annotations )); } @@ -160422,7 +162214,7 @@ function withContext(context, typePrintMode, cb) { } function typeToTypeNode2(type, enclosingDeclaration, flags = 0 /* None */) { let isTruncated = false; - const result2 = typeToAutoImportableTypeNode(typeChecker, importAdder, type, enclosingDeclaration, scriptTarget, declarationEmitNodeBuilderFlags2 | flags, declarationEmitInternalNodeBuilderFlags2, { + const minimizedTypeNode = typeToMinimizedReferenceType(typeChecker, type, enclosingDeclaration, declarationEmitNodeBuilderFlags2 | flags, declarationEmitInternalNodeBuilderFlags2, { moduleResolverHost: program, trackSymbol() { return true; @@ -160431,6 +162223,10 @@ function withContext(context, typePrintMode, cb) { isTruncated = true; } }); + if (!minimizedTypeNode) { + return void 0; + } + const result2 = typeNodeToAutoImportableTypeNode(minimizedTypeNode, importAdder, scriptTarget); return isTruncated ? factory.createKeywordTypeNode(133 /* AnyKeyword */) : result2; } function typePredicateToTypeNode(typePredicate, enclosingDeclaration, flags = 0 /* None */) { @@ -160486,26 +162282,26 @@ function withContext(context, typePrintMode, cb) { } // src/services/codefixes/fixAwaitInSyncFunction.ts -var fixId37 = "fixAwaitInSyncFunction"; -var errorCodes48 = [ +var fixId38 = "fixAwaitInSyncFunction"; +var errorCodes49 = [ Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function.code ]; registerCodeFix({ - errorCodes: errorCodes48, + errorCodes: errorCodes49, getCodeActions(context) { const { sourceFile, span } = context; const nodes = getNodes3(sourceFile, span.start); if (!nodes) return void 0; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange31(t, sourceFile, nodes)); - return [createCodeFixAction(fixId37, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId37, Diagnostics.Add_all_missing_async_modifiers)]; + return [createCodeFixAction(fixId38, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId38, Diagnostics.Add_all_missing_async_modifiers)]; }, - fixIds: [fixId37], + fixIds: [fixId38], getAllCodeActions: function getAllCodeActionsToFixAwaitInSyncFunction(context) { - const seen = /* @__PURE__ */ new Map(); - return codeFixAll(context, errorCodes48, (changes, diag2) => { + const seen = /* @__PURE__ */ new Set(); + return codeFixAll(context, errorCodes49, (changes, diag2) => { const nodes = getNodes3(diag2.file, diag2.start); if (!nodes || !addToSeen(seen, getNodeId(nodes.insertBefore))) return; doChange31(changes, context.sourceFile, nodes); @@ -160558,21 +162354,21 @@ function doChange31(changes, sourceFile, { insertBefore, returnType }) { } // src/services/codefixes/fixPropertyOverrideAccessor.ts -var errorCodes49 = [ +var errorCodes50 = [ Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property.code, Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor.code ]; -var fixId38 = "fixPropertyOverrideAccessor"; +var fixId39 = "fixPropertyOverrideAccessor"; registerCodeFix({ - errorCodes: errorCodes49, + errorCodes: errorCodes50, getCodeActions(context) { const edits = doChange32(context.sourceFile, context.span.start, context.span.length, context.errorCode, context); if (edits) { - return [createCodeFixAction(fixId38, edits, Diagnostics.Generate_get_and_set_accessors, fixId38, Diagnostics.Generate_get_and_set_accessors_for_all_overriding_properties)]; + return [createCodeFixAction(fixId39, edits, Diagnostics.Generate_get_and_set_accessors, fixId39, Diagnostics.Generate_get_and_set_accessors_for_all_overriding_properties)]; } }, - fixIds: [fixId38], - getAllCodeActions: (context) => codeFixAll(context, errorCodes49, (changes, diag2) => { + fixIds: [fixId39], + getAllCodeActions: (context) => codeFixAll(context, errorCodes50, (changes, diag2) => { const edits = doChange32(diag2.file, diag2.start, diag2.length, diag2.code, context); if (edits) { for (const edit of edits) { @@ -160608,8 +162404,8 @@ function doChange32(file, start, length2, code, context) { } // src/services/codefixes/inferFromUsage.ts -var fixId39 = "inferFromUsage"; -var errorCodes50 = [ +var fixId40 = "inferFromUsage"; +var errorCodes51 = [ // Variable declarations Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code, // Variable uses @@ -160643,7 +162439,7 @@ var errorCodes50 = [ Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code ]; registerCodeFix({ - errorCodes: errorCodes50, + errorCodes: errorCodes51, getCodeActions(context) { const { sourceFile, program, span: { start }, errorCode, cancellationToken, host, preferences } = context; const token = getTokenAtPosition(sourceFile, start); @@ -160663,13 +162459,13 @@ registerCodeFix({ ); }); const name = declaration && getNameOfDeclaration(declaration); - return !name || changes.length === 0 ? void 0 : [createCodeFixAction(fixId39, changes, [getDiagnostic(errorCode, token), getTextOfNode(name)], fixId39, Diagnostics.Infer_all_types_from_usage)]; + return !name || changes.length === 0 ? void 0 : [createCodeFixAction(fixId40, changes, [getDiagnostic(errorCode, token), getTextOfNode(name)], fixId40, Diagnostics.Infer_all_types_from_usage)]; }, - fixIds: [fixId39], + fixIds: [fixId40], getAllCodeActions(context) { const { sourceFile, program, cancellationToken, host, preferences } = context; const markSeen = nodeSeenTracker(); - return codeFixAll(context, errorCodes50, (changes, err) => { + return codeFixAll(context, errorCodes51, (changes, err) => { doChange33(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, preferences); }); } @@ -160679,6 +162475,7 @@ function getDiagnostic(errorCode, token) { case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: case Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage.code: return isSetAccessorDeclaration(getContainingFunction(token)) ? Diagnostics.Infer_type_of_0_from_usage : Diagnostics.Infer_parameter_types_from_usage; + // TODO: GH#18217 case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage.code: return Diagnostics.Infer_parameter_types_from_usage; @@ -160717,6 +162514,7 @@ function doChange33(changes, sourceFile, token, errorCode, program, cancellation const importAdder = createImportAdder(sourceFile, program, preferences, host); errorCode = mapSuggestionDiagnostic(errorCode); switch (errorCode) { + // Variable and Property declarations case Diagnostics.Member_0_implicitly_has_an_1_type.code: case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if (isVariableDeclaration(parent2) && markSeen(parent2) || isPropertyDeclaration(parent2) || isPropertySignature(parent2)) { @@ -160757,12 +162555,14 @@ function doChange33(changes, sourceFile, token, errorCode, program, cancellation } let declaration; switch (errorCode) { + // Parameter declarations case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (isSetAccessorDeclaration(containingFunction)) { annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken); declaration = containingFunction; break; } + // falls through case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { const param = cast(parent2, isParameter); @@ -160770,6 +162570,7 @@ function doChange33(changes, sourceFile, token, errorCode, program, cancellation declaration = param; } break; + // Get Accessor declarations case Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: if (isGetAccessorDeclaration(containingFunction) && isIdentifier(containingFunction.name)) { @@ -160777,12 +162578,14 @@ function doChange33(changes, sourceFile, token, errorCode, program, cancellation declaration = containingFunction; } break; + // Set Accessor declarations case Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: if (isSetAccessorDeclaration(containingFunction)) { annotateSetAccessor(changes, importAdder, sourceFile, containingFunction, program, host, cancellationToken); declaration = containingFunction; } break; + // Function 'this' case Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code: if (ts_textChanges_exports.isThisTypeAnnotatable(containingFunction) && markSeen(containingFunction)) { annotateThis(changes, sourceFile, containingFunction, program, host, cancellationToken); @@ -161164,6 +162967,7 @@ function inferTypeFromReferences(program, references, cancellationToken) { break; } } + // falls through default: return inferTypeFromContextualType(node, usage); } @@ -161191,16 +162995,25 @@ function inferTypeFromReferences(program, references, cancellationToken) { } function inferTypeFromBinaryExpression(node, parent2, usage) { switch (parent2.operatorToken.kind) { + // ExponentiationOperator case 43 /* AsteriskAsteriskToken */: + // MultiplicativeOperator + // falls through case 42 /* AsteriskToken */: case 44 /* SlashToken */: case 45 /* PercentToken */: + // ShiftOperator + // falls through case 48 /* LessThanLessThanToken */: case 49 /* GreaterThanGreaterThanToken */: case 50 /* GreaterThanGreaterThanGreaterThanToken */: + // BitwiseOperator + // falls through case 51 /* AmpersandToken */: case 52 /* BarToken */: case 53 /* CaretToken */: + // CompoundAssignmentOperator + // falls through case 66 /* MinusEqualsToken */: case 68 /* AsteriskAsteriskEqualsToken */: case 67 /* AsteriskEqualsToken */: @@ -161212,7 +163025,11 @@ function inferTypeFromReferences(program, references, cancellationToken) { case 71 /* LessThanLessThanEqualsToken */: case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */: case 72 /* GreaterThanGreaterThanEqualsToken */: + // AdditiveOperator + // falls through case 41 /* MinusToken */: + // RelationalOperator + // falls through case 30 /* LessThanToken */: case 33 /* LessThanEqualsToken */: case 32 /* GreaterThanToken */: @@ -161238,6 +163055,7 @@ function inferTypeFromReferences(program, references, cancellationToken) { usage.isNumberOrString = true; } break; + // AssignmentOperators case 64 /* EqualsToken */: case 35 /* EqualsEqualsToken */: case 37 /* EqualsEqualsEqualsToken */: @@ -161253,6 +163071,7 @@ function inferTypeFromReferences(program, references, cancellationToken) { usage.isString = true; } break; + // LogicalOperator Or NullishCoalescing case 57 /* BarBarToken */: case 61 /* QuestionQuestionToken */: if (node === parent2.left && (node.parent.parent.kind === 260 /* VariableDeclaration */ || isAssignmentExpression( @@ -161600,13 +163419,13 @@ function inferTypeFromReferences(program, references, cancellationToken) { } // src/services/codefixes/fixReturnTypeInAsyncFunction.ts -var fixId40 = "fixReturnTypeInAsyncFunction"; -var errorCodes51 = [ +var fixId41 = "fixReturnTypeInAsyncFunction"; +var errorCodes52 = [ Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0.code ]; registerCodeFix({ - errorCodes: errorCodes51, - fixIds: [fixId40], + errorCodes: errorCodes52, + fixIds: [fixId41], getCodeActions: function getCodeActionsToFixReturnTypeInAsyncFunction(context) { const { sourceFile, program, span } = context; const checker = program.getTypeChecker(); @@ -161617,14 +163436,14 @@ registerCodeFix({ const { returnTypeNode, returnType, promisedTypeNode, promisedType } = info; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange34(t, sourceFile, returnTypeNode, promisedTypeNode)); return [createCodeFixAction( - fixId40, + fixId41, changes, [Diagnostics.Replace_0_with_Promise_1, checker.typeToString(returnType), checker.typeToString(promisedType)], - fixId40, + fixId41, Diagnostics.Fix_all_incorrect_return_type_of_an_async_functions )]; }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes51, (changes, diag2) => { + getAllCodeActions: (context) => codeFixAll(context, errorCodes52, (changes, diag2) => { const info = getInfo16(diag2.file, context.program.getTypeChecker(), diag2.start); if (info) { doChange34(changes, diag2.file, info.returnTypeNode, info.promisedTypeNode); @@ -161660,13 +163479,13 @@ function doChange34(changes, sourceFile, returnTypeNode, promisedTypeNode) { // src/services/codefixes/disableJsDiagnostics.ts var fixName4 = "disableJsDiagnostics"; -var fixId41 = "disableJsDiagnostics"; -var errorCodes52 = mapDefined(Object.keys(Diagnostics), (key) => { +var fixId42 = "disableJsDiagnostics"; +var errorCodes53 = mapDefined(Object.keys(Diagnostics), (key) => { const diag2 = Diagnostics[key]; return diag2.category === 1 /* Error */ ? diag2.code : void 0; }); registerCodeFix({ - errorCodes: errorCodes52, + errorCodes: errorCodes53, getCodeActions: function getCodeActionsToDisableJsDiagnostics(context) { const { sourceFile, program, span, host, formatContext } = context; if (!isInJSFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { @@ -161687,21 +163506,21 @@ registerCodeFix({ ) ]; if (ts_textChanges_exports.isValidLocationToAddComment(sourceFile, span.start)) { - fixes.unshift(createCodeFixAction(fixName4, ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange8(t, sourceFile, span.start)), Diagnostics.Ignore_this_error_message, fixId41, Diagnostics.Add_ts_ignore_to_all_error_messages)); + fixes.unshift(createCodeFixAction(fixName4, ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange9(t, sourceFile, span.start)), Diagnostics.Ignore_this_error_message, fixId42, Diagnostics.Add_ts_ignore_to_all_error_messages)); } return fixes; }, - fixIds: [fixId41], + fixIds: [fixId42], getAllCodeActions: (context) => { const seenLines = /* @__PURE__ */ new Set(); - return codeFixAll(context, errorCodes52, (changes, diag2) => { + return codeFixAll(context, errorCodes53, (changes, diag2) => { if (ts_textChanges_exports.isValidLocationToAddComment(diag2.file, diag2.start)) { - makeChange8(changes, diag2.file, diag2.start, seenLines); + makeChange9(changes, diag2.file, diag2.start, seenLines); } }); } }); -function makeChange8(changes, sourceFile, position, seenLines) { +function makeChange9(changes, sourceFile, position, seenLines) { const { line: lineNumber } = getLineAndCharacterOfPosition(sourceFile, position); if (!seenLines || tryAddToSet(seenLines, lineNumber)) { changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore"); @@ -161757,11 +163576,10 @@ function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, con const optional = !!(symbol.flags & 16777216 /* Optional */); const ambient = !!(enclosingDeclaration.flags & 33554432 /* Ambient */) || isAmbient; const quotePreference = getQuotePreference(sourceFile, preferences); + const flags = 1 /* NoTruncation */ | (quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0 /* None */); switch (kind) { case 171 /* PropertySignature */: case 172 /* PropertyDeclaration */: - let flags = 1 /* NoTruncation */; - flags |= quotePreference === 0 /* Single */ ? 268435456 /* UseSingleQuotesForStringLiteralType */ : 0; let typeNode = checker.typeToTypeNode(type, enclosingDeclaration, flags, 8 /* AllowUnresolvedNames */, getNoopSymbolTrackerWithResolver(context)); if (importAdder) { const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget); @@ -161785,8 +163603,7 @@ function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, con let typeNode2 = checker.typeToTypeNode( type, enclosingDeclaration, - /*flags*/ - void 0, + flags, /*internalFlags*/ void 0, getNoopSymbolTrackerWithResolver(context) @@ -162113,7 +163930,13 @@ function createTypeParameterName(index) { return 84 /* T */ + index <= 90 /* Z */ ? String.fromCharCode(84 /* T */ + index) : `T${index}`; } function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, scriptTarget, flags, internalFlags, tracker) { - let typeNode = checker.typeToTypeNode(type, contextNode, flags, internalFlags, tracker); + const typeNode = checker.typeToTypeNode(type, contextNode, flags, internalFlags, tracker); + if (!typeNode) { + return void 0; + } + return typeNodeToAutoImportableTypeNode(typeNode, importAdder, scriptTarget); +} +function typeNodeToAutoImportableTypeNode(typeNode, importAdder, scriptTarget) { if (typeNode && isImportTypeNode(typeNode)) { const importableReference = tryGetAutoImportableReferenceFromTypeNode(typeNode, scriptTarget); if (importableReference) { @@ -162123,6 +163946,42 @@ function typeToAutoImportableTypeNode(checker, importAdder, type, contextNode, s } return getSynthesizedDeepClone(typeNode); } +function endOfRequiredTypeParameters(checker, type) { + Debug.assert(type.typeArguments); + const fullTypeArguments = type.typeArguments; + const target = type.target; + for (let cutoff = 0; cutoff < fullTypeArguments.length; cutoff++) { + const typeArguments = fullTypeArguments.slice(0, cutoff); + const filledIn = checker.fillMissingTypeArguments( + typeArguments, + target.typeParameters, + cutoff, + /*isJavaScriptImplicitAny*/ + false + ); + if (filledIn.every((fill, i) => fill === fullTypeArguments[i])) { + return cutoff; + } + } + return fullTypeArguments.length; +} +function typeToMinimizedReferenceType(checker, type, contextNode, flags, internalFlags, tracker) { + let typeNode = checker.typeToTypeNode(type, contextNode, flags, internalFlags, tracker); + if (!typeNode) { + return void 0; + } + if (isTypeReferenceNode(typeNode)) { + const genericType = type; + if (genericType.typeArguments && typeNode.typeArguments) { + const cutoff = endOfRequiredTypeParameters(checker, genericType); + if (cutoff < typeNode.typeArguments.length) { + const newTypeArguments = factory.createNodeArray(typeNode.typeArguments.slice(0, cutoff)); + typeNode = factory.updateTypeReferenceNode(typeNode, typeNode.typeName, newTypeArguments); + } + } + } + return typeNode; +} function typePredicateToAutoImportableTypeNode(checker, importAdder, typePredicate, contextNode, scriptTarget, flags, internalFlags, tracker) { let typePredicateNode = checker.typePredicateToTypePredicateNode(typePredicate, contextNode, flags, internalFlags, tracker); if ((typePredicateNode == null ? void 0 : typePredicateNode.type) && isImportTypeNode(typePredicateNode.type)) { @@ -162714,9 +164573,9 @@ var fixName6 = "strictClassInitialization"; var fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions"; var fixIdAddUndefinedType = "addMissingPropertyUndefinedType"; var fixIdAddInitializer = "addMissingPropertyInitializer"; -var errorCodes53 = [Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code]; +var errorCodes54 = [Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor.code]; registerCodeFix({ - errorCodes: errorCodes53, + errorCodes: errorCodes54, getCodeActions: function getCodeActionsForStrictClassInitializationErrors(context) { const info = getInfo17(context.sourceFile, context.span.start); if (!info) return; @@ -162728,7 +164587,7 @@ registerCodeFix({ }, fixIds: [fixIdAddDefiniteAssignmentAssertions, fixIdAddUndefinedType, fixIdAddInitializer], getAllCodeActions: (context) => { - return codeFixAll(context, errorCodes53, (changes, diag2) => { + return codeFixAll(context, errorCodes54, (changes, diag2) => { const info = getInfo17(diag2.file, diag2.start); if (!info) return; switch (context.fixId) { @@ -162851,20 +164710,20 @@ function getDefaultValueFromType(checker, type) { } // src/services/codefixes/requireInTs.ts -var fixId42 = "requireInTs"; -var errorCodes54 = [Diagnostics.require_call_may_be_converted_to_an_import.code]; +var fixId43 = "requireInTs"; +var errorCodes55 = [Diagnostics.require_call_may_be_converted_to_an_import.code]; registerCodeFix({ - errorCodes: errorCodes54, + errorCodes: errorCodes55, getCodeActions(context) { const info = getInfo18(context.sourceFile, context.program, context.span.start, context.preferences); if (!info) { return void 0; } const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange35(t, context.sourceFile, info)); - return [createCodeFixAction(fixId42, changes, Diagnostics.Convert_require_to_import, fixId42, Diagnostics.Convert_all_require_to_import)]; + return [createCodeFixAction(fixId43, changes, Diagnostics.Convert_require_to_import, fixId43, Diagnostics.Convert_all_require_to_import)]; }, - fixIds: [fixId42], - getAllCodeActions: (context) => codeFixAll(context, errorCodes54, (changes, diag2) => { + fixIds: [fixId43], + getAllCodeActions: (context) => codeFixAll(context, errorCodes55, (changes, diag2) => { const info = getInfo18(diag2.file, context.program, diag2.start, context.preferences); if (info) { doChange35(changes, context.sourceFile, info); @@ -162941,19 +164800,19 @@ function tryCreateNamedImportsFromObjectBindingPattern(node) { } // src/services/codefixes/useDefaultImport.ts -var fixId43 = "useDefaultImport"; -var errorCodes55 = [Diagnostics.Import_may_be_converted_to_a_default_import.code]; +var fixId44 = "useDefaultImport"; +var errorCodes56 = [Diagnostics.Import_may_be_converted_to_a_default_import.code]; registerCodeFix({ - errorCodes: errorCodes55, + errorCodes: errorCodes56, getCodeActions(context) { const { sourceFile, span: { start } } = context; const info = getInfo19(sourceFile, start); if (!info) return void 0; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange36(t, sourceFile, info, context.preferences)); - return [createCodeFixAction(fixId43, changes, Diagnostics.Convert_to_default_import, fixId43, Diagnostics.Convert_all_to_default_imports)]; + return [createCodeFixAction(fixId44, changes, Diagnostics.Convert_to_default_import, fixId44, Diagnostics.Convert_all_to_default_imports)]; }, - fixIds: [fixId43], - getAllCodeActions: (context) => codeFixAll(context, errorCodes55, (changes, diag2) => { + fixIds: [fixId44], + getAllCodeActions: (context) => codeFixAll(context, errorCodes56, (changes, diag2) => { const info = getInfo19(diag2.file, diag2.start); if (info) doChange36(changes, diag2.file, info, context.preferences); }) @@ -162980,24 +164839,24 @@ function doChange36(changes, sourceFile, info, preferences) { } // src/services/codefixes/useBigintLiteral.ts -var fixId44 = "useBigintLiteral"; -var errorCodes56 = [ +var fixId45 = "useBigintLiteral"; +var errorCodes57 = [ Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers.code ]; registerCodeFix({ - errorCodes: errorCodes56, + errorCodes: errorCodes57, getCodeActions: function getCodeActionsToUseBigintLiteral(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange9(t, context.sourceFile, context.span)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange10(t, context.sourceFile, context.span)); if (changes.length > 0) { - return [createCodeFixAction(fixId44, changes, Diagnostics.Convert_to_a_bigint_numeric_literal, fixId44, Diagnostics.Convert_all_to_bigint_numeric_literals)]; + return [createCodeFixAction(fixId45, changes, Diagnostics.Convert_to_a_bigint_numeric_literal, fixId45, Diagnostics.Convert_all_to_bigint_numeric_literals)]; } }, - fixIds: [fixId44], + fixIds: [fixId45], getAllCodeActions: (context) => { - return codeFixAll(context, errorCodes56, (changes, diag2) => makeChange9(changes, diag2.file, diag2)); + return codeFixAll(context, errorCodes57, (changes, diag2) => makeChange10(changes, diag2.file, diag2)); } }); -function makeChange9(changeTracker, sourceFile, span) { +function makeChange10(changeTracker, sourceFile, span) { const numericLiteral = tryCast(getTokenAtPosition(sourceFile, span.start), isNumericLiteral); if (!numericLiteral) { return; @@ -163008,18 +164867,18 @@ function makeChange9(changeTracker, sourceFile, span) { // src/services/codefixes/fixAddModuleReferTypeMissingTypeof.ts var fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof"; -var fixId45 = fixIdAddMissingTypeof; -var errorCodes57 = [Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code]; +var fixId46 = fixIdAddMissingTypeof; +var errorCodes58 = [Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code]; registerCodeFix({ - errorCodes: errorCodes57, + errorCodes: errorCodes58, getCodeActions: function getCodeActionsToAddMissingTypeof(context) { const { sourceFile, span } = context; const importType = getImportTypeNode(sourceFile, span.start); const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange37(t, sourceFile, importType)); - return [createCodeFixAction(fixId45, changes, Diagnostics.Add_missing_typeof, fixId45, Diagnostics.Add_missing_typeof)]; + return [createCodeFixAction(fixId46, changes, Diagnostics.Add_missing_typeof, fixId46, Diagnostics.Add_missing_typeof)]; }, - fixIds: [fixId45], - getAllCodeActions: (context) => codeFixAll(context, errorCodes57, (changes, diag2) => doChange37(changes, context.sourceFile, getImportTypeNode(diag2.file, diag2.start))) + fixIds: [fixId46], + getAllCodeActions: (context) => codeFixAll(context, errorCodes58, (changes, diag2) => doChange37(changes, context.sourceFile, getImportTypeNode(diag2.file, diag2.start))) }); function getImportTypeNode(sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); @@ -163042,9 +164901,9 @@ function doChange37(changes, sourceFile, importType) { // src/services/codefixes/wrapJsxInFragment.ts var fixID2 = "wrapJsxInFragment"; -var errorCodes58 = [Diagnostics.JSX_expressions_must_have_one_parent_element.code]; +var errorCodes59 = [Diagnostics.JSX_expressions_must_have_one_parent_element.code]; registerCodeFix({ - errorCodes: errorCodes58, + errorCodes: errorCodes59, getCodeActions: function getCodeActionsToWrapJsxInFragment(context) { const { sourceFile, span } = context; const node = findNodeToFix(sourceFile, span.start); @@ -163053,7 +164912,7 @@ registerCodeFix({ return [createCodeFixAction(fixID2, changes, Diagnostics.Wrap_in_JSX_fragment, fixID2, Diagnostics.Wrap_all_unparented_JSX_in_JSX_fragment)]; }, fixIds: [fixID2], - getAllCodeActions: (context) => codeFixAll(context, errorCodes58, (changes, diag2) => { + getAllCodeActions: (context) => codeFixAll(context, errorCodes59, (changes, diag2) => { const node = findNodeToFix(context.sourceFile, diag2.start); if (!node) return void 0; doChange38(changes, context.sourceFile, node); @@ -163092,18 +164951,18 @@ function flattenInvalidBinaryExpr(node) { } // src/services/codefixes/wrapDecoratorInParentheses.ts -var fixId46 = "wrapDecoratorInParentheses"; -var errorCodes59 = [Diagnostics.Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator.code]; +var fixId47 = "wrapDecoratorInParentheses"; +var errorCodes60 = [Diagnostics.Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator.code]; registerCodeFix({ - errorCodes: errorCodes59, + errorCodes: errorCodes60, getCodeActions: function getCodeActionsToWrapDecoratorExpressionInParentheses(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange10(t, context.sourceFile, context.span.start)); - return [createCodeFixAction(fixId46, changes, Diagnostics.Wrap_in_parentheses, fixId46, Diagnostics.Wrap_all_invalid_decorator_expressions_in_parentheses)]; + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange11(t, context.sourceFile, context.span.start)); + return [createCodeFixAction(fixId47, changes, Diagnostics.Wrap_in_parentheses, fixId47, Diagnostics.Wrap_all_invalid_decorator_expressions_in_parentheses)]; }, - fixIds: [fixId46], - getAllCodeActions: (context) => codeFixAll(context, errorCodes59, (changes, diag2) => makeChange10(changes, diag2.file, diag2.start)) + fixIds: [fixId47], + getAllCodeActions: (context) => codeFixAll(context, errorCodes60, (changes, diag2) => makeChange11(changes, diag2.file, diag2.start)) }); -function makeChange10(changeTracker, sourceFile, pos) { +function makeChange11(changeTracker, sourceFile, pos) { const token = getTokenAtPosition(sourceFile, pos); const decorator = findAncestor(token, isDecorator); Debug.assert(!!decorator, "Expected position to be owned by a decorator."); @@ -163112,20 +164971,20 @@ function makeChange10(changeTracker, sourceFile, pos) { } // src/services/codefixes/convertToMappedObjectType.ts -var fixId47 = "fixConvertToMappedObjectType"; -var errorCodes60 = [Diagnostics.An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead.code]; +var fixId48 = "fixConvertToMappedObjectType"; +var errorCodes61 = [Diagnostics.An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead.code]; registerCodeFix({ - errorCodes: errorCodes60, + errorCodes: errorCodes61, getCodeActions: function getCodeActionsToConvertToMappedTypeObject(context) { const { sourceFile, span } = context; const info = getInfo20(sourceFile, span.start); if (!info) return void 0; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange39(t, sourceFile, info)); const name = idText(info.container.name); - return [createCodeFixAction(fixId47, changes, [Diagnostics.Convert_0_to_mapped_object_type, name], fixId47, [Diagnostics.Convert_0_to_mapped_object_type, name])]; + return [createCodeFixAction(fixId48, changes, [Diagnostics.Convert_0_to_mapped_object_type, name], fixId48, [Diagnostics.Convert_0_to_mapped_object_type, name])]; }, - fixIds: [fixId47], - getAllCodeActions: (context) => codeFixAll(context, errorCodes60, (changes, diag2) => { + fixIds: [fixId48], + getAllCodeActions: (context) => codeFixAll(context, errorCodes61, (changes, diag2) => { const info = getInfo20(diag2.file, diag2.start); if (info) doChange39(changes, diag2.file, info); }) @@ -163170,12 +165029,12 @@ function doChange39(changes, sourceFile, { indexSignature, container }) { } // src/services/codefixes/removeAccidentalCallParentheses.ts -var fixId48 = "removeAccidentalCallParentheses"; -var errorCodes61 = [ +var fixId49 = "removeAccidentalCallParentheses"; +var errorCodes62 = [ Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without.code ]; registerCodeFix({ - errorCodes: errorCodes61, + errorCodes: errorCodes62, getCodeActions(context) { const callExpression = findAncestor(getTokenAtPosition(context.sourceFile, context.span.start), isCallExpression); if (!callExpression) { @@ -163184,30 +165043,30 @@ registerCodeFix({ const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => { t.deleteRange(context.sourceFile, { pos: callExpression.expression.end, end: callExpression.end }); }); - return [createCodeFixActionWithoutFixAll(fixId48, changes, Diagnostics.Remove_parentheses)]; + return [createCodeFixActionWithoutFixAll(fixId49, changes, Diagnostics.Remove_parentheses)]; }, - fixIds: [fixId48] + fixIds: [fixId49] }); // src/services/codefixes/removeUnnecessaryAwait.ts -var fixId49 = "removeUnnecessaryAwait"; -var errorCodes62 = [ +var fixId50 = "removeUnnecessaryAwait"; +var errorCodes63 = [ Diagnostics.await_has_no_effect_on_the_type_of_this_expression.code ]; registerCodeFix({ - errorCodes: errorCodes62, + errorCodes: errorCodes63, getCodeActions: function getCodeActionsToRemoveUnnecessaryAwait(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange11(t, context.sourceFile, context.span)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange12(t, context.sourceFile, context.span)); if (changes.length > 0) { - return [createCodeFixAction(fixId49, changes, Diagnostics.Remove_unnecessary_await, fixId49, Diagnostics.Remove_all_unnecessary_uses_of_await)]; + return [createCodeFixAction(fixId50, changes, Diagnostics.Remove_unnecessary_await, fixId50, Diagnostics.Remove_all_unnecessary_uses_of_await)]; } }, - fixIds: [fixId49], + fixIds: [fixId50], getAllCodeActions: (context) => { - return codeFixAll(context, errorCodes62, (changes, diag2) => makeChange11(changes, diag2.file, diag2)); + return codeFixAll(context, errorCodes63, (changes, diag2) => makeChange12(changes, diag2.file, diag2)); } }); -function makeChange11(changeTracker, sourceFile, span) { +function makeChange12(changeTracker, sourceFile, span) { const awaitKeyword = tryCast(getTokenAtPosition(sourceFile, span.start), (node) => node.kind === 135 /* AwaitKeyword */); const awaitExpression = awaitKeyword && tryCast(awaitKeyword.parent, isAwaitExpression); if (!awaitExpression) { @@ -163232,20 +165091,20 @@ function makeChange11(changeTracker, sourceFile, span) { } // src/services/codefixes/splitTypeOnlyImport.ts -var errorCodes63 = [Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both.code]; -var fixId50 = "splitTypeOnlyImport"; +var errorCodes64 = [Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both.code]; +var fixId51 = "splitTypeOnlyImport"; registerCodeFix({ - errorCodes: errorCodes63, - fixIds: [fixId50], + errorCodes: errorCodes64, + fixIds: [fixId51], getCodeActions: function getCodeActionsToSplitTypeOnlyImport(context) { const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => { return splitTypeOnlyImport(t, getImportDeclaration2(context.sourceFile, context.span), context); }); if (changes.length) { - return [createCodeFixAction(fixId50, changes, Diagnostics.Split_into_two_separate_import_declarations, fixId50, Diagnostics.Split_all_invalid_type_only_imports)]; + return [createCodeFixAction(fixId51, changes, Diagnostics.Split_into_two_separate_import_declarations, fixId51, Diagnostics.Split_all_invalid_type_only_imports)]; } }, - getAllCodeActions: (context) => codeFixAll(context, errorCodes63, (changes, error2) => { + getAllCodeActions: (context) => codeFixAll(context, errorCodes64, (changes, error2) => { splitTypeOnlyImport(changes, getImportDeclaration2(context.sourceFile, error2), context); }) }); @@ -163294,22 +165153,22 @@ function splitTypeOnlyImport(changes, importDeclaration, context) { } // src/services/codefixes/convertConstToLet.ts -var fixId51 = "fixConvertConstToLet"; -var errorCodes64 = [Diagnostics.Cannot_assign_to_0_because_it_is_a_constant.code]; +var fixId52 = "fixConvertConstToLet"; +var errorCodes65 = [Diagnostics.Cannot_assign_to_0_because_it_is_a_constant.code]; registerCodeFix({ - errorCodes: errorCodes64, + errorCodes: errorCodes65, getCodeActions: function getCodeActionsToConvertConstToLet(context) { const { sourceFile, span, program } = context; const info = getInfo21(sourceFile, span.start, program); if (info === void 0) return; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange40(t, sourceFile, info.token)); - return [createCodeFixActionMaybeFixAll(fixId51, changes, Diagnostics.Convert_const_to_let, fixId51, Diagnostics.Convert_all_const_to_let)]; + return [createCodeFixActionMaybeFixAll(fixId52, changes, Diagnostics.Convert_const_to_let, fixId52, Diagnostics.Convert_all_const_to_let)]; }, getAllCodeActions: (context) => { const { program } = context; - const seen = /* @__PURE__ */ new Map(); + const seen = /* @__PURE__ */ new Set(); return createCombinedCodeActions(ts_textChanges_exports.ChangeTracker.with(context, (changes) => { - eachDiagnostic(context, errorCodes64, (diag2) => { + eachDiagnostic(context, errorCodes65, (diag2) => { const info = getInfo21(diag2.file, diag2.start, program); if (info) { if (addToSeen(seen, getSymbolId(info.symbol))) { @@ -163320,7 +165179,7 @@ registerCodeFix({ }); })); }, - fixIds: [fixId51] + fixIds: [fixId52] }); function getInfo21(sourceFile, pos, program) { var _a; @@ -163338,26 +165197,26 @@ function doChange40(changes, sourceFile, token) { } // src/services/codefixes/fixExpectedComma.ts -var fixId52 = "fixExpectedComma"; +var fixId53 = "fixExpectedComma"; var expectedErrorCode = Diagnostics._0_expected.code; -var errorCodes65 = [expectedErrorCode]; +var errorCodes66 = [expectedErrorCode]; registerCodeFix({ - errorCodes: errorCodes65, + errorCodes: errorCodes66, getCodeActions(context) { const { sourceFile } = context; const info = getInfo22(sourceFile, context.span.start, context.errorCode); if (!info) return void 0; const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => doChange41(t, sourceFile, info)); return [createCodeFixAction( - fixId52, + fixId53, changes, [Diagnostics.Change_0_to_1, ";", ","], - fixId52, + fixId53, [Diagnostics.Change_0_to_1, ";", ","] )]; }, - fixIds: [fixId52], - getAllCodeActions: (context) => codeFixAll(context, errorCodes65, (changes, diag2) => { + fixIds: [fixId53], + getAllCodeActions: (context) => codeFixAll(context, errorCodes66, (changes, diag2) => { const info = getInfo22(diag2.file, diag2.start, diag2.code); if (info) doChange41(changes, context.sourceFile, info); }) @@ -163373,25 +165232,25 @@ function doChange41(changes, sourceFile, { node }) { // src/services/codefixes/fixAddVoidToPromise.ts var fixName7 = "addVoidToPromise"; -var fixId53 = "addVoidToPromise"; -var errorCodes66 = [ +var fixId54 = "addVoidToPromise"; +var errorCodes67 = [ Diagnostics.Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_without_arguments.code, Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise.code ]; registerCodeFix({ - errorCodes: errorCodes66, - fixIds: [fixId53], + errorCodes: errorCodes67, + fixIds: [fixId54], getCodeActions(context) { - const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange12(t, context.sourceFile, context.span, context.program)); + const changes = ts_textChanges_exports.ChangeTracker.with(context, (t) => makeChange13(t, context.sourceFile, context.span, context.program)); if (changes.length > 0) { - return [createCodeFixAction(fixName7, changes, Diagnostics.Add_void_to_Promise_resolved_without_a_value, fixId53, Diagnostics.Add_void_to_all_Promises_resolved_without_a_value)]; + return [createCodeFixAction(fixName7, changes, Diagnostics.Add_void_to_Promise_resolved_without_a_value, fixId54, Diagnostics.Add_void_to_all_Promises_resolved_without_a_value)]; } }, getAllCodeActions(context) { - return codeFixAll(context, errorCodes66, (changes, diag2) => makeChange12(changes, diag2.file, diag2, context.program, /* @__PURE__ */ new Set())); + return codeFixAll(context, errorCodes67, (changes, diag2) => makeChange13(changes, diag2.file, diag2, context.program, /* @__PURE__ */ new Set())); } }); -function makeChange12(changes, sourceFile, span, program, seen) { +function makeChange13(changes, sourceFile, span, program, seen) { const node = getTokenAtPosition(sourceFile, span.start); if (!isIdentifier(node) || !isCallExpression(node.parent) || node.parent.expression !== node || node.parent.arguments.length !== 0) return; const checker = program.getTypeChecker(); @@ -163483,6 +165342,8 @@ var SortText = { return sortText + "1"; } }; +var allCommitCharacters = [".", ",", ";"]; +var noCommaCommitCharacters = [".", ";"]; var CompletionSource = /* @__PURE__ */ ((CompletionSource2) => { CompletionSource2["ThisProperty"] = "ThisProperty/"; CompletionSource2["ClassMemberSnippet"] = "ClassMemberSnippet/"; @@ -163589,7 +165450,7 @@ function getDefaultCommitCharacters(isNewIdentifierLocation) { if (isNewIdentifierLocation) { return []; } - return [".", ",", ";"]; + return allCommitCharacters; } function getCompletionsAtPosition(host, program, log, sourceFile, position, preferences, triggerCharacter, completionKind, cancellationToken, formatContext, includeSymbol = false) { var _a; @@ -164087,7 +165948,8 @@ function completionInfoFromData(sourceFile, host, program, compilerOptions, log, importStatementCompletion, insideJsDocTagTypeExpression, symbolToSortTextMap, - hasUnresolvedAutoImports + hasUnresolvedAutoImports, + defaultCommitCharacters } = completionData; let literals = completionData.literals; const checker = program.getTypeChecker(); @@ -164205,7 +166067,7 @@ function completionInfoFromData(sourceFile, host, program, compilerOptions, log, isNewIdentifierLocation, optionalReplacementSpan: getOptionalReplacementSpan(location), entries, - defaultCommitCharacters: getDefaultCommitCharacters(isNewIdentifierLocation) + defaultCommitCharacters: defaultCommitCharacters ?? getDefaultCommitCharacters(isNewIdentifierLocation) }; } function isCheckedFile(sourceFile, compilerOptions) { @@ -164540,9 +166402,13 @@ function createCompletionEntry(symbol, sortText, replacementToken, contextToken, if (parentNamedImportOrExport) { const languageVersion = getEmitScriptTarget(host.getCompilationSettings()); if (!isIdentifierText(name, languageVersion)) { - insertText = JSON.stringify(name); + insertText = quotePropertyName(sourceFile, preferences, name); if (parentNamedImportOrExport.kind === 275 /* NamedImports */) { - insertText += " as " + generateIdentifierForArbitraryString(name, languageVersion); + scanner.setText(sourceFile.text); + scanner.resetTokenState(position); + if (!(scanner.scan() === 130 /* AsKeyword */ && scanner.scan() === 80 /* Identifier */)) { + insertText += " as " + generateIdentifierForArbitraryString(name, languageVersion); + } } } else if (parentNamedImportOrExport.kind === 275 /* NamedImports */) { const possibleToken = stringToToken(name); @@ -165104,7 +166970,7 @@ function getSourceFromOrigin(origin) { } function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, contextToken, location, position, sourceFile, host, program, target, log, kind, preferences, compilerOptions, formatContext, isTypeOnlyLocation, propertyAccessToConvert, jsxIdentifierExpected, isJsxInitializer, importStatementCompletion, recommendedCompletion, symbolToOriginInfoMap, symbolToSortTextMap, isJsxIdentifierExpected, isRightOfOpenTag, includeSymbol = false) { const start = timestamp(); - const variableOrParameterDeclaration = getVariableOrParameterDeclaration(contextToken, location); + const closestSymbolDeclaration = getClosestSymbolDeclaration(contextToken, location); const useSemicolons = probablyUsesSemicolons(sourceFile); const typeChecker = program.getTypeChecker(); const uniques = /* @__PURE__ */ new Map(); @@ -165174,15 +167040,26 @@ function getCompletionEntriesFromSymbols(symbols, entries, replacementToken, con if (isExportAssignment(location.parent)) { return true; } - if (tryCast(variableOrParameterDeclaration, isVariableDeclaration) && symbol.valueDeclaration === variableOrParameterDeclaration) { + if (tryCast(closestSymbolDeclaration, isVariableDeclaration) && symbol.valueDeclaration === closestSymbolDeclaration) { return false; } const symbolDeclaration = symbol.valueDeclaration ?? ((_a = symbol.declarations) == null ? void 0 : _a[0]); - if (variableOrParameterDeclaration && symbolDeclaration && (isTypeParameterDeclaration(variableOrParameterDeclaration) && isTypeParameterDeclaration(symbolDeclaration) || isParameter(variableOrParameterDeclaration) && isParameter(symbolDeclaration))) { - const symbolDeclarationPos = symbolDeclaration.pos; - const parameters = isParameter(variableOrParameterDeclaration) ? variableOrParameterDeclaration.parent.parameters : isInferTypeNode(variableOrParameterDeclaration.parent) ? void 0 : variableOrParameterDeclaration.parent.typeParameters; - if (symbolDeclarationPos >= variableOrParameterDeclaration.pos && parameters && symbolDeclarationPos < parameters.end) { - return false; + if (closestSymbolDeclaration && symbolDeclaration) { + if (isParameter(closestSymbolDeclaration) && isParameter(symbolDeclaration)) { + const parameters = closestSymbolDeclaration.parent.parameters; + if (symbolDeclaration.pos >= closestSymbolDeclaration.pos && symbolDeclaration.pos < parameters.end) { + return false; + } + } else if (isTypeParameterDeclaration(closestSymbolDeclaration) && isTypeParameterDeclaration(symbolDeclaration)) { + if (closestSymbolDeclaration === symbolDeclaration && (contextToken == null ? void 0 : contextToken.kind) === 96 /* ExtendsKeyword */) { + return false; + } + if (isInTypeParameterDefault(contextToken) && !isInferTypeNode(closestSymbolDeclaration.parent)) { + const typeParameters = closestSymbolDeclaration.parent.typeParameters; + if (typeParameters && symbolDeclaration.pos >= closestSymbolDeclaration.pos && symbolDeclaration.pos < typeParameters.end) { + return false; + } + } } } const symbolOrigin = skipAlias(symbol, typeChecker); @@ -165499,6 +167376,7 @@ function getContextualType(previousToken, position, sourceFile, checker) { switch (parent2.kind) { case 260 /* VariableDeclaration */: return checker.getContextualType(parent2.initializer); + // TODO: GH#18217 case 226 /* BinaryExpression */: return checker.getTypeAtLocation(parent2.left); case 291 /* JsxAttribute */: @@ -165604,6 +167482,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, let keywordFilters = 0 /* None */; let isNewIdentifierLocation = false; let flags = 0 /* None */; + let defaultCommitCharacters; if (contextToken) { const importStatementCompletionInfo = getImportStatementCompletionInfo(contextToken, sourceFile); if (importStatementCompletionInfo.keywordCompletion) { @@ -165623,7 +167502,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, } if (!importStatementCompletionInfo.replacementSpan && isCompletionListBlocker(contextToken)) { log("Returning an empty list because completion was requested in an invalid position."); - return keywordFilters ? keywordCompletionData(keywordFilters, isJsOnlyLocation, isNewIdentifierDefinitionLocation()) : void 0; + return keywordFilters ? keywordCompletionData(keywordFilters, isJsOnlyLocation, computeCommitCharactersAndIsNewIdentifier().isNewIdentifierLocation) : void 0; } let parent2 = contextToken.parent; if (contextToken.kind === 25 /* DotToken */ || contextToken.kind === 29 /* QuestionDotToken */) { @@ -165684,6 +167563,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, if (!binaryExpressionMayBeOpenTag(parent2)) { break; } + // falls through case 285 /* JsxSelfClosingElement */: case 284 /* JsxElement */: case 286 /* JsxOpeningElement */: @@ -165725,7 +167605,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, let importSpecifierResolver; const symbolToOriginInfoMap = []; const symbolToSortTextMap = []; - const seenPropertySymbols = /* @__PURE__ */ new Map(); + const seenPropertySymbols = /* @__PURE__ */ new Set(); const isTypeOnlyLocation = isTypeOnlyCompletion(); const getModuleSpecifierResolutionHost = memoizeOne((isFromPackageJson) => { return createModuleSpecifierResolutionHost(isFromPackageJson ? host.getPackageJsonAutoImportProvider() : program, host); @@ -165782,7 +167662,8 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, isRightOfDotOrQuestionDot: isRightOfDot || isRightOfQuestionDot, importStatementCompletion, hasUnresolvedAutoImports, - flags + flags, + defaultCommitCharacters }; function isTagWithTypeExpression(tag) { switch (tag.kind) { @@ -165817,7 +167698,10 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, const isRhsOfImportDeclaration = isInRightSideOfInternalImportEqualsDeclaration(node); if (isEntityName(node) || isImportType || isPropertyAccessExpression(node)) { const isNamespaceName = isModuleDeclaration(node.parent); - if (isNamespaceName) isNewIdentifierLocation = true; + if (isNamespaceName) { + isNewIdentifierLocation = true; + defaultCommitCharacters = []; + } let symbol = typeChecker.getSymbolAtLocation(node); if (symbol) { symbol = skipAlias(symbol, typeChecker); @@ -165887,9 +167771,13 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, } } function addTypeProperties(type, insertAwait, insertQuestionDot) { - isNewIdentifierLocation = !!type.getStringIndexType(); + if (type.getStringIndexType()) { + isNewIdentifierLocation = true; + defaultCommitCharacters = []; + } if (isRightOfQuestionDot && some(type.getCallSignatures())) { isNewIdentifierLocation = true; + defaultCommitCharacters ?? (defaultCommitCharacters = allCommitCharacters); } const propertyAccess = node.kind === 205 /* ImportType */ ? node : node.parent; if (inCheckedFile) { @@ -166028,7 +167916,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, function getGlobalCompletions() { keywordFilters = tryGetFunctionLikeBodyCompletionContainer(contextToken) ? 5 /* FunctionLikeBodyKeywords */ : 1 /* All */; completionKind = 1 /* Global */; - isNewIdentifierLocation = isNewIdentifierDefinitionLocation(); + ({ isNewIdentifierLocation, defaultCommitCharacters } = computeCommitCharactersAndIsNewIdentifier()); if (previousToken !== contextToken) { Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); } @@ -166190,18 +168078,11 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, } ); function isImportableExportInfo(info) { - const moduleFile = tryCast(info.moduleSymbol.valueDeclaration, isSourceFile); - if (!moduleFile) { - const moduleName = stripQuotes(info.moduleSymbol.name); - if (ts_JsTyping_exports.nodeCoreModules.has(moduleName) && startsWith(moduleName, "node:") !== shouldUseUriStyleNodeCoreModules(sourceFile, program)) { - return false; - } - return ((packageJsonFilter == null ? void 0 : packageJsonFilter.allowsImportingAmbientModule(info.moduleSymbol, getModuleSpecifierResolutionHost(info.isFromPackageJson))) ?? true) || fileContainsPackageImport(sourceFile, moduleName); - } - return isImportableFile( + return isImportable( info.isFromPackageJson ? packageJsonAutoImportProvider : program, sourceFile, - moduleFile, + tryCast(info.moduleSymbol.valueDeclaration, isSourceFile), + info.moduleSymbol, preferences, packageJsonFilter, getModuleSpecifierResolutionHost(info.isFromPackageJson), @@ -166294,41 +168175,121 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, } return false; } - function isNewIdentifierDefinitionLocation() { + function computeCommitCharactersAndIsNewIdentifier() { if (contextToken) { const containingNodeKind = contextToken.parent.kind; const tokenKind = keywordForNode(contextToken); switch (tokenKind) { case 28 /* CommaToken */: - return containingNodeKind === 213 /* CallExpression */ || containingNodeKind === 176 /* Constructor */ || containingNodeKind === 214 /* NewExpression */ || containingNodeKind === 209 /* ArrayLiteralExpression */ || containingNodeKind === 226 /* BinaryExpression */ || containingNodeKind === 184 /* FunctionType */ || containingNodeKind === 210 /* ObjectLiteralExpression */; + switch (containingNodeKind) { + case 213 /* CallExpression */: + // func( a, | + case 214 /* NewExpression */: { + const expression = contextToken.parent.expression; + if (getLineAndCharacterOfPosition(sourceFile, expression.end).line !== getLineAndCharacterOfPosition(sourceFile, position).line) { + return { defaultCommitCharacters: noCommaCommitCharacters, isNewIdentifierLocation: true }; + } + return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: true }; + } + case 226 /* BinaryExpression */: + return { defaultCommitCharacters: noCommaCommitCharacters, isNewIdentifierLocation: true }; + case 176 /* Constructor */: + // constructor( a, | /* public, protected, private keywords are allowed here, so show completion */ + case 184 /* FunctionType */: + // var x: (s: string, list| + case 210 /* ObjectLiteralExpression */: + return { defaultCommitCharacters: [], isNewIdentifierLocation: true }; + case 209 /* ArrayLiteralExpression */: + return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: true }; + default: + return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false }; + } case 21 /* OpenParenToken */: - return containingNodeKind === 213 /* CallExpression */ || containingNodeKind === 176 /* Constructor */ || containingNodeKind === 214 /* NewExpression */ || containingNodeKind === 217 /* ParenthesizedExpression */ || containingNodeKind === 196 /* ParenthesizedType */; + switch (containingNodeKind) { + case 213 /* CallExpression */: + // func( | + case 214 /* NewExpression */: { + const expression = contextToken.parent.expression; + if (getLineAndCharacterOfPosition(sourceFile, expression.end).line !== getLineAndCharacterOfPosition(sourceFile, position).line) { + return { defaultCommitCharacters: noCommaCommitCharacters, isNewIdentifierLocation: true }; + } + return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: true }; + } + case 217 /* ParenthesizedExpression */: + return { defaultCommitCharacters: noCommaCommitCharacters, isNewIdentifierLocation: true }; + case 176 /* Constructor */: + // constructor( | + case 196 /* ParenthesizedType */: + return { defaultCommitCharacters: [], isNewIdentifierLocation: true }; + default: + return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false }; + } case 23 /* OpenBracketToken */: - return containingNodeKind === 209 /* ArrayLiteralExpression */ || containingNodeKind === 181 /* IndexSignature */ || containingNodeKind === 167 /* ComputedPropertyName */; + switch (containingNodeKind) { + case 209 /* ArrayLiteralExpression */: + // [ | + case 181 /* IndexSignature */: + // [ | : string ] + case 189 /* TupleType */: + // [ | : string ] + case 167 /* ComputedPropertyName */: + return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: true }; + default: + return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false }; + } case 144 /* ModuleKeyword */: + // module | case 145 /* NamespaceKeyword */: + // namespace | case 102 /* ImportKeyword */: - return true; + return { defaultCommitCharacters: [], isNewIdentifierLocation: true }; case 25 /* DotToken */: - return containingNodeKind === 267 /* ModuleDeclaration */; + switch (containingNodeKind) { + case 267 /* ModuleDeclaration */: + return { defaultCommitCharacters: [], isNewIdentifierLocation: true }; + default: + return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false }; + } case 19 /* OpenBraceToken */: - return containingNodeKind === 263 /* ClassDeclaration */ || containingNodeKind === 210 /* ObjectLiteralExpression */; + switch (containingNodeKind) { + case 263 /* ClassDeclaration */: + // class A { | + case 210 /* ObjectLiteralExpression */: + return { defaultCommitCharacters: [], isNewIdentifierLocation: true }; + default: + return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false }; + } case 64 /* EqualsToken */: - return containingNodeKind === 260 /* VariableDeclaration */ || containingNodeKind === 226 /* BinaryExpression */; + switch (containingNodeKind) { + case 260 /* VariableDeclaration */: + // const x = a| + case 226 /* BinaryExpression */: + return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: true }; + default: + return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false }; + } case 16 /* TemplateHead */: - return containingNodeKind === 228 /* TemplateExpression */; + return { + defaultCommitCharacters: allCommitCharacters, + isNewIdentifierLocation: containingNodeKind === 228 /* TemplateExpression */ + // `aa ${| + }; case 17 /* TemplateMiddle */: - return containingNodeKind === 239 /* TemplateSpan */; + return { + defaultCommitCharacters: allCommitCharacters, + isNewIdentifierLocation: containingNodeKind === 239 /* TemplateSpan */ + // `aa ${10} dd ${| + }; case 134 /* AsyncKeyword */: - return containingNodeKind === 174 /* MethodDeclaration */ || containingNodeKind === 304 /* ShorthandPropertyAssignment */; + return containingNodeKind === 174 /* MethodDeclaration */ || containingNodeKind === 304 /* ShorthandPropertyAssignment */ ? { defaultCommitCharacters: [], isNewIdentifierLocation: true } : { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false }; case 42 /* AsteriskToken */: - return containingNodeKind === 174 /* MethodDeclaration */; + return containingNodeKind === 174 /* MethodDeclaration */ ? { defaultCommitCharacters: [], isNewIdentifierLocation: true } : { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false }; } if (isClassMemberCompletionKeyword(tokenKind)) { - return true; + return { defaultCommitCharacters: [], isNewIdentifierLocation: true }; } } - return false; + return { defaultCommitCharacters: allCommitCharacters, isNewIdentifierLocation: false }; } function isInStringOrRegularExpressionOrTemplateLiteral(contextToken2) { return (isRegularExpressionLiteral(contextToken2) || isStringTextContainingNode(contextToken2)) && (rangeContainsPositionExclusive(contextToken2, position) || position === contextToken2.end && (!!contextToken2.isUnterminated || isRegularExpressionLiteral(contextToken2))); @@ -166556,6 +168517,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, const parent2 = contextToken2.parent; switch (contextToken2.kind) { case 32 /* GreaterThanToken */: + // End of a type argument list case 31 /* LessThanSlashToken */: case 44 /* SlashToken */: case 80 /* Identifier */: @@ -166578,6 +168540,9 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, return parent2.parent.parent; } break; + // The context token is the closing } or " of an attribute, which means + // its parent is a JsxExpression, whose parent is a JsxAttribute, + // whose parent is a JsxOpeningLikeElement case 11 /* StringLiteral */: if (parent2 && (parent2.kind === 291 /* JsxAttribute */ || parent2.kind === 293 /* JsxSpreadAttribute */)) { return parent2.parent.parent; @@ -166612,14 +168577,18 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, isClassLike(parent2) && !!parent2.typeParameters && parent2.typeParameters.end >= contextToken2.pos; case 25 /* DotToken */: return containingNodeKind === 207 /* ArrayBindingPattern */; + // var [.| case 59 /* ColonToken */: return containingNodeKind === 208 /* BindingElement */; + // var {x :html| case 23 /* OpenBracketToken */: return containingNodeKind === 207 /* ArrayBindingPattern */; + // var [x| case 21 /* OpenParenToken */: return containingNodeKind === 299 /* CatchClause */ || isFunctionLikeButNotConstructor(containingNodeKind); case 19 /* OpenBraceToken */: return containingNodeKind === 266 /* EnumDeclaration */; + // enum a { | case 30 /* LessThanToken */: return containingNodeKind === 263 /* ClassDeclaration */ || // class A< | containingNodeKind === 231 /* ClassExpression */ || // var C = class D< | @@ -166630,6 +168599,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, return containingNodeKind === 172 /* PropertyDeclaration */ && !isClassLike(parent2.parent); case 26 /* DotDotDotToken */: return containingNodeKind === 169 /* Parameter */ || !!parent2.parent && parent2.parent.kind === 207 /* ArrayBindingPattern */; + // var [...z| case 125 /* PublicKeyword */: case 123 /* PrivateKeyword */: case 124 /* ProtectedKeyword */: @@ -166640,7 +168610,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, case 153 /* SetKeyword */: return !isFromObjectTypeDeclaration(contextToken2); case 80 /* Identifier */: { - if (containingNodeKind === 276 /* ImportSpecifier */ && contextToken2 === parent2.name && contextToken2.text === "type") { + if ((containingNodeKind === 276 /* ImportSpecifier */ || containingNodeKind === 281 /* ExportSpecifier */) && contextToken2 === parent2.name && contextToken2.text === "type") { return false; } const ancestorVariableDeclaration = findAncestor( @@ -166856,6 +168826,7 @@ function tryGetObjectLikeCompletionContainer(contextToken, position, sourceFile) const { parent: parent2 } = contextToken; switch (contextToken.kind) { case 19 /* OpenBraceToken */: + // const x = { | case 28 /* CommaToken */: if (isObjectLiteralExpression(parent2) || isObjectBindingPattern(parent2)) { return parent2; @@ -167133,9 +169104,11 @@ function tryGetObjectTypeDeclarationCompletionContainer(sourceFile, contextToken case 64 /* EqualsToken */: return void 0; case 27 /* SemicolonToken */: + // class c {getValue(): number; | } case 20 /* CloseBraceToken */: return isFromObjectTypeDeclaration(location) && location.parent.name === location ? location.parent.parent : tryCast(location, isObjectTypeDeclaration); case 19 /* OpenBraceToken */: + // class c { | case 28 /* CommaToken */: return tryCast(contextToken.parent, isObjectTypeDeclaration); default: @@ -167369,20 +169342,37 @@ function isModuleSpecifierMissingOrEmpty(specifier) { if (nodeIsMissing(specifier)) return true; return !((_a = tryCast(isExternalModuleReference(specifier) ? specifier.expression : specifier, isStringLiteralLike)) == null ? void 0 : _a.text); } -function getVariableOrParameterDeclaration(contextToken, location) { +function getClosestSymbolDeclaration(contextToken, location) { if (!contextToken) return; - const possiblyParameterDeclaration = findAncestor(contextToken, (node) => isFunctionBlock(node) || isArrowFunctionBody(node) || isBindingPattern(node) ? "quit" : (isParameter(node) || isTypeParameterDeclaration(node)) && !isIndexSignatureDeclaration(node.parent)); - const possiblyVariableDeclaration = findAncestor(location, (node) => isFunctionBlock(node) || isArrowFunctionBody(node) || isBindingPattern(node) ? "quit" : isVariableDeclaration(node)); - return possiblyParameterDeclaration || possiblyVariableDeclaration; + let closestDeclaration = findAncestor(contextToken, (node) => isFunctionBlock(node) || isArrowFunctionBody(node) || isBindingPattern(node) ? "quit" : (isParameter(node) || isTypeParameterDeclaration(node)) && !isIndexSignatureDeclaration(node.parent)); + if (!closestDeclaration) { + closestDeclaration = findAncestor(location, (node) => isFunctionBlock(node) || isArrowFunctionBody(node) || isBindingPattern(node) ? "quit" : isVariableDeclaration(node)); + } + return closestDeclaration; +} +function isInTypeParameterDefault(contextToken) { + if (!contextToken) { + return false; + } + let node = contextToken; + let parent2 = contextToken.parent; + while (parent2) { + if (isTypeParameterDeclaration(parent2)) { + return parent2.default === node || node.kind === 64 /* EqualsToken */; + } + node = parent2; + parent2 = parent2.parent; + } + return false; } function isArrowFunctionBody(node) { return node.parent && isArrowFunction(node.parent) && (node.parent.body === node || // const a = () => /**/; node.kind === 39 /* EqualsGreaterThanToken */); } -function symbolCanBeReferencedAtTypeLocation(symbol, checker, seenModules = /* @__PURE__ */ new Map()) { +function symbolCanBeReferencedAtTypeLocation(symbol, checker, seenModules = /* @__PURE__ */ new Set()) { return nonAliasCanBeReferencedAtTypeLocation(symbol) || nonAliasCanBeReferencedAtTypeLocation(skipAlias(symbol.exportSymbol || symbol, checker)); function nonAliasCanBeReferencedAtTypeLocation(symbol2) { - return !!(symbol2.flags & 788968 /* Type */) || checker.isUnknownSymbol(symbol2) || !!(symbol2.flags & 1536 /* Module */) && addToSeen(seenModules, getSymbolId(symbol2)) && checker.getExportsOfModule(symbol2).some((e) => symbolCanBeReferencedAtTypeLocation(e, checker, seenModules)); + return !!(symbol2.flags & 788968 /* Type */) || checker.isUnknownSymbol(symbol2) || !!(symbol2.flags & 1536 /* Module */) && addToSeen(seenModules, symbol2) && checker.getExportsOfModule(symbol2).some((e) => symbolCanBeReferencedAtTypeLocation(e, checker, seenModules)); } } function isDeprecated(symbol, checker) { @@ -167454,7 +169444,7 @@ function createNameAndKindSet() { } function getStringLiteralCompletions(sourceFile, position, contextToken, options, host, program, log, preferences, includeSymbol) { if (isInReferenceComment(sourceFile, position)) { - const entries = getTripleSlashReferenceCompletion(sourceFile, position, program, host); + const entries = getTripleSlashReferenceCompletion(sourceFile, position, program, host, createModuleSpecifierResolutionHost(program, host)); return entries && convertPathCompletions(entries); } if (isInString(sourceFile, position, contextToken)) { @@ -167641,6 +169631,7 @@ function getStringLiteralCompletionEntries(sourceFile, node, position, program, const argumentInfo = ts_SignatureHelp_exports.getArgumentInfoForCompletions(parent2.kind === 291 /* JsxAttribute */ ? parent2.parent : node, position, sourceFile, typeChecker); return argumentInfo && getStringLiteralCompletionsFromSignature(argumentInfo.invocation, node, argumentInfo, typeChecker) || fromContextualType(0 /* None */); } + // falls through (is `require("")` or `require(""` or `import("")`) case 272 /* ImportDeclaration */: case 278 /* ExportDeclaration */: case 283 /* ExternalModuleReference */: @@ -167726,7 +169717,7 @@ function getAlreadyUsedTypesInStringLiteralUnion(union, current) { } function getStringLiteralCompletionsFromSignature(call, arg, argumentInfo, checker) { let isNewIdentifier = false; - const uniques = /* @__PURE__ */ new Map(); + const uniques = /* @__PURE__ */ new Set(); const editingArgument = isJsxOpeningLikeElement(call) ? Debug.checkDefined(findAncestor(arg.parent, isJsxAttribute)) : arg; const candidates = checker.getCandidateSignaturesForStringLiteralCompletions(call, editingArgument); const types = flatMap(candidates, (candidate) => { @@ -167766,7 +169757,7 @@ function stringLiteralCompletionsForObjectLiteral(checker, objectLiteralExpressi hasIndexSignature: hasIndexSignature(contextualType) }; } -function getStringLiteralTypes(type, uniques = /* @__PURE__ */ new Map()) { +function getStringLiteralTypes(type, uniques = /* @__PURE__ */ new Set()) { if (!type) return emptyArray; type = skipConstraint(type); return type.isUnion() ? flatMap(type.types, (t) => getStringLiteralTypes(t, uniques)) : type.isStringLiteral() && !(type.flags & 1024 /* EnumLiteral */) && addToSeen(uniques, type.value) ? [type] : emptyArray; @@ -167797,8 +169788,9 @@ function getStringLiteralCompletionsFromModuleNamesWorker(sourceFile, node, prog const scriptDirectory = getDirectoryPath(scriptPath); const compilerOptions = program.getCompilerOptions(); const typeChecker = program.getTypeChecker(); + const moduleSpecifierResolutionHost = createModuleSpecifierResolutionHost(program, host); const extensionOptions = getExtensionOptions(compilerOptions, 1 /* ModuleSpecifier */, sourceFile, typeChecker, preferences, mode); - return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && !compilerOptions.paths && (isRootedDiskPath(literalValue) || isUrl(literalValue)) ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, program, host, scriptPath, extensionOptions) : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, mode, program, host, extensionOptions); + return isPathRelativeToScript(literalValue) || !compilerOptions.baseUrl && !compilerOptions.paths && (isRootedDiskPath(literalValue) || isUrl(literalValue)) ? getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, program, host, moduleSpecifierResolutionHost, scriptPath, extensionOptions) : getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, mode, program, host, moduleSpecifierResolutionHost, extensionOptions); } function getExtensionOptions(compilerOptions, referenceKind, importingSourceFile, typeChecker, preferences, resolutionMode) { return { @@ -167809,7 +169801,7 @@ function getExtensionOptions(compilerOptions, referenceKind, importingSourceFile resolutionMode }; } -function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, program, host, scriptPath, extensionOptions) { +function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, program, host, moduleSpecifierResolutionHost, scriptPath, extensionOptions) { const compilerOptions = program.getCompilerOptions(); if (compilerOptions.rootDirs) { return getCompletionEntriesForDirectoryFragmentWithRootDirs( @@ -167819,6 +169811,7 @@ function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, p extensionOptions, program, host, + moduleSpecifierResolutionHost, scriptPath ); } else { @@ -167828,6 +169821,7 @@ function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, p extensionOptions, program, host, + moduleSpecifierResolutionHost, /*moduleSpecifierIsRelative*/ true, scriptPath @@ -167853,7 +169847,7 @@ function getBaseDirectoriesFromRootDirs(rootDirs, basePath, scriptDirectory, ign compareStringsCaseSensitive ); } -function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, program, host, exclude) { +function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptDirectory, extensionOptions, program, host, moduleSpecifierResolutionHost, exclude) { const compilerOptions = program.getCompilerOptions(); const basePath = compilerOptions.project || host.getCurrentDirectory(); const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); @@ -167865,6 +169859,7 @@ function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment extensionOptions, program, host, + moduleSpecifierResolutionHost, /*moduleSpecifierIsRelative*/ true, exclude @@ -167872,7 +169867,7 @@ function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment (itemA, itemB) => itemA.name === itemB.name && itemA.kind === itemB.kind && itemA.extension === itemB.extension ); } -function getCompletionEntriesForDirectoryFragment(fragment, scriptDirectory, extensionOptions, program, host, moduleSpecifierIsRelative, exclude, result = createNameAndKindSet()) { +function getCompletionEntriesForDirectoryFragment(fragment, scriptDirectory, extensionOptions, program, host, moduleSpecifierResolutionHost, moduleSpecifierIsRelative, exclude, result = createNameAndKindSet()) { var _a; if (fragment === void 0) { fragment = ""; @@ -167897,7 +169892,7 @@ function getCompletionEntriesForDirectoryFragment(fragment, scriptDirectory, ext if (versionPaths) { const packageDirectory = getDirectoryPath(packageJsonPath); const pathInPackage = absolutePath.slice(ensureTrailingDirectorySeparator(packageDirectory).length); - if (addCompletionEntriesFromPaths(result, pathInPackage, packageDirectory, extensionOptions, program, host, versionPaths)) { + if (addCompletionEntriesFromPaths(result, pathInPackage, packageDirectory, extensionOptions, program, host, moduleSpecifierResolutionHost, versionPaths)) { return result; } } @@ -167925,7 +169920,7 @@ function getCompletionEntriesForDirectoryFragment(fragment, scriptDirectory, ext getBaseFileName(filePath), program, extensionOptions, - /*isExportsWildcard*/ + /*isExportsOrImportsWildcard*/ false ); result.add(nameAndKind(name, "script" /* scriptElement */, extension)); @@ -167942,7 +169937,7 @@ function getCompletionEntriesForDirectoryFragment(fragment, scriptDirectory, ext } return result; } -function getFilenameWithExtensionOption(name, program, extensionOptions, isExportsWildcard) { +function getFilenameWithExtensionOption(name, program, extensionOptions, isExportsOrImportsWildcard) { const nonJsResult = ts_moduleSpecifiers_exports.tryGetRealFileNameForNonJsDeclarationFileName(name); if (nonJsResult) { return { name: nonJsResult, extension: tryGetExtensionFromPath2(nonJsResult) }; @@ -167956,7 +169951,7 @@ function getFilenameWithExtensionOption(name, program, extensionOptions, isExpor program.getCompilerOptions(), extensionOptions.importingSourceFile ).getAllowedEndingsInPreferredOrder(extensionOptions.resolutionMode); - if (isExportsWildcard) { + if (isExportsOrImportsWildcard) { allowedEndings = allowedEndings.filter((e) => e !== 0 /* Minimal */ && e !== 1 /* Index */); } if (allowedEndings[0] === 3 /* TsExtension */) { @@ -167966,13 +169961,13 @@ function getFilenameWithExtensionOption(name, program, extensionOptions, isExpor const outputExtension2 = ts_moduleSpecifiers_exports.tryGetJSExtensionForFile(name, program.getCompilerOptions()); return outputExtension2 ? { name: changeExtension(name, outputExtension2), extension: outputExtension2 } : { name, extension: tryGetExtensionFromPath2(name) }; } - if (!isExportsWildcard && (allowedEndings[0] === 0 /* Minimal */ || allowedEndings[0] === 1 /* Index */) && fileExtensionIsOneOf(name, [".js" /* Js */, ".jsx" /* Jsx */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */])) { + if (!isExportsOrImportsWildcard && (allowedEndings[0] === 0 /* Minimal */ || allowedEndings[0] === 1 /* Index */) && fileExtensionIsOneOf(name, [".js" /* Js */, ".jsx" /* Jsx */, ".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */])) { return { name: removeFileExtension(name), extension: tryGetExtensionFromPath2(name) }; } const outputExtension = ts_moduleSpecifiers_exports.tryGetJSExtensionForFile(name, program.getCompilerOptions()); return outputExtension ? { name: changeExtension(name, outputExtension), extension: outputExtension } : { name, extension: tryGetExtensionFromPath2(name) }; } -function addCompletionEntriesFromPaths(result, fragment, baseDirectory, extensionOptions, program, host, paths) { +function addCompletionEntriesFromPaths(result, fragment, baseDirectory, extensionOptions, program, host, moduleSpecifierResolutionHost, paths) { const getPatternsForKey = (key) => paths[key]; const comparePaths2 = (a, b) => { const patternA = tryParsePattern(a); @@ -167981,40 +169976,43 @@ function addCompletionEntriesFromPaths(result, fragment, baseDirectory, extensio const lengthB = typeof patternB === "object" ? patternB.prefix.length : b.length; return compareValues(lengthB, lengthA); }; - return addCompletionEntriesFromPathsOrExports( + return addCompletionEntriesFromPathsOrExportsOrImports( result, /*isExports*/ false, + /*isImports*/ + false, fragment, baseDirectory, extensionOptions, program, host, + moduleSpecifierResolutionHost, getOwnKeys(paths), getPatternsForKey, comparePaths2 ); } -function addCompletionEntriesFromPathsOrExports(result, isExports, fragment, baseDirectory, extensionOptions, program, host, keys, getPatternsForKey, comparePaths2) { +function addCompletionEntriesFromPathsOrExportsOrImports(result, isExports, isImports, fragment, baseDirectory, extensionOptions, program, host, moduleSpecifierResolutionHost, keys, getPatternsForKey, comparePaths2) { let pathResults = []; let matchedPath; for (const key of keys) { if (key === ".") continue; - const keyWithoutLeadingDotSlash = key.replace(/^\.\//, ""); + const keyWithoutLeadingDotSlash = key.replace(/^\.\//, "") + ((isExports || isImports) && endsWith(key, "/") ? "*" : ""); const patterns = getPatternsForKey(key); if (patterns) { const pathPattern = tryParsePattern(keyWithoutLeadingDotSlash); if (!pathPattern) continue; const isMatch = typeof pathPattern === "object" && isPatternMatch(pathPattern, fragment); - const isLongestMatch = isMatch && (matchedPath === void 0 || comparePaths2(key, matchedPath) === -1 /* LessThan */); + const isLongestMatch = isMatch && (matchedPath === void 0 || comparePaths2(keyWithoutLeadingDotSlash, matchedPath) === -1 /* LessThan */); if (isLongestMatch) { - matchedPath = key; + matchedPath = keyWithoutLeadingDotSlash; pathResults = pathResults.filter((r) => !r.matchedPattern); } - if (typeof pathPattern === "string" || matchedPath === void 0 || comparePaths2(key, matchedPath) !== 1 /* GreaterThan */) { + if (typeof pathPattern === "string" || matchedPath === void 0 || comparePaths2(keyWithoutLeadingDotSlash, matchedPath) !== 1 /* GreaterThan */) { pathResults.push({ matchedPattern: isMatch, - results: getCompletionsForPathMapping(keyWithoutLeadingDotSlash, patterns, fragment, baseDirectory, extensionOptions, isExports && isMatch, program, host).map(({ name, kind, extension }) => nameAndKind(name, kind, extension)) + results: getCompletionsForPathMapping(keyWithoutLeadingDotSlash, patterns, fragment, baseDirectory, extensionOptions, isExports, isImports, program, host, moduleSpecifierResolutionHost).map(({ name, kind, extension }) => nameAndKind(name, kind, extension)) }); } } @@ -168022,7 +170020,7 @@ function addCompletionEntriesFromPathsOrExports(result, isExports, fragment, bas pathResults.forEach((pathResult) => pathResult.results.forEach((r) => result.add(r))); return matchedPath !== void 0; } -function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, program, host, extensionOptions) { +function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, program, host, moduleSpecifierResolutionHost, extensionOptions) { const typeChecker = program.getTypeChecker(); const compilerOptions = program.getCompilerOptions(); const { baseUrl, paths } = compilerOptions; @@ -168036,6 +170034,7 @@ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, p extensionOptions, program, host, + moduleSpecifierResolutionHost, /*moduleSpecifierIsRelative*/ false, /*exclude*/ @@ -168045,7 +170044,7 @@ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, p } if (paths) { const absolute = getPathsBasePath(compilerOptions, host); - addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions, program, host, paths); + addCompletionEntriesFromPaths(result, fragment, absolute, extensionOptions, program, host, moduleSpecifierResolutionHost, paths); } const fragmentDirectory = getFragmentDirectory(fragment); for (const ambientName of getAmbientModuleCompletions(fragment, fragmentDirectory, typeChecker)) { @@ -168056,7 +170055,7 @@ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, p void 0 )); } - getCompletionEntriesFromTypings(host, program, scriptPath, fragmentDirectory, extensionOptions, result); + getCompletionEntriesFromTypings(program, host, moduleSpecifierResolutionHost, scriptPath, fragmentDirectory, extensionOptions, result); if (moduleResolutionUsesNodeModules(moduleResolution)) { let foundGlobal = false; if (fragmentDirectory === void 0) { @@ -168074,6 +170073,26 @@ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, p } } if (!foundGlobal) { + const resolvePackageJsonExports = getResolvePackageJsonExports(compilerOptions); + const resolvePackageJsonImports = getResolvePackageJsonImports(compilerOptions); + let seenPackageScope = false; + const importsLookup = (directory) => { + if (resolvePackageJsonImports && !seenPackageScope) { + const packageFile = combinePaths(directory, "package.json"); + if (seenPackageScope = tryFileExists(host, packageFile)) { + const packageJson = readJson(packageFile, host); + exportsOrImportsLookup( + packageJson.imports, + fragment, + directory, + /*isExports*/ + false, + /*isImports*/ + true + ); + } + } + }; let ancestorLookup = (ancestor) => { const nodeModules = combinePaths(ancestor, "node_modules"); if (tryDirectoryExists(host, nodeModules)) { @@ -168083,6 +170102,7 @@ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, p extensionOptions, program, host, + moduleSpecifierResolutionHost, /*moduleSpecifierIsRelative*/ false, /*exclude*/ @@ -168090,58 +170110,77 @@ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, p result ); } + importsLookup(ancestor); }; - if (fragmentDirectory && getResolvePackageJsonExports(compilerOptions)) { - const nodeModulesDirectoryLookup = ancestorLookup; + if (fragmentDirectory && resolvePackageJsonExports) { + const nodeModulesDirectoryOrImportsLookup = ancestorLookup; ancestorLookup = (ancestor) => { const components = getPathComponents(fragment); components.shift(); let packagePath = components.shift(); if (!packagePath) { - return nodeModulesDirectoryLookup(ancestor); + return nodeModulesDirectoryOrImportsLookup(ancestor); } if (startsWith(packagePath, "@")) { const subName = components.shift(); if (!subName) { - return nodeModulesDirectoryLookup(ancestor); + return nodeModulesDirectoryOrImportsLookup(ancestor); } packagePath = combinePaths(packagePath, subName); } + if (resolvePackageJsonImports && startsWith(packagePath, "#")) { + return importsLookup(ancestor); + } const packageDirectory = combinePaths(ancestor, "node_modules", packagePath); const packageFile = combinePaths(packageDirectory, "package.json"); if (tryFileExists(host, packageFile)) { const packageJson = readJson(packageFile, host); - const exports2 = packageJson.exports; - if (exports2) { - if (typeof exports2 !== "object" || exports2 === null) { - return; - } - const keys = getOwnKeys(exports2); - const fragmentSubpath = components.join("/") + (components.length && hasTrailingDirectorySeparator(fragment) ? "/" : ""); - const conditions = getConditions(compilerOptions, mode); - addCompletionEntriesFromPathsOrExports( - result, - /*isExports*/ - true, - fragmentSubpath, - packageDirectory, - extensionOptions, - program, - host, - keys, - (key) => singleElementArray(getPatternFromFirstMatchingCondition(exports2[key], conditions)), - comparePatternKeys - ); - return; - } + const fragmentSubpath = components.join("/") + (components.length && hasTrailingDirectorySeparator(fragment) ? "/" : ""); + exportsOrImportsLookup( + packageJson.exports, + fragmentSubpath, + packageDirectory, + /*isExports*/ + true, + /*isImports*/ + false + ); + return; } - return nodeModulesDirectoryLookup(ancestor); + return nodeModulesDirectoryOrImportsLookup(ancestor); }; } - forEachAncestorDirectory(scriptPath, ancestorLookup); + forEachAncestorDirectoryStoppingAtGlobalCache(host, scriptPath, ancestorLookup); } } return arrayFrom(result.values()); + function exportsOrImportsLookup(lookupTable, fragment2, baseDirectory, isExports, isImports) { + if (typeof lookupTable !== "object" || lookupTable === null) { + return; + } + const keys = getOwnKeys(lookupTable); + const conditions = getConditions(compilerOptions, mode); + addCompletionEntriesFromPathsOrExportsOrImports( + result, + isExports, + isImports, + fragment2, + baseDirectory, + extensionOptions, + program, + host, + moduleSpecifierResolutionHost, + keys, + (key) => { + const pattern = getPatternFromFirstMatchingCondition(lookupTable[key], conditions); + if (pattern === void 0) { + return void 0; + } + return singleElementArray(endsWith(key, "/") && endsWith(pattern, "/") ? pattern + "*" : pattern); + }, + comparePatternKeys + ); + } } function getPatternFromFirstMatchingCondition(target, conditions) { if (typeof target === "string") { @@ -168159,25 +170198,28 @@ function getPatternFromFirstMatchingCondition(target, conditions) { function getFragmentDirectory(fragment) { return containsSlash(fragment) ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : void 0; } -function getCompletionsForPathMapping(path, patterns, fragment, packageDirectory, extensionOptions, isExportsWildcard, program, host) { - if (!endsWith(path, "*")) { - return !path.includes("*") ? justPathMappingName(path, "script" /* scriptElement */) : emptyArray; +function getCompletionsForPathMapping(path, patterns, fragment, packageDirectory, extensionOptions, isExports, isImports, program, host, moduleSpecifierResolutionHost) { + const parsedPath = tryParsePattern(path); + if (!parsedPath) { + return emptyArray; + } + if (typeof parsedPath === "string") { + return justPathMappingName(path, "script" /* scriptElement */); } - const pathPrefix = path.slice(0, path.length - 1); - const remainingFragment = tryRemovePrefix(fragment, pathPrefix); + const remainingFragment = tryRemovePrefix(fragment, parsedPath.prefix); if (remainingFragment === void 0) { - const starIsFullPathComponent = path[path.length - 2] === "/"; - return starIsFullPathComponent ? justPathMappingName(pathPrefix, "directory" /* directory */) : flatMap(patterns, (pattern) => { + const starIsFullPathComponent = endsWith(path, "/*"); + return starIsFullPathComponent ? justPathMappingName(parsedPath.prefix, "directory" /* directory */) : flatMap(patterns, (pattern) => { var _a; - return (_a = getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, isExportsWildcard, program, host)) == null ? void 0 : _a.map(({ name, ...rest }) => ({ name: pathPrefix + name, ...rest })); + return (_a = getModulesForPathsPattern("", packageDirectory, pattern, extensionOptions, isExports, isImports, program, host, moduleSpecifierResolutionHost)) == null ? void 0 : _a.map(({ name, ...rest }) => ({ name: parsedPath.prefix + name + parsedPath.suffix, ...rest })); }); } - return flatMap(patterns, (pattern) => getModulesForPathsPattern(remainingFragment, packageDirectory, pattern, extensionOptions, isExportsWildcard, program, host)); + return flatMap(patterns, (pattern) => getModulesForPathsPattern(remainingFragment, packageDirectory, pattern, extensionOptions, isExports, isImports, program, host, moduleSpecifierResolutionHost)); function justPathMappingName(name, kind) { return startsWith(name, fragment) ? [{ name: removeTrailingDirectorySeparator(name), kind, extension: void 0 }] : emptyArray; } } -function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensionOptions, isExportsWildcard, program, host) { +function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensionOptions, isExports, isImports, program, host, moduleSpecifierResolutionHost) { if (!host.readDirectory) { return void 0; } @@ -168190,35 +170232,67 @@ function getModulesForPathsPattern(fragment, packageDirectory, pattern, extensio const normalizedPrefixBase = hasTrailingDirectorySeparator(parsed.prefix) ? "" : getBaseFileName(normalizedPrefix); const fragmentHasPath = containsSlash(fragment); const fragmentDirectory = fragmentHasPath ? hasTrailingDirectorySeparator(fragment) ? fragment : getDirectoryPath(fragment) : void 0; + const getCommonSourceDirectory2 = () => moduleSpecifierResolutionHost.getCommonSourceDirectory(); + const ignoreCase = !hostUsesCaseSensitiveFileNames(moduleSpecifierResolutionHost); + const outDir = program.getCompilerOptions().outDir; + const declarationDir = program.getCompilerOptions().declarationDir; const expandedPrefixDirectory = fragmentHasPath ? combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + fragmentDirectory) : normalizedPrefixDirectory; + const baseDirectory = normalizePath(combinePaths(packageDirectory, expandedPrefixDirectory)); + const possibleInputBaseDirectoryForOutDir = isImports && outDir && getPossibleOriginalInputPathWithoutChangingExt(baseDirectory, ignoreCase, outDir, getCommonSourceDirectory2); + const possibleInputBaseDirectoryForDeclarationDir = isImports && declarationDir && getPossibleOriginalInputPathWithoutChangingExt(baseDirectory, ignoreCase, declarationDir, getCommonSourceDirectory2); const normalizedSuffix = normalizePath(parsed.suffix); const declarationExtension = normalizedSuffix && getDeclarationEmitExtensionForPath("_" + normalizedSuffix); - const matchingSuffixes = declarationExtension ? [changeExtension(normalizedSuffix, declarationExtension), normalizedSuffix] : [normalizedSuffix]; - const baseDirectory = normalizePath(combinePaths(packageDirectory, expandedPrefixDirectory)); - const completePrefix = fragmentHasPath ? baseDirectory : ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + const inputExtension = normalizedSuffix ? getPossibleOriginalInputExtensionForExtension("_" + normalizedSuffix) : void 0; + const matchingSuffixes = [ + declarationExtension && changeExtension(normalizedSuffix, declarationExtension), + ...inputExtension ? inputExtension.map((ext) => changeExtension(normalizedSuffix, ext)) : [], + normalizedSuffix + ].filter(isString); const includeGlobs = normalizedSuffix ? matchingSuffixes.map((suffix) => "**/*" + suffix) : ["./*"]; - const matches = mapDefined(tryReadDirectory( - host, - baseDirectory, - extensionOptions.extensionsToSearch, - /*exclude*/ - void 0, - includeGlobs - ), (match) => { - const trimmedWithPattern = trimPrefixAndSuffix(match); - if (trimmedWithPattern) { - if (containsSlash(trimmedWithPattern)) { - return directoryResult(getPathComponents(removeLeadingDirectorySeparator(trimmedWithPattern))[1]); - } - const { name, extension } = getFilenameWithExtensionOption(trimmedWithPattern, program, extensionOptions, isExportsWildcard); - return nameAndKind(name, "script" /* scriptElement */, extension); + const isExportsOrImportsWildcard = (isExports || isImports) && endsWith(pattern, "/*"); + let matches = getMatchesWithPrefix(baseDirectory); + if (possibleInputBaseDirectoryForOutDir) { + matches = concatenate(matches, getMatchesWithPrefix(possibleInputBaseDirectoryForOutDir)); + } + if (possibleInputBaseDirectoryForDeclarationDir) { + matches = concatenate(matches, getMatchesWithPrefix(possibleInputBaseDirectoryForDeclarationDir)); + } + if (!normalizedSuffix) { + matches = concatenate(matches, getDirectoryMatches(baseDirectory)); + if (possibleInputBaseDirectoryForOutDir) { + matches = concatenate(matches, getDirectoryMatches(possibleInputBaseDirectoryForOutDir)); } - }); - const directories = normalizedSuffix ? emptyArray : mapDefined(tryGetDirectories(host, baseDirectory), (dir) => dir === "node_modules" ? void 0 : directoryResult(dir)); - return [...matches, ...directories]; - function trimPrefixAndSuffix(path) { + if (possibleInputBaseDirectoryForDeclarationDir) { + matches = concatenate(matches, getDirectoryMatches(possibleInputBaseDirectoryForDeclarationDir)); + } + } + return matches; + function getMatchesWithPrefix(directory) { + const completePrefix = fragmentHasPath ? directory : ensureTrailingDirectorySeparator(directory) + normalizedPrefixBase; + return mapDefined(tryReadDirectory( + host, + directory, + extensionOptions.extensionsToSearch, + /*exclude*/ + void 0, + includeGlobs + ), (match) => { + const trimmedWithPattern = trimPrefixAndSuffix(match, completePrefix); + if (trimmedWithPattern) { + if (containsSlash(trimmedWithPattern)) { + return directoryResult(getPathComponents(removeLeadingDirectorySeparator(trimmedWithPattern))[1]); + } + const { name, extension } = getFilenameWithExtensionOption(trimmedWithPattern, program, extensionOptions, isExportsOrImportsWildcard); + return nameAndKind(name, "script" /* scriptElement */, extension); + } + }); + } + function getDirectoryMatches(directoryName) { + return mapDefined(tryGetDirectories(host, directoryName), (dir) => dir === "node_modules" ? void 0 : directoryResult(dir)); + } + function trimPrefixAndSuffix(path, prefix) { return firstDefined(matchingSuffixes, (suffix) => { - const inner = withoutStartAndEnd(normalizePath(path), completePrefix, suffix); + const inner = withoutStartAndEnd(normalizePath(path), prefix, suffix); return inner === void 0 ? void 0 : removeLeadingDirectorySeparator(inner); }); } @@ -168238,7 +170312,7 @@ function getAmbientModuleCompletions(fragment, fragmentDirectory, checker) { } return nonRelativeModuleNames; } -function getTripleSlashReferenceCompletion(sourceFile, position, program, host) { +function getTripleSlashReferenceCompletion(sourceFile, position, program, host, moduleSpecifierResolutionHost) { const compilerOptions = program.getCompilerOptions(); const token = getTokenAtPosition(sourceFile, position); const commentRanges = getLeadingCommentRanges(sourceFile.text, token.pos); @@ -168259,13 +170333,14 @@ function getTripleSlashReferenceCompletion(sourceFile, position, program, host) getExtensionOptions(compilerOptions, 0 /* Filename */, sourceFile), program, host, + moduleSpecifierResolutionHost, /*moduleSpecifierIsRelative*/ true, sourceFile.path - ) : kind === "types" ? getCompletionEntriesFromTypings(host, program, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions, 1 /* ModuleSpecifier */, sourceFile)) : Debug.fail(); + ) : kind === "types" ? getCompletionEntriesFromTypings(program, host, moduleSpecifierResolutionHost, scriptPath, getFragmentDirectory(toComplete), getExtensionOptions(compilerOptions, 1 /* ModuleSpecifier */, sourceFile)) : Debug.fail(); return addReplacementSpans(toComplete, range.pos + prefix.length, arrayFrom(names.values())); } -function getCompletionEntriesFromTypings(host, program, scriptPath, fragmentDirectory, extensionOptions, result = createNameAndKindSet()) { +function getCompletionEntriesFromTypings(program, host, moduleSpecifierResolutionHost, scriptPath, fragmentDirectory, extensionOptions, result = createNameAndKindSet()) { const options = program.getCompilerOptions(); const seen = /* @__PURE__ */ new Map(); const typeRoots = tryAndIgnoreErrors(() => getEffectiveTypeRoots(options, host)) || emptyArray; @@ -168302,6 +170377,7 @@ function getCompletionEntriesFromTypings(host, program, scriptPath, fragmentDire extensionOptions, program, host, + moduleSpecifierResolutionHost, /*moduleSpecifierIsRelative*/ false, /*exclude*/ @@ -168447,6 +170523,7 @@ function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, { break; case 80 /* Identifier */: break; + // TODO: GH#23879 case 271 /* ImportEqualsDeclaration */: handleNamespaceImport( direct, @@ -169053,7 +171130,7 @@ function getImplementationsAtPosition(program, cancellationToken, sourceFiles, s referenceEntries = entries && [...entries]; } else if (entries) { const queue = createQueue(entries); - const seenNodes = /* @__PURE__ */ new Map(); + const seenNodes = /* @__PURE__ */ new Set(); while (!queue.isEmpty()) { const entry = queue.dequeue(); if (!addToSeen(seenNodes, getNodeId(entry.node))) { @@ -169341,6 +171418,7 @@ function declarationIsWriteAccess(decl) { case 306 /* EnumMember */: case 281 /* ExportSpecifier */: case 273 /* ImportClause */: + // default import case 271 /* ImportEqualsDeclaration */: case 276 /* ImportSpecifier */: case 264 /* InterfaceDeclaration */: @@ -169727,6 +171805,7 @@ var Core; Debug.assert(node.parent.name === node); return 2 /* Class */; } + // falls through default: return 0 /* None */; } @@ -170058,6 +172137,7 @@ var Core; if (isJSDocMemberName(node.parent)) { return true; } + // falls through I guess case 80 /* Identifier */: return node.text.length === searchSymbolName.length; case 15 /* NoSubstitutionTemplateLiteral */: @@ -170483,6 +172563,7 @@ var Core; searchSpaceNode = searchSpaceNode.parent; break; } + // falls through case 172 /* PropertyDeclaration */: case 171 /* PropertySignature */: case 176 /* Constructor */: @@ -170495,9 +172576,12 @@ var Core; if (isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) { return void 0; } + // falls through case 262 /* FunctionDeclaration */: case 218 /* FunctionExpression */: break; + // Computed properties in classes are not handled here because references to this are illegal, + // so there is no point finding references to them. default: return void 0; } @@ -170698,10 +172782,10 @@ var Core; } } function getPropertySymbolsFromBaseTypes(symbol, propertyName, checker, cb) { - const seen = /* @__PURE__ */ new Map(); + const seen = /* @__PURE__ */ new Set(); return recur(symbol); function recur(symbol2) { - if (!(symbol2.flags & (32 /* Class */ | 64 /* Interface */)) || !addToSeen(seen, getSymbolId(symbol2))) return; + if (!(symbol2.flags & (32 /* Class */ | 64 /* Interface */)) || !addToSeen(seen, symbol2)) return; return firstDefined(symbol2.declarations, (declaration) => firstDefined(getAllSuperTypeNodes(declaration), (typeReference) => { const type = checker.getTypeAtLocation(typeReference); const propertySymbol = type && type.symbol && checker.getPropertyOfType(type, propertyName); @@ -170837,6 +172921,7 @@ function getDefinitionAtPosition(program, sourceFile, position, searchOtherFiles if (!isDefaultClause(node.parent)) { break; } + // falls through case 84 /* CaseKeyword */: const switchStatement = findAncestor(node.parent, isSwitchStatement); if (switchStatement) { @@ -171281,6 +173366,8 @@ function isDefinitionVisible(checker, declaration) { case 178 /* SetAccessor */: case 174 /* MethodDeclaration */: if (hasEffectiveModifier(declaration, 2 /* Private */)) return false; + // Public properties/methods are visible if its parents are visible, so: + // falls through case 176 /* Constructor */: case 303 /* PropertyAssignment */: case 304 /* ShorthandPropertyAssignment */: @@ -171484,11 +173571,8 @@ function provideInlayHints(context) { if (!args || !args.length) { return; } - const candidates = []; - const signature = checker.getResolvedSignatureForSignatureHelp(expr, candidates); - if (!signature || !candidates.length) { - return; - } + const signature = checker.getResolvedSignature(expr); + if (signature === void 0) return; let signatureParamPos = 0; for (const originalArg of args) { const arg = skipParentheses(originalArg); @@ -172257,6 +174341,7 @@ function getCommentHavingNodes(declaration) { if (isJSDocOverloadTag(declaration.parent)) { return [declaration.parent.parent]; } + // falls through default: return getJSDocCommentsAndTags(declaration); } @@ -173594,6 +175679,7 @@ function getOutliningSpanForNode(n, sourceFile) { const node = findChildOfKind(tryStatement, 98 /* FinallyKeyword */, sourceFile); if (node) return spanForNode(node); } + // falls through default: return createOutliningSpan(createTextSpanFromNode(n, sourceFile), "code" /* Code */); } @@ -175344,6 +177430,7 @@ __export(ts_textChanges_exports, { assignPositionsToNode: () => assignPositionsToNode, createWriter: () => createWriter, deleteNode: () => deleteNode, + getAdjustedEndPosition: () => getAdjustedEndPosition, isThisTypeAnnotatable: () => isThisTypeAnnotatable, isValidLocationToAddComment: () => isValidLocationToAddComment }); @@ -175843,7 +177930,10 @@ var ChangeTracker = class _ChangeTracker { getInsertNodeAtStartInsertOptions(sourceFile, node, indentation) { const members = getMembersOrProperties(node); const isEmpty = members.length === 0; - const isFirstInsertion = addToSeen(this.classesWithNodesInsertedAtStart, getNodeId(node), { node, sourceFile }); + const isFirstInsertion = !this.classesWithNodesInsertedAtStart.has(getNodeId(node)); + if (isFirstInsertion) { + this.classesWithNodesInsertedAtStart.set(getNodeId(node), { node, sourceFile }); + } const insertTrailingComma = isObjectLiteralExpression(node) && (!isJsonSourceFile(sourceFile) || !isEmpty); const insertLeadingComma = isObjectLiteralExpression(node) && isJsonSourceFile(sourceFile) && isEmpty && !isFirstInsertion; return { @@ -177419,19 +179509,34 @@ function isBinaryOpContext(context) { case 193 /* IntersectionType */: case 238 /* SatisfiesExpression */: return true; + // equals in binding elements: function foo([[x, y] = [1, 2]]) case 208 /* BindingElement */: + // equals in type X = ... + // falls through case 265 /* TypeAliasDeclaration */: + // equal in import a = module('a'); + // falls through case 271 /* ImportEqualsDeclaration */: + // equal in export = 1 + // falls through case 277 /* ExportAssignment */: + // equal in let a = 0 + // falls through case 260 /* VariableDeclaration */: + // equal in p = 0 + // falls through case 169 /* Parameter */: case 306 /* EnumMember */: case 172 /* PropertyDeclaration */: case 171 /* PropertySignature */: return context.currentTokenSpan.kind === 64 /* EqualsToken */ || context.nextTokenSpan.kind === 64 /* EqualsToken */; + // "in" keyword in for (let x in []) { } case 249 /* ForInStatement */: + // "in" keyword in [P in keyof T]: T[P] + // falls through case 168 /* TypeParameter */: return context.currentTokenSpan.kind === 103 /* InKeyword */ || context.nextTokenSpan.kind === 103 /* InKeyword */ || context.currentTokenSpan.kind === 64 /* EqualsToken */ || context.nextTokenSpan.kind === 64 /* EqualsToken */; + // Technically, "of" is not a binary operator, but format it the same way as "in" case 250 /* ForOfStatement */: return context.currentTokenSpan.kind === 165 /* OfKeyword */ || context.nextTokenSpan.kind === 165 /* OfKeyword */; } @@ -177495,12 +179600,20 @@ function isFunctionDeclContext(context) { case 262 /* FunctionDeclaration */: case 174 /* MethodDeclaration */: case 173 /* MethodSignature */: + // case SyntaxKind.MemberFunctionDeclaration: + // falls through case 177 /* GetAccessor */: case 178 /* SetAccessor */: + // case SyntaxKind.MethodSignature: + // falls through case 179 /* CallSignature */: case 218 /* FunctionExpression */: case 176 /* Constructor */: case 219 /* ArrowFunction */: + // case SyntaxKind.ConstructorDeclaration: + // case SyntaxKind.SimpleArrowFunctionExpression: + // case SyntaxKind.ParenthesizedArrowFunctionExpression: + // falls through case 264 /* InterfaceDeclaration */: return true; } @@ -177560,6 +179673,9 @@ function isControlDeclContext(context) { case 258 /* TryStatement */: case 246 /* DoStatement */: case 254 /* WithStatement */: + // TODO + // case SyntaxKind.ElseClause: + // falls through case 299 /* CatchClause */: return true; default: @@ -177727,6 +179843,9 @@ function isSemicolonDeletionContext(context) { if (startLine === endLine) { return nextTokenKind === 20 /* CloseBraceToken */ || nextTokenKind === 1 /* EndOfFileToken */; } + if (nextTokenKind === 27 /* SemicolonToken */ && context.currentTokenSpan.kind === 27 /* SemicolonToken */) { + return true; + } if (nextTokenKind === 240 /* SemicolonClassElement */ || nextTokenKind === 27 /* SemicolonToken */) { return false; } @@ -178188,6 +180307,7 @@ function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delt if (node.asteriskToken) { return 42 /* AsteriskToken */; } + // falls through case 172 /* PropertyDeclaration */: case 169 /* Parameter */: const name = getNameOfDeclaration(node); @@ -178200,6 +180320,10 @@ function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delt return { getIndentationForComment: (kind, tokenIndentation, container) => { switch (kind) { + // preceding comment to the token that closes the indentation scope inherits the indentation from the scope + // .. { + // // comment + // } case 20 /* CloseBraceToken */: case 24 /* CloseBracketToken */: case 22 /* CloseParenToken */: @@ -178229,6 +180353,7 @@ function formatSpanWorker(originalRange, enclosingNode, initialIndentation, delt }; function shouldAddDelta(line, kind, container) { switch (kind) { + // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent case 19 /* OpenBraceToken */: case 20 /* CloseBraceToken */: case 22 /* CloseParenToken */: @@ -179386,6 +181511,48 @@ var SmartIndenter; } })(SmartIndenter || (SmartIndenter = {})); +// src/services/_namespaces/ts.preparePasteEdits.ts +var ts_preparePasteEdits_exports = {}; +__export(ts_preparePasteEdits_exports, { + preparePasteEdits: () => preparePasteEdits +}); + +// src/services/preparePasteEdits.ts +function preparePasteEdits(sourceFile, copiedFromRange, checker) { + let shouldProvidePasteEdits = false; + copiedFromRange.forEach((range) => { + const enclosingNode = findAncestor( + getTokenAtPosition(sourceFile, range.pos), + (ancestorNode) => rangeContainsRange(ancestorNode, range) + ); + if (!enclosingNode) return; + forEachChild(enclosingNode, function checkNameResolution(node) { + var _a; + if (shouldProvidePasteEdits) return; + if (isIdentifier(node) && rangeContainsPosition(range, node.getStart(sourceFile))) { + const resolvedSymbol = checker.resolveName( + node.text, + node, + -1 /* All */, + /*excludeGlobals*/ + false + ); + if (resolvedSymbol && resolvedSymbol.declarations) { + for (const decl of resolvedSymbol.declarations) { + if (isInImport(decl) || !!(node.text && sourceFile.symbol && ((_a = sourceFile.symbol.exports) == null ? void 0 : _a.has(node.escapedText)))) { + shouldProvidePasteEdits = true; + return; + } + } + } + } + node.forEachChild(checkNameResolution); + }); + if (shouldProvidePasteEdits) return; + }); + return shouldProvidePasteEdits; +} + // src/services/_namespaces/ts.PasteEdits.ts var ts_PasteEdits_exports = {}; __export(ts_PasteEdits_exports, { @@ -179393,10 +181560,10 @@ __export(ts_PasteEdits_exports, { }); // src/services/pasteEdits.ts -var fixId54 = "providePostPasteEdits"; +var fixId55 = "providePostPasteEdits"; function pasteEditsProvider(targetFile, pastedText, pasteLocations, copiedFrom, host, preferences, formatContext, cancellationToken) { const changes = ts_textChanges_exports.ChangeTracker.with({ host, formatContext, preferences }, (changeTracker) => pasteEdits(targetFile, pastedText, pasteLocations, copiedFrom, host, preferences, formatContext, cancellationToken, changeTracker)); - return { edits: changes, fixId: fixId54 }; + return { edits: changes, fixId: fixId55 }; } function pasteEdits(targetFile, pastedText, pasteLocations, copiedFrom, host, preferences, formatContext, cancellationToken, changes) { let actualPastedText; @@ -179424,11 +181591,13 @@ function pasteEdits(targetFile, pastedText, pasteLocations, copiedFrom, host, pr } statements.push(...statementsInSourceFile.slice(startNodeIndex, endNodeIndex === -1 ? statementsInSourceFile.length : endNodeIndex + 1)); }); - const usage = getUsageInfo(copiedFrom.file, statements, originalProgram.getTypeChecker(), getExistingLocals(updatedFile, statements, originalProgram.getTypeChecker()), { pos: copiedFrom.range[0].pos, end: copiedFrom.range[copiedFrom.range.length - 1].end }); - Debug.assertIsDefined(originalProgram); + Debug.assertIsDefined(originalProgram, "no original program found"); + const originalProgramTypeChecker = originalProgram.getTypeChecker(); + const usageInfoRange = getUsageInfoRangeForPasteEdits(copiedFrom); + const usage = getUsageInfo(copiedFrom.file, statements, originalProgramTypeChecker, getExistingLocals(updatedFile, statements, originalProgramTypeChecker), usageInfoRange); const useEsModuleSyntax = !fileShouldUseJavaScriptRequire(targetFile.fileName, originalProgram, host, !!copiedFrom.file.commonJsModuleIndicator); addExportsInOldFile(copiedFrom.file, usage.targetFileImportsFromOldFile, changes, useEsModuleSyntax); - addTargetFileImports(copiedFrom.file, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, originalProgram.getTypeChecker(), updatedProgram, importAdder); + addTargetFileImports(copiedFrom.file, usage.oldImportsNeededByTargetFile, usage.targetFileImportsFromOldFile, originalProgramTypeChecker, updatedProgram, importAdder); } else { const context = { sourceFile: updatedFile, @@ -179484,6 +181653,16 @@ function pasteEdits(targetFile, pastedText, pasteLocations, copiedFrom, host, pr ); }); } +function getUsageInfoRangeForPasteEdits({ file: sourceFile, range }) { + const pos = range[0].pos; + const end = range[range.length - 1].end; + const startToken = getTokenAtPosition(sourceFile, pos); + const endToken = findTokenOnLeftOfPosition(sourceFile, pos) ?? getTokenAtPosition(sourceFile, end); + return { + pos: isIdentifier(startToken) && pos <= startToken.getStart(sourceFile) ? startToken.getFullStart() : pos, + end: isIdentifier(endToken) && end === endToken.getEnd() ? ts_textChanges_exports.getAdjustedEndPosition(sourceFile, endToken, {}) : end + }; +} // src/server/_namespaces/ts.ts var ts_exports2 = {}; @@ -179596,6 +181775,7 @@ __export(ts_exports2, { PollingWatchKind: () => PollingWatchKind, PragmaKindFlags: () => PragmaKindFlags, PredicateSemantics: () => PredicateSemantics, + PreparePasteEdits: () => ts_preparePasteEdits_exports, PrivateIdentifierKind: () => PrivateIdentifierKind, ProcessLevel: () => ProcessLevel, ProgramUpdateLevel: () => ProgramUpdateLevel, @@ -179691,7 +181871,6 @@ __export(ts_exports2, { buildOverload: () => buildOverload, bundlerModuleNameResolver: () => bundlerModuleNameResolver, canBeConvertedToAsync: () => canBeConvertedToAsync, - canEmitTsBuildInfo: () => canEmitTsBuildInfo, canHaveDecorators: () => canHaveDecorators, canHaveExportModifier: () => canHaveExportModifier, canHaveFlowNode: () => canHaveFlowNode, @@ -179711,6 +181890,7 @@ __export(ts_exports2, { canWatchAffectingLocation: () => canWatchAffectingLocation, canWatchAtTypes: () => canWatchAtTypes, canWatchDirectoryOrFile: () => canWatchDirectoryOrFile, + canWatchDirectoryOrFilePath: () => canWatchDirectoryOrFilePath, cartesianProduct: () => cartesianProduct, cast: () => cast, chainBundle: () => chainBundle, @@ -179981,6 +182161,7 @@ __export(ts_exports2, { escapeTemplateSubstitution: () => escapeTemplateSubstitution, evaluatorResult: () => evaluatorResult, every: () => every, + exclusivelyPrefixedNodeCoreModules: () => exclusivelyPrefixedNodeCoreModules, executeCommandLine: () => executeCommandLine, expandPreOrPostfixIncrementOrDecrementExpression: () => expandPreOrPostfixIncrementOrDecrementExpression, explainFiles: () => explainFiles, @@ -179993,7 +182174,6 @@ __export(ts_exports2, { extensionsNotSupportingExtensionlessResolution: () => extensionsNotSupportingExtensionlessResolution, externalHelpersModuleNameText: () => externalHelpersModuleNameText, factory: () => factory, - fileContainsPackageImport: () => fileContainsPackageImport, fileExtensionIs: () => fileExtensionIs, fileExtensionIsOneOf: () => fileExtensionIsOneOf, fileIncludeReasonToDiagnostics: () => fileIncludeReasonToDiagnostics, @@ -180043,8 +182223,10 @@ __export(ts_exports2, { forEach: () => forEach, forEachAncestor: () => forEachAncestor, forEachAncestorDirectory: () => forEachAncestorDirectory, + forEachAncestorDirectoryStoppingAtGlobalCache: () => forEachAncestorDirectoryStoppingAtGlobalCache, forEachChild: () => forEachChild, forEachChildRecursively: () => forEachChildRecursively, + forEachDynamicImportOrRequireCall: () => forEachDynamicImportOrRequireCall, forEachEmittedFile: () => forEachEmittedFile, forEachEnclosingBlockScopeContainer: () => forEachEnclosingBlockScopeContainer, forEachEntry: () => forEachEntry, @@ -180085,6 +182267,7 @@ __export(ts_exports2, { getAllKeys: () => getAllKeys, getAllProjectOutputs: () => getAllProjectOutputs, getAllSuperTypeNodes: () => getAllSuperTypeNodes, + getAllowImportingTsExtensions: () => getAllowImportingTsExtensions, getAllowJSCompilerOption: () => getAllowJSCompilerOption, getAllowSyntheticDefaultImports: () => getAllowSyntheticDefaultImports, getAncestor: () => getAncestor, @@ -180393,6 +182576,7 @@ __export(ts_exports2, { getPositionOfLineAndCharacter: () => getPositionOfLineAndCharacter, getPossibleGenericSignatures: () => getPossibleGenericSignatures, getPossibleOriginalInputExtensionForExtension: () => getPossibleOriginalInputExtensionForExtension, + getPossibleOriginalInputPathWithoutChangingExt: () => getPossibleOriginalInputPathWithoutChangingExt, getPossibleTypeArgumentsInfo: () => getPossibleTypeArgumentsInfo, getPreEmitDiagnostics: () => getPreEmitDiagnostics, getPrecedingNonSpaceCharacterPosition: () => getPrecedingNonSpaceCharacterPosition, @@ -180656,7 +182840,7 @@ __export(ts_exports2, { isBooleanLiteral: () => isBooleanLiteral, isBreakOrContinueStatement: () => isBreakOrContinueStatement, isBreakStatement: () => isBreakStatement, - isBuild: () => isBuild, + isBuildCommand: () => isBuildCommand, isBuildInfoFile: () => isBuildInfoFile, isBuilderProgram: () => isBuilderProgram, isBundle: () => isBundle, @@ -180843,7 +183027,7 @@ __export(ts_exports2, { isImportSpecifier: () => isImportSpecifier, isImportTypeAssertionContainer: () => isImportTypeAssertionContainer, isImportTypeNode: () => isImportTypeNode, - isImportableFile: () => isImportableFile, + isImportable: () => isImportable, isInComment: () => isInComment, isInCompoundLikeAssignment: () => isInCompoundLikeAssignment, isInExpressionContext: () => isInExpressionContext, @@ -180942,6 +183126,7 @@ __export(ts_exports2, { isJsxAttributeLike: () => isJsxAttributeLike, isJsxAttributeName: () => isJsxAttributeName, isJsxAttributes: () => isJsxAttributes, + isJsxCallLike: () => isJsxCallLike, isJsxChild: () => isJsxChild, isJsxClosingElement: () => isJsxClosingElement, isJsxClosingFragment: () => isJsxClosingFragment, @@ -181024,6 +183209,7 @@ __export(ts_exports2, { isNamespaceReexportDeclaration: () => isNamespaceReexportDeclaration, isNewExpression: () => isNewExpression, isNewExpressionTarget: () => isNewExpressionTarget, + isNewScopeNode: () => isNewScopeNode, isNoSubstitutionTemplateLiteral: () => isNoSubstitutionTemplateLiteral, isNodeArray: () => isNodeArray, isNodeArrayMultiLine: () => isNodeArrayMultiLine, @@ -181072,6 +183258,7 @@ __export(ts_exports2, { isParseTreeNode: () => isParseTreeNode, isPartOfParameterDeclaration: () => isPartOfParameterDeclaration, isPartOfTypeNode: () => isPartOfTypeNode, + isPartOfTypeOnlyImportOrExportDeclaration: () => isPartOfTypeOnlyImportOrExportDeclaration, isPartOfTypeQuery: () => isPartOfTypeQuery, isPartiallyEmittedExpression: () => isPartiallyEmittedExpression, isPatternMatch: () => isPatternMatch, @@ -181140,6 +183327,7 @@ __export(ts_exports2, { isSimpleInlineableExpression: () => isSimpleInlineableExpression, isSimpleParameterList: () => isSimpleParameterList, isSingleOrDoubleQuote: () => isSingleOrDoubleQuote, + isSolutionConfig: () => isSolutionConfig, isSourceElement: () => isSourceElement, isSourceFile: () => isSourceFile, isSourceFileFromLibrary: () => isSourceFileFromLibrary, @@ -181248,7 +183436,6 @@ __export(ts_exports2, { isVariableDeclarationInitializedToRequire: () => isVariableDeclarationInitializedToRequire, isVariableDeclarationList: () => isVariableDeclarationList, isVariableLike: () => isVariableLike, - isVariableLikeOrAccessor: () => isVariableLikeOrAccessor, isVariableStatement: () => isVariableStatement, isVoidExpression: () => isVoidExpression, isWatchSet: () => isWatchSet, @@ -181285,6 +183472,7 @@ __export(ts_exports2, { matchPatternOrExact: () => matchPatternOrExact, matchedText: () => matchedText, matchesExclude: () => matchesExclude, + matchesExcludeWorker: () => matchesExcludeWorker, maxBy: () => maxBy, maybeBind: () => maybeBind, maybeSetLocalizedDiagnosticMessages: () => maybeSetLocalizedDiagnosticMessages, @@ -181324,6 +183512,7 @@ __export(ts_exports2, { noTransformers: () => noTransformers, noTruncationMaximumTruncationLength: () => noTruncationMaximumTruncationLength, nodeCanBeDecorated: () => nodeCanBeDecorated, + nodeCoreModules: () => nodeCoreModules, nodeHasName: () => nodeHasName, nodeIsDecorated: () => nodeIsDecorated, nodeIsMissing: () => nodeIsMissing, @@ -181468,6 +183657,7 @@ __export(ts_exports2, { returnTrue: () => returnTrue, returnUndefined: () => returnUndefined, returnsPromise: () => returnsPromise, + rewriteModuleSpecifier: () => rewriteModuleSpecifier, sameFlatMap: () => sameFlatMap, sameMap: () => sameMap, sameMapping: () => sameMapping, @@ -181513,6 +183703,7 @@ __export(ts_exports2, { setValueDeclaration: () => setValueDeclaration, shouldAllowImportingTsExtension: () => shouldAllowImportingTsExtension, shouldPreserveConstEnums: () => shouldPreserveConstEnums, + shouldRewriteModuleSpecifier: () => shouldRewriteModuleSpecifier, shouldUseUriStyleNodeCoreModules: () => shouldUseUriStyleNodeCoreModules, showModuleSpecifier: () => showModuleSpecifier, signatureHasRestParameter: () => signatureHasRestParameter, @@ -181570,6 +183761,7 @@ __export(ts_exports2, { tagNamesAreEquivalent: () => tagNamesAreEquivalent, takeWhile: () => takeWhile, targetOptionDeclaration: () => targetOptionDeclaration, + targetToLibMap: () => targetToLibMap, testFormatSettings: () => testFormatSettings, textChangeRangeIsUnchanged: () => textChangeRangeIsUnchanged, textChangeRangeNewSpan: () => textChangeRangeNewSpan, @@ -181663,6 +183855,7 @@ __export(ts_exports2, { tryRemoveExtension: () => tryRemoveExtension, tryRemovePrefix: () => tryRemovePrefix, tryRemoveSuffix: () => tryRemoveSuffix, + tscBuildOption: () => tscBuildOption, typeAcquisitionDeclarations: () => typeAcquisitionDeclarations, typeAliasNamePart: () => typeAliasNamePart, typeDirectiveIsEqualTo: () => typeDirectiveIsEqualTo, @@ -181674,6 +183867,7 @@ __export(ts_exports2, { unescapeLeadingUnderscores: () => unescapeLeadingUnderscores, unmangleScopedPackageName: () => unmangleScopedPackageName, unorderedRemoveItem: () => unorderedRemoveItem, + unprefixedNodeCoreModules: () => unprefixedNodeCoreModules, unreachableCodeIsError: () => unreachableCodeIsError, unsetNodeChildren: () => unsetNodeChildren, unusedLabelIsError: () => unusedLabelIsError, @@ -181887,6 +184081,7 @@ __export(ts_server_exports3, { formatDiagnosticToProtocol: () => formatDiagnosticToProtocol, formatMessage: () => formatMessage2, getBaseConfigFileName: () => getBaseConfigFileName, + getDetailWatchInfo: () => getDetailWatchInfo, getLocationInNewDocument: () => getLocationInNewDocument, hasArgument: () => hasArgument, hasNoTypeScriptSource: () => hasNoTypeScriptSource, @@ -181909,6 +184104,8 @@ __export(ts_server_exports3, { nullCancellationToken: () => nullCancellationToken, nullTypingsInstaller: () => nullTypingsInstaller, protocol: () => ts_server_protocol_exports, + scriptInfoIsContainedByBackgroundProject: () => scriptInfoIsContainedByBackgroundProject, + scriptInfoIsContainedByDeferredClosedProject: () => scriptInfoIsContainedByDeferredClosedProject, stringifyIndented: () => stringifyIndented, toEvent: () => toEvent, toNormalizedPath: () => toNormalizedPath, @@ -182594,6 +184791,7 @@ var CommandTypes = /* @__PURE__ */ ((CommandTypes2) => { CommandTypes2["GetApplicableRefactors"] = "getApplicableRefactors"; CommandTypes2["GetEditsForRefactor"] = "getEditsForRefactor"; CommandTypes2["GetMoveToRefactoringFileSuggestions"] = "getMoveToRefactoringFileSuggestions"; + CommandTypes2["PreparePasteEdits"] = "preparePasteEdits"; CommandTypes2["GetPasteEdits"] = "getPasteEdits"; CommandTypes2["GetEditsForRefactorFull"] = "getEditsForRefactor-full"; CommandTypes2["OrganizeImports"] = "organizeImports"; @@ -182617,6 +184815,7 @@ var CommandTypes = /* @__PURE__ */ ((CommandTypes2) => { CommandTypes2["ProvideInlayHints"] = "provideInlayHints"; CommandTypes2["WatchChange"] = "watchChange"; CommandTypes2["MapCode"] = "mapCode"; + CommandTypes2["CopilotRelated"] = "copilotRelated"; return CommandTypes2; })(CommandTypes || {}); var WatchFileKind2 = /* @__PURE__ */ ((WatchFileKind3) => { @@ -182701,6 +184900,7 @@ var ScriptTarget11 = /* @__PURE__ */ ((ScriptTarget12) => { ScriptTarget12["ES2021"] = "es2021"; ScriptTarget12["ES2022"] = "es2022"; ScriptTarget12["ES2023"] = "es2023"; + ScriptTarget12["ES2024"] = "es2024"; ScriptTarget12["ESNext"] = "esnext"; ScriptTarget12["JSON"] = "json"; ScriptTarget12["Latest"] = "esnext" /* ESNext */; @@ -183145,13 +185345,6 @@ var ScriptInfo = class { isOrphan() { return this.deferredDelete || !forEach(this.containingProjects, (p) => !p.isOrphan()); } - /** @internal */ - isContainedByBackgroundProject() { - return some( - this.containingProjects, - isBackgroundProject - ); - } /** * @param line 1 based index */ @@ -183189,6 +185382,18 @@ function failIfInvalidLocation(location) { Debug.assert(location.line > 0, `Expected line to be non-${location.line === 0 ? "zero" : "negative"}`); Debug.assert(location.offset > 0, `Expected offset to be non-${location.offset === 0 ? "zero" : "negative"}`); } +function scriptInfoIsContainedByBackgroundProject(info) { + return some( + info.containingProjects, + isBackgroundProject + ); +} +function scriptInfoIsContainedByDeferredClosedProject(info) { + return some( + info.containingProjects, + isProjectDeferredClose + ); +} // src/server/project.ts var ProjectKind = /* @__PURE__ */ ((ProjectKind2) => { @@ -183305,10 +185510,9 @@ function unresolvedImportsChanged(imports1, imports2) { } var Project2 = class _Project { /** @internal */ - constructor(projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, watchOptions, directoryStructureHost, currentDirectory) { + constructor(projectName, projectKind, projectService, hasExplicitListOfFiles, lastFileExceededProgramSize, compilerOptions, compileOnSaveEnabled, watchOptions, directoryStructureHost, currentDirectory) { this.projectKind = projectKind; this.projectService = projectService; - this.documentRegistry = documentRegistry; this.compilerOptions = compilerOptions; this.compileOnSaveEnabled = compileOnSaveEnabled; this.watchOptions = watchOptions; @@ -183343,7 +185547,8 @@ var Project2 = class _Project { * @internal */ this.projectStateVersion = 0; - this.isInitialLoadPending = returnFalse; + /** @internal */ + this.initialLoadPending = false; /** @internal */ this.dirty = false; /** @internal */ @@ -183355,6 +185560,7 @@ var Project2 = class _Project { this.globalCacheResolutionModuleName = ts_JsTyping_exports.nonRelativeModuleNameForTypingCache; /** @internal */ this.updateFromProjectInProgress = false; + projectService.logger.info(`Creating ${ProjectKind[projectKind]}Project: ${projectName}, currentDirectory: ${currentDirectory}`); this.projectName = projectName; this.directoryStructureHost = directoryStructureHost; this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory); @@ -183400,7 +185606,11 @@ var Project2 = class _Project { /*logChangesWhenResolvingModule*/ true ); - this.languageService = createLanguageService(this, this.documentRegistry, this.projectService.serverMode); + this.languageService = createLanguageService( + this, + this.projectService.documentRegistry, + this.projectService.serverMode + ); if (lastFileExceededProgramSize) { this.disableLanguageService(lastFileExceededProgramSize); } @@ -183474,7 +185684,7 @@ var Project2 = class _Project { } /** @internal */ getGlobalTypingsCacheLocation() { - return this.getGlobalCache(); + return this.getTypeAcquisition().enable ? this.projectService.typingsInstaller.globalTypingsCacheLocation : void 0; } /** @internal */ getSymlinkCache() { @@ -183689,10 +185899,6 @@ var Project2 = class _Project { this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); } /** @internal */ - getGlobalCache() { - return this.getTypeAcquisition().enable ? this.projectService.typingsInstaller.globalTypingsCacheLocation : void 0; - } - /** @internal */ fileIsOpen(filePath) { return this.projectService.openFiles.has(filePath); } @@ -184095,19 +186301,12 @@ var Project2 = class _Project { } /** @internal */ onAutoImportProviderSettingsChanged() { - var _a; - if (this.autoImportProviderHost === false) { - this.autoImportProviderHost = void 0; - } else { - (_a = this.autoImportProviderHost) == null ? void 0 : _a.markAsDirty(); - } + this.markAutoImportProviderAsDirty(); } /** @internal */ onPackageJsonChange() { this.moduleSpecifierCache.clear(); - if (this.autoImportProviderHost) { - this.autoImportProviderHost.markAsDirty(); - } + this.markAutoImportProviderAsDirty(); } /** @internal */ onFileAddedOrRemoved(isSymlink) { @@ -184229,14 +186428,15 @@ var Project2 = class _Project { const canonicalPath = this.toPath(path); toRemove.delete(canonicalPath); if (!this.typingWatchers.has(canonicalPath)) { + const watchType = typingsWatcherType === "FileWatcher" /* FileWatcher */ ? WatchType.TypingInstallerLocationFile : WatchType.TypingInstallerLocationDirectory; this.typingWatchers.set( canonicalPath, - typingsWatcherType === "FileWatcher" /* FileWatcher */ ? this.projectService.watchFactory.watchFile( + canWatchDirectoryOrFilePath(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, + watchType, this ) : this.projectService.watchFactory.watchDirectory( path, @@ -184248,9 +186448,9 @@ var Project2 = class _Project { }, 1 /* Recursive */, this.projectService.getWatchOptions(this), - WatchType.TypingInstallerLocationDirectory, + watchType, this - ) + ) : (this.writeLog(`Skipping watcher creation at ${path}:: ${getDetailWatchInfo(watchType, this)}`), noopFileWatcher) ); } }; @@ -184286,7 +186486,7 @@ var Project2 = class _Project { } removeExistingTypings(include) { if (!include.length) return include; - const existing = getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost); + const existing = getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this); return filter(include, (i) => !existing.includes(i)); } updateGraphWorker() { @@ -184541,7 +186741,7 @@ var Project2 = class _Project { ); } filesToStringWorker(writeProjectFileNames, writeFileExplaination, writeFileVersionAndText) { - if (this.isInitialLoadPending()) return " Files (0) InitialLoadPending\n"; + if (this.initialLoadPending) return " Files (0) InitialLoadPending\n"; if (!this.program) return " Files (0) NoProgram\n"; const sourceFiles = this.program.getSourceFiles(); let strBuilder = ` Files (${sourceFiles.length}) @@ -184628,7 +186828,7 @@ var Project2 = class _Project { fileName, isSourceOfProjectReferenceRedirect })) : (files) => arrayFrom(files.keys()); - if (!this.isInitialLoadPending()) { + if (!this.initialLoadPending) { updateProjectIfDirty(this); } const info = { @@ -184792,7 +186992,7 @@ var Project2 = class _Project { } /** @internal */ getNearestAncestorDirectoryWithPackageJson(fileName) { - return this.projectService.getNearestAncestorDirectoryWithPackageJson(fileName); + return this.projectService.getNearestAncestorDirectoryWithPackageJson(fileName, this); } /** @internal */ getPackageJsonsForAutoImport(rootDir) { @@ -184863,7 +187063,11 @@ var Project2 = class _Project { if (dependencySelection) { (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "getPackageJsonAutoImportProvider"); const start = timestamp(); - this.autoImportProviderHost = AutoImportProviderProject.create(dependencySelection, this, this.getHostForAutoImportProvider(), this.documentRegistry); + this.autoImportProviderHost = AutoImportProviderProject.create( + dependencySelection, + this, + this.getHostForAutoImportProvider() + ) ?? false; if (this.autoImportProviderHost) { updateProjectIfDirty(this.autoImportProviderHost); this.sendPerformanceEvent("CreatePackageJsonAutoImportProvider", timestamp() - start); @@ -184890,11 +187094,12 @@ var Project2 = class _Project { /** @internal */ getNoDtsResolutionProject(rootFile) { Debug.assert(this.projectService.serverMode === 0 /* Semantic */); - if (!this.noDtsResolutionProject) { - this.noDtsResolutionProject = new AuxiliaryProject(this.projectService, this.documentRegistry, this.getCompilerOptionsForNoDtsResolutionProject(), this.currentDirectory); - } + this.noDtsResolutionProject ?? (this.noDtsResolutionProject = new AuxiliaryProject(this)); if (this.noDtsResolutionProject.rootFile !== rootFile) { - this.projectService.setFileNamesOfAutpImportProviderOrAuxillaryProject(this.noDtsResolutionProject, [rootFile]); + this.projectService.setFileNamesOfAutoImportProviderOrAuxillaryProject( + this.noDtsResolutionProject, + [rootFile] + ); this.noDtsResolutionProject.rootFile = rootFile; } return this.noDtsResolutionProject; @@ -184913,6 +187118,7 @@ var Project2 = class _Project { (_d = this.getScriptInfo(rootFile)) == null ? void 0 : _d.editContent(0, updatedText.length, originalText); } } + /** @internal */ getCompilerOptionsForNoDtsResolutionProject() { return { ...this.getCompilerOptions(), @@ -184955,15 +187161,13 @@ function extractUnresolvedImportsFromSourceFile(program, file, ambientModules, c } var InferredProject2 = class extends Project2 { /** @internal */ - constructor(projectService, documentRegistry, compilerOptions, watchOptions, projectRootPath, currentDirectory, typeAcquisition) { + constructor(projectService, compilerOptions, watchOptions, projectRootPath, currentDirectory, typeAcquisition) { super( projectService.newInferredProjectName(), 0 /* Inferred */, projectService, - documentRegistry, - // TODO: GH#18217 - /*files*/ - void 0, + /*hasExplicitListOfFiles*/ + false, /*lastFileExceededProgramSize*/ void 0, compilerOptions, @@ -185048,23 +187252,22 @@ var InferredProject2 = class extends Project2 { } }; var AuxiliaryProject = class extends Project2 { - constructor(projectService, documentRegistry, compilerOptions, currentDirectory) { + constructor(hostProject) { super( - projectService.newAuxiliaryProjectName(), + hostProject.projectService.newAuxiliaryProjectName(), 4 /* Auxiliary */, - projectService, - documentRegistry, + hostProject.projectService, /*hasExplicitListOfFiles*/ false, /*lastFileExceededProgramSize*/ void 0, - compilerOptions, + hostProject.getCompilerOptionsForNoDtsResolutionProject(), /*compileOnSaveEnabled*/ false, /*watchOptions*/ void 0, - projectService.host, - currentDirectory + hostProject.projectService.host, + hostProject.currentDirectory ); } isOrphan() { @@ -185076,12 +187279,11 @@ var AuxiliaryProject = class extends Project2 { }; var _AutoImportProviderProject = class _AutoImportProviderProject extends Project2 { /** @internal */ - constructor(hostProject, initialRootNames, documentRegistry, compilerOptions) { + constructor(hostProject, initialRootNames, compilerOptions) { super( hostProject.projectService.newAutoImportProviderProjectName(), 3 /* AutoImportProvider */, hostProject.projectService, - documentRegistry, /*hasExplicitListOfFiles*/ false, /*lastFileExceededProgramSize*/ @@ -185121,7 +187323,7 @@ var _AutoImportProviderProject = class _AutoImportProviderProject extends Projec if (dependencyNames) { const symlinkCache = hostProject.getSymlinkCache(); for (const name of arrayFrom(dependencyNames.keys())) { - if (dependencySelection === 2 /* Auto */ && dependenciesAdded > this.maxDependencies) { + if (dependencySelection === 2 /* Auto */ && dependenciesAdded >= this.maxDependencies) { hostProject.log(`AutoImportProviderProject: attempted to add more than ${this.maxDependencies} dependencies. Aborting.`); return emptyArray; } @@ -185242,7 +187444,7 @@ var _AutoImportProviderProject = class _AutoImportProviderProject extends Projec } } /** @internal */ - static create(dependencySelection, hostProject, host, documentRegistry) { + static create(dependencySelection, hostProject, host) { if (dependencySelection === 0 /* Off */) { return void 0; } @@ -185254,7 +187456,7 @@ var _AutoImportProviderProject = class _AutoImportProviderProject extends Projec if (!rootNames.length) { return void 0; } - return new _AutoImportProviderProject(hostProject, rootNames, documentRegistry, compilerOptions); + return new _AutoImportProviderProject(hostProject, rootNames, compilerOptions); } /** @internal */ isEmpty() { @@ -185274,7 +187476,7 @@ var _AutoImportProviderProject = class _AutoImportProviderProject extends Projec this.getCompilationSettings() ); } - this.projectService.setFileNamesOfAutpImportProviderOrAuxillaryProject(this, rootFileNames); + this.projectService.setFileNamesOfAutoImportProviderOrAuxillaryProject(this, rootFileNames); this.rootFileNames = rootFileNames; const oldProgram = this.getCurrentProgram(); const hasSameSetOfFiles = super.updateGraph(); @@ -185343,12 +187545,11 @@ _AutoImportProviderProject.compilerOptionsOverrides = { var AutoImportProviderProject = _AutoImportProviderProject; var ConfiguredProject2 = class extends Project2 { /** @internal */ - constructor(configFileName, canonicalConfigFilePath, projectService, documentRegistry, cachedDirectoryStructureHost, pendingUpdateReason) { + constructor(configFileName, canonicalConfigFilePath, projectService, cachedDirectoryStructureHost, pendingUpdateReason) { super( configFileName, 1 /* Configured */, projectService, - documentRegistry, /*hasExplicitListOfFiles*/ false, /*lastFileExceededProgramSize*/ @@ -185366,9 +187567,7 @@ var ConfiguredProject2 = class extends Project2 { /** @internal */ this.openFileWatchTriggered = /* @__PURE__ */ new Map(); /** @internal */ - this.canConfigFileJsonReportNoInputFiles = false; - /** @internal */ - this.isInitialLoadPending = returnTrue; + this.initialLoadPending = true; /** @internal */ this.sendLoadingProjectFinish = false; this.pendingUpdateLevel = 2 /* Full */; @@ -185388,7 +187587,7 @@ var ConfiguredProject2 = class extends Project2 { } /** @internal */ getParsedCommandLine(fileName) { - const configFileName = asNormalizedPath(normalizePath(fileName)); + const configFileName = toNormalizedPath(fileName); const canonicalConfigFilePath = asNormalizedPath(this.projectService.toCanonicalFileName(configFileName)); let configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (!configFileExistenceInfo) { @@ -185402,7 +187601,7 @@ var ConfiguredProject2 = class extends Project2 { } /** @internal */ onReleaseParsedCommandLine(fileName) { - this.releaseParsedConfig(asNormalizedPath(this.projectService.toCanonicalFileName(asNormalizedPath(normalizePath(fileName))))); + this.releaseParsedConfig(asNormalizedPath(this.projectService.toCanonicalFileName(toNormalizedPath(fileName)))); } releaseParsedConfig(canonicalConfigFilePath) { this.projectService.stopWatchingWildCards(canonicalConfigFilePath, this); @@ -185415,7 +187614,7 @@ var ConfiguredProject2 = class extends Project2 { updateGraph() { if (this.deferredClose) return false; const isDirty = this.dirty; - this.isInitialLoadPending = returnFalse; + this.initialLoadPending = false; const updateLevel = this.pendingUpdateLevel; this.pendingUpdateLevel = 0 /* Update */; let result; @@ -185467,7 +187666,7 @@ var ConfiguredProject2 = class extends Project2 { } /** @internal */ setPotentialProjectReference(canonicalConfigPath) { - Debug.assert(this.isInitialLoadPending()); + Debug.assert(this.initialLoadPending); (this.potentialProjectReferences || (this.potentialProjectReferences = /* @__PURE__ */ new Set())).add(canonicalConfigPath); } /** @internal */ @@ -185531,10 +187730,6 @@ var ConfiguredProject2 = class extends Project2 { super.markAsDirty(); } /** @internal */ - isSolution() { - return this.getRootFilesMap().size === 0 && !this.canConfigFileJsonReportNoInputFiles; - } - /** @internal */ isOrphan() { return !!this.deferredClose; } @@ -185542,18 +187737,24 @@ var ConfiguredProject2 = class extends Project2 { return getEffectiveTypeRoots(this.getCompilationSettings(), this) || []; } /** @internal */ - updateErrorOnNoInputFiles(fileNames) { - updateErrorForNoInputFiles(fileNames, this.getConfigFilePath(), this.getCompilerOptions().configFile.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles); + updateErrorOnNoInputFiles(parsedCommandLine) { + this.parsedCommandLine = parsedCommandLine; + updateErrorForNoInputFiles( + parsedCommandLine.fileNames, + this.getConfigFilePath(), + this.getCompilerOptions().configFile.configFileSpecs, + this.projectErrors, + canJsonReportNoInputFiles(parsedCommandLine.raw) + ); } }; var ExternalProject = class extends Project2 { /** @internal */ - constructor(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath, watchOptions) { + constructor(externalProjectName, projectService, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath, watchOptions) { super( externalProjectName, 2 /* External */, projectService, - documentRegistry, /*hasExplicitListOfFiles*/ true, lastFileExceededProgramSize, @@ -185765,8 +187966,23 @@ var nullTypingsInstaller = { }; var noopConfigFileWatcher = { close: noop }; function getConfigFileNameFromCache(info, cache) { - if (!cache || isAncestorConfigFileInfo(info)) return void 0; - return cache.get(info.path); + if (!cache) return void 0; + const configFileForOpenFile = cache.get(info.path); + if (configFileForOpenFile === void 0) return void 0; + if (!isAncestorConfigFileInfo(info)) { + return isString(configFileForOpenFile) || !configFileForOpenFile ? configFileForOpenFile : ( + // direct result + configFileForOpenFile.get( + /*key*/ + false + ) + ); + } else { + return configFileForOpenFile && !isString(configFileForOpenFile) ? ( + // Map with fileName as key + configFileForOpenFile.get(info.fileName) + ) : void 0; + } } function isOpenScriptInfo(infoOrFileNameOrConfig) { return !!infoOrFileNameOrConfig.containingProjects; @@ -185775,125 +187991,159 @@ function isAncestorConfigFileInfo(infoOrFileNameOrConfig) { return !!infoOrFileNameOrConfig.configFileInfo; } var ConfiguredProjectLoadKind = /* @__PURE__ */ ((ConfiguredProjectLoadKind2) => { - ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["Find"] = 0] = "Find"; - ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["Create"] = 1] = "Create"; - ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["Reload"] = 2] = "Reload"; + ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["FindOptimized"] = 0] = "FindOptimized"; + ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["Find"] = 1] = "Find"; + ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["CreateReplayOptimized"] = 2] = "CreateReplayOptimized"; + ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["CreateReplay"] = 3] = "CreateReplay"; + ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["CreateOptimized"] = 4] = "CreateOptimized"; + ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["Create"] = 5] = "Create"; + ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["ReloadOptimized"] = 6] = "ReloadOptimized"; + ConfiguredProjectLoadKind2[ConfiguredProjectLoadKind2["Reload"] = 7] = "Reload"; return ConfiguredProjectLoadKind2; })(ConfiguredProjectLoadKind || {}); -function forEachAncestorProject(info, project, cb, kind, reason, allowDeferredClosed, reloadedProjects, delayReloadedConfiguredProjects) { +function toConfiguredProjectLoadOptimized(kind) { + return kind - 1; +} +function forEachAncestorProjectLoad(info, project, cb, kind, reason, allowDeferredClosed, reloadedProjects, searchOnlyPotentialSolution, delayReloadedConfiguredProjects) { + var _a; while (true) { - if (!project.isInitialLoadPending() && (!project.getCompilerOptions().composite || project.getCompilerOptions().disableSolutionSearching)) return; - const configFileName = project.projectService.getConfigFileNameForFile({ - fileName: project.getConfigFilePath(), - path: info.path, - configFileInfo: true - }, kind === 0 /* Find */); + if (project.parsedCommandLine && (searchOnlyPotentialSolution && !project.parsedCommandLine.options.composite || // Currently disableSolutionSearching is shared for finding solution/project when + // - loading solution for find all references + // - trying to find default project + project.parsedCommandLine.options.disableSolutionSearching)) return; + const configFileName = project.projectService.getConfigFileNameForFile( + { + fileName: project.getConfigFilePath(), + path: info.path, + configFileInfo: true, + isForDefaultProject: !searchOnlyPotentialSolution + }, + kind <= 3 /* CreateReplay */ + ); if (!configFileName) return; const ancestor = project.projectService.findCreateOrReloadConfiguredProject( configFileName, kind, reason, allowDeferredClosed, - /*triggerFile*/ - void 0, + !searchOnlyPotentialSolution ? info.fileName : void 0, + // Config Diag event for project if its for default project reloadedProjects, - /*delayLoad*/ - true, + searchOnlyPotentialSolution, + // Delay load if we are searching for solution delayReloadedConfiguredProjects ); if (!ancestor) return; - if (ancestor.project.isInitialLoadPending() && project.getCompilerOptions().composite) { + if (!ancestor.project.parsedCommandLine && ((_a = project.parsedCommandLine) == null ? void 0 : _a.options.composite)) { ancestor.project.setPotentialProjectReference(project.canonicalConfigFilePath); } - const result = cb(ancestor.project); + const result = cb(ancestor); if (result) return result; project = ancestor.project; } } -function forEachResolvedProjectReferenceProject(project, fileName, cb, kind, reason, allowDeferredClosed, triggerFile, reloadedProjects) { - var _a; - const resolvedRefs = (_a = project.getCurrentProgram()) == null ? void 0 : _a.getResolvedProjectReferences(); - if (!resolvedRefs) return void 0; - const possibleDefaultRef = fileName ? project.getResolvedProjectReferenceToRedirect(fileName) : void 0; - if (possibleDefaultRef) { - const configFileName = toNormalizedPath(possibleDefaultRef.sourceFile.fileName); - const child = project.projectService.findConfiguredProjectByProjectName( - configFileName, - allowDeferredClosed - ); - if (child) { - const result = callbackWithProjectFoundUsingFind(child); - if (result) return result; - } else if (kind !== 0 /* Find */) { - const result = forEachResolvedProjectReferenceProjectWorker( - resolvedRefs, - project.getCompilerOptions(), - (ref, loadKind) => possibleDefaultRef === ref ? callback(ref, loadKind) : void 0, - kind, - project.projectService - ); - if (result) return result; +function forEachResolvedProjectReferenceProjectLoad(project, parentConfig, cb, kind, reason, allowDeferredClosed, reloadedProjects, seenResolvedRefs) { + const loadKind = parentConfig.options.disableReferencedProjectLoad ? 0 /* FindOptimized */ : kind; + let children; + return forEach( + parentConfig.projectReferences, + (ref) => { + var _a; + const childConfigName = toNormalizedPath(resolveProjectReferencePath(ref)); + const childCanonicalConfigPath = asNormalizedPath(project.projectService.toCanonicalFileName(childConfigName)); + const seenValue = seenResolvedRefs == null ? void 0 : seenResolvedRefs.get(childCanonicalConfigPath); + if (seenValue !== void 0 && seenValue >= loadKind) return void 0; + const configFileExistenceInfo = project.projectService.configFileExistenceInfoCache.get(childCanonicalConfigPath); + let childConfig = loadKind === 0 /* FindOptimized */ ? (configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.exists) || ((_a = project.resolvedChildConfigs) == null ? void 0 : _a.has(childCanonicalConfigPath)) ? configFileExistenceInfo.config.parsedCommandLine : void 0 : project.getParsedCommandLine(childConfigName); + if (childConfig && loadKind !== kind && loadKind > 2 /* CreateReplayOptimized */) { + childConfig = project.getParsedCommandLine(childConfigName); + } + if (!childConfig) return void 0; + const childProject = project.projectService.findConfiguredProjectByProjectName(childConfigName, allowDeferredClosed); + if (loadKind === 2 /* CreateReplayOptimized */ && !configFileExistenceInfo && !childProject) return void 0; + switch (loadKind) { + case 6 /* ReloadOptimized */: + if (childProject) childProject.projectService.reloadConfiguredProjectOptimized(childProject, reason, reloadedProjects); + // falls through + case 4 /* CreateOptimized */: + (project.resolvedChildConfigs ?? (project.resolvedChildConfigs = /* @__PURE__ */ new Set())).add(childCanonicalConfigPath); + // falls through + case 2 /* CreateReplayOptimized */: + case 0 /* FindOptimized */: + if (childProject || loadKind !== 0 /* FindOptimized */) { + const result = cb( + configFileExistenceInfo ?? project.projectService.configFileExistenceInfoCache.get(childCanonicalConfigPath), + childProject, + childConfigName, + reason, + project, + childCanonicalConfigPath + ); + if (result) return result; + } + break; + default: + Debug.assertNever(loadKind); + } + (seenResolvedRefs ?? (seenResolvedRefs = /* @__PURE__ */ new Map())).set(childCanonicalConfigPath, loadKind); + (children ?? (children = [])).push(childConfig); } - } - return forEachResolvedProjectReferenceProjectWorker( - resolvedRefs, - project.getCompilerOptions(), - (ref, loadKind) => possibleDefaultRef !== ref ? callback(ref, loadKind) : void 0, - kind, - project.projectService - ); - function callback(ref, loadKind) { - const result = project.projectService.findCreateOrReloadConfiguredProject( - toNormalizedPath(ref.sourceFile.fileName), + ) || forEach( + children, + (childConfig) => childConfig.projectReferences && forEachResolvedProjectReferenceProjectLoad( + project, + childConfig, + cb, loadKind, reason, allowDeferredClosed, - triggerFile, - reloadedProjects - ); - return result && (loadKind === kind ? cb(result.project, result.sentConfigFileDiag) : callbackWithProjectFoundUsingFind(result.project)); - } - function callbackWithProjectFoundUsingFind(child) { - let sentConfigFileDiag = false; - switch (kind) { - case 1 /* Create */: - sentConfigFileDiag = updateConfiguredProject(child, triggerFile); - break; - case 2 /* Reload */: - sentConfigFileDiag = child.projectService.reloadConfiguredProjectClearingSemanticCache(child, reason, reloadedProjects); - break; - case 0 /* Find */: - break; - default: - Debug.assertNever(kind); - } - const result = cb(child, sentConfigFileDiag); - if (result) return result; - } + reloadedProjects, + seenResolvedRefs + ) + ); } -function forEachResolvedProjectReferenceProjectWorker(resolvedProjectReferences, parentOptions, cb, kind, projectService, seenResolvedRefs) { - const loadKind = parentOptions.disableReferencedProjectLoad ? 0 /* Find */ : kind; - return forEach(resolvedProjectReferences, (ref) => { - if (!ref) return void 0; - const configFileName = toNormalizedPath(ref.sourceFile.fileName); - const canonicalPath = projectService.toCanonicalFileName(configFileName); - const seenValue = seenResolvedRefs == null ? void 0 : seenResolvedRefs.get(canonicalPath); - if (seenValue !== void 0 && seenValue >= loadKind) { - return void 0; - } - const result = cb(ref, loadKind); - if (result) { - return result; - } - (seenResolvedRefs || (seenResolvedRefs = /* @__PURE__ */ new Map())).set(canonicalPath, loadKind); - return ref.references && forEachResolvedProjectReferenceProjectWorker(ref.references, ref.commandLine.options, cb, loadKind, projectService, seenResolvedRefs); - }); +function updateProjectFoundUsingFind(project, kind, triggerFile, reason, reloadedProjects) { + let sentConfigFileDiag = false; + let configFileExistenceInfo; + switch (kind) { + case 2 /* CreateReplayOptimized */: + case 3 /* CreateReplay */: + if (useConfigFileExistenceInfoForOptimizedLoading(project)) { + configFileExistenceInfo = project.projectService.configFileExistenceInfoCache.get(project.canonicalConfigFilePath); + } + break; + case 4 /* CreateOptimized */: + configFileExistenceInfo = configFileExistenceInfoForOptimizedLoading(project); + if (configFileExistenceInfo) break; + // falls through + case 5 /* Create */: + sentConfigFileDiag = updateConfiguredProject(project, triggerFile); + break; + case 6 /* ReloadOptimized */: + project.projectService.reloadConfiguredProjectOptimized(project, reason, reloadedProjects); + configFileExistenceInfo = configFileExistenceInfoForOptimizedLoading(project); + if (configFileExistenceInfo) break; + // falls through + case 7 /* Reload */: + sentConfigFileDiag = project.projectService.reloadConfiguredProjectClearingSemanticCache( + project, + reason, + reloadedProjects + ); + break; + case 0 /* FindOptimized */: + case 1 /* Find */: + break; + default: + Debug.assertNever(kind); + } + return { project, sentConfigFileDiag, configFileExistenceInfo, reason }; } function forEachPotentialProjectReference(project, cb) { - return project.potentialProjectReferences && forEachKey(project.potentialProjectReferences, cb); + return project.initialLoadPending ? (project.potentialProjectReferences && forEachKey(project.potentialProjectReferences, cb)) ?? (project.resolvedChildConfigs && forEachKey(project.resolvedChildConfigs, cb)) : void 0; } function forEachAnyProjectReferenceKind(project, cb, cbProjectRef, cbPotentialProjectRef) { - return project.getCurrentProgram() ? project.forEachResolvedProjectReference(cb) : project.isInitialLoadPending() ? forEachPotentialProjectReference(project, cbPotentialProjectRef) : forEach(project.getProjectReferences(), cbProjectRef); + return project.getCurrentProgram() ? project.forEachResolvedProjectReference(cb) : project.initialLoadPending ? forEachPotentialProjectReference(project, cbPotentialProjectRef) : forEach(project.getProjectReferences(), cbProjectRef); } function callbackRefProject(project, cb, refPath) { const refProject = refPath && project.projectService.configuredProjects.get(refPath); @@ -185943,6 +188193,27 @@ function updateConfiguredProject(project, triggerFile) { } return false; } +function configFileExistenceInfoForOptimizedLoading(project) { + const configFileName = toNormalizedPath(project.getConfigFilePath()); + const configFileExistenceInfo = project.projectService.ensureParsedConfigUptoDate( + configFileName, + project.canonicalConfigFilePath, + project.projectService.configFileExistenceInfoCache.get(project.canonicalConfigFilePath), + project + ); + const parsedCommandLine = configFileExistenceInfo.config.parsedCommandLine; + project.parsedCommandLine = parsedCommandLine; + project.resolvedChildConfigs = void 0; + project.updateReferences(parsedCommandLine.projectReferences); + if (useConfigFileExistenceInfoForOptimizedLoading(project)) return configFileExistenceInfo; +} +function useConfigFileExistenceInfoForOptimizedLoading(project) { + return !!project.parsedCommandLine && (!!project.parsedCommandLine.options.composite || // If solution, no need to load it to determine if file belongs to it + !!isSolutionConfig(project.parsedCommandLine)); +} +function configFileExistenceInfoForOptimizedReplay(project) { + return useConfigFileExistenceInfoForOptimizedLoading(project) ? project.projectService.configFileExistenceInfoCache.get(project.canonicalConfigFilePath) : void 0; +} function fileOpenReason(info) { return `Creating possible configured project for ${info.fileName} to open`; } @@ -186064,7 +188335,7 @@ var _ProjectService = class _ProjectService { */ this.filenameToScriptInfoVersion = /* @__PURE__ */ new Map(); // Set of all '.js' files ever opened. - this.allJsFilesForOpenFileTelemetry = /* @__PURE__ */ new Map(); + this.allJsFilesForOpenFileTelemetry = /* @__PURE__ */ new Set(); /** * maps external project file name to list of config files that were the part of this project */ @@ -186161,6 +188432,9 @@ var _ProjectService = class _ProjectService { this.toCanonicalFileName = createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); this.globalCacheLocationDirectoryPath = this.typingsInstaller.globalTypingsCacheLocation ? ensureTrailingDirectorySeparator(this.toPath(this.typingsInstaller.globalTypingsCacheLocation)) : void 0; this.throttledOperations = new ThrottledOperations(this.host, this.logger); + this.logger.info(`currentDirectory:: ${this.host.getCurrentDirectory()} useCaseSensitiveFileNames:: ${this.host.useCaseSensitiveFileNames}`); + this.logger.info(`libs Location:: ${getDirectoryPath(this.host.getExecutingFilePath())}`); + this.logger.info(`globalTypingsCacheLocation:: ${this.typingsInstaller.globalTypingsCacheLocation}`); if (this.typesMapLocation) { this.loadTypesMap(); } else { @@ -186173,7 +188447,12 @@ var _ProjectService = class _ProjectService { hostInfo: "Unknown host", extraFileExtensions: [] }; - this.documentRegistry = createDocumentRegistryInternal(this.host.useCaseSensitiveFileNames, this.currentDirectory, this.jsDocParsingMode, this); + this.documentRegistry = createDocumentRegistryInternal( + this.host.useCaseSensitiveFileNames, + this.currentDirectory, + this.jsDocParsingMode, + this + ); const watchLogLevel = this.logger.hasLevel(3 /* verbose */) ? 2 /* Verbose */ : this.logger.loggingEnabled() ? 1 /* TriggerOnly */ : 0 /* None */; const log = watchLogLevel !== 0 /* None */ ? (s) => this.logger.info(s) : noop; this.packageJsonCache = createPackageJsonCache(this); @@ -186460,7 +188739,7 @@ var _ProjectService = class _ProjectService { if ((_a = this.pendingOpenFileProjectUpdates) == null ? void 0 : _a.delete(scriptInfo.path)) { this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo( scriptInfo, - 1 /* Create */ + 5 /* Create */ ); if (scriptInfo.isOrphan()) { this.assignOrphanScriptInfoToInferredProject(scriptInfo, this.openFiles.get(scriptInfo.path)); @@ -186675,22 +188954,35 @@ var _ProjectService = class _ProjectService { if (!(configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config)) return false; let scheduledAnyProjectUpdate = false; configFileExistenceInfo.config.updateLevel = 2 /* Full */; + configFileExistenceInfo.config.cachedDirectoryStructureHost.clearCache(); configFileExistenceInfo.config.projects.forEach((_watchWildcardDirectories, projectCanonicalPath) => { - var _a; + var _a, _b, _c; const project = this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath); if (!project) return; scheduledAnyProjectUpdate = true; if (projectCanonicalPath === canonicalConfigFilePath) { - if (project.isInitialLoadPending()) return; + if (project.initialLoadPending) return; project.pendingUpdateLevel = 2 /* Full */; project.pendingUpdateReason = loadReason; this.delayUpdateProjectGraph(project); project.markAutoImportProviderAsDirty(); } else { + if (project.initialLoadPending) { + (_b = (_a = this.configFileExistenceInfoCache.get(projectCanonicalPath)) == null ? void 0 : _a.openFilesImpactedByConfigFile) == null ? void 0 : _b.forEach((path2) => { + var _a2; + if (!((_a2 = this.pendingOpenFileProjectUpdates) == null ? void 0 : _a2.has(path2))) { + (this.pendingOpenFileProjectUpdates ?? (this.pendingOpenFileProjectUpdates = /* @__PURE__ */ new Map())).set( + path2, + this.configFileForOpenFiles.get(path2) + ); + } + }); + return; + } const path = this.toPath(canonicalConfigFilePath); project.resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); this.delayUpdateProjectGraph(project); - if (this.getHostPreferences().includeCompletionsForModuleExports && find((_a = project.getCurrentProgram()) == null ? void 0 : _a.getResolvedProjectReferences(), (ref) => (ref == null ? void 0 : ref.sourceFile.path) === path)) { + if (this.getHostPreferences().includeCompletionsForModuleExports && find((_c = project.getCurrentProgram()) == null ? void 0 : _c.getResolvedProjectReferences(), (ref) => (ref == null ? void 0 : ref.sourceFile.path) === path)) { project.markAutoImportProviderAsDirty(); } } @@ -186715,7 +189007,6 @@ var _ProjectService = class _ProjectService { canonicalConfigFilePath, "Change in config file detected" ); - const updatedProjects = new Set(project ? [project] : void 0); this.openFiles.forEach((_projectRootPath, path) => { var _a, _b; const configFileForOpenFile = this.configFileForOpenFiles.get(path); @@ -186728,16 +189019,9 @@ var _ProjectService = class _ProjectService { false ); if (!newConfigFileNameForInfo) return; - const projectForInfo = this.findConfiguredProjectByProjectName(newConfigFileNameForInfo) ?? this.createConfiguredProject( - newConfigFileNameForInfo, - `Change in config file ${configFileName} detected, ${fileOpenReason(info)}` - ); if (!((_b = this.pendingOpenFileProjectUpdates) == null ? void 0 : _b.has(path))) { (this.pendingOpenFileProjectUpdates ?? (this.pendingOpenFileProjectUpdates = /* @__PURE__ */ new Map())).set(path, configFileForOpenFile); } - if (tryAddToSet(updatedProjects, projectForInfo) && projectForInfo.isInitialLoadPending()) { - this.delayUpdateProjectGraph(projectForInfo); - } }); this.delayEnsureProjectForOpenFiles(); } @@ -186909,7 +189193,7 @@ var _ProjectService = class _ProjectService { configFileExists(configFileName, canonicalConfigFilePath, info) { const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); let openFilesImpactedByConfigFile; - if (this.openFiles.has(info.path) && !isAncestorConfigFileInfo(info)) { + if (this.openFiles.has(info.path) && (!isAncestorConfigFileInfo(info) || info.isForDefaultProject)) { if (configFileExistenceInfo) (configFileExistenceInfo.openFilesImpactedByConfigFile ?? (configFileExistenceInfo.openFilesImpactedByConfigFile = /* @__PURE__ */ new Set())).add(info.path); else (openFilesImpactedByConfigFile = /* @__PURE__ */ new Set()).add(info.path); } @@ -186931,6 +189215,9 @@ var _ProjectService = class _ProjectService { forProject ); } + this.ensureConfigFileWatcherForProject(configFileExistenceInfo, forProject); + } + ensureConfigFileWatcherForProject(configFileExistenceInfo, forProject) { const projects = configFileExistenceInfo.config.projects; projects.set(forProject.canonicalConfigFilePath, projects.get(forProject.canonicalConfigFilePath) || false); } @@ -186945,7 +189232,7 @@ var _ProjectService = class _ProjectService { Debug.checkDefined(configFileExistenceInfo.watcher); if ((_c = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _c.size) { if (configFileExistenceInfo.inferredProjectRoots) { - if (!canWatchDirectoryOrFile(getPathComponents(getDirectoryPath(canonicalConfigFilePath)))) { + if (!canWatchDirectoryOrFilePath(getDirectoryPath(canonicalConfigFilePath))) { configFileExistenceInfo.watcher.close(); configFileExistenceInfo.watcher = noopConfigFileWatcher; } @@ -187008,7 +189295,7 @@ var _ProjectService = class _ProjectService { configFileExistenceInfo.inferredProjectRoots = (configFileExistenceInfo.inferredProjectRoots ?? 0) + 1; } (configFileExistenceInfo.openFilesImpactedByConfigFile ?? (configFileExistenceInfo.openFilesImpactedByConfigFile = /* @__PURE__ */ new Set())).add(info.path); - configFileExistenceInfo.watcher || (configFileExistenceInfo.watcher = canWatchDirectoryOrFile(getPathComponents(getDirectoryPath(canonicalConfigFilePath))) ? this.watchFactory.watchFile( + configFileExistenceInfo.watcher || (configFileExistenceInfo.watcher = canWatchDirectoryOrFilePath(getDirectoryPath(canonicalConfigFilePath)) ? this.watchFactory.watchFile( configFileName, (_filename, eventKind) => this.onConfigFileChanged(configFileName, canonicalConfigFilePath, eventKind), 2e3 /* High */, @@ -187036,34 +189323,48 @@ var _ProjectService = class _ProjectService { let searchPath = asNormalizedPath(getDirectoryPath(info.fileName)); const isSearchPathInProjectRoot = () => containsPath(projectRootPath, searchPath, this.currentDirectory, !this.host.useCaseSensitiveFileNames); const anySearchPathOk = !projectRootPath || !isSearchPathInProjectRoot(); - let searchInDirectory = !isAncestorConfigFileInfo(info); + let searchTsconfig = true; + let searchJsconfig = true; + if (isAncestorConfigFileInfo(info)) { + if (endsWith(info.fileName, "tsconfig.json")) searchTsconfig = false; + else searchTsconfig = searchJsconfig = false; + } do { - if (searchInDirectory) { - const canonicalSearchPath = normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName); + const canonicalSearchPath = normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName); + if (searchTsconfig) { const tsconfigFileName = asNormalizedPath(combinePaths(searchPath, "tsconfig.json")); - let result = action(combinePaths(canonicalSearchPath, "tsconfig.json"), tsconfigFileName); + const result = action(combinePaths(canonicalSearchPath, "tsconfig.json"), tsconfigFileName); if (result) return tsconfigFileName; + } + if (searchJsconfig) { const jsconfigFileName = asNormalizedPath(combinePaths(searchPath, "jsconfig.json")); - result = action(combinePaths(canonicalSearchPath, "jsconfig.json"), jsconfigFileName); + const result = action(combinePaths(canonicalSearchPath, "jsconfig.json"), jsconfigFileName); if (result) return jsconfigFileName; - if (isNodeModulesDirectory(canonicalSearchPath)) { - break; - } + } + if (isNodeModulesDirectory(canonicalSearchPath)) { + break; } const parentPath = asNormalizedPath(getDirectoryPath(searchPath)); if (parentPath === searchPath) break; searchPath = parentPath; - searchInDirectory = true; + searchTsconfig = searchJsconfig = true; } while (anySearchPathOk || isSearchPathInProjectRoot()); return void 0; } /** @internal */ findDefaultConfiguredProject(info) { var _a; - return info.isScriptOpen() ? (_a = this.tryFindDefaultConfiguredProjectForOpenScriptInfo( + return (_a = this.findDefaultConfiguredProjectWorker( info, - 0 /* Find */ - )) == null ? void 0 : _a.defaultProject : void 0; + 1 /* Find */ + )) == null ? void 0 : _a.defaultProject; + } + /** @internal */ + findDefaultConfiguredProjectWorker(info, kind) { + return info.isScriptOpen() ? this.tryFindDefaultConfiguredProjectForOpenScriptInfo( + info, + kind + ) : void 0; } /** Get cached configFileName for scriptInfo or ancestor of open script info */ getConfigFileNameForFileFromCache(info, lookInPendingFilesForValue) { @@ -187076,8 +189377,19 @@ var _ProjectService = class _ProjectService { /** Caches the configFilename for script info or ancestor of open script info */ setConfigFileNameForFileInCache(info, configFileName) { if (!this.openFiles.has(info.path)) return; - if (isAncestorConfigFileInfo(info)) return; - this.configFileForOpenFiles.set(info.path, configFileName || false); + const config = configFileName || false; + if (!isAncestorConfigFileInfo(info)) { + this.configFileForOpenFiles.set(info.path, config); + } else { + let configFileForOpenFile = this.configFileForOpenFiles.get(info.path); + if (!configFileForOpenFile || isString(configFileForOpenFile)) { + this.configFileForOpenFiles.set( + info.path, + configFileForOpenFile = (/* @__PURE__ */ new Map()).set(false, configFileForOpenFile) + ); + } + configFileForOpenFile.set(info.fileName, config); + } } /** * This function tries to search for a tsconfig.json for the given file. @@ -187157,7 +189469,6 @@ var _ProjectService = class _ProjectService { const project = new ExternalProject( projectFileName, this, - this.documentRegistry, compilerOptions, /*lastFileExceededProgramSize*/ this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), @@ -187228,7 +189539,6 @@ var _ProjectService = class _ProjectService { createConfiguredProject(configFileName, reason) { var _a; (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "createConfiguredProject", { configFilePath: configFileName }); - this.logger.info(`Creating configuration project ${configFileName}`); const canonicalConfigFilePath = asNormalizedPath(this.toCanonicalFileName(configFileName)); let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (!configFileExistenceInfo) { @@ -187247,7 +189557,6 @@ var _ProjectService = class _ProjectService { configFileName, canonicalConfigFilePath, this, - this.documentRegistry, configFileExistenceInfo.config.cachedDirectoryStructureHost, reason ); @@ -187263,7 +189572,7 @@ var _ProjectService = class _ProjectService { var _a, _b; (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "loadConfiguredProject", { configFilePath: project.canonicalConfigFilePath }); this.sendProjectLoadingStartEvent(project, reason); - const configFilename = asNormalizedPath(normalizePath(project.getConfigFilePath())); + const configFilename = toNormalizedPath(project.getConfigFilePath()); const configFileExistenceInfo = this.ensureParsedConfigUptoDate( configFilename, project.canonicalConfigFilePath, @@ -187281,7 +189590,7 @@ var _ProjectService = class _ProjectService { configHasExcludeProperty: parsedCommandLine.raw.exclude !== void 0 }; } - project.canConfigFileJsonReportNoInputFiles = canJsonReportNoInputFiles(parsedCommandLine.raw); + project.parsedCommandLine = parsedCommandLine; project.setProjectErrors(parsedCommandLine.options.configFile.parseDiagnostics); project.updateReferences(parsedCommandLine.projectReferences); const lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); @@ -187303,12 +189612,19 @@ var _ProjectService = class _ProjectService { ensureParsedConfigUptoDate(configFilename, canonicalConfigFilePath, configFileExistenceInfo, forProject) { var _a, _b, _c; if (configFileExistenceInfo.config) { - if (!configFileExistenceInfo.config.updateLevel) return configFileExistenceInfo; if (configFileExistenceInfo.config.updateLevel === 1 /* RootNamesAndUpdate */) { this.reloadFileNamesOfParsedConfig(configFilename, configFileExistenceInfo.config); + } + if (!configFileExistenceInfo.config.updateLevel) { + this.ensureConfigFileWatcherForProject(configFileExistenceInfo, forProject); return configFileExistenceInfo; } } + if (!configFileExistenceInfo.exists && configFileExistenceInfo.config) { + configFileExistenceInfo.config.updateLevel = void 0; + this.ensureConfigFileWatcherForProject(configFileExistenceInfo, forProject); + return configFileExistenceInfo; + } const cachedDirectoryStructureHost = ((_a = configFileExistenceInfo.config) == null ? void 0 : _a.cachedDirectoryStructureHost) || createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); const configFileContent = tryReadFile(configFilename, (fileName) => this.host.readFile(fileName)); const configFile = parseJsonText(configFilename, isString(configFileContent) ? configFileContent : ""); @@ -187503,14 +189819,18 @@ var _ProjectService = class _ProjectService { * @internal */ reloadFileNamesOfConfiguredProject(project) { - const fileNames = this.reloadFileNamesOfParsedConfig(project.getConfigFilePath(), this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath).config); - project.updateErrorOnNoInputFiles(fileNames); - this.updateNonInferredProjectFiles(project, fileNames.concat(project.getExternalFiles(1 /* RootNamesAndUpdate */)), fileNamePropertyReader); + const config = this.reloadFileNamesOfParsedConfig(project.getConfigFilePath(), this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath).config); + project.updateErrorOnNoInputFiles(config); + this.updateNonInferredProjectFiles( + project, + config.fileNames.concat(project.getExternalFiles(1 /* RootNamesAndUpdate */)), + fileNamePropertyReader + ); project.markAsDirty(); return project.updateGraph(); } reloadFileNamesOfParsedConfig(configFileName, config) { - if (config.updateLevel === void 0) return config.parsedCommandLine.fileNames; + if (config.updateLevel === void 0) return config.parsedCommandLine; Debug.assert(config.updateLevel === 1 /* RootNamesAndUpdate */); const configFileSpecs = config.parsedCommandLine.options.configFile.configFileSpecs; const fileNames = getFileNamesFromConfigSpecs( @@ -187521,30 +189841,42 @@ var _ProjectService = class _ProjectService { this.hostConfiguration.extraFileExtensions ); config.parsedCommandLine = { ...config.parsedCommandLine, fileNames }; - return fileNames; + config.updateLevel = void 0; + return config.parsedCommandLine; } /** @internal */ - setFileNamesOfAutpImportProviderOrAuxillaryProject(project, fileNames) { + setFileNamesOfAutoImportProviderOrAuxillaryProject(project, fileNames) { this.updateNonInferredProjectFiles(project, fileNames, fileNamePropertyReader); } /** @internal */ + reloadConfiguredProjectOptimized(project, reason, reloadedProjects) { + if (reloadedProjects.has(project)) return; + reloadedProjects.set(project, 6 /* ReloadOptimized */); + if (!project.initialLoadPending) { + this.setProjectForReload(project, 2 /* Full */, reason); + } + } + /** @internal */ reloadConfiguredProjectClearingSemanticCache(project, reason, reloadedProjects) { - if (!tryAddToSet(reloadedProjects, project)) return false; + if (reloadedProjects.get(project) === 7 /* Reload */) return false; + reloadedProjects.set(project, 7 /* Reload */); this.clearSemanticCache(project); this.reloadConfiguredProject(project, reloadReason(reason)); return true; } + setProjectForReload(project, updateLevel, reason) { + if (updateLevel === 2 /* Full */) this.clearSemanticCache(project); + project.pendingUpdateReason = reason && reloadReason(reason); + project.pendingUpdateLevel = updateLevel; + } /** * Read the config file of the project again by clearing the cache and update the project graph * * @internal */ reloadConfiguredProject(project, reason) { - project.isInitialLoadPending = returnFalse; - project.pendingUpdateReason = void 0; - project.pendingUpdateLevel = 0 /* Update */; - const host = project.getCachedDirectoryStructureHost(); - host.clearCache(); + project.initialLoadPending = false; + this.setProjectForReload(project, 0 /* Update */); this.loadConfiguredProject(project, reason); updateWithTriggerFile( project, @@ -187614,9 +189946,11 @@ var _ProjectService = class _ProjectService { return this.inferredProjects[0]; } return this.createInferredProject( - "", + this.currentDirectory, /*isSingleInferredProject*/ - true + true, + /*projectRootPath*/ + void 0 ); } getOrCreateSingleInferredWithoutProjectRoot(currentDirectory) { @@ -187627,7 +189961,13 @@ var _ProjectService = class _ProjectService { return inferredProject; } } - return this.createInferredProject(currentDirectory); + return this.createInferredProject( + currentDirectory, + /*isSingleInferredProject*/ + false, + /*projectRootPath*/ + void 0 + ); } createInferredProject(currentDirectory, isSingleInferredProject, projectRootPath) { const compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; @@ -187644,7 +189984,14 @@ var _ProjectService = class _ProjectService { typeAcquisition = this.typeAcquisitionForInferredProjects; } watchOptionsAndErrors = watchOptionsAndErrors || void 0; - const project = new InferredProject2(this, this.documentRegistry, compilerOptions, watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions, projectRootPath, currentDirectory, typeAcquisition); + const project = new InferredProject2( + this, + compilerOptions, + watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions, + projectRootPath, + currentDirectory, + typeAcquisition + ); project.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors); if (isSingleInferredProject) { this.inferredProjects.unshift(project); @@ -188175,25 +190522,23 @@ Dynamic files must always be opened with service's current directory or service this.pendingOpenFileProjectUpdates = void 0; this.pendingEnsureProjectForOpenFiles = false; this.configFileExistenceInfoCache.forEach((info) => { - if (info.config) info.config.updateLevel = 2 /* Full */; + if (info.config) { + info.config.updateLevel = 2 /* Full */; + info.config.cachedDirectoryStructureHost.clearCache(); + } }); this.configFileForOpenFiles.clear(); this.externalProjects.forEach((project) => { this.clearSemanticCache(project); project.updateGraph(); }); - const reloadedConfiguredProjects = /* @__PURE__ */ new Set(); + const reloadedConfiguredProjects = /* @__PURE__ */ new Map(); const delayReloadedConfiguredProjects = /* @__PURE__ */ new Set(); this.externalProjectToConfiguredProjectMap.forEach((projects, externalProjectName) => { const reason = `Reloading configured project in external project: ${externalProjectName}`; projects.forEach((project) => { if (this.getHostPreferences().lazyConfiguredProjectsFromExternalProject) { - if (!project.isInitialLoadPending()) { - this.clearSemanticCache(project); - project.pendingUpdateLevel = 2 /* Full */; - project.pendingUpdateReason = reloadReason(reason); - } - delayReloadedConfiguredProjects.add(project); + this.reloadConfiguredProjectOptimized(project, reason, reloadedConfiguredProjects); } else { this.reloadConfiguredProjectClearingSemanticCache( project, @@ -188208,12 +190553,12 @@ Dynamic files must always be opened with service's current directory or service if (find(info.containingProjects, isExternalProject)) return; this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo( info, - 2 /* Reload */, + 7 /* Reload */, reloadedConfiguredProjects, delayReloadedConfiguredProjects ); }); - delayReloadedConfiguredProjects.forEach((p) => reloadedConfiguredProjects.add(p)); + delayReloadedConfiguredProjects.forEach((p) => reloadedConfiguredProjects.set(p, 7 /* Reload */)); this.inferredProjects.forEach((project) => this.clearSemanticCache(project)); this.ensureProjectForOpenFiles(); this.cleanupProjectsAndScriptInfos( @@ -188255,7 +190600,7 @@ Dynamic files must always be opened with service's current directory or service pendingOpenFileProjectUpdates == null ? void 0 : pendingOpenFileProjectUpdates.forEach( (_config, path) => this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo( this.getScriptInfoForPath(path), - 1 /* Create */ + 5 /* Create */ ) ); this.openFiles.forEach((projectRootPath, path) => { @@ -188311,23 +190656,18 @@ Dynamic files must always be opened with service's current directory or service } configuredProject = this.createConfiguredProject(configFileName, `Creating project for original file: ${originalFileInfo.fileName}${location !== originalLocation ? " for location: " + location.fileName : ""}`); } - updateProjectIfDirty(configuredProject); - const projectContainsOriginalInfo = (project2) => { - const info = this.getScriptInfo(fileName); - return info && project2.containsScriptInfo(info) && !project2.isSourceOfProjectReferenceRedirect(info.path); - }; - if (configuredProject.isSolution() || !projectContainsOriginalInfo(configuredProject)) { - configuredProject = forEachResolvedProjectReferenceProject( + const result = this.tryFindDefaultConfiguredProjectForOpenScriptInfoOrClosedFileInfo( + originalFileInfo, + 5 /* Create */, + updateProjectFoundUsingFind( configuredProject, - fileName, - (child) => projectContainsOriginalInfo(child) ? child : void 0, - 1 /* Create */, - `Creating project referenced in solution ${configuredProject.projectName} to find possible configured project for original file: ${originalFileInfo.fileName}${location !== originalLocation ? " for location: " + location.fileName : ""}` - ); - if (!configuredProject) return void 0; - if (configuredProject === project) return originalLocation; - } - addOriginalConfiguredProject(configuredProject); + 4 /* CreateOptimized */ + ), + (project2) => `Creating project referenced in solution ${project2.projectName} to find possible configured project for original file: ${originalFileInfo.fileName}${location !== originalLocation ? " for location: " + location.fileName : ""}` + ); + if (!result.defaultProject) return void 0; + if (result.defaultProject === project) return originalLocation; + addOriginalConfiguredProject(result.defaultProject); const originalScriptInfo = this.getScriptInfo(fileName); if (!originalScriptInfo || !originalScriptInfo.containingProjects.length) return void 0; originalScriptInfo.containingProjects.forEach((project2) => { @@ -188376,7 +190716,7 @@ Dynamic files must always be opened with service's current directory or service if (!project && this.serverMode === 0 /* Semantic */) { const result = this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo( info, - 1 /* Create */ + 5 /* Create */ ); if (result) { retainProjects = result.seenProjects; @@ -188389,8 +190729,8 @@ Dynamic files must always be opened with service's current directory or service } info.containingProjects.forEach(updateProjectIfDirty); if (info.isOrphan()) { - retainProjects == null ? void 0 : retainProjects.forEach((project2) => { - if (!sentConfigDiag.has(project2)) this.sendConfigFileDiagEvent( + retainProjects == null ? void 0 : retainProjects.forEach((kind, project2) => { + if (kind !== 4 /* CreateOptimized */ && !sentConfigDiag.has(project2)) this.sendConfigFileDiagEvent( project2, info.fileName, /*force*/ @@ -188410,30 +190750,49 @@ Dynamic files must always be opened with service's current directory or service * - Reload - if the project doesnt exist, it creates one. If not delayLoad, the project is reloaded clearing semantic cache * @internal */ - findCreateOrReloadConfiguredProject(configFileName, kind, reason, allowDeferredClosed, triggerFile, reloadedProjects, delayLoad, delayReloadedConfiguredProjects) { - let project = this.findConfiguredProjectByProjectName(configFileName, allowDeferredClosed); + findCreateOrReloadConfiguredProject(configFileName, kind, reason, allowDeferredClosed, triggerFile, reloadedProjects, delayLoad, delayReloadedConfiguredProjects, projectForConfigFile) { + let project = projectForConfigFile ?? this.findConfiguredProjectByProjectName(configFileName, allowDeferredClosed); let sentConfigFileDiag = false; + let configFileExistenceInfo; switch (kind) { - case 0 /* Find */: + case 0 /* FindOptimized */: + case 1 /* Find */: + case 3 /* CreateReplay */: if (!project) return; break; - case 1 /* Create */: + case 2 /* CreateReplayOptimized */: + if (!project) return; + configFileExistenceInfo = configFileExistenceInfoForOptimizedReplay(project); + break; + case 4 /* CreateOptimized */: + case 5 /* Create */: project ?? (project = this.createConfiguredProject(configFileName, reason)); - sentConfigFileDiag = !delayLoad && updateConfiguredProject(project, triggerFile); + if (!delayLoad) { + ({ sentConfigFileDiag, configFileExistenceInfo } = updateProjectFoundUsingFind( + project, + kind, + triggerFile + )); + } break; - case 2 /* Reload */: + case 6 /* ReloadOptimized */: + project ?? (project = this.createConfiguredProject(configFileName, reloadReason(reason))); + project.projectService.reloadConfiguredProjectOptimized(project, reason, reloadedProjects); + configFileExistenceInfo = configFileExistenceInfoForOptimizedLoading(project); + if (configFileExistenceInfo) break; + // falls through + case 7 /* Reload */: project ?? (project = this.createConfiguredProject(configFileName, reloadReason(reason))); sentConfigFileDiag = !delayReloadedConfiguredProjects && this.reloadConfiguredProjectClearingSemanticCache(project, reason, reloadedProjects); if (delayReloadedConfiguredProjects && !delayReloadedConfiguredProjects.has(project) && !reloadedProjects.has(project)) { - project.pendingUpdateLevel = 2 /* Full */; - project.pendingUpdateReason = reloadReason(reason); + this.setProjectForReload(project, 2 /* Full */, reason); delayReloadedConfiguredProjects.add(project); } break; default: Debug.assertNever(kind); } - return { project, sentConfigFileDiag }; + return { project, sentConfigFileDiag, configFileExistenceInfo, reason }; } /** * Finds the default configured project for given info @@ -188441,54 +190800,167 @@ Dynamic files must always be opened with service's current directory or service * The search happens for all tsconfigs till projectRootPath */ tryFindDefaultConfiguredProjectForOpenScriptInfo(info, kind, allowDeferredClosed, reloadedProjects) { - const configFileName = this.getConfigFileNameForFile(info, kind === 0 /* Find */); + const configFileName = this.getConfigFileNameForFile(info, kind <= 3 /* CreateReplay */); if (!configFileName) return; + const optimizedKind = toConfiguredProjectLoadOptimized(kind); const result = this.findCreateOrReloadConfiguredProject( configFileName, - kind, + optimizedKind, fileOpenReason(info), allowDeferredClosed, info.fileName, reloadedProjects ); - if (!result) return; - const seenProjects = /* @__PURE__ */ new Set(); - const sentConfigDiag = new Set(result.sentConfigFileDiag ? [result.project] : void 0); + return result && this.tryFindDefaultConfiguredProjectForOpenScriptInfoOrClosedFileInfo( + info, + kind, + result, + (project) => `Creating project referenced in solution ${project.projectName} to find possible configured project for ${info.fileName} to open`, + allowDeferredClosed, + reloadedProjects + ); + } + isMatchedByConfig(configFileName, config, info) { + if (config.fileNames.some((rootName) => this.toPath(rootName) === info.path)) return true; + if (isSupportedSourceFileName( + info.fileName, + config.options, + this.hostConfiguration.extraFileExtensions + )) return false; + const { validatedFilesSpec, validatedIncludeSpecs, validatedExcludeSpecs } = config.options.configFile.configFileSpecs; + const basePath = toNormalizedPath(getNormalizedAbsolutePath(getDirectoryPath(configFileName), this.currentDirectory)); + if (validatedFilesSpec == null ? void 0 : validatedFilesSpec.some((fileSpec) => this.toPath(getNormalizedAbsolutePath(fileSpec, basePath)) === info.path)) return true; + if (!(validatedIncludeSpecs == null ? void 0 : validatedIncludeSpecs.length)) return false; + if (matchesExcludeWorker( + info.fileName, + validatedExcludeSpecs, + this.host.useCaseSensitiveFileNames, + this.currentDirectory, + basePath + )) return false; + return validatedIncludeSpecs == null ? void 0 : validatedIncludeSpecs.some((includeSpec) => { + const pattern = getPatternFromSpec(includeSpec, basePath, "files"); + return !!pattern && getRegexFromPattern(`(${pattern})$`, this.host.useCaseSensitiveFileNames).test(info.fileName); + }); + } + tryFindDefaultConfiguredProjectForOpenScriptInfoOrClosedFileInfo(info, kind, initialConfigResult, referencedProjectReason, allowDeferredClosed, reloadedProjects) { + const infoIsOpenScriptInfo = isOpenScriptInfo(info); + const optimizedKind = toConfiguredProjectLoadOptimized(kind); + const seenProjects = /* @__PURE__ */ new Map(); + let seenConfigs; + const sentConfigDiag = /* @__PURE__ */ new Set(); let defaultProject; let possiblyDefault; - tryFindDefaultConfiguredProject(result.project); + let tsconfigOfDefault; + let tsconfigOfPossiblyDefault; + tryFindDefaultConfiguredProject(initialConfigResult); return { defaultProject: defaultProject ?? possiblyDefault, + tsconfigProject: tsconfigOfDefault ?? tsconfigOfPossiblyDefault, sentConfigDiag, - seenProjects + seenProjects, + seenConfigs }; - function tryFindDefaultConfiguredProject(project) { - return isDefaultProject(project) ? defaultProject : tryFindDefaultConfiguredProjectFromReferences(project); - } - function isDefaultProject(project) { - if (!tryAddToSet(seenProjects, project)) return; - const projectWithInfo = project.containsScriptInfo(info); - if (projectWithInfo && !project.isSourceOfProjectReferenceRedirect(info.path)) return defaultProject = project; - possiblyDefault ?? (possiblyDefault = projectWithInfo ? project : void 0); + function tryFindDefaultConfiguredProject(result) { + return isDefaultProjectOptimized(result, result.project) ?? tryFindDefaultConfiguredProjectFromReferences(result.project) ?? tryFindDefaultConfiguredProjectFromAncestor(result.project); } - function tryFindDefaultConfiguredProjectFromReferences(project) { - return forEachResolvedProjectReferenceProject( + function isDefaultConfigFileExistenceInfo(configFileExistenceInfo, project, childConfigName, reason, tsconfigProject, canonicalConfigFilePath) { + if (project) { + if (seenProjects.has(project)) return; + seenProjects.set(project, optimizedKind); + } else { + if (seenConfigs == null ? void 0 : seenConfigs.has(canonicalConfigFilePath)) return; + (seenConfigs ?? (seenConfigs = /* @__PURE__ */ new Set())).add(canonicalConfigFilePath); + } + if (!tsconfigProject.projectService.isMatchedByConfig( + childConfigName, + configFileExistenceInfo.config.parsedCommandLine, + info + )) { + if (tsconfigProject.languageServiceEnabled) { + tsconfigProject.projectService.watchWildcards( + childConfigName, + configFileExistenceInfo, + tsconfigProject + ); + } + return; + } + const result = project ? updateProjectFoundUsingFind( project, - info.path, - (child, sentConfigFileDiag) => { - if (sentConfigFileDiag) sentConfigDiag.add(child); - return isDefaultProject(child); - }, kind, - `Creating project referenced in solution ${project.projectName} to find possible configured project for ${info.fileName} to open`, + info.fileName, + reason, + reloadedProjects + ) : tsconfigProject.projectService.findCreateOrReloadConfiguredProject( + childConfigName, + kind, + reason, allowDeferredClosed, info.fileName, reloadedProjects ); + if (!result) { + Debug.assert(kind === 3 /* CreateReplay */); + return void 0; + } + seenProjects.set(result.project, optimizedKind); + if (result.sentConfigFileDiag) sentConfigDiag.add(result.project); + return isDefaultProject(result.project, tsconfigProject); + } + function isDefaultProject(project, tsconfigProject) { + if (seenProjects.get(project) === kind) return; + seenProjects.set(project, kind); + const scriptInfo = infoIsOpenScriptInfo ? info : project.projectService.getScriptInfo(info.fileName); + const projectWithInfo = scriptInfo && project.containsScriptInfo(scriptInfo); + if (projectWithInfo && !project.isSourceOfProjectReferenceRedirect(scriptInfo.path)) { + tsconfigOfDefault = tsconfigProject; + return defaultProject = project; + } + if (!possiblyDefault && infoIsOpenScriptInfo && projectWithInfo) { + tsconfigOfPossiblyDefault = tsconfigProject; + possiblyDefault = project; + } + } + function isDefaultProjectOptimized(result, tsconfigProject) { + if (result.sentConfigFileDiag) sentConfigDiag.add(result.project); + return result.configFileExistenceInfo ? isDefaultConfigFileExistenceInfo( + result.configFileExistenceInfo, + result.project, + toNormalizedPath(result.project.getConfigFilePath()), + result.reason, + result.project, + result.project.canonicalConfigFilePath + ) : isDefaultProject(result.project, tsconfigProject); + } + function tryFindDefaultConfiguredProjectFromReferences(project) { + return project.parsedCommandLine && forEachResolvedProjectReferenceProjectLoad( + project, + project.parsedCommandLine, + isDefaultConfigFileExistenceInfo, + optimizedKind, + referencedProjectReason(project), + allowDeferredClosed, + reloadedProjects + ); + } + function tryFindDefaultConfiguredProjectFromAncestor(project) { + return infoIsOpenScriptInfo ? forEachAncestorProjectLoad( + // If not in referenced projects, try ancestors and its references + info, + project, + tryFindDefaultConfiguredProject, + optimizedKind, + `Creating possible configured project for ${info.fileName} to open`, + allowDeferredClosed, + reloadedProjects, + /*searchOnlyPotentialSolution*/ + false + ) : void 0; } } tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo(info, kind, reloadedProjects, delayReloadedConfiguredProjects) { - const allowDeferredClosed = kind === 0 /* Find */; + const allowDeferredClosed = kind === 1 /* Find */; const result = this.tryFindDefaultConfiguredProjectForOpenScriptInfo( info, kind, @@ -188496,18 +190968,20 @@ Dynamic files must always be opened with service's current directory or service reloadedProjects ); if (!result) return; - const { defaultProject, seenProjects } = result; + const { defaultProject, tsconfigProject, seenProjects } = result; if (defaultProject) { - forEachAncestorProject( + forEachAncestorProjectLoad( info, - defaultProject, + tsconfigProject, (ancestor) => { - seenProjects.add(ancestor); + seenProjects.set(ancestor.project, kind); }, kind, `Creating project possibly referencing default composite project ${defaultProject.getProjectName()} of open file ${info.fileName}`, allowDeferredClosed, reloadedProjects, + /*searchOnlyPotentialSolution*/ + true, delayReloadedConfiguredProjects ); } @@ -188516,7 +190990,7 @@ Dynamic files must always be opened with service's current directory or service /** @internal */ loadAncestorProjectTree(forProjects) { forProjects ?? (forProjects = new Set( - mapDefinedIterator(this.configuredProjects.entries(), ([key, project]) => !project.isInitialLoadPending() ? key : void 0) + mapDefinedIterator(this.configuredProjects.entries(), ([key, project]) => !project.initialLoadPending ? key : void 0) )); const seenProjects = /* @__PURE__ */ new Set(); const currentConfiguredProjects = arrayFrom(this.configuredProjects.values()); @@ -188622,7 +191096,8 @@ Dynamic files must always be opened with service's current directory or service ); } }; - toRetainConfiguredProjects == null ? void 0 : toRetainConfiguredProjects.forEach(retainConfiguredProject); + toRetainConfiguredProjects == null ? void 0 : toRetainConfiguredProjects.forEach((_, project) => retainConfiguredProject(project)); + if (!toRemoveConfiguredProjects.size) return toRemoveConfiguredProjects; this.inferredProjects.forEach(markOriginalProjectsAsUsed); this.externalProjects.forEach(markOriginalProjectsAsUsed); this.externalProjectToConfiguredProjectMap.forEach((projects, externalProjectName) => { @@ -188630,22 +191105,26 @@ Dynamic files must always be opened with service's current directory or service projects.forEach(retainConfiguredProject); } }); - this.openFiles.forEach((_projectRootPath, path) => { + if (!toRemoveConfiguredProjects.size) return toRemoveConfiguredProjects; + forEachEntry(this.openFiles, (_projectRootPath, path) => { if (openFilesWithRetainedConfiguredProject == null ? void 0 : openFilesWithRetainedConfiguredProject.has(path)) return; const info = this.getScriptInfoForPath(path); if (find(info.containingProjects, isExternalProject)) return; const result = this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo( info, - 0 /* Find */ + 1 /* Find */ ); if (result == null ? void 0 : result.defaultProject) { - result == null ? void 0 : result.seenProjects.forEach(retainConfiguredProject); + result == null ? void 0 : result.seenProjects.forEach((_, project) => retainConfiguredProject(project)); + if (!toRemoveConfiguredProjects.size) return toRemoveConfiguredProjects; } }); - this.configuredProjects.forEach((project) => { + if (!toRemoveConfiguredProjects.size) return toRemoveConfiguredProjects; + forEachEntry(this.configuredProjects, (project) => { if (toRemoveConfiguredProjects.has(project)) { if (isPendingUpdate(project) || forEachReferencedProject(project, isRetained)) { retainConfiguredProject(project); + if (!toRemoveConfiguredProjects.size) return toRemoveConfiguredProjects; } } }); @@ -188667,7 +191146,7 @@ Dynamic files must always be opened with service's current directory or service const toRemoveScriptInfos = new Map(this.filenameToScriptInfo); this.filenameToScriptInfo.forEach((info) => { if (info.deferredDelete) return; - if (!info.isScriptOpen() && info.isOrphan() && !info.isContainedByBackgroundProject()) { + if (!info.isScriptOpen() && info.isOrphan() && !scriptInfoIsContainedByDeferredClosedProject(info) && !scriptInfoIsContainedByBackgroundProject(info)) { if (!info.sourceMapFilePath) return; let sourceInfos; if (isString(info.sourceMapFilePath)) { @@ -188785,10 +191264,14 @@ Dynamic files must always be opened with service's current directory or service existingOpenScriptInfos, (existing, index) => !existing && openScriptInfos[index] && !openScriptInfos[index].isDynamic ? this.tryInvokeWildCardDirectories(openScriptInfos[index]) : void 0 ); - openScriptInfos == null ? void 0 : openScriptInfos.forEach((info) => { - var _a; - return (_a = this.assignProjectToOpenedScriptInfo(info).retainProjects) == null ? void 0 : _a.forEach((p) => (retainProjects ?? (retainProjects = /* @__PURE__ */ new Set())).add(p)); - }); + openScriptInfos == null ? void 0 : openScriptInfos.forEach( + (info) => { + var _a; + return (_a = this.assignProjectToOpenedScriptInfo(info).retainProjects) == null ? void 0 : _a.forEach( + (kind, p) => (retainProjects ?? (retainProjects = /* @__PURE__ */ new Map())).set(p, kind) + ); + } + ); if (assignOrphanScriptInfosToInferredProject) { this.assignOrphanScriptInfosToInferredProject(); } @@ -189004,7 +191487,7 @@ Dynamic files must always be opened with service's current directory or service if (cleanupAfter) { this.cleanupConfiguredProjects( configuredProjects, - new Set(proj.projectFileName) + /* @__PURE__ */ new Set([proj.projectFileName]) ); this.printProjects(); } @@ -189142,9 +191625,11 @@ Dynamic files must always be opened with service's current directory or service const result = []; const processDirectory = (directory) => { switch (packageJsonCache.directoryHasPackageJson(directory)) { + // Sync and check same directory again case 3 /* Maybe */: - packageJsonCache.searchDirectoryAndAncestors(directory); + packageJsonCache.searchDirectoryAndAncestors(directory, project); return processDirectory(directory); + // Check package.json case -1 /* True */: const packageJsonFileName = combinePaths(directory, "package.json"); this.watchPackageJsonFile(packageJsonFileName, this.toPath(packageJsonFileName), project); @@ -189155,21 +191640,29 @@ Dynamic files must always be opened with service's current directory or service return true; } }; - forEachAncestorDirectory(getDirectoryPath(fileName), processDirectory); + forEachAncestorDirectoryStoppingAtGlobalCache( + project, + getDirectoryPath(fileName), + processDirectory + ); return result; } /** @internal */ - getNearestAncestorDirectoryWithPackageJson(fileName) { - return forEachAncestorDirectory(fileName, (directory) => { - switch (this.packageJsonCache.directoryHasPackageJson(directory)) { - case -1 /* True */: - return directory; - case 0 /* False */: - return void 0; - case 3 /* Maybe */: - return this.host.fileExists(combinePaths(directory, "package.json")) ? directory : void 0; + getNearestAncestorDirectoryWithPackageJson(fileName, project) { + return forEachAncestorDirectoryStoppingAtGlobalCache( + project, + fileName, + (directory) => { + switch (this.packageJsonCache.directoryHasPackageJson(directory)) { + case -1 /* True */: + return directory; + case 0 /* False */: + return void 0; + case 3 /* Maybe */: + return this.host.fileExists(combinePaths(directory, "package.json")) ? directory : void 0; + } } - }); + ); } watchPackageJsonFile(file, path, project) { Debug.assert(project !== void 0); @@ -189382,19 +191875,23 @@ function createPackageJsonCache(host) { return packageJsons.get(host.toPath(combinePaths(directory, "package.json"))) || void 0; }, directoryHasPackageJson: (directory) => directoryHasPackageJson(host.toPath(directory)), - searchDirectoryAndAncestors: (directory) => { - forEachAncestorDirectory(directory, (ancestor) => { - const ancestorPath = host.toPath(ancestor); - if (directoryHasPackageJson(ancestorPath) !== 3 /* Maybe */) { - return true; - } - const packageJsonFileName = combinePaths(ancestor, "package.json"); - if (tryFileExists(host, packageJsonFileName)) { - addOrUpdate(packageJsonFileName, combinePaths(ancestorPath, "package.json")); - } else { - directoriesWithoutPackageJson.set(ancestorPath, true); + searchDirectoryAndAncestors: (directory, project) => { + forEachAncestorDirectoryStoppingAtGlobalCache( + project, + directory, + (ancestor) => { + const ancestorPath = host.toPath(ancestor); + if (directoryHasPackageJson(ancestorPath) !== 3 /* Maybe */) { + return true; + } + const packageJsonFileName = combinePaths(ancestor, "package.json"); + if (tryFileExists(host, packageJsonFileName)) { + addOrUpdate(packageJsonFileName, combinePaths(ancestorPath, "package.json")); + } else { + directoriesWithoutPackageJson.set(ancestorPath, true); + } } - }); + ); } }; function addOrUpdate(fileName, path) { @@ -189615,8 +192112,13 @@ function getRenameLocationsWorker(projects, defaultProject, initialLocation, fin projects, defaultProject, initialLocation, - /*isForRename*/ - true, + getDefinitionLocation( + defaultProject, + initialLocation, + /*isForRename*/ + true + ), + mapDefinitionInProject, (project, position) => project.getLanguageService().findRenameLocations(position.fileName, position.pos, findInStrings, findInComments, preferences), (renameLocation, cb) => cb(documentSpanLocation(renameLocation)) ); @@ -189653,8 +192155,13 @@ function getReferencesWorker(projects, defaultProject, initialLocation, useCaseS projects, defaultProject, initialLocation, - /*isForRename*/ - false, + getDefinitionLocation( + defaultProject, + initialLocation, + /*isForRename*/ + false + ), + mapDefinitionInProject, (project, position) => { logger.info(`Finding references to ${position.fileName} position ${position.pos} in project ${project.getProjectName()}`); return project.getLanguageService().findReferences(position.fileName, position.pos); @@ -189749,7 +192256,7 @@ function forEachProjectInProjects(projects, path, cb) { }); } } -function getPerProjectReferences(projects, defaultProject, initialLocation, isForRename, getResultsForPosition, forPositionInResult) { +function getPerProjectReferences(projects, defaultProject, initialLocation, defaultDefinition, mapDefinitionInProject2, getResultsForPosition, forPositionInResult) { const resultsMap = /* @__PURE__ */ new Map(); const queue = createQueue(); queue.enqueue({ project: defaultProject, location: initialLocation }); @@ -189759,7 +192266,6 @@ function getPerProjectReferences(projects, defaultProject, initialLocation, isFo }); const projectService = defaultProject.projectService; const cancellationToken = defaultProject.getCancellationToken(); - const defaultDefinition = getDefinitionLocation(defaultProject, initialLocation, isForRename); const getGeneratedDefinition = memoize( () => defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition.fileName) ? defaultDefinition : defaultProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(defaultDefinition) ); @@ -189787,7 +192293,7 @@ function getPerProjectReferences(projects, defaultProject, initialLocation, isFo projectService.forEachEnabledProject((project) => { if (cancellationToken.isCancellationRequested()) return; if (resultsMap.has(project)) return; - const location = mapDefinitionInProject(defaultDefinition, project, getGeneratedDefinition, getSourceDefinition); + const location = mapDefinitionInProject2(defaultDefinition, project, getGeneratedDefinition, getSourceDefinition); if (location) { queue.enqueue({ project, location }); } @@ -189800,7 +192306,7 @@ function getPerProjectReferences(projects, defaultProject, initialLocation, isFo return resultsMap; function searchPosition(project, location) { const projectResults = getResultsForPosition(project, location); - if (!projectResults) return void 0; + if (!projectResults || !forPositionInResult) return projectResults; for (const result of projectResults) { forPositionInResult(result, (position) => { const originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, position); @@ -189826,10 +192332,14 @@ function getPerProjectReferences(projects, defaultProject, initialLocation, isFo return projectResults; } } -function mapDefinitionInProject(definition, project, getGeneratedDefinition, getSourceDefinition) { +function mapDefinitionInProjectIfFileInProject(definition, project) { if (project.containsFile(toNormalizedPath(definition.fileName)) && !isLocationProjectReferenceRedirect(project, definition)) { return definition; } +} +function mapDefinitionInProject(definition, project, getGeneratedDefinition, getSourceDefinition) { + const result = mapDefinitionInProjectIfFileInProject(definition, project); + if (result) return result; const generatedDefinition = getGeneratedDefinition(); if (generatedDefinition && project.containsFile(toNormalizedPath(generatedDefinition.fileName))) return generatedDefinition; const sourceDefinition = getSourceDefinition(); @@ -189889,7 +192399,8 @@ var invalidPartialSemanticModeCommands = [ "prepareCallHierarchy" /* PrepareCallHierarchy */, "provideCallHierarchyIncomingCalls" /* ProvideCallHierarchyIncomingCalls */, "provideCallHierarchyOutgoingCalls" /* ProvideCallHierarchyOutgoingCalls */, - "getPasteEdits" /* GetPasteEdits */ + "getPasteEdits" /* GetPasteEdits */, + "copilotRelated" /* CopilotRelated */ ]; var invalidSyntacticModeCommands = [ ...invalidPartialSemanticModeCommands, @@ -189917,7 +192428,8 @@ var invalidSyntacticModeCommands = [ "navto" /* Navto */, "navto-full" /* NavtoFull */, "documentHighlights" /* DocumentHighlights */, - "documentHighlights-full" /* DocumentHighlightsFull */ + "documentHighlights-full" /* DocumentHighlightsFull */, + "preparePasteEdits" /* PreparePasteEdits */ ]; var Session3 = class _Session { constructor(opts) { @@ -190441,6 +192953,9 @@ var Session3 = class _Session { ["getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */]: (request) => { return this.requiredResponse(this.getMoveToRefactoringFileSuggestions(request.arguments)); }, + ["preparePasteEdits" /* PreparePasteEdits */]: (request) => { + return this.requiredResponse(this.preparePasteEdits(request.arguments)); + }, ["getPasteEdits" /* GetPasteEdits */]: (request) => { return this.requiredResponse(this.getPasteEdits(request.arguments)); }, @@ -190567,6 +193082,9 @@ var Session3 = class _Session { }, ["mapCode" /* MapCode */]: (request) => { return this.requiredResponse(this.mapCode(request.arguments)); + }, + ["copilotRelated" /* CopilotRelated */]: () => { + return this.requiredResponse(this.getCopilotRelatedInfo()); } })); this.host = opts.host; @@ -191514,6 +194032,11 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const changes = languageService.mapCode(file, args.mapping.contents, focusLocations, formatOptions, preferences); return this.mapTextChangesToCodeEdits(changes); } + getCopilotRelatedInfo() { + return { + relatedFiles: [] + }; + } setCompilerOptionsForInferredProjects(args) { this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath); } @@ -191522,11 +194045,12 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter args.file, args.projectFileName, args.needFileNameList, + args.needDefaultConfiguredProjectInfo, /*excludeConfigFiles*/ false ); } - getProjectInfoWorker(uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles) { + getProjectInfoWorker(uncheckedFileName, projectFileName, needFileNameList, needDefaultConfiguredProjectInfo, excludeConfigFiles) { const { project } = this.getFileAndProjectWorker(uncheckedFileName, projectFileName); updateProjectIfDirty(project); const projectInfo = { @@ -191536,10 +194060,38 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter /*excludeFilesFromExternalLibraries*/ false, excludeConfigFiles - ) : void 0 + ) : void 0, + configuredProjectInfo: needDefaultConfiguredProjectInfo ? this.getDefaultConfiguredProjectInfo(uncheckedFileName) : void 0 }; return projectInfo; } + getDefaultConfiguredProjectInfo(uncheckedFileName) { + var _a; + const info = this.projectService.getScriptInfo(uncheckedFileName); + if (!info) return; + const result = this.projectService.findDefaultConfiguredProjectWorker( + info, + 3 /* CreateReplay */ + ); + if (!result) return void 0; + let notMatchedByConfig; + let notInProject; + result.seenProjects.forEach((kind, project) => { + if (project !== result.defaultProject) { + if (kind !== 3 /* CreateReplay */) { + (notMatchedByConfig ?? (notMatchedByConfig = [])).push(toNormalizedPath(project.getConfigFilePath())); + } else { + (notInProject ?? (notInProject = [])).push(toNormalizedPath(project.getConfigFilePath())); + } + } + }); + (_a = result.seenConfigs) == null ? void 0 : _a.forEach((config) => (notMatchedByConfig ?? (notMatchedByConfig = [])).push(config)); + return { + notMatchedByConfig, + notInProject, + defaultProject: result.defaultProject && toNormalizedPath(result.defaultProject.getConfigFilePath()) + }; + } getRenameInfo(args) { const { file, project } = this.getFileAndProject(args); const position = this.getPositionInFile(args, file); @@ -191656,27 +194208,35 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter } getFileReferences(args, simplifiedResult) { const projects = this.getProjects(args); - const fileName = args.file; - const preferences = this.getPreferences(toNormalizedPath(fileName)); - const references = []; - const seen = createDocumentSpanSet(this.host.useCaseSensitiveFileNames); - forEachProjectInProjects( + const fileName = toNormalizedPath(args.file); + const preferences = this.getPreferences(fileName); + const initialLocation = { fileName, pos: 0 }; + const perProjectResults = getPerProjectReferences( projects, - /*path*/ - void 0, + this.getDefaultProject(args), + initialLocation, + initialLocation, + mapDefinitionInProjectIfFileInProject, (project) => { - if (project.getCancellationToken().isCancellationRequested()) return; - const projectOutputs = project.getLanguageService().getFileReferences(fileName); - if (projectOutputs) { - for (const referenceEntry of projectOutputs) { - if (!seen.has(referenceEntry)) { - references.push(referenceEntry); - seen.add(referenceEntry); - } - } - } + this.logger.info(`Finding references to file ${fileName} in project ${project.getProjectName()}`); + return project.getLanguageService().getFileReferences(fileName); } ); + let references; + if (isArray(perProjectResults)) { + references = perProjectResults; + } else { + references = []; + const seen = createDocumentSpanSet(this.host.useCaseSensitiveFileNames); + perProjectResults.forEach((projectOutputs) => { + for (const referenceEntry of projectOutputs) { + if (!seen.has(referenceEntry)) { + references.push(referenceEntry); + seen.add(referenceEntry); + } + } + }); + } if (!simplifiedResult) return references; const refs = references.map((entry) => referenceEntryToReferencesResponseItem(this.projectService, entry, preferences)); return { @@ -192268,8 +194828,13 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter const scriptInfo = project.getScriptInfoForNormalizedPath(file); return project.getLanguageService().getMoveToRefactoringFileSuggestions(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file)); } + preparePasteEdits(args) { + const { file, project } = this.getFileAndProject(args); + return project.getLanguageService().preparePasteEditsForFile(file, args.copiedTextSpan.map((copies) => this.getRange({ file, startLine: copies.start.line, startOffset: copies.start.offset, endLine: copies.end.line, endOffset: copies.end.offset }, this.projectService.getScriptInfoForNormalizedPath(file)))); + } getPasteEdits(args) { const { file, project } = this.getFileAndProject(args); + if (isDynamicFileName(file)) return void 0; const copiedFrom = args.copiedFrom ? { file: args.copiedFrom.file, range: args.copiedFrom.spans.map((copies) => this.getRange({ file: args.copiedFrom.file, startLine: copies.start.line, startOffset: copies.start.offset, endLine: copies.end.line, endOffset: copies.end.offset }, project.getScriptInfoForNormalizedPath(toNormalizedPath(args.copiedFrom.file)))) } : void 0; const result = project.getLanguageService().getPasteEdits( { @@ -192349,10 +194914,10 @@ ${e.message}`; } return simplifiedResult ? codeActions.map((codeAction) => this.mapCodeFixAction(codeAction)) : codeActions; } - getCombinedCodeFix({ scope, fixId: fixId55 }, simplifiedResult) { + getCombinedCodeFix({ scope, fixId: fixId56 }, simplifiedResult) { Debug.assert(scope.type === "file"); const { file, project } = this.getFileAndProject(scope.args); - const res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId55, this.getFormatOptions(file), this.getPreferences(file)); + const res = project.getLanguageService().getCombinedCodeFix({ type: "file", fileName: file }, fixId56, this.getFormatOptions(file), this.getPreferences(file)); if (simplifiedResult) { return { changes: this.mapTextChangesToCodeEdits(res.changes), commands: res.commands }; } else { @@ -192391,11 +194956,11 @@ ${e.message}`; mapCodeAction({ description: description3, changes, commands }) { return { description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands }; } - mapCodeFixAction({ fixName: fixName8, description: description3, changes, commands, fixId: fixId55, fixAllDescription }) { - return { fixName: fixName8, description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands, fixId: fixId55, fixAllDescription }; + mapCodeFixAction({ fixName: fixName8, description: description3, changes, commands, fixId: fixId56, fixAllDescription }) { + return { fixName: fixName8, description: description3, changes: this.mapTextChangesToCodeEdits(changes), commands, fixId: fixId56, fixAllDescription }; } - mapPasteEditsAction({ edits, fixId: fixId55 }) { - return { edits: this.mapTextChangesToCodeEdits(edits), fixId: fixId55 }; + mapPasteEditsAction({ edits, fixId: fixId56 }) { + return { edits: this.mapTextChangesToCodeEdits(edits), fixId: fixId56 }; } mapTextChangesToCodeEdits(textChanges2) { return textChanges2.map((change) => this.mapTextChangeToCodeEdit(change)); @@ -192434,16 +194999,14 @@ ${e.message}`; void 0, /*needFileNameList*/ true, + /*needDefaultConfiguredProjectInfo*/ + void 0, /*excludeConfigFiles*/ true ); - if (languageServiceDisabled) { - return; - } + if (languageServiceDisabled) return; const fileNamesInProject = fileNames.filter((value) => !value.includes("lib.d.ts")); - if (fileNamesInProject.length === 0) { - return; - } + if (fileNamesInProject.length === 0) return; const highPriorityFiles = []; const mediumPriorityFiles = []; const lowPriorityFiles = []; @@ -193354,6 +195917,7 @@ var LineNode = class _LineNode { } } walk(rangeStart, rangeLength, walkFns) { + if (this.children.length === 0) return; let childIndex = 0; let childCharCount = this.children[childIndex].charCount(); let adjustedStart = rangeStart; @@ -193797,6 +196361,7 @@ __export(ts_server_exports4, { formatDiagnosticToProtocol: () => formatDiagnosticToProtocol, formatMessage: () => formatMessage2, getBaseConfigFileName: () => getBaseConfigFileName, + getDetailWatchInfo: () => getDetailWatchInfo, getLocationInNewDocument: () => getLocationInNewDocument, hasArgument: () => hasArgument, hasNoTypeScriptSource: () => hasNoTypeScriptSource, @@ -193819,6 +196384,8 @@ __export(ts_server_exports4, { nullCancellationToken: () => nullCancellationToken, nullTypingsInstaller: () => nullTypingsInstaller, protocol: () => ts_server_protocol_exports, + scriptInfoIsContainedByBackgroundProject: () => scriptInfoIsContainedByBackgroundProject, + scriptInfoIsContainedByDeferredClosedProject: () => scriptInfoIsContainedByDeferredClosedProject, stringifyIndented: () => stringifyIndented, toEvent: () => toEvent, toNormalizedPath: () => toNormalizedPath, @@ -193954,6 +196521,7 @@ if (typeof console !== "undefined") { PollingWatchKind, PragmaKindFlags, PredicateSemantics, + PreparePasteEdits, PrivateIdentifierKind, ProcessLevel, ProgramUpdateLevel, @@ -194049,7 +196617,6 @@ if (typeof console !== "undefined") { buildOverload, bundlerModuleNameResolver, canBeConvertedToAsync, - canEmitTsBuildInfo, canHaveDecorators, canHaveExportModifier, canHaveFlowNode, @@ -194069,6 +196636,7 @@ if (typeof console !== "undefined") { canWatchAffectingLocation, canWatchAtTypes, canWatchDirectoryOrFile, + canWatchDirectoryOrFilePath, cartesianProduct, cast, chainBundle, @@ -194339,6 +196907,7 @@ if (typeof console !== "undefined") { escapeTemplateSubstitution, evaluatorResult, every, + exclusivelyPrefixedNodeCoreModules, executeCommandLine, expandPreOrPostfixIncrementOrDecrementExpression, explainFiles, @@ -194351,7 +196920,6 @@ if (typeof console !== "undefined") { extensionsNotSupportingExtensionlessResolution, externalHelpersModuleNameText, factory, - fileContainsPackageImport, fileExtensionIs, fileExtensionIsOneOf, fileIncludeReasonToDiagnostics, @@ -194401,8 +196969,10 @@ if (typeof console !== "undefined") { forEach, forEachAncestor, forEachAncestorDirectory, + forEachAncestorDirectoryStoppingAtGlobalCache, forEachChild, forEachChildRecursively, + forEachDynamicImportOrRequireCall, forEachEmittedFile, forEachEnclosingBlockScopeContainer, forEachEntry, @@ -194443,6 +197013,7 @@ if (typeof console !== "undefined") { getAllKeys, getAllProjectOutputs, getAllSuperTypeNodes, + getAllowImportingTsExtensions, getAllowJSCompilerOption, getAllowSyntheticDefaultImports, getAncestor, @@ -194751,6 +197322,7 @@ if (typeof console !== "undefined") { getPositionOfLineAndCharacter, getPossibleGenericSignatures, getPossibleOriginalInputExtensionForExtension, + getPossibleOriginalInputPathWithoutChangingExt, getPossibleTypeArgumentsInfo, getPreEmitDiagnostics, getPrecedingNonSpaceCharacterPosition, @@ -195014,7 +197586,7 @@ if (typeof console !== "undefined") { isBooleanLiteral, isBreakOrContinueStatement, isBreakStatement, - isBuild, + isBuildCommand, isBuildInfoFile, isBuilderProgram, isBundle, @@ -195201,7 +197773,7 @@ if (typeof console !== "undefined") { isImportSpecifier, isImportTypeAssertionContainer, isImportTypeNode, - isImportableFile, + isImportable, isInComment, isInCompoundLikeAssignment, isInExpressionContext, @@ -195300,6 +197872,7 @@ if (typeof console !== "undefined") { isJsxAttributeLike, isJsxAttributeName, isJsxAttributes, + isJsxCallLike, isJsxChild, isJsxClosingElement, isJsxClosingFragment, @@ -195382,6 +197955,7 @@ if (typeof console !== "undefined") { isNamespaceReexportDeclaration, isNewExpression, isNewExpressionTarget, + isNewScopeNode, isNoSubstitutionTemplateLiteral, isNodeArray, isNodeArrayMultiLine, @@ -195430,6 +198004,7 @@ if (typeof console !== "undefined") { isParseTreeNode, isPartOfParameterDeclaration, isPartOfTypeNode, + isPartOfTypeOnlyImportOrExportDeclaration, isPartOfTypeQuery, isPartiallyEmittedExpression, isPatternMatch, @@ -195498,6 +198073,7 @@ if (typeof console !== "undefined") { isSimpleInlineableExpression, isSimpleParameterList, isSingleOrDoubleQuote, + isSolutionConfig, isSourceElement, isSourceFile, isSourceFileFromLibrary, @@ -195606,7 +198182,6 @@ if (typeof console !== "undefined") { isVariableDeclarationInitializedToRequire, isVariableDeclarationList, isVariableLike, - isVariableLikeOrAccessor, isVariableStatement, isVoidExpression, isWatchSet, @@ -195643,6 +198218,7 @@ if (typeof console !== "undefined") { matchPatternOrExact, matchedText, matchesExclude, + matchesExcludeWorker, maxBy, maybeBind, maybeSetLocalizedDiagnosticMessages, @@ -195682,6 +198258,7 @@ if (typeof console !== "undefined") { noTransformers, noTruncationMaximumTruncationLength, nodeCanBeDecorated, + nodeCoreModules, nodeHasName, nodeIsDecorated, nodeIsMissing, @@ -195826,6 +198403,7 @@ if (typeof console !== "undefined") { returnTrue, returnUndefined, returnsPromise, + rewriteModuleSpecifier, sameFlatMap, sameMap, sameMapping, @@ -195871,6 +198449,7 @@ if (typeof console !== "undefined") { setValueDeclaration, shouldAllowImportingTsExtension, shouldPreserveConstEnums, + shouldRewriteModuleSpecifier, shouldUseUriStyleNodeCoreModules, showModuleSpecifier, signatureHasRestParameter, @@ -195928,6 +198507,7 @@ if (typeof console !== "undefined") { tagNamesAreEquivalent, takeWhile, targetOptionDeclaration, + targetToLibMap, testFormatSettings, textChangeRangeIsUnchanged, textChangeRangeNewSpan, @@ -196021,6 +198601,7 @@ if (typeof console !== "undefined") { tryRemoveExtension, tryRemovePrefix, tryRemoveSuffix, + tscBuildOption, typeAcquisitionDeclarations, typeAliasNamePart, typeDirectiveIsEqualTo, @@ -196032,6 +198613,7 @@ if (typeof console !== "undefined") { unescapeLeadingUnderscores, unmangleScopedPackageName, unorderedRemoveItem, + unprefixedNodeCoreModules, unreachableCodeIsError, unsetNodeChildren, unusedLabelIsError, diff --git a/packages/schematics/angular/utility/latest-versions/package.json b/packages/schematics/angular/utility/latest-versions/package.json index cee728d87854..52b8488b35fd 100644 --- a/packages/schematics/angular/utility/latest-versions/package.json +++ b/packages/schematics/angular/utility/latest-versions/package.json @@ -3,7 +3,7 @@ "comment": "This file is needed so that dependencies are synced by Renovate.", "private": true, "dependencies": { - "@angular/core": "^19.0.0", + "@angular/core": "^19.1.0-next.0", "@types/express": "^4.17.17", "@types/jasmine": "~5.1.0", "@types/node": "^18.18.0", @@ -23,7 +23,7 @@ "rxjs": "~7.8.0", "tslib": "^2.3.0", "ts-node": "~10.9.0", - "typescript": "~5.6.2", + "typescript": "~5.7.2", "zone.js": "~0.15.0" } } diff --git a/yarn.lock b/yarn.lock index 74a256274d48..a52997630f0e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -130,7 +130,7 @@ __metadata: ng-packagr: ^19.0.0 protractor: ^7.0.0 tailwindcss: ^2.0.0 || ^3.0.0 - typescript: ">=5.5 <5.7" + typescript: ">=5.5 <5.8" dependenciesMeta: esbuild: optional: true @@ -245,14 +245,14 @@ __metadata: languageName: unknown linkType: soft -"@angular/animations@npm:19.0.1": - version: 19.0.1 - resolution: "@angular/animations@npm:19.0.1" +"@angular/animations@npm:19.1.0-next.0": + version: 19.1.0-next.0 + resolution: "@angular/animations@npm:19.1.0-next.0" dependencies: tslib: "npm:^2.3.0" peerDependencies: - "@angular/core": 19.0.1 - checksum: 10c0/ebacea8ea6a7f1b51fce210c8d7ad72eb902c6b65f35b231b3b746a3e70ffcb28b867ab1926b07b1bcc6326ef9e43e18b8e689b8cd01603d3d08226251635585 + "@angular/core": 19.1.0-next.0 + checksum: 10c0/d3d1fe745f7aa5310565cfd56cddaf5e9f40db6cfa322f7ac7a0f01c670ef71efccb13932c0bb98acb3f8aa531348402fe5e253bde79873f02d3140ae7325bb9 languageName: node linkType: hard @@ -407,7 +407,7 @@ __metadata: less: ^4.2.0 postcss: ^8.4.0 tailwindcss: ^2.0.0 || ^3.0.0 - typescript: ">=5.5 <5.7" + typescript: ">=5.5 <5.8" dependenciesMeta: lmdb: optional: true @@ -496,20 +496,20 @@ __metadata: languageName: node linkType: hard -"@angular/cdk@npm:19.0.0": - version: 19.0.0 - resolution: "@angular/cdk@npm:19.0.0" +"@angular/cdk@npm:19.1.0-next.0": + version: 19.1.0-next.0 + resolution: "@angular/cdk@npm:19.1.0-next.0" dependencies: parse5: "npm:^7.1.2" tslib: "npm:^2.3.0" peerDependencies: - "@angular/common": ^19.0.0 || ^20.0.0 - "@angular/core": ^19.0.0 || ^20.0.0 + "@angular/common": ^19.0.0-0 || ^19.1.0-0 || ^19.2.0-0 || ^19.3.0-0 || ^20.0.0-0 + "@angular/core": ^19.0.0-0 || ^19.1.0-0 || ^19.2.0-0 || ^19.3.0-0 || ^20.0.0-0 rxjs: ^6.5.3 || ^7.4.0 dependenciesMeta: parse5: optional: true - checksum: 10c0/542659c4fd19a08514b26c4ab5428ce1efcae6921243eb13d6bd27ed2f3a63466fc1625e087e9509da381cb9aa0ffded1ecd102ab9c84ad689916f4b475bbe44 + checksum: 10c0/adb7cf5c1c523225d1415611629ea443bf0ae93eabf383077ddf1be7c5bd13aeb123c671585cd3123cadb6e672934977c8f288286d1a2a8650478e322f368e60 languageName: node linkType: hard @@ -539,21 +539,21 @@ __metadata: languageName: unknown linkType: soft -"@angular/common@npm:19.0.1": - version: 19.0.1 - resolution: "@angular/common@npm:19.0.1" +"@angular/common@npm:19.1.0-next.0": + version: 19.1.0-next.0 + resolution: "@angular/common@npm:19.1.0-next.0" dependencies: tslib: "npm:^2.3.0" peerDependencies: - "@angular/core": 19.0.1 + "@angular/core": 19.1.0-next.0 rxjs: ^6.5.3 || ^7.4.0 - checksum: 10c0/20791a8eeafc701bcff8939f26441e696a62dac8f15e3a834345e30857ec11b2e213c44259af2ca26bfcea2b10a9f18b5752ebd2d087518911cceddd85f2daa9 + checksum: 10c0/d0a579a389f7e9205eeb651eec3c48e19e34db51f8b244f3be8f68905839594f6a01b4ff8ce5d8cd37542d25326e63e0f8886c44266d5af3f158499af3b0f5be languageName: node linkType: hard -"@angular/compiler-cli@npm:19.0.1": - version: 19.0.1 - resolution: "@angular/compiler-cli@npm:19.0.1" +"@angular/compiler-cli@npm:19.1.0-next.0": + version: 19.1.0-next.0 + resolution: "@angular/compiler-cli@npm:19.1.0-next.0" dependencies: "@babel/core": "npm:7.26.0" "@jridgewell/sourcemap-codec": "npm:^1.4.14" @@ -564,39 +564,39 @@ __metadata: tslib: "npm:^2.3.0" yargs: "npm:^17.2.1" peerDependencies: - "@angular/compiler": 19.0.1 - typescript: ">=5.5 <5.7" + "@angular/compiler": 19.1.0-next.0 + typescript: ">=5.5 <5.8" bin: ng-xi18n: bundles/src/bin/ng_xi18n.js ngc: bundles/src/bin/ngc.js ngcc: bundles/ngcc/index.js - checksum: 10c0/fe250abccdf5be4be611404cf78d4151054c9f7c228106244f94e4cfa858bf333877d729423af6c6ef1ab1f5fbfcc5f0f81264bbfe76b1f3ac27eae05b8b7995 + checksum: 10c0/21f66911fb8c43b7c4cb7bae9ee1eeba2706e9e2ae2900ba8951f1f957fb8ff67c8b6fffe12b1f1eb19d7d0e06f6b905aa1591a390b9835a680fb67b2de8d1a2 languageName: node linkType: hard -"@angular/compiler@npm:19.0.1": - version: 19.0.1 - resolution: "@angular/compiler@npm:19.0.1" +"@angular/compiler@npm:19.1.0-next.0": + version: 19.1.0-next.0 + resolution: "@angular/compiler@npm:19.1.0-next.0" dependencies: tslib: "npm:^2.3.0" peerDependencies: - "@angular/core": 19.0.1 + "@angular/core": 19.1.0-next.0 peerDependenciesMeta: "@angular/core": optional: true - checksum: 10c0/e5588d14fe1d829f1bede996f33a5c7c48c77cb02954085f18f5b1d60fbfe2c7212c48febed33f7b4d457b107af4a58a866f2c3f5cb3751766f44fa4aec7ab25 + checksum: 10c0/702a30d919a9132b784ac17dfe2af52ba49dc85a49bcb4df1f5d0fbc48e8682b4ef1f2b55a0342662f1f7cfd88f8a67a7f21c19f9662c0fee1e246a0ee06d11c languageName: node linkType: hard -"@angular/core@npm:19.0.1": - version: 19.0.1 - resolution: "@angular/core@npm:19.0.1" +"@angular/core@npm:19.1.0-next.0": + version: 19.1.0-next.0 + resolution: "@angular/core@npm:19.1.0-next.0" dependencies: tslib: "npm:^2.3.0" peerDependencies: rxjs: ^6.5.3 || ^7.4.0 zone.js: ~0.15.0 - checksum: 10c0/b9c9178de2d729faee24ddf7548b2de166aa30d257363cb3748e5dbe6e8007075a32ea800d61d84eec6fba83e734c7c2d0f2f17e68433e67183c517d7d0e3355 + checksum: 10c0/5f930946d65ea171bf6fad7ba27f497f42cc61b8e50acad85c01372e129b5ae451ce4ce698413ed2b0de24f3837cad2b64f28da396c0becf3d46a1ffd6574361 languageName: node linkType: hard @@ -627,23 +627,23 @@ __metadata: resolution: "@angular/devkit-repo@workspace:." dependencies: "@ampproject/remapping": "npm:2.3.0" - "@angular/animations": "npm:19.0.1" + "@angular/animations": "npm:19.1.0-next.0" "@angular/bazel": "patch:@angular/bazel@https%3A//github.com/angular/bazel-builds.git%23commit=07617f0f8540d27f8895b1820a6f994e1e5b7277#~/.yarn/patches/@angular-bazel-https-9848736cf4.patch" "@angular/build-tooling": "https://github.com/angular/dev-infra-private-build-tooling-builds.git#41d5efafd8094da3c8455e1b54b381e346d0c7a9" - "@angular/cdk": "npm:19.0.0" - "@angular/common": "npm:19.0.1" - "@angular/compiler": "npm:19.0.1" - "@angular/compiler-cli": "npm:19.0.1" - "@angular/core": "npm:19.0.1" - "@angular/forms": "npm:19.0.1" - "@angular/localize": "npm:19.0.1" - "@angular/material": "npm:19.0.0" + "@angular/cdk": "npm:19.1.0-next.0" + "@angular/common": "npm:19.1.0-next.0" + "@angular/compiler": "npm:19.1.0-next.0" + "@angular/compiler-cli": "npm:19.1.0-next.0" + "@angular/core": "npm:19.1.0-next.0" + "@angular/forms": "npm:19.1.0-next.0" + "@angular/localize": "npm:19.1.0-next.0" + "@angular/material": "npm:19.1.0-next.0" "@angular/ng-dev": "https://github.com/angular/dev-infra-private-ng-dev-builds.git#47ccf2ca29307997c021994c859c03c71fae686e" - "@angular/platform-browser": "npm:19.0.1" - "@angular/platform-browser-dynamic": "npm:19.0.1" - "@angular/platform-server": "npm:19.0.1" - "@angular/router": "npm:19.0.1" - "@angular/service-worker": "npm:19.0.1" + "@angular/platform-browser": "npm:19.1.0-next.0" + "@angular/platform-browser-dynamic": "npm:19.1.0-next.0" + "@angular/platform-server": "npm:19.1.0-next.0" + "@angular/router": "npm:19.1.0-next.0" + "@angular/service-worker": "npm:19.1.0-next.0" "@babel/core": "npm:7.26.0" "@babel/generator": "npm:7.26.2" "@babel/helper-annotate-as-pure": "npm:7.25.9" @@ -743,7 +743,7 @@ __metadata: magic-string: "npm:0.30.14" mini-css-extract-plugin: "npm:2.9.2" mrmime: "npm:2.0.0" - ng-packagr: "npm:19.0.1" + ng-packagr: "npm:19.1.0-next.0" npm: "npm:^10.8.1" npm-package-arg: "npm:12.0.0" npm-pick-manifest: "npm:10.0.0" @@ -777,7 +777,7 @@ __metadata: tree-kill: "npm:1.2.2" ts-node: "npm:^10.9.1" tslib: "npm:2.8.1" - typescript: "npm:5.6.3" + typescript: "npm:5.7.2" undici: "npm:6.21.0" unenv: "npm:^1.10.0" verdaccio: "npm:6.0.2" @@ -800,53 +800,53 @@ __metadata: languageName: unknown linkType: soft -"@angular/forms@npm:19.0.1": - version: 19.0.1 - resolution: "@angular/forms@npm:19.0.1" +"@angular/forms@npm:19.1.0-next.0": + version: 19.1.0-next.0 + resolution: "@angular/forms@npm:19.1.0-next.0" dependencies: tslib: "npm:^2.3.0" peerDependencies: - "@angular/common": 19.0.1 - "@angular/core": 19.0.1 - "@angular/platform-browser": 19.0.1 + "@angular/common": 19.1.0-next.0 + "@angular/core": 19.1.0-next.0 + "@angular/platform-browser": 19.1.0-next.0 rxjs: ^6.5.3 || ^7.4.0 - checksum: 10c0/0dc8bd1737469bf733f8d5386ef0cac7753bac170eb7f4d309f54f71d3808e8ed906ee87d45d4560d19f118bc51f25c7b5c8845b606b0fe74689f03e63d76926 + checksum: 10c0/afee46b77661b2a88a05e94e1789fa881af0e442003fdcfd328ae4ebc56c473b7f4666a345fbdd60e2cc92167aefb2a4ca5e80e0c66f66ebb10b7294f07e5561 languageName: node linkType: hard -"@angular/localize@npm:19.0.1": - version: 19.0.1 - resolution: "@angular/localize@npm:19.0.1" +"@angular/localize@npm:19.1.0-next.0": + version: 19.1.0-next.0 + resolution: "@angular/localize@npm:19.1.0-next.0" dependencies: "@babel/core": "npm:7.26.0" "@types/babel__core": "npm:7.20.5" fast-glob: "npm:3.3.2" yargs: "npm:^17.2.1" peerDependencies: - "@angular/compiler": 19.0.1 - "@angular/compiler-cli": 19.0.1 + "@angular/compiler": 19.1.0-next.0 + "@angular/compiler-cli": 19.1.0-next.0 bin: localize-extract: tools/bundles/src/extract/cli.js localize-migrate: tools/bundles/src/migrate/cli.js localize-translate: tools/bundles/src/translate/cli.js - checksum: 10c0/3306748a3f616df313fadfcce00ff939fe90ef1aba808a4c835be6fd2b48e33acab23d47039d076cb1f448ca5858c687f5e81fa90887195ac58696e9a9d93b0c + checksum: 10c0/b55ccdf384562da4f6527799eb1259620af7dcbdbbc82941ceb92494f71e7bf47189262f89831738940d156c81c9dff5c7918a0058d097fa7daf5ebce17aa32e languageName: node linkType: hard -"@angular/material@npm:19.0.0": - version: 19.0.0 - resolution: "@angular/material@npm:19.0.0" +"@angular/material@npm:19.1.0-next.0": + version: 19.1.0-next.0 + resolution: "@angular/material@npm:19.1.0-next.0" dependencies: tslib: "npm:^2.3.0" peerDependencies: - "@angular/animations": ^19.0.0 || ^20.0.0 - "@angular/cdk": 19.0.0 - "@angular/common": ^19.0.0 || ^20.0.0 - "@angular/core": ^19.0.0 || ^20.0.0 - "@angular/forms": ^19.0.0 || ^20.0.0 - "@angular/platform-browser": ^19.0.0 || ^20.0.0 + "@angular/animations": ^19.0.0-0 || ^19.1.0-0 || ^19.2.0-0 || ^19.3.0-0 || ^20.0.0-0 + "@angular/cdk": 19.1.0-next.0 + "@angular/common": ^19.0.0-0 || ^19.1.0-0 || ^19.2.0-0 || ^19.3.0-0 || ^20.0.0-0 + "@angular/core": ^19.0.0-0 || ^19.1.0-0 || ^19.2.0-0 || ^19.3.0-0 || ^20.0.0-0 + "@angular/forms": ^19.0.0-0 || ^19.1.0-0 || ^19.2.0-0 || ^19.3.0-0 || ^20.0.0-0 + "@angular/platform-browser": ^19.0.0-0 || ^19.1.0-0 || ^19.2.0-0 || ^19.3.0-0 || ^20.0.0-0 rxjs: ^6.5.3 || ^7.4.0 - checksum: 10c0/dd8ad1a2fac0b9437dd2f22e04c5c3c1b9aeaff936cc10c4044489063e4a83a8eced8ddcd42654995a8d78182348e1431d227a667151fde8fc06a208d3728115 + checksum: 10c0/9ef62e3ef1309c1d2899baf5227e46f6149900aadfcb0b56023d52a5433540cf7b451d5bdc07cc093538653e4dcfd90c13485b8bb4f61bf7593413a5f41bc531 languageName: node linkType: hard @@ -871,49 +871,49 @@ __metadata: languageName: node linkType: hard -"@angular/platform-browser-dynamic@npm:19.0.1": - version: 19.0.1 - resolution: "@angular/platform-browser-dynamic@npm:19.0.1" +"@angular/platform-browser-dynamic@npm:19.1.0-next.0": + version: 19.1.0-next.0 + resolution: "@angular/platform-browser-dynamic@npm:19.1.0-next.0" dependencies: tslib: "npm:^2.3.0" peerDependencies: - "@angular/common": 19.0.1 - "@angular/compiler": 19.0.1 - "@angular/core": 19.0.1 - "@angular/platform-browser": 19.0.1 - checksum: 10c0/e1d7555d361d50435d68ca68c499aea945a428c917f2871a1f1c4900e4d1615f7929d945e55696b0492998474f5e66da0290977a58930ad14fcd52ea2eaf35d3 + "@angular/common": 19.1.0-next.0 + "@angular/compiler": 19.1.0-next.0 + "@angular/core": 19.1.0-next.0 + "@angular/platform-browser": 19.1.0-next.0 + checksum: 10c0/6c94a65cef61cb7a076cebc245f410e72da0c0138fe874a6a8b4a8263e0c921180235ef7c02d2cc0a8f9f0af1af05dbec44636f8ce80692d0a07114b84bf3582 languageName: node linkType: hard -"@angular/platform-browser@npm:19.0.1": - version: 19.0.1 - resolution: "@angular/platform-browser@npm:19.0.1" +"@angular/platform-browser@npm:19.1.0-next.0": + version: 19.1.0-next.0 + resolution: "@angular/platform-browser@npm:19.1.0-next.0" dependencies: tslib: "npm:^2.3.0" peerDependencies: - "@angular/animations": 19.0.1 - "@angular/common": 19.0.1 - "@angular/core": 19.0.1 + "@angular/animations": 19.1.0-next.0 + "@angular/common": 19.1.0-next.0 + "@angular/core": 19.1.0-next.0 peerDependenciesMeta: "@angular/animations": optional: true - checksum: 10c0/c810b17ded350e2d694f327310860c31d934a82e02f56bbb80f9a6f6bb96ac85493d27007f4b0f42bcc3ef152a4482e400b6217364a7078ed900e38e42201f3c + checksum: 10c0/e00f00e7b6d566735ca5cce0af9c0b4195036b3cad18e4dc604df9d77e8b13e3d259fcd57426b060faab76f1628ecdb78dc61511e6567cfaa6dcdc9ed7458644 languageName: node linkType: hard -"@angular/platform-server@npm:19.0.1": - version: 19.0.1 - resolution: "@angular/platform-server@npm:19.0.1" +"@angular/platform-server@npm:19.1.0-next.0": + version: 19.1.0-next.0 + resolution: "@angular/platform-server@npm:19.1.0-next.0" dependencies: tslib: "npm:^2.3.0" xhr2: "npm:^0.2.0" peerDependencies: - "@angular/animations": 19.0.1 - "@angular/common": 19.0.1 - "@angular/compiler": 19.0.1 - "@angular/core": 19.0.1 - "@angular/platform-browser": 19.0.1 - checksum: 10c0/1418b813a1eda77e24139624286a1aaf5ad45c3759d685c4359cce51dfe7bb66cf432039cdab5181031a3cace16bc357c4ab0c4cab64daea756e159cf2991a01 + "@angular/animations": 19.1.0-next.0 + "@angular/common": 19.1.0-next.0 + "@angular/compiler": 19.1.0-next.0 + "@angular/core": 19.1.0-next.0 + "@angular/platform-browser": 19.1.0-next.0 + checksum: 10c0/4587209a039d2cb171ceb57c8885841a786c7162d2c7b9a22e52733718f0be2f9e3605299e66eeef3c28084e45d5ce4d48d9b63f1c9455090e19d6c919c63816 languageName: node linkType: hard @@ -932,31 +932,31 @@ __metadata: languageName: unknown linkType: soft -"@angular/router@npm:19.0.1": - version: 19.0.1 - resolution: "@angular/router@npm:19.0.1" +"@angular/router@npm:19.1.0-next.0": + version: 19.1.0-next.0 + resolution: "@angular/router@npm:19.1.0-next.0" dependencies: tslib: "npm:^2.3.0" peerDependencies: - "@angular/common": 19.0.1 - "@angular/core": 19.0.1 - "@angular/platform-browser": 19.0.1 + "@angular/common": 19.1.0-next.0 + "@angular/core": 19.1.0-next.0 + "@angular/platform-browser": 19.1.0-next.0 rxjs: ^6.5.3 || ^7.4.0 - checksum: 10c0/6f717d2c8c31e52094909d964f7187a12cdfcfcb5fceec03fa4f2d5897086ed5b5ae9e722c8a004258f15f406a109b5cdf5e35783fe8c75345360dcdc68c3a46 + checksum: 10c0/fbb3a6b0de491135d81e5ad8f34108e56e47ed16f0a0a0de222ebd30b18551eb30bfc80a39fe6237e939a03cd67f4dce1810da76f6858c6c2a8808d4579d293c languageName: node linkType: hard -"@angular/service-worker@npm:19.0.1": - version: 19.0.1 - resolution: "@angular/service-worker@npm:19.0.1" +"@angular/service-worker@npm:19.1.0-next.0": + version: 19.1.0-next.0 + resolution: "@angular/service-worker@npm:19.1.0-next.0" dependencies: tslib: "npm:^2.3.0" peerDependencies: - "@angular/common": 19.0.1 - "@angular/core": 19.0.1 + "@angular/common": 19.1.0-next.0 + "@angular/core": 19.1.0-next.0 bin: ngsw-config: ngsw-config.js - checksum: 10c0/b9dbf95b95038a9999afb04b6a93294042463a4d6c0519f9dede7bab91af57225fe4a556c031ca343ca19065cf4b7daec6a3c8c14a841d9524dec8507161a8a0 + checksum: 10c0/76acbd4284cbf7dfd30c3043ff31f75d0c86309e300e9c57db9716bba1795a806e4e3766d51902623e78fd8e35a32c083efc0c911792637518118dec3f85c45a languageName: node linkType: hard @@ -964,12 +964,12 @@ __metadata: version: 0.0.0-use.local resolution: "@angular/ssr@workspace:packages/angular/ssr" dependencies: - "@angular/common": "npm:19.0.1" - "@angular/compiler": "npm:19.0.1" - "@angular/core": "npm:19.0.1" - "@angular/platform-browser": "npm:19.0.1" - "@angular/platform-server": "npm:19.0.1" - "@angular/router": "npm:19.0.1" + "@angular/common": "npm:19.1.0-next.0" + "@angular/compiler": "npm:19.1.0-next.0" + "@angular/core": "npm:19.1.0-next.0" + "@angular/platform-browser": "npm:19.1.0-next.0" + "@angular/platform-server": "npm:19.1.0-next.0" + "@angular/router": "npm:19.1.0-next.0" "@bazel/runfiles": "npm:^5.8.1" tslib: "npm:^2.3.0" peerDependencies: @@ -3628,13 +3628,13 @@ __metadata: resolution: "@ngtools/webpack@workspace:packages/ngtools/webpack" dependencies: "@angular-devkit/core": "npm:0.0.0-PLACEHOLDER" - "@angular/compiler": "npm:19.0.1" - "@angular/compiler-cli": "npm:19.0.1" - typescript: "npm:5.6.3" + "@angular/compiler": "npm:19.1.0-next.0" + "@angular/compiler-cli": "npm:19.1.0-next.0" + typescript: "npm:5.7.2" webpack: "npm:5.96.1" peerDependencies: "@angular/compiler-cli": ^19.0.0 - typescript: ">=5.5 <5.7" + typescript: ">=5.5 <5.8" webpack: ^5.54.0 languageName: unknown linkType: soft @@ -14074,9 +14074,9 @@ __metadata: languageName: node linkType: hard -"ng-packagr@npm:19.0.1": - version: 19.0.1 - resolution: "ng-packagr@npm:19.0.1" +"ng-packagr@npm:19.1.0-next.0": + version: 19.1.0-next.0 + resolution: "ng-packagr@npm:19.1.0-next.0" dependencies: "@rollup/plugin-json": "npm:^6.1.0" "@rollup/wasm-node": "npm:^4.24.0" @@ -14103,7 +14103,7 @@ __metadata: "@angular/compiler-cli": ^19.0.0-next.0 tailwindcss: ^2.0.0 || ^3.0.0 tslib: ^2.3.0 - typescript: ">=5.5 <5.7" + typescript: ">=5.5 <5.8" dependenciesMeta: rollup: optional: true @@ -14112,7 +14112,7 @@ __metadata: optional: true bin: ng-packagr: cli/main.js - checksum: 10c0/56a1d29b017a694f0350b44ba60bee88716208d7ae067ba09e94bab63b6d9110550eaa1c913131bce0f31cc87fcbc426a081f63c1a2cf337e4d53bc3ac4787c9 + checksum: 10c0/5c0b28b01d65c407628b31942e02147368c62f13b1cd2b359f3957a9fba2fdda848133ae624421245396120cbef3eea16f234072a1b238a75c675a6dfb5084fc languageName: node linkType: hard @@ -18220,6 +18220,16 @@ __metadata: languageName: node linkType: hard +"typescript@npm:5.7.2": + version: 5.7.2 + resolution: "typescript@npm:5.7.2" + bin: + tsc: bin/tsc + tsserver: bin/tsserver + checksum: 10c0/a873118b5201b2ef332127ef5c63fb9d9c155e6fdbe211cbd9d8e65877283797cca76546bad742eea36ed7efbe3424a30376818f79c7318512064e8625d61622 + languageName: node + linkType: hard + "typescript@npm:~4.9.0": version: 4.9.5 resolution: "typescript@npm:4.9.5" @@ -18240,6 +18250,16 @@ __metadata: languageName: node linkType: hard +"typescript@patch:typescript@npm%3A5.7.2#optional!builtin": + version: 5.7.2 + resolution: "typescript@patch:typescript@npm%3A5.7.2#optional!builtin::version=5.7.2&hash=8c6c40" + bin: + tsc: bin/tsc + tsserver: bin/tsserver + checksum: 10c0/c891ccf04008bc1305ba34053db951f8a4584b4a1bf2f68fd972c4a354df3dc5e62c8bfed4f6ac2d12e5b3b1c49af312c83a651048f818cd5b4949d17baacd79 + languageName: node + linkType: hard + "typescript@patch:typescript@npm%3A~4.9.0#optional!builtin": version: 4.9.5 resolution: "typescript@patch:typescript@npm%3A4.9.5#optional!builtin::version=4.9.5&hash=289587"