diff --git a/Cargo.lock b/Cargo.lock index 49a668dee7570f..cf0e5efc0562bd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8027,6 +8027,7 @@ dependencies = [ "once_cell", "os_pipe", "parking_lot", + "percent-encoding", "pretty_assertions", "prost", "prost-build", diff --git a/cli/build.rs b/cli/build.rs index c8e156a265d300..2e7227aba28d56 100644 --- a/cli/build.rs +++ b/cli/build.rs @@ -133,7 +133,10 @@ mod ts { // Deno built-in type libraries "decorators", "decorators.legacy", - "es5", + "dom.asynciterable", + "dom", + "dom.extras", + "dom.iterable", "es2015.collection", "es2015.core", "es2015", @@ -145,10 +148,13 @@ mod ts { "es2015.symbol", "es2015.symbol.wellknown", "es2016.array.include", - "es2016.intl", "es2016", + "es2016.full", + "es2016.intl", + "es2017.arraybuffer", "es2017", "es2017.date", + "es2017.full", "es2017.intl", "es2017.object", "es2017.sharedmemory", @@ -157,11 +163,13 @@ mod ts { "es2018.asyncgenerator", "es2018.asynciterable", "es2018", + "es2018.full", "es2018.intl", "es2018.promise", "es2018.regexp", "es2019.array", "es2019", + "es2019.full", "es2019.intl", "es2019.object", "es2019.string", @@ -169,6 +177,7 @@ mod ts { "es2020.bigint", "es2020", "es2020.date", + "es2020.full", "es2020.intl", "es2020.number", "es2020.promise", @@ -176,33 +185,48 @@ mod ts { "es2020.string", "es2020.symbol.wellknown", "es2021", + "es2021.full", "es2021.intl", "es2021.promise", "es2021.string", "es2021.weakref", - "es2022", "es2022.array", + "es2022", "es2022.error", + "es2022.full", "es2022.intl", "es2022.object", "es2022.regexp", - "es2022.sharedmemory", "es2022.string", - "es2023", "es2023.array", "es2023.collection", + "es2023", + "es2023.full", "es2023.intl", - "esnext", + "es2024.arraybuffer", + "es2024.collection", + "es2024", + "es2024.full", + "es2024.object", + "es2024.promise", + "es2024.regexp", + "es2024.sharedmemory", + "es2024.string", + "es5", + "es6", "esnext.array", "esnext.collection", + "esnext", "esnext.decorators", "esnext.disposable", + "esnext.full", "esnext.intl", "esnext.iterator", - "esnext.object", - "esnext.promise", - "esnext.regexp", - "esnext.string", + "scripthost", + "webworker.asynciterable", + "webworker", + "webworker.importscripts", + "webworker.iterable", ]; let path_dts = cwd.join("tsc/dts"); diff --git a/cli/lib/args.rs b/cli/lib/args.rs index 22bebdf5d9fef7..0a5f120e1f9f57 100644 --- a/cli/lib/args.rs +++ b/cli/lib/args.rs @@ -60,6 +60,8 @@ pub enum RootCertStoreLoadError { FailedAddPemFile(String), #[error("Failed opening CA file: {0}")] CaFileOpenError(String), + #[error("Failed to load platform certificates: {0}")] + FailedNativeCerts(String), } /// Create and populate a root cert store based on the passed options and @@ -89,7 +91,9 @@ pub fn get_root_cert_store( root_cert_store.extend(webpki_roots::TLS_SERVER_ROOTS.to_vec()); } "system" => { - let roots = load_native_certs().expect("could not load platform certs"); + let roots = load_native_certs().map_err(|err| { + RootCertStoreLoadError::FailedNativeCerts(err.to_string()) + })?; for root in roots { if let Err(err) = root_cert_store .add(rustls::pki_types::CertificateDer::from(root.0.clone())) diff --git a/cli/lib/version.rs b/cli/lib/version.rs index 88a25dffeb115f..3fb23247260a8f 100644 --- a/cli/lib/version.rs +++ b/cli/lib/version.rs @@ -14,7 +14,7 @@ pub fn otel_runtime_config() -> OtelRuntimeConfig { } const GIT_COMMIT_HASH: &str = env!("GIT_COMMIT_HASH"); -const TYPESCRIPT: &str = "5.6.2"; +const TYPESCRIPT: &str = "5.7.3"; const DENO_VERSION: &str = env!("DENO_VERSION"); // TODO(bartlomieju): ideally we could remove this const. const IS_CANARY: bool = option_env!("DENO_CANARY").is_some(); diff --git a/cli/lsp/language_server.rs b/cli/lsp/language_server.rs index 012cdd1e452e87..3ff69e19f2de89 100644 --- a/cli/lsp/language_server.rs +++ b/cli/lsp/language_server.rs @@ -1880,7 +1880,7 @@ impl Inner { })?; let asset_or_doc = self.get_asset_or_document(&action_data.specifier)?; let line_index = asset_or_doc.line_index(); - let refactor_edit_info = self + let mut refactor_edit_info = self .ts_server .get_edits_for_refactor( self.snapshot(), @@ -1901,34 +1901,19 @@ impl Inner { )), asset_or_doc.scope().cloned(), ) - .await; - - match refactor_edit_info { - Ok(mut refactor_edit_info) => { - if kind_suffix == ".rewrite.function.returnType" - || kind_suffix == ".move.newFile" - { - refactor_edit_info.edits = - fix_ts_import_changes(&refactor_edit_info.edits, self).map_err( - |err| { - error!("Unable to remap changes: {:#}", err); - LspError::internal_error() - }, - )? - } - code_action.edit = refactor_edit_info.to_workspace_edit(self)?; - } - Err(err) => { - // TODO(nayeemrmn): Investigate cause for - // https://github.com/denoland/deno/issues/27778. Prevent popups for - // this error for now. - if kind_suffix == ".move.newFile" { - lsp_warn!("{:#}", err); - } else { - return Err(err); - } - } + .await?; + if kind_suffix == ".rewrite.function.returnType" + || kind_suffix == ".move.newFile" + { + refactor_edit_info.edits = + fix_ts_import_changes(&refactor_edit_info.edits, self).map_err( + |err| { + error!("Unable to remap changes: {:#}", err); + LspError::internal_error() + }, + )? } + code_action.edit = refactor_edit_info.to_workspace_edit(self)?; code_action } else { // The code action doesn't need to be resolved diff --git a/cli/lsp/tsc.rs b/cli/lsp/tsc.rs index e523e0b31fc35d..a134878aab25e9 100644 --- a/cli/lsp/tsc.rs +++ b/cli/lsp/tsc.rs @@ -6015,11 +6015,25 @@ mod tests { // get some notification when the size of the assets grows let mut total_size = 0; - for asset in assets { + for asset in &assets { total_size += asset.text().len(); } assert!(total_size > 0); - assert!(total_size < 2_000_000); // currently as of TS 4.6, it's 0.7MB + #[allow(clippy::print_stderr)] + // currently as of TS 5.7, it's 3MB + if total_size > 3_500_000 { + let mut sizes = Vec::new(); + for asset in &assets { + sizes.push((asset.specifier(), asset.text().len())); + } + sizes.sort_by_cached_key(|(_, size)| *size); + sizes.reverse(); + for (specifier, size) in &sizes { + eprintln!("{}: {}", specifier, size); + } + eprintln!("Total size: {}", total_size); + panic!("Assets were quite large."); + } } #[tokio::test] diff --git a/cli/npm/installer/resolution.rs b/cli/npm/installer/resolution.rs index 06bbcd4f76bf0f..267ca2f4326090 100644 --- a/cli/npm/installer/resolution.rs +++ b/cli/npm/installer/resolution.rs @@ -189,7 +189,7 @@ fn get_add_pkg_reqs_options(package_reqs: &[PackageReq]) -> AddPkgReqsOptions { // WARNING: When bumping this version, check if anything needs to be // updated in the `setNodeOnlyGlobalNames` call in 99_main_compiler.js types_node_version_req: Some( - VersionReq::parse_from_npm("22.0.0 - 22.5.4").unwrap(), + VersionReq::parse_from_npm("22.9.0 - 22.12.0").unwrap(), ), } } diff --git a/cli/snapshot/shared.rs b/cli/snapshot/shared.rs index eec982776a74dc..61da61f408a0b4 100644 --- a/cli/snapshot/shared.rs +++ b/cli/snapshot/shared.rs @@ -1,3 +1,3 @@ // Copyright 2018-2025 the Deno authors. MIT license. -pub static TS_VERSION: &str = "5.6.2"; +pub static TS_VERSION: &str = "5.7.3"; diff --git a/cli/tsc/00_typescript.js b/cli/tsc/00_typescript.js index b7626fe08269bb..c266ad5270ca4a 100644 --- a/cli/tsc/00_typescript.js +++ b/cli/tsc/00_typescript.js @@ -93,7 +93,7 @@ __export(typescript_exports, { IndexKind: () => IndexKind, InferenceFlags: () => InferenceFlags, InferencePriority: () => InferencePriority, - InlayHintKind: () => InlayHintKind2, + InlayHintKind: () => InlayHintKind, InlayHints: () => ts_InlayHints_exports, InternalEmitFlags: () => InternalEmitFlags, InternalNodeBuilderFlags: () => InternalNodeBuilderFlags, @@ -144,6 +144,7 @@ __export(typescript_exports, { PollingWatchKind: () => PollingWatchKind, PragmaKindFlags: () => PragmaKindFlags, PredicateSemantics: () => PredicateSemantics, + PreparePasteEdits: () => ts_preparePasteEdits_exports, PrivateIdentifierKind: () => PrivateIdentifierKind, ProcessLevel: () => ProcessLevel, ProgramUpdateLevel: () => ProgramUpdateLevel, @@ -236,10 +237,8 @@ __export(typescript_exports, { breakIntoWordSpans: () => breakIntoWordSpans, buildLinkParts: () => buildLinkParts, buildOpts: () => buildOpts, - buildOverload: () => buildOverload, bundlerModuleNameResolver: () => bundlerModuleNameResolver, canBeConvertedToAsync: () => canBeConvertedToAsync, - canEmitTsBuildInfo: () => canEmitTsBuildInfo, canHaveDecorators: () => canHaveDecorators, canHaveExportModifier: () => canHaveExportModifier, canHaveFlowNode: () => canHaveFlowNode, @@ -259,6 +258,7 @@ __export(typescript_exports, { canWatchAffectingLocation: () => canWatchAffectingLocation, canWatchAtTypes: () => canWatchAtTypes, canWatchDirectoryOrFile: () => canWatchDirectoryOrFile, + canWatchDirectoryOrFilePath: () => canWatchDirectoryOrFilePath, cartesianProduct: () => cartesianProduct, cast: () => cast, chainBundle: () => chainBundle, @@ -424,7 +424,6 @@ __export(typescript_exports, { createNodeConverters: () => createNodeConverters, createNodeFactory: () => createNodeFactory, createOptionNameMap: () => createOptionNameMap, - createOverload: () => createOverload, createPackageJsonImportFilter: () => createPackageJsonImportFilter, createPackageJsonInfo: () => createPackageJsonInfo, createParenthesizerRules: () => createParenthesizerRules, @@ -530,6 +529,7 @@ __export(typescript_exports, { escapeTemplateSubstitution: () => escapeTemplateSubstitution, evaluatorResult: () => evaluatorResult, every: () => every, + exclusivelyPrefixedNodeCoreModules: () => exclusivelyPrefixedNodeCoreModules, executeCommandLine: () => executeCommandLine, expandPreOrPostfixIncrementOrDecrementExpression: () => expandPreOrPostfixIncrementOrDecrementExpression, explainFiles: () => explainFiles, @@ -542,7 +542,6 @@ __export(typescript_exports, { extensionsNotSupportingExtensionlessResolution: () => extensionsNotSupportingExtensionlessResolution, externalHelpersModuleNameText: () => externalHelpersModuleNameText, factory: () => factory, - fileContainsPackageImport: () => fileContainsPackageImport, fileExtensionIs: () => fileExtensionIs, fileExtensionIsOneOf: () => fileExtensionIsOneOf, fileIncludeReasonToDiagnostics: () => fileIncludeReasonToDiagnostics, @@ -592,8 +591,10 @@ __export(typescript_exports, { forEach: () => forEach, forEachAncestor: () => forEachAncestor, forEachAncestorDirectory: () => forEachAncestorDirectory, + forEachAncestorDirectoryStoppingAtGlobalCache: () => forEachAncestorDirectoryStoppingAtGlobalCache, forEachChild: () => forEachChild, forEachChildRecursively: () => forEachChildRecursively, + forEachDynamicImportOrRequireCall: () => forEachDynamicImportOrRequireCall, forEachEmittedFile: () => forEachEmittedFile, forEachEnclosingBlockScopeContainer: () => forEachEnclosingBlockScopeContainer, forEachEntry: () => forEachEntry, @@ -634,6 +635,7 @@ __export(typescript_exports, { getAllKeys: () => getAllKeys, getAllProjectOutputs: () => getAllProjectOutputs, getAllSuperTypeNodes: () => getAllSuperTypeNodes, + getAllowImportingTsExtensions: () => getAllowImportingTsExtensions, getAllowJSCompilerOption: () => getAllowJSCompilerOption, getAllowSyntheticDefaultImports: () => getAllowSyntheticDefaultImports, getAncestor: () => getAncestor, @@ -942,6 +944,7 @@ __export(typescript_exports, { getPositionOfLineAndCharacter: () => getPositionOfLineAndCharacter, getPossibleGenericSignatures: () => getPossibleGenericSignatures, getPossibleOriginalInputExtensionForExtension: () => getPossibleOriginalInputExtensionForExtension, + getPossibleOriginalInputPathWithoutChangingExt: () => getPossibleOriginalInputPathWithoutChangingExt, getPossibleTypeArgumentsInfo: () => getPossibleTypeArgumentsInfo, getPreEmitDiagnostics: () => getPreEmitDiagnostics, getPrecedingNonSpaceCharacterPosition: () => getPrecedingNonSpaceCharacterPosition, @@ -1205,7 +1208,7 @@ __export(typescript_exports, { isBooleanLiteral: () => isBooleanLiteral, isBreakOrContinueStatement: () => isBreakOrContinueStatement, isBreakStatement: () => isBreakStatement, - isBuild: () => isBuild, + isBuildCommand: () => isBuildCommand, isBuildInfoFile: () => isBuildInfoFile, isBuilderProgram: () => isBuilderProgram, isBundle: () => isBundle, @@ -1392,7 +1395,7 @@ __export(typescript_exports, { isImportSpecifier: () => isImportSpecifier, isImportTypeAssertionContainer: () => isImportTypeAssertionContainer, isImportTypeNode: () => isImportTypeNode, - isImportableFile: () => isImportableFile, + isImportable: () => isImportable, isInComment: () => isInComment, isInCompoundLikeAssignment: () => isInCompoundLikeAssignment, isInExpressionContext: () => isInExpressionContext, @@ -1491,6 +1494,7 @@ __export(typescript_exports, { isJsxAttributeLike: () => isJsxAttributeLike, isJsxAttributeName: () => isJsxAttributeName, isJsxAttributes: () => isJsxAttributes, + isJsxCallLike: () => isJsxCallLike, isJsxChild: () => isJsxChild, isJsxClosingElement: () => isJsxClosingElement, isJsxClosingFragment: () => isJsxClosingFragment, @@ -1573,6 +1577,7 @@ __export(typescript_exports, { isNamespaceReexportDeclaration: () => isNamespaceReexportDeclaration, isNewExpression: () => isNewExpression, isNewExpressionTarget: () => isNewExpressionTarget, + isNewScopeNode: () => isNewScopeNode, isNoSubstitutionTemplateLiteral: () => isNoSubstitutionTemplateLiteral, isNodeArray: () => isNodeArray, isNodeArrayMultiLine: () => isNodeArrayMultiLine, @@ -1621,6 +1626,7 @@ __export(typescript_exports, { isParseTreeNode: () => isParseTreeNode, isPartOfParameterDeclaration: () => isPartOfParameterDeclaration, isPartOfTypeNode: () => isPartOfTypeNode, + isPartOfTypeOnlyImportOrExportDeclaration: () => isPartOfTypeOnlyImportOrExportDeclaration, isPartOfTypeQuery: () => isPartOfTypeQuery, isPartiallyEmittedExpression: () => isPartiallyEmittedExpression, isPatternMatch: () => isPatternMatch, @@ -1689,6 +1695,7 @@ __export(typescript_exports, { isSimpleInlineableExpression: () => isSimpleInlineableExpression, isSimpleParameterList: () => isSimpleParameterList, isSingleOrDoubleQuote: () => isSingleOrDoubleQuote, + isSolutionConfig: () => isSolutionConfig, isSourceElement: () => isSourceElement, isSourceFile: () => isSourceFile, isSourceFileFromLibrary: () => isSourceFileFromLibrary, @@ -1797,7 +1804,6 @@ __export(typescript_exports, { isVariableDeclarationInitializedToRequire: () => isVariableDeclarationInitializedToRequire, isVariableDeclarationList: () => isVariableDeclarationList, isVariableLike: () => isVariableLike, - isVariableLikeOrAccessor: () => isVariableLikeOrAccessor, isVariableStatement: () => isVariableStatement, isVoidExpression: () => isVoidExpression, isWatchSet: () => isWatchSet, @@ -1834,6 +1840,7 @@ __export(typescript_exports, { matchPatternOrExact: () => matchPatternOrExact, matchedText: () => matchedText, matchesExclude: () => matchesExclude, + matchesExcludeWorker: () => matchesExcludeWorker, maxBy: () => maxBy, maybeBind: () => maybeBind, maybeSetLocalizedDiagnosticMessages: () => maybeSetLocalizedDiagnosticMessages, @@ -1873,6 +1880,7 @@ __export(typescript_exports, { noTransformers: () => noTransformers, noTruncationMaximumTruncationLength: () => noTruncationMaximumTruncationLength, nodeCanBeDecorated: () => nodeCanBeDecorated, + nodeCoreModules: () => nodeCoreModules, nodeHasName: () => nodeHasName, nodeIsDecorated: () => nodeIsDecorated, nodeIsMissing: () => nodeIsMissing, @@ -2017,6 +2025,7 @@ __export(typescript_exports, { returnTrue: () => returnTrue, returnUndefined: () => returnUndefined, returnsPromise: () => returnsPromise, + rewriteModuleSpecifier: () => rewriteModuleSpecifier, sameFlatMap: () => sameFlatMap, sameMap: () => sameMap, sameMapping: () => sameMapping, @@ -2024,7 +2033,7 @@ __export(typescript_exports, { scanner: () => scanner, semanticDiagnosticsOptionDeclarations: () => semanticDiagnosticsOptionDeclarations, serializeCompilerOptions: () => serializeCompilerOptions, - server: () => ts_server_exports4, + server: () => ts_server_exports, servicesVersion: () => servicesVersion, setCommentRange: () => setCommentRange, setConfigFileInOptions: () => setConfigFileInOptions, @@ -2062,6 +2071,7 @@ __export(typescript_exports, { setValueDeclaration: () => setValueDeclaration, shouldAllowImportingTsExtension: () => shouldAllowImportingTsExtension, shouldPreserveConstEnums: () => shouldPreserveConstEnums, + shouldRewriteModuleSpecifier: () => shouldRewriteModuleSpecifier, shouldUseUriStyleNodeCoreModules: () => shouldUseUriStyleNodeCoreModules, showModuleSpecifier: () => showModuleSpecifier, signatureHasRestParameter: () => signatureHasRestParameter, @@ -2119,6 +2129,7 @@ __export(typescript_exports, { tagNamesAreEquivalent: () => tagNamesAreEquivalent, takeWhile: () => takeWhile, targetOptionDeclaration: () => targetOptionDeclaration, + targetToLibMap: () => targetToLibMap, testFormatSettings: () => testFormatSettings, textChangeRangeIsUnchanged: () => textChangeRangeIsUnchanged, textChangeRangeNewSpan: () => textChangeRangeNewSpan, @@ -2212,6 +2223,7 @@ __export(typescript_exports, { tryRemoveExtension: () => tryRemoveExtension, tryRemovePrefix: () => tryRemovePrefix, tryRemoveSuffix: () => tryRemoveSuffix, + tscBuildOption: () => tscBuildOption, typeAcquisitionDeclarations: () => typeAcquisitionDeclarations, typeAliasNamePart: () => typeAliasNamePart, typeDirectiveIsEqualTo: () => typeDirectiveIsEqualTo, @@ -2223,6 +2235,7 @@ __export(typescript_exports, { unescapeLeadingUnderscores: () => unescapeLeadingUnderscores, unmangleScopedPackageName: () => unmangleScopedPackageName, unorderedRemoveItem: () => unorderedRemoveItem, + unprefixedNodeCoreModules: () => unprefixedNodeCoreModules, unreachableCodeIsError: () => unreachableCodeIsError, unsetNodeChildren: () => unsetNodeChildren, unusedLabelIsError: () => unusedLabelIsError, @@ -2263,8 +2276,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.3"; var Comparison = /* @__PURE__ */ ((Comparison3) => { Comparison3[Comparison3["LessThan"] = -1] = "LessThan"; Comparison3[Comparison3["EqualTo"] = 0] = "EqualTo"; @@ -2732,7 +2745,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 */: @@ -3617,7 +3633,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; } @@ -3746,13 +3762,13 @@ function isNodeLikeSystem() { } // src/compiler/debug.ts -var LogLevel = /* @__PURE__ */ ((LogLevel3) => { - LogLevel3[LogLevel3["Off"] = 0] = "Off"; - LogLevel3[LogLevel3["Error"] = 1] = "Error"; - LogLevel3[LogLevel3["Warning"] = 2] = "Warning"; - LogLevel3[LogLevel3["Info"] = 3] = "Info"; - LogLevel3[LogLevel3["Verbose"] = 4] = "Verbose"; - return LogLevel3; +var LogLevel = /* @__PURE__ */ ((LogLevel2) => { + LogLevel2[LogLevel2["Off"] = 0] = "Off"; + LogLevel2[LogLevel2["Error"] = 1] = "Error"; + LogLevel2[LogLevel2["Warning"] = 2] = "Warning"; + LogLevel2[LogLevel2["Info"] = 3] = "Info"; + LogLevel2[LogLevel2["Verbose"] = 4] = "Verbose"; + return LogLevel2; })(LogLevel || {}); var Debug; ((Debug2) => { @@ -5853,10 +5869,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"; @@ -6660,14 +6677,14 @@ function diagnosticCategoryName(d, lowerCase = true) { const name = DiagnosticCategory[d.category]; return lowerCase ? name.toLowerCase() : name; } -var ModuleResolutionKind = /* @__PURE__ */ ((ModuleResolutionKind3) => { - ModuleResolutionKind3[ModuleResolutionKind3["Classic"] = 1] = "Classic"; - ModuleResolutionKind3[ModuleResolutionKind3["NodeJs"] = 2] = "NodeJs"; - ModuleResolutionKind3[ModuleResolutionKind3["Node10"] = 2] = "Node10"; - ModuleResolutionKind3[ModuleResolutionKind3["Node16"] = 3] = "Node16"; - ModuleResolutionKind3[ModuleResolutionKind3["NodeNext"] = 99] = "NodeNext"; - ModuleResolutionKind3[ModuleResolutionKind3["Bundler"] = 100] = "Bundler"; - return ModuleResolutionKind3; +var ModuleResolutionKind = /* @__PURE__ */ ((ModuleResolutionKind2) => { + ModuleResolutionKind2[ModuleResolutionKind2["Classic"] = 1] = "Classic"; + ModuleResolutionKind2[ModuleResolutionKind2["NodeJs"] = 2] = "NodeJs"; + ModuleResolutionKind2[ModuleResolutionKind2["Node10"] = 2] = "Node10"; + ModuleResolutionKind2[ModuleResolutionKind2["Node16"] = 3] = "Node16"; + ModuleResolutionKind2[ModuleResolutionKind2["NodeNext"] = 99] = "NodeNext"; + ModuleResolutionKind2[ModuleResolutionKind2["Bundler"] = 100] = "Bundler"; + return ModuleResolutionKind2; })(ModuleResolutionKind || {}); var ModuleDetectionKind = /* @__PURE__ */ ((ModuleDetectionKind2) => { ModuleDetectionKind2[ModuleDetectionKind2["Legacy"] = 1] = "Legacy"; @@ -6675,52 +6692,52 @@ var ModuleDetectionKind = /* @__PURE__ */ ((ModuleDetectionKind2) => { ModuleDetectionKind2[ModuleDetectionKind2["Force"] = 3] = "Force"; return ModuleDetectionKind2; })(ModuleDetectionKind || {}); -var WatchFileKind = /* @__PURE__ */ ((WatchFileKind3) => { - WatchFileKind3[WatchFileKind3["FixedPollingInterval"] = 0] = "FixedPollingInterval"; - WatchFileKind3[WatchFileKind3["PriorityPollingInterval"] = 1] = "PriorityPollingInterval"; - WatchFileKind3[WatchFileKind3["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; - WatchFileKind3[WatchFileKind3["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; - WatchFileKind3[WatchFileKind3["UseFsEvents"] = 4] = "UseFsEvents"; - WatchFileKind3[WatchFileKind3["UseFsEventsOnParentDirectory"] = 5] = "UseFsEventsOnParentDirectory"; - return WatchFileKind3; +var WatchFileKind = /* @__PURE__ */ ((WatchFileKind2) => { + WatchFileKind2[WatchFileKind2["FixedPollingInterval"] = 0] = "FixedPollingInterval"; + WatchFileKind2[WatchFileKind2["PriorityPollingInterval"] = 1] = "PriorityPollingInterval"; + WatchFileKind2[WatchFileKind2["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; + WatchFileKind2[WatchFileKind2["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; + WatchFileKind2[WatchFileKind2["UseFsEvents"] = 4] = "UseFsEvents"; + WatchFileKind2[WatchFileKind2["UseFsEventsOnParentDirectory"] = 5] = "UseFsEventsOnParentDirectory"; + return WatchFileKind2; })(WatchFileKind || {}); -var WatchDirectoryKind = /* @__PURE__ */ ((WatchDirectoryKind3) => { - WatchDirectoryKind3[WatchDirectoryKind3["UseFsEvents"] = 0] = "UseFsEvents"; - WatchDirectoryKind3[WatchDirectoryKind3["FixedPollingInterval"] = 1] = "FixedPollingInterval"; - WatchDirectoryKind3[WatchDirectoryKind3["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; - WatchDirectoryKind3[WatchDirectoryKind3["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; - return WatchDirectoryKind3; +var WatchDirectoryKind = /* @__PURE__ */ ((WatchDirectoryKind2) => { + WatchDirectoryKind2[WatchDirectoryKind2["UseFsEvents"] = 0] = "UseFsEvents"; + WatchDirectoryKind2[WatchDirectoryKind2["FixedPollingInterval"] = 1] = "FixedPollingInterval"; + WatchDirectoryKind2[WatchDirectoryKind2["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling"; + WatchDirectoryKind2[WatchDirectoryKind2["FixedChunkSizePolling"] = 3] = "FixedChunkSizePolling"; + return WatchDirectoryKind2; })(WatchDirectoryKind || {}); -var PollingWatchKind = /* @__PURE__ */ ((PollingWatchKind3) => { - PollingWatchKind3[PollingWatchKind3["FixedInterval"] = 0] = "FixedInterval"; - PollingWatchKind3[PollingWatchKind3["PriorityInterval"] = 1] = "PriorityInterval"; - PollingWatchKind3[PollingWatchKind3["DynamicPriority"] = 2] = "DynamicPriority"; - PollingWatchKind3[PollingWatchKind3["FixedChunkSize"] = 3] = "FixedChunkSize"; - return PollingWatchKind3; +var PollingWatchKind = /* @__PURE__ */ ((PollingWatchKind2) => { + PollingWatchKind2[PollingWatchKind2["FixedInterval"] = 0] = "FixedInterval"; + PollingWatchKind2[PollingWatchKind2["PriorityInterval"] = 1] = "PriorityInterval"; + PollingWatchKind2[PollingWatchKind2["DynamicPriority"] = 2] = "DynamicPriority"; + PollingWatchKind2[PollingWatchKind2["FixedChunkSize"] = 3] = "FixedChunkSize"; + return PollingWatchKind2; })(PollingWatchKind || {}); -var ModuleKind = /* @__PURE__ */ ((ModuleKind3) => { - ModuleKind3[ModuleKind3["None"] = 0] = "None"; - ModuleKind3[ModuleKind3["CommonJS"] = 1] = "CommonJS"; - ModuleKind3[ModuleKind3["AMD"] = 2] = "AMD"; - ModuleKind3[ModuleKind3["UMD"] = 3] = "UMD"; - ModuleKind3[ModuleKind3["System"] = 4] = "System"; - ModuleKind3[ModuleKind3["ES2015"] = 5] = "ES2015"; - ModuleKind3[ModuleKind3["ES2020"] = 6] = "ES2020"; - ModuleKind3[ModuleKind3["ES2022"] = 7] = "ES2022"; - ModuleKind3[ModuleKind3["ESNext"] = 99] = "ESNext"; - ModuleKind3[ModuleKind3["Node16"] = 100] = "Node16"; - ModuleKind3[ModuleKind3["NodeNext"] = 199] = "NodeNext"; - ModuleKind3[ModuleKind3["Preserve"] = 200] = "Preserve"; - return ModuleKind3; +var ModuleKind = /* @__PURE__ */ ((ModuleKind2) => { + ModuleKind2[ModuleKind2["None"] = 0] = "None"; + ModuleKind2[ModuleKind2["CommonJS"] = 1] = "CommonJS"; + ModuleKind2[ModuleKind2["AMD"] = 2] = "AMD"; + ModuleKind2[ModuleKind2["UMD"] = 3] = "UMD"; + ModuleKind2[ModuleKind2["System"] = 4] = "System"; + ModuleKind2[ModuleKind2["ES2015"] = 5] = "ES2015"; + ModuleKind2[ModuleKind2["ES2020"] = 6] = "ES2020"; + ModuleKind2[ModuleKind2["ES2022"] = 7] = "ES2022"; + ModuleKind2[ModuleKind2["ESNext"] = 99] = "ESNext"; + ModuleKind2[ModuleKind2["Node16"] = 100] = "Node16"; + ModuleKind2[ModuleKind2["NodeNext"] = 199] = "NodeNext"; + ModuleKind2[ModuleKind2["Preserve"] = 200] = "Preserve"; + return ModuleKind2; })(ModuleKind || {}); -var JsxEmit = /* @__PURE__ */ ((JsxEmit3) => { - JsxEmit3[JsxEmit3["None"] = 0] = "None"; - JsxEmit3[JsxEmit3["Preserve"] = 1] = "Preserve"; - JsxEmit3[JsxEmit3["React"] = 2] = "React"; - JsxEmit3[JsxEmit3["ReactNative"] = 3] = "ReactNative"; - JsxEmit3[JsxEmit3["ReactJSX"] = 4] = "ReactJSX"; - JsxEmit3[JsxEmit3["ReactJSXDev"] = 5] = "ReactJSXDev"; - return JsxEmit3; +var JsxEmit = /* @__PURE__ */ ((JsxEmit2) => { + JsxEmit2[JsxEmit2["None"] = 0] = "None"; + JsxEmit2[JsxEmit2["Preserve"] = 1] = "Preserve"; + JsxEmit2[JsxEmit2["React"] = 2] = "React"; + JsxEmit2[JsxEmit2["ReactNative"] = 3] = "ReactNative"; + JsxEmit2[JsxEmit2["ReactJSX"] = 4] = "ReactJSX"; + JsxEmit2[JsxEmit2["ReactJSXDev"] = 5] = "ReactJSXDev"; + return JsxEmit2; })(JsxEmit || {}); var ImportsNotUsedAsValues = /* @__PURE__ */ ((ImportsNotUsedAsValues2) => { ImportsNotUsedAsValues2[ImportsNotUsedAsValues2["Remove"] = 0] = "Remove"; @@ -6728,38 +6745,39 @@ var ImportsNotUsedAsValues = /* @__PURE__ */ ((ImportsNotUsedAsValues2) => { ImportsNotUsedAsValues2[ImportsNotUsedAsValues2["Error"] = 2] = "Error"; return ImportsNotUsedAsValues2; })(ImportsNotUsedAsValues || {}); -var NewLineKind = /* @__PURE__ */ ((NewLineKind3) => { - NewLineKind3[NewLineKind3["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; - NewLineKind3[NewLineKind3["LineFeed"] = 1] = "LineFeed"; - return NewLineKind3; +var NewLineKind = /* @__PURE__ */ ((NewLineKind2) => { + NewLineKind2[NewLineKind2["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; + NewLineKind2[NewLineKind2["LineFeed"] = 1] = "LineFeed"; + return NewLineKind2; })(NewLineKind || {}); -var ScriptKind = /* @__PURE__ */ ((ScriptKind7) => { - ScriptKind7[ScriptKind7["Unknown"] = 0] = "Unknown"; - ScriptKind7[ScriptKind7["JS"] = 1] = "JS"; - ScriptKind7[ScriptKind7["JSX"] = 2] = "JSX"; - ScriptKind7[ScriptKind7["TS"] = 3] = "TS"; - ScriptKind7[ScriptKind7["TSX"] = 4] = "TSX"; - ScriptKind7[ScriptKind7["External"] = 5] = "External"; - ScriptKind7[ScriptKind7["JSON"] = 6] = "JSON"; - ScriptKind7[ScriptKind7["Deferred"] = 7] = "Deferred"; - return ScriptKind7; +var ScriptKind = /* @__PURE__ */ ((ScriptKind6) => { + ScriptKind6[ScriptKind6["Unknown"] = 0] = "Unknown"; + ScriptKind6[ScriptKind6["JS"] = 1] = "JS"; + ScriptKind6[ScriptKind6["JSX"] = 2] = "JSX"; + ScriptKind6[ScriptKind6["TS"] = 3] = "TS"; + ScriptKind6[ScriptKind6["TSX"] = 4] = "TSX"; + ScriptKind6[ScriptKind6["External"] = 5] = "External"; + ScriptKind6[ScriptKind6["JSON"] = 6] = "JSON"; + ScriptKind6[ScriptKind6["Deferred"] = 7] = "Deferred"; + return ScriptKind6; })(ScriptKind || {}); -var ScriptTarget = /* @__PURE__ */ ((ScriptTarget12) => { - ScriptTarget12[ScriptTarget12["ES3"] = 0] = "ES3"; - ScriptTarget12[ScriptTarget12["ES5"] = 1] = "ES5"; - ScriptTarget12[ScriptTarget12["ES2015"] = 2] = "ES2015"; - ScriptTarget12[ScriptTarget12["ES2016"] = 3] = "ES2016"; - ScriptTarget12[ScriptTarget12["ES2017"] = 4] = "ES2017"; - ScriptTarget12[ScriptTarget12["ES2018"] = 5] = "ES2018"; - ScriptTarget12[ScriptTarget12["ES2019"] = 6] = "ES2019"; - ScriptTarget12[ScriptTarget12["ES2020"] = 7] = "ES2020"; - ScriptTarget12[ScriptTarget12["ES2021"] = 8] = "ES2021"; - ScriptTarget12[ScriptTarget12["ES2022"] = 9] = "ES2022"; - ScriptTarget12[ScriptTarget12["ES2023"] = 10] = "ES2023"; - ScriptTarget12[ScriptTarget12["ESNext"] = 99] = "ESNext"; - ScriptTarget12[ScriptTarget12["JSON"] = 100] = "JSON"; - ScriptTarget12[ScriptTarget12["Latest"] = 99 /* ESNext */] = "Latest"; - return ScriptTarget12; +var ScriptTarget = /* @__PURE__ */ ((ScriptTarget11) => { + ScriptTarget11[ScriptTarget11["ES3"] = 0] = "ES3"; + ScriptTarget11[ScriptTarget11["ES5"] = 1] = "ES5"; + ScriptTarget11[ScriptTarget11["ES2015"] = 2] = "ES2015"; + ScriptTarget11[ScriptTarget11["ES2016"] = 3] = "ES2016"; + ScriptTarget11[ScriptTarget11["ES2017"] = 4] = "ES2017"; + ScriptTarget11[ScriptTarget11["ES2018"] = 5] = "ES2018"; + ScriptTarget11[ScriptTarget11["ES2019"] = 6] = "ES2019"; + ScriptTarget11[ScriptTarget11["ES2020"] = 7] = "ES2020"; + ScriptTarget11[ScriptTarget11["ES2021"] = 8] = "ES2021"; + ScriptTarget11[ScriptTarget11["ES2022"] = 9] = "ES2022"; + ScriptTarget11[ScriptTarget11["ES2023"] = 10] = "ES2023"; + ScriptTarget11[ScriptTarget11["ES2024"] = 11] = "ES2024"; + ScriptTarget11[ScriptTarget11["ESNext"] = 99] = "ESNext"; + ScriptTarget11[ScriptTarget11["JSON"] = 100] = "JSON"; + ScriptTarget11[ScriptTarget11["Latest"] = 99 /* ESNext */] = "Latest"; + return ScriptTarget11; })(ScriptTarget || {}); var LanguageVariant = /* @__PURE__ */ ((LanguageVariant4) => { LanguageVariant4[LanguageVariant4["Standard"] = 0] = "Standard"; @@ -7032,43 +7050,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"; @@ -7096,6 +7113,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"; @@ -7257,12 +7275,12 @@ var commentPragmas = { kind: 4 /* MultiLine */ } }; -var JSDocParsingMode = /* @__PURE__ */ ((JSDocParsingMode6) => { - JSDocParsingMode6[JSDocParsingMode6["ParseAll"] = 0] = "ParseAll"; - JSDocParsingMode6[JSDocParsingMode6["ParseNone"] = 1] = "ParseNone"; - JSDocParsingMode6[JSDocParsingMode6["ParseForTypeErrors"] = 2] = "ParseForTypeErrors"; - JSDocParsingMode6[JSDocParsingMode6["ParseForTypeInfo"] = 3] = "ParseForTypeInfo"; - return JSDocParsingMode6; +var JSDocParsingMode = /* @__PURE__ */ ((JSDocParsingMode4) => { + JSDocParsingMode4[JSDocParsingMode4["ParseAll"] = 0] = "ParseAll"; + JSDocParsingMode4[JSDocParsingMode4["ParseNone"] = 1] = "ParseNone"; + JSDocParsingMode4[JSDocParsingMode4["ParseForTypeErrors"] = 2] = "ParseForTypeErrors"; + JSDocParsingMode4[JSDocParsingMode4["ParseForTypeInfo"] = 3] = "ParseForTypeInfo"; + return JSDocParsingMode4; })(JSDocParsingMode || {}); // src/compiler/sys.ts @@ -7996,6 +8014,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 @@ -8244,6 +8263,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; @@ -8325,12 +8345,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; }, @@ -8373,7 +8390,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) { @@ -8427,11 +8448,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 }); @@ -8550,12 +8568,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 { @@ -8578,25 +8592,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) { @@ -8620,15 +8626,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 { @@ -9544,6 +9542,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( @@ -10115,6 +10117,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}'."), @@ -10290,7 +10298,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."), @@ -10672,6 +10679,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."), @@ -10851,7 +10859,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, @@ -10942,7 +10950,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."), @@ -10957,7 +10965,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}."), @@ -11251,6 +11259,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?"), @@ -11305,15 +11315,20 @@ __export(deno_exports, { parseNpmPackageReference: () => parseNpmPackageReference, setIsNodeSourceFileCallback: () => setIsNodeSourceFileCallback, setNodeOnlyGlobalNames: () => setNodeOnlyGlobalNames, + setTypesNodeIgnorableNames: () => setTypesNodeIgnorableNames, tryParseNpmPackageReference: () => tryParseNpmPackageReference }); var isNodeSourceFile = () => false; var nodeOnlyGlobalNames = /* @__PURE__ */ new Set(); +var typesNodeIgnorableNames = /* @__PURE__ */ new Set(); function setIsNodeSourceFileCallback(callback) { isNodeSourceFile = callback; } function setNodeOnlyGlobalNames(names) { - nodeOnlyGlobalNames = new Set(names); + nodeOnlyGlobalNames = names; +} +function setTypesNodeIgnorableNames(names) { + typesNodeIgnorableNames = names; } function createDenoForkContext({ mergeSymbol, @@ -11337,12 +11352,31 @@ function createDenoForkContext({ function mergeGlobalSymbolTable(node, source, unidirectional = false) { const sourceFile = getSourceFileOfNode(node); const isNodeFile = hasNodeSourceFile(sourceFile); + const isTypesNodeSourceFile = isNodeFile && isTypesNodePkgPath(sourceFile.path); source.forEach((sourceSymbol, id) => { const target = isNodeFile ? getGlobalsForName(id) : globals; const targetSymbol = target.get(id); + if (isTypesNodeSourceFile && targetSymbol !== void 0 && typesNodeIgnorableNames.has(id) && !symbolHasAnyTypesNodePkgDecl(targetSymbol)) { + return; + } target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol); }); } + function symbolHasAnyTypesNodePkgDecl(symbol) { + if (symbol.declarations) { + for (const decl of symbol.declarations) { + const sourceFile = getSourceFileOfNode(decl); + const isNodeFile = hasNodeSourceFile(sourceFile); + if (isNodeFile && isTypesNodePkgPath(sourceFile.path)) { + return true; + } + } + } + return false; + } + function isTypesNodePkgPath(path) { + return path.endsWith(".d.ts") && path.includes("/@types/node/"); + } function createNodeGlobalsSymbolTable() { return new Proxy(globals, { get(target, prop, receiver) { @@ -11610,11 +11644,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]; @@ -11683,6 +11717,7 @@ function computeLineStarts(text) { if (text.charCodeAt(pos) === 10 /* lineFeed */) { pos++; } + // falls through case 10 /* lineFeed */: result.push(lineStart); lineStart = pos; @@ -11785,6 +11820,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 */: @@ -11808,6 +11845,7 @@ function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments, inJSDoc) { if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) { pos++; } + // falls through case 10 /* lineFeed */: pos++; if (stopAfterLineBreak) { @@ -11954,6 +11992,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) { @@ -12519,12 +12558,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 */: @@ -12622,10 +12665,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 */: @@ -13056,6 +13102,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 */: @@ -13575,6 +13622,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan break; } } + // falls through case 42 /* asterisk */: case 43 /* plus */: case 63 /* question */: @@ -13605,6 +13653,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan if (isInGroup) { return; } + // falls through case 93 /* closeBracket */: case 125 /* closeBrace */: if (anyUnicodeModeOrNonAnnexB || ch === 41 /* closeParen */) { @@ -13667,6 +13716,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*/ @@ -13804,6 +13854,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); @@ -13909,6 +13960,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); @@ -14006,6 +14058,7 @@ function createScanner(languageVersion, skipTrivia2, languageVariant = 0 /* Stan } } pos--; + // falls through default: return scanClassSetCharacter(); } @@ -14152,6 +14205,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 */) { @@ -14459,6 +14513,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 */; @@ -14663,28 +14718,35 @@ function isExternalModuleNameRelative(moduleName) { function sortAndDeduplicateDiagnostics(diagnostics) { return sortAndDeduplicate(diagnostics, compareDiagnostics, diagnosticsEqualityComparer); } +var targetToLibMap = /* @__PURE__ */ new Map([ + [99 /* ESNext */, "lib.esnext.full.d.ts"], + [11 /* ES2024 */, "lib.es2024.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 11 /* ES2024 */: 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"; } @@ -15477,6 +15539,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); } @@ -15625,7 +15690,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); @@ -15687,7 +15752,9 @@ function isObjectBindingOrAssignmentElement(node) { switch (node.kind) { case 208 /* BindingElement */: case 303 /* PropertyAssignment */: + // AssignmentProperty case 304 /* ShorthandPropertyAssignment */: + // AssignmentProperty case 305 /* SpreadAssignment */: return true; } @@ -15705,11 +15772,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; } @@ -15732,13 +15805,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; } @@ -15770,6 +15846,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 */: @@ -15785,6 +15862,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: @@ -15841,8 +15919,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: @@ -16079,6 +16157,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 */; @@ -16719,11 +16801,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 @@ -16745,6 +16861,9 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2018: [ "dotAll" + ], + es2024: [ + "unicodeSets" ] })), Reflect: new Map(Object.entries({ @@ -16791,6 +16910,9 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2022: [ "hasOwn" + ], + es2024: [ + "groupBy" ] })), NumberConstructor: new Map(Object.entries({ @@ -16831,11 +16953,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({ @@ -16850,6 +16986,9 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( ], es2021: [ "any" + ], + es2024: [ + "withResolvers" ] })), Symbol: new Map(Object.entries({ @@ -16916,7 +17055,7 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( es2022: [ "at" ], - esnext: [ + es2024: [ "isWellFormed", "toWellFormed" ] @@ -16961,6 +17100,11 @@ var getScriptTargetFeatures = /* @__PURE__ */ memoize( SymbolConstructor: new Map(Object.entries({ es2020: [ "matchAll" + ], + esnext: [ + "metadata", + "dispose", + "asyncDispose" ] })), DataView: new Map(Object.entries({ @@ -17581,6 +17725,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 */: @@ -17752,6 +17898,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; @@ -17759,6 +17907,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 */: { @@ -17900,9 +18049,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 */; } @@ -18027,6 +18173,7 @@ function getThisContainer(node, includeArrowFunctions, includeClassComputedPrope if (!includeArrowFunctions) { continue; } + // falls through case 262 /* FunctionDeclaration */: case 218 /* FunctionExpression */: case 267 /* ModuleDeclaration */: @@ -18049,6 +18196,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 */: @@ -18115,6 +18264,7 @@ function getSuperContainer(node, stopOnFunctions) { if (!stopOnFunctions) { continue; } + // falls through case 172 /* PropertyDeclaration */: case 171 /* PropertySignature */: case 174 /* MethodDeclaration */: @@ -18168,6 +18318,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; @@ -18183,6 +18334,8 @@ function getInvokedExpression(node) { return node.tagName; case 226 /* BinaryExpression */: return node.right; + case 289 /* JsxOpeningFragment */: + return node; default: return node.expression; } @@ -18332,6 +18485,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 */: @@ -18786,12 +18940,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 */: @@ -18836,17 +18995,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; } @@ -19246,6 +19403,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; @@ -19416,6 +19574,7 @@ function getFunctionFlags(node) { if (node.asteriskToken) { flags |= 1 /* Generator */; } + // falls through case 219 /* ArrowFunction */: if (hasSyntacticModifier(node, 1024 /* Async */)) { flags |= 2 /* Async */; @@ -19686,7 +19845,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 */; @@ -19718,6 +19877,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 */: @@ -19900,7 +20060,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", @@ -20220,6 +20380,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; @@ -21093,6 +21259,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))) { @@ -21177,6 +21349,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 */; } @@ -21269,11 +21444,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) { @@ -21349,11 +21524,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; @@ -21753,7 +21929,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) => { @@ -21764,7 +21946,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: { @@ -21772,7 +21954,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; @@ -21796,7 +21978,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: { @@ -21811,7 +21993,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 */: @@ -21826,13 +22008,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; } @@ -21851,7 +22033,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; } @@ -21873,7 +22055,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: { @@ -21885,7 +22067,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: { @@ -21897,7 +22079,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: { @@ -21909,7 +22091,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: { @@ -21967,22 +22149,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 */; } @@ -22527,8 +22711,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); @@ -22556,15 +22765,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); } @@ -22641,6 +22848,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; @@ -22888,7 +23096,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; @@ -23429,6 +23637,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)) { @@ -23512,6 +23721,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 */) { @@ -23527,6 +23744,7 @@ function createNameResolver({ if (getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */) { break; } + // falls through case 174 /* MethodDeclaration */: case 176 /* Constructor */: case 177 /* GetAccessor */: @@ -23774,6 +23992,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); @@ -23784,6 +24005,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() { @@ -24107,6 +24440,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); } @@ -24888,6 +25222,7 @@ function createNodeFactory(flags, baseFactory2) { createSyntheticExpression, createSyntaxList: createSyntaxList3, createNotEmittedStatement, + createNotEmittedTypeElement, createPartiallyEmittedExpression, updatePartiallyEmittedExpression, createCommaListExpression, @@ -27914,7 +28249,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 */; @@ -27924,6 +28259,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)) { @@ -27936,7 +28274,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; @@ -27945,7 +28283,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); @@ -28192,7 +28530,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); } } @@ -28737,7 +29075,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 */; @@ -29110,7 +29448,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 */); @@ -29599,6 +29939,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 */; @@ -29979,13 +30328,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", @@ -30104,6 +30463,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, @@ -30446,10 +30819,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 */; @@ -30605,7 +30978,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 */; @@ -31228,7 +31601,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; @@ -31266,23 +31639,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, @@ -31299,57 +31670,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) { @@ -31672,10 +32040,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: @@ -32303,7 +32674,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) { @@ -32399,7 +32770,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); @@ -32769,6 +33140,7 @@ var Parser; expression2 = parseLiteralNode(); break; } + // falls through default: expression2 = parseObjectLiteralExpression(); break; @@ -33610,10 +33982,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(); } @@ -33631,6 +34005,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); @@ -33690,6 +34067,7 @@ var Parser; case 25 /* DotToken */: return true; } + // falls through case 11 /* ArgumentExpressions */: return token() === 26 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: @@ -33723,6 +34101,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'."); } @@ -34039,6 +34418,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 */: @@ -34086,6 +34466,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); } @@ -35010,10 +35391,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 */: @@ -35891,6 +36274,7 @@ var Parser; if (isAwaitExpression2()) { return parseAwaitExpression(); } + // falls through default: return parseUpdateExpression(); } @@ -35910,6 +36294,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; } @@ -36483,10 +36869,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 */: @@ -36504,6 +36896,7 @@ var Parser; false ); } + // falls through case 9 /* NumericLiteral */: case 10 /* BigIntLiteral */: case 11 /* StringLiteral */: @@ -37007,6 +37400,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(); @@ -37079,6 +37493,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; @@ -37217,6 +37634,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(); @@ -37635,10 +38054,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: @@ -38545,6 +38969,7 @@ var Parser; linkEnd = scanner2.getTokenEnd(); break; } + // fallthrough if it's not a {@link sequence default: state = 2 /* SavingComments */; pushComment(scanner2.getTokenText()); @@ -38803,6 +39228,8 @@ var Parser; indent3 += 1; break; } + // record the * as a comment + // falls through default: if (state !== 3 /* SavingBackticks */) { state = 2 /* SavingComments */; @@ -39774,9 +40201,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; @@ -39883,6 +40311,7 @@ function processPragmasIntoFields(context, reportDiagnostic) { case "jsximportsource": case "jsxruntime": return; + // Accessed directly default: Debug.fail("Unhandled pragma kind"); } @@ -40020,6 +40449,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"], @@ -40043,6 +40473,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"], @@ -40075,12 +40506,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"], @@ -40089,13 +40526,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"] @@ -40394,6 +40831,7 @@ var targetOptionDeclaration = { es2021: 8 /* ES2021 */, es2022: 9 /* ES2022 */, es2023: 10 /* ES2023 */, + es2024: 11 /* ES2024 */, esnext: 99 /* ESNext */ })), affectsSourceFile: true, @@ -40472,15 +40910,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", @@ -41005,6 +41434,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", @@ -41465,7 +41903,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", @@ -41604,8 +42052,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); @@ -41740,6 +42194,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++; @@ -41793,10 +42248,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) { @@ -42080,6 +42535,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)); @@ -42173,7 +42629,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) { @@ -42184,6 +42640,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); } @@ -42559,8 +43026,6 @@ function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, exis validatedFilesSpecBeforeSubstitution, validatedIncludeSpecsBeforeSubstitution, validatedExcludeSpecsBeforeSubstitution, - pathPatterns: void 0, - // Initialized on first use isDefaultIncludeSpec }; } @@ -42699,6 +43164,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"); } @@ -42740,7 +43208,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) { @@ -42764,9 +43232,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")) { @@ -43288,6 +43761,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)) : ""; @@ -43808,7 +44282,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); @@ -44264,8 +44738,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) { @@ -44274,7 +44747,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, @@ -44586,25 +45059,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)); } @@ -44732,10 +45208,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); @@ -44897,6 +45374,7 @@ function loadEntrypointsFromExportMap(scope, exports2, state, extensions) { const result = loadFileNameFromPackageJsonField( extensions, finalPath, + target, /*onlyRecordFailures*/ false, state @@ -44941,7 +45419,8 @@ function getTemporaryModuleResolutionState(packageJsonInfoCache, host, options) }; } function getPackageScopeForPath(directory, state) { - return forEachAncestorDirectory( + return forEachAncestorDirectoryStoppingAtGlobalCache( + state.host, directory, (dir) => getPackageJsonInfo( dir, @@ -45037,7 +45516,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); } @@ -45073,17 +45559,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); } @@ -45146,7 +45623,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, @@ -45156,7 +45633,7 @@ function loadModuleFromExports(scope, extensions, subpath, state, cache, redirec /*isImports*/ false ); - return loadModuleFromTargetImportOrExport( + return loadModuleFromTargetExportOrImport( mainExport, "", /*pattern*/ @@ -45174,7 +45651,7 @@ function loadModuleFromExports(scope, extensions, subpath, state, cache, redirec void 0 ); } - const result = loadModuleFromImportsOrExports( + const result = loadModuleFromExportsOrImports( extensions, state, cache, @@ -45228,7 +45705,7 @@ function loadModuleFromImports(extensions, moduleName, directory, state, cache, void 0 ); } - const result = loadModuleFromImportsOrExports( + const result = loadModuleFromExportsOrImports( extensions, state, cache, @@ -45255,19 +45732,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*/ "", @@ -45282,7 +45759,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*/ @@ -45292,7 +45769,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*/ @@ -45302,7 +45779,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*/ @@ -45322,9 +45799,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) { @@ -45402,6 +45879,7 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField( extensions, finalPath, + target, /*onlyRecordFailures*/ false, state @@ -45413,7 +45891,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); @@ -45438,7 +45916,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; } @@ -45514,6 +45992,8 @@ function getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirec return toSearchResult(withPackageId(scope, loadFileNameFromPackageJsonField( extensions, possibleInputWithInputExtension, + /*packageJsonValue*/ + void 0, /*onlyRecordFailures*/ false, state @@ -45589,17 +46069,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); @@ -45675,17 +46168,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; } @@ -45693,7 +46177,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); @@ -45805,28 +46288,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); @@ -45869,7 +46356,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); @@ -45960,20 +46447,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 */) { @@ -45990,6 +46481,7 @@ function getModuleInstanceStateWorker(node, visited) { return state; } break; + // 5. other uninstantiated module declarations. case 268 /* ModuleBlock */: { let state = 0 /* NonInstantiated */; forEachChild(node, (n) => { @@ -46107,7 +46599,7 @@ function createBinder() { var inStrictMode; var inAssignmentPattern = false; var symbolCount = 0; - var Symbol47; + var Symbol48; var classifiableNames; var unreachableFlow = createFlowNode( 1 /* Unreachable */, @@ -46136,7 +46628,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) { @@ -46187,7 +46679,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; @@ -46600,6 +47092,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); @@ -46620,6 +47113,7 @@ function createBinder() { case 303 /* PropertyAssignment */: case 230 /* SpreadElement */: inAssignmentPattern = saveInAssignmentPattern; + // falls through default: bindEachChild(node); break; @@ -46641,6 +47135,7 @@ function createBinder() { if (isJSDocTypeAssertion(expr)) { return false; } + // fallthrough case 235 /* NonNullExpression */: return isNarrowingExpression(expr.expression); case 226 /* BinaryExpression */: @@ -47472,6 +47967,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 */: @@ -47613,6 +48112,7 @@ function createBinder() { declareModuleMember(node, symbolFlags, symbolExcludes); break; } + // falls through default: Debug.assertNode(blockScopeContainer, canHaveLocals); if (!blockScopeContainer.locals) { @@ -47933,6 +48433,7 @@ function createBinder() { } function bindWorker(node) { switch (node.kind) { + /* Strict mode checks */ case 80 /* Identifier */: if (node.flags & 4096 /* IdentifierIsInJSDocNamespace */) { let parentNode = node.parent; @@ -47942,6 +48443,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; @@ -48030,6 +48532,7 @@ function createBinder() { return; case 182 /* TypePredicate */: break; + // Binding the children will handle everything case 168 /* TypeParameter */: return bindTypeParameter(node); case 169 /* Parameter */: @@ -48094,6 +48597,7 @@ function createBinder() { return bindObjectDefinePrototypeProperty(node); case 0 /* None */: break; + // Nothing to do default: return Debug.fail("Unknown call expression assignment declaration kind"); } @@ -48101,6 +48605,7 @@ function createBinder() { bindCallExpression(node); } break; + // Members of classes, interfaces, and modules case 231 /* ClassExpression */: case 263 /* ClassDeclaration */: inStrictMode = true; @@ -48113,10 +48618,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 */: @@ -48137,6 +48644,7 @@ function createBinder() { if (!isFunctionLikeOrClassStaticBlockDeclaration(node.parent)) { return; } + // falls through case 268 /* ModuleBlock */: return updateStrictModeStatementList(node.statements); case 341 /* JSDocParameterTag */: @@ -48146,6 +48654,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 */; @@ -48358,6 +48867,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: @@ -48854,6 +49364,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 */: @@ -49301,31 +49812,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 }; @@ -49371,7 +49880,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; } @@ -49427,9 +49936,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; @@ -49447,25 +49958,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 = {}) { @@ -49594,10 +50109,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, @@ -49926,6 +50442,8 @@ function tryGetModuleNameAsNodeModule({ path, isRedirect }, { getCanonicalFileNa subModuleName, versionPaths.paths, allowedEndings, + packageRootPath, + getCanonicalFileName, host, options ); @@ -50219,9 +50737,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; @@ -50253,17 +50771,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 @@ -50281,34 +50789,10 @@ function createTypeChecker(host) { nodeGlobals, mergeSymbol }); - const nodeGlobalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */); + var nodeGlobalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */); nodeGlobalThisSymbol.exports = denoContext.combinedGlobals; nodeGlobalThisSymbol.declarations = []; nodeGlobals.set(nodeGlobalThisSymbol.escapedName, nodeGlobalThisSymbol); - nodeGlobals.set( - "onmessage", - createSymbol(1536 /* Module */, "onmessage", 8 /* Readonly */) - ); - nodeGlobals.set( - "onabort", - createSymbol(1536 /* Module */, "onabort", 8 /* Readonly */) - ); - nodeGlobals.set( - "ReportingObserver", - createSymbol(1536 /* Module */, "ReportingObserver", 8 /* Readonly */) - ); - nodeGlobals.set( - "PerformanceObserver", - createSymbol(1536 /* Module */, "PerformanceObserver", 8 /* Readonly */) - ); - nodeGlobals.set( - "PerformanceObserverEntryList", - createSymbol(1536 /* Module */, "PerformanceObserverEntryList", 8 /* Readonly */) - ); - nodeGlobals.set( - "PerformanceResourceTiming", - createSymbol(1536 /* Module */, "PerformanceResourceTiming", 8 /* Readonly */) - ); var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); var requireSymbol = createSymbol(4 /* Property */, "require"); var isolatedModulesLikeFlagName = compilerOptions.verbatimModuleSyntax ? "verbatimModuleSyntax" : "isolatedModules"; @@ -50402,6 +50886,7 @@ function createTypeChecker(host) { getBaseTypeOfLiteralType, getWidenedType, getWidenedLiteralType, + fillMissingTypeArguments, getTypeFromTypeNode: (nodeIn) => { const node = getParseTreeNode(nodeIn, isTypeNode); return node ? getTypeFromTypeNode(node) : errorType; @@ -50958,6 +51443,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); @@ -51082,6 +51576,12 @@ function createTypeChecker(host) { /*isReadonly*/ true ); + var anyBaseTypeIndexInfo = createIndexInfo( + stringType, + anyType, + /*isReadonly*/ + false + ); var iterationTypesCache = /* @__PURE__ */ new Map(); var noIterationTypes = { get yieldType() { @@ -51439,7 +51939,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; @@ -52052,6 +52552,7 @@ function createTypeChecker(host) { if (isEntityNameExpression(node.expression)) { return node.expression; } + // falls through default: return void 0; } @@ -52347,10 +52848,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; } @@ -52418,7 +52928,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) { @@ -52620,12 +53130,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; @@ -53238,14 +53750,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) { @@ -53253,7 +53765,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, @@ -53262,11 +53774,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)) { @@ -53292,14 +53834,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) )); } } @@ -53926,6 +54465,7 @@ function createTypeChecker(host) { if (!isExternalOrCommonJsModule(location)) { break; } + // falls through case 267 /* ModuleDeclaration */: const sym = getSymbolOfDeclaration(location); if (result = callback( @@ -53991,7 +54531,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); } @@ -54448,12 +54988,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 = addOptionality(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, @@ -54501,65 +55223,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) { @@ -54583,6 +55246,7 @@ function createTypeChecker(host) { internalFlags: internalFlags || 0 /* None */, tracker: void 0, encounteredError: false, + suppressReportInferenceFallback: false, reportedDiagnostic: false, visitedTypes: void 0, symbolDepth: void 0, @@ -54601,6 +55265,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); @@ -54610,6 +55275,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; @@ -55021,8 +55699,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; } @@ -55364,6 +56042,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, @@ -55401,15 +56082,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; } @@ -55427,7 +56113,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; @@ -55503,7 +56189,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; @@ -55538,8 +56224,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) { @@ -55547,8 +56233,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; } @@ -55563,15 +56249,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 @@ -55587,11 +56275,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); @@ -55761,14 +56451,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); @@ -55911,7 +56672,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); @@ -56525,41 +57286,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; @@ -56570,37 +57336,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))) { @@ -56651,7 +57412,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) { @@ -56672,7 +57433,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 @@ -56680,7 +57441,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) }; } @@ -56724,6 +57485,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); @@ -56733,29 +57503,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 */) { @@ -56764,511 +57521,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; @@ -57520,7 +57781,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(); } } @@ -57743,13 +58006,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( @@ -57982,7 +58239,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; @@ -58178,6 +58435,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); @@ -58468,7 +58726,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 */)) { @@ -58498,6 +58756,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( @@ -58511,39 +58770,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; @@ -58554,19 +58802,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 */)) { @@ -58584,7 +58826,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 = []; @@ -58627,7 +58869,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], @@ -58640,11 +58882,11 @@ function createTypeChecker(host) { true, compareTypesIdentical )) { - failed = true; + failed2 = true; break; } } - if (!failed) { + if (!failed2) { return []; } } @@ -58950,6 +59192,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 */: @@ -58974,6 +59217,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 */: @@ -58991,14 +59236,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: @@ -59808,7 +60059,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); @@ -59842,7 +60093,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( @@ -60087,7 +60337,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 @@ -60943,11 +61193,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 */; @@ -60956,6 +61215,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); } @@ -61009,6 +61272,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]) { @@ -61023,6 +61304,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); } } } @@ -61131,12 +61414,7 @@ function createTypeChecker(host) { addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType)); callSignatures = concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); constructSignatures = concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */)); - const inheritedIndexInfos = instantiatedBaseType !== anyType ? getIndexInfosOfType(instantiatedBaseType) : [createIndexInfo( - stringType, - anyType, - /*isReadonly*/ - false - )]; + const inheritedIndexInfos = instantiatedBaseType !== anyType ? getIndexInfosOfType(instantiatedBaseType) : [anyBaseTypeIndexInfo]; indexInfos = concatenate(indexInfos, filter(inheritedIndexInfos, (info) => !findIndexInfo(indexInfos, info.keyType))); } } @@ -61153,7 +61431,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; @@ -61480,8 +61758,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( @@ -61494,7 +61777,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]); @@ -61657,17 +61940,12 @@ function createTypeChecker(host) { members = createSymbolTable(getNamedOrIndexSignatureMembers(members)); addInheritedMembers(members, getPropertiesOfType(baseConstructorType)); } else if (baseConstructorType === anyType) { - baseConstructorIndexInfo = createIndexInfo( - stringType, - anyType, - /*isReadonly*/ - false - ); + baseConstructorIndexInfo = anyBaseTypeIndexInfo; } } const indexSymbol = getIndexSymbolFromSymbolTable(members); if (indexSymbol) { - indexInfos = getIndexInfosOfIndexSymbol(indexSymbol); + indexInfos = getIndexInfosOfIndexSymbol(indexSymbol, arrayFrom(members.values())); } else { if (baseConstructorIndexInfo) { indexInfos = append(indexInfos, baseConstructorIndexInfo); @@ -63286,7 +63564,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 */); @@ -63296,23 +63574,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; @@ -66158,7 +66474,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); @@ -66550,6 +66866,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 */: @@ -66797,6 +67116,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); @@ -67216,6 +67536,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); @@ -68311,7 +68632,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); @@ -71343,7 +71664,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); } @@ -71361,11 +71682,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); + } } } }); @@ -72535,6 +72882,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; @@ -72568,6 +72916,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 */: @@ -74121,6 +74470,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( @@ -74564,6 +74916,7 @@ function createTypeChecker(host) { } } } + // falls through case 110 /* ThisKeyword */: case 108 /* SuperKeyword */: case 211 /* PropertyAccessExpression */: @@ -74624,6 +74977,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, @@ -74643,7 +75002,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)); @@ -74664,12 +75023,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; @@ -74686,7 +75052,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; @@ -74919,15 +75286,16 @@ 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; + const shouldFactoryRefErr = compilerOptions.jsx !== 1 /* Preserve */ && compilerOptions.jsx !== 3 /* ReactNative */; let jsxFactorySym; if (!(isJsxOpeningFragment(node) && jsxFactoryNamespace === "null")) { jsxFactorySym = resolveName( jsxFactoryLocation, jsxFactoryNamespace, - 111551 /* Value */, + shouldFactoryRefErr ? 111551 /* Value */ : 111551 /* Value */ & ~384 /* Enum */, jsxFactoryRefErr, /*isUse*/ true @@ -74946,7 +75314,7 @@ function createTypeChecker(host) { resolveName( jsxFactoryLocation, localJsxNamespace, - 111551 /* Value */, + shouldFactoryRefErr ? 111551 /* Value */ : 111551 /* Value */ & ~384 /* Enum */, jsxFactoryRefErr, /*isUse*/ true @@ -75270,6 +75638,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; } @@ -75315,7 +75684,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)) { @@ -76223,46 +76593,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 */) { @@ -76675,7 +77107,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); @@ -76706,6 +77138,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); @@ -76805,13 +77238,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); @@ -76826,8 +77260,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( @@ -76840,7 +77279,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]); @@ -76959,7 +77398,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); @@ -76993,7 +77432,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); @@ -77112,7 +77551,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]; @@ -77121,7 +77560,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."); @@ -77218,7 +77657,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) { @@ -77284,9 +77723,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) { @@ -77335,7 +77775,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("-"); @@ -77347,8 +77788,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; @@ -77357,96 +77796,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(), + 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 (!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( @@ -77458,14 +77906,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 @@ -77478,14 +77926,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) { @@ -77567,7 +78018,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; @@ -77791,10 +78242,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; @@ -78195,7 +78646,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 */); } @@ -78430,6 +78881,13 @@ function createTypeChecker(host) { return getIntersectionType(x); } function reportNonexistentProperty(propNode, containingType, isUncheckedJS) { + const links = getNodeLinks(propNode); + const cache = links.nonExistentPropCheckCache || (links.nonExistentPropCheckCache = /* @__PURE__ */ new Set()); + const key = `${getTypeId(containingType)}|${isUncheckedJS}`; + if (cache.has(key)) { + return; + } + cache.add(key); let errorInfo; let relatedInfo; if (!isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 402784252 /* Primitive */)) { @@ -78821,6 +79279,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); @@ -79094,9 +79553,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*/ @@ -79108,8 +79567,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, @@ -79180,10 +79639,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); @@ -79201,8 +79661,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; } @@ -79302,6 +79762,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())]; @@ -79586,25 +80049,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); @@ -79724,7 +80194,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)); @@ -79734,12 +80204,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) { @@ -80372,24 +80842,55 @@ 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); + const shouldResolveFactoryReference = (compilerOptions.jsx === 2 /* React */ || compilerOptions.jsxFragmentFactory !== void 0) && jsxFragmentFactoryName !== "null"; + if (!shouldResolveFactoryReference) return sourceFileLinks.jsxFragmentType = anyType; + const shouldModuleRefErr = compilerOptions.jsx !== 1 /* Preserve */ && compilerOptions.jsx !== 3 /* ReactNative */; + 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, + shouldModuleRefErr ? 111551 /* Value */ : 111551 /* Value */ & ~384 /* Enum */, + /*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); @@ -80405,7 +80906,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 */); @@ -80447,6 +80952,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); @@ -80815,7 +81321,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); @@ -80934,9 +81440,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))); @@ -81991,7 +82505,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, @@ -82310,6 +82824,7 @@ function createTypeChecker(host) { hasError = true; break; } + // fallthrough case 7 /* ES2022 */: case 99 /* ESNext */: case 200 /* Preserve */: @@ -82317,6 +82832,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; @@ -82525,7 +83041,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)) { @@ -82586,7 +83102,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 = []; @@ -82607,7 +83123,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; @@ -82734,9 +83250,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; } @@ -82899,7 +83419,9 @@ function createTypeChecker(host) { switch (node.kind) { case 223 /* AwaitExpression */: case 213 /* CallExpression */: + case 215 /* TaggedTemplateExpression */: case 212 /* ElementAccessExpression */: + case 236 /* MetaProperty */: case 214 /* NewExpression */: case 211 /* PropertyAccessExpression */: case 229 /* YieldExpression */: @@ -82915,6 +83437,8 @@ function createTypeChecker(host) { case 56 /* AmpersandAmpersandToken */: case 77 /* AmpersandAmpersandEqualsToken */: return 3 /* Sometimes */; + case 28 /* CommaToken */: + return getSyntacticNullishnessSemantics(node.right); } return 2 /* Never */; case 227 /* ConditionalExpression */: @@ -83377,10 +83901,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 */); } } @@ -83611,7 +84135,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); @@ -83623,6 +84147,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 */) { @@ -83982,6 +84509,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 */: @@ -84070,7 +84598,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) }); @@ -84209,13 +84737,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 */); } } @@ -84351,6 +84879,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)); @@ -84397,15 +84926,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) => { @@ -84447,7 +84978,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 */; } @@ -85094,6 +85625,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 */: @@ -85114,6 +85647,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 */: @@ -85127,6 +85662,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 */: @@ -85475,6 +86011,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; @@ -85581,7 +86118,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) { @@ -86247,7 +86784,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 */) { @@ -86283,7 +86820,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); @@ -86437,7 +86974,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); @@ -86651,11 +87188,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 */) { @@ -86888,7 +87425,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) { @@ -87056,11 +87593,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); } @@ -87696,12 +88249,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) { @@ -87728,7 +88281,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*/ @@ -87788,7 +88341,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); @@ -88294,6 +88847,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); @@ -88328,6 +88884,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 */) { @@ -88696,6 +89255,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; @@ -88708,6 +89268,7 @@ function createTypeChecker(host) { } break; } + // falls through case 263 /* ClassDeclaration */: case 266 /* EnumDeclaration */: case 262 /* FunctionDeclaration */: @@ -88971,6 +89532,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) { @@ -88983,18 +89545,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 (!importClause.isTypeOnly && moduleKind === 199 /* NodeNext */ && 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; @@ -89384,6 +89955,7 @@ function createTypeChecker(host) { return checkJSDocPropertyTag(node); case 317 /* JSDocFunctionType */: checkJSDocFunctionType(node); + // falls through case 315 /* JSDocNonNullableType */: case 314 /* JSDocNullableType */: case 312 /* JSDocAllType */: @@ -89807,6 +90379,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; @@ -89818,6 +90391,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) { @@ -89929,6 +90505,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); @@ -90108,7 +90685,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, @@ -90222,6 +90799,7 @@ function createTypeChecker(host) { if (!isThisInTypeQuery(node)) { return getSymbolOfNameOrPropertyAccessExpression(node); } + // falls through case 110 /* ThisKeyword */: const container = getThisContainer( node, @@ -90239,6 +90817,7 @@ function createTypeChecker(host) { if (isInExpressionContext(node)) { return checkExpression(node).symbol; } + // falls through case 197 /* ThisType */: return getTypeFromThisTypeNode(node).symbol; case 108 /* SuperKeyword */: @@ -90261,6 +90840,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)); @@ -90290,6 +90870,7 @@ function createTypeChecker(host) { const symbol = getIntrinsicTagSymbol(node.parent); return symbol === unknownSymbol ? void 0 : symbol; } + // falls through default: return void 0; } @@ -90695,7 +91276,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); @@ -90982,16 +91563,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); @@ -91008,52 +91585,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 denoGlobals.has(escapeLeadingUnderscores(name)); @@ -91204,22 +91748,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, @@ -91298,7 +91826,30 @@ 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; + if (info === anyBaseTypeIndexInfo) 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); @@ -91604,6 +92155,8 @@ function createTypeChecker(host) { return ["__propKey"]; case 16777216 /* AddDisposableResourceAndDisposeResources */: return ["__addDisposableResource", "__disposeResources"]; + case 33554432 /* RewriteRelativeImportExtension */: + return ["__rewriteRelativeImportExtension"]; default: return Debug.fail("Unrecognized helper"); } @@ -92387,6 +92940,7 @@ function createTypeChecker(host) { ); break; } + // fallthrough case 7 /* ES2022 */: case 99 /* ESNext */: case 200 /* Preserve */: @@ -92394,6 +92948,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) @@ -92751,7 +93306,7 @@ function createTypeChecker(host) { } return false; } - function allowLetAndConstDeclarations(parent2) { + function allowBlockDeclarations(parent2) { switch (parent2.kind) { case 245 /* IfStatement */: case 246 /* DoStatement */: @@ -92762,12 +93317,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"); @@ -93178,6 +93733,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 */: @@ -93203,7 +93762,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), @@ -93211,7 +93770,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 { @@ -93300,10 +93860,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 @@ -94582,13 +95151,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) @@ -95543,9 +96112,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; } @@ -95559,18 +96128,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; } @@ -95580,7 +96158,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; } @@ -95591,12 +96169,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; } @@ -95641,6 +96219,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) => { @@ -96464,7 +97049,7 @@ function transformTypeScript(context) { let currentNamespaceContainerName; let currentLexicalScope; let currentScopeFirstDeclarationsOfName; - let enabledSubstitutions; + let enabledSubstitutions = 0 /* None */; let applicableSubstitutions; return transformSourceFileOrBundle; function transformSourceFileOrBundle(node) { @@ -96694,6 +97279,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 */: @@ -96722,6 +97309,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 */: @@ -97965,7 +98554,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( @@ -98004,8 +98600,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; @@ -98272,7 +98870,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; @@ -98404,7 +99002,7 @@ function transformClassFields(context) { /*discarded*/ true ); - case 355 /* CommaListExpression */: + case 356 /* CommaListExpression */: return visitCommaListExpression( node, /*discarded*/ @@ -100344,6 +100942,7 @@ function transformClassFields(context) { if (isArrowFunction(original) || getEmitFlags(node) & 524288 /* AsyncFunctionBody */) { break; } + // falls through case 262 /* FunctionDeclaration */: case 176 /* Constructor */: case 177 /* GetAccessor */: @@ -100619,6 +101218,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 */: @@ -101218,7 +101818,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; @@ -101464,6 +102068,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, @@ -101484,7 +102089,7 @@ function transformESDecorators(context) { return visitForStatement(node); case 244 /* ExpressionStatement */: return visitExpressionStatement(node); - case 355 /* CommaListExpression */: + case 356 /* CommaListExpression */: return visitCommaListExpression( node, /*discarded*/ @@ -101496,7 +102101,7 @@ function transformESDecorators(context) { /*discarded*/ false ); - case 354 /* PartiallyEmittedExpression */: + case 355 /* PartiallyEmittedExpression */: return visitPartiallyEmittedExpression( node, /*discarded*/ @@ -101520,6 +102125,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 */: @@ -101582,7 +102188,7 @@ function transformESDecorators(context) { /*discarded*/ true ); - case 355 /* CommaListExpression */: + case 356 /* CommaListExpression */: return visitCommaListExpression( node, /*discarded*/ @@ -101728,7 +102334,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 */); @@ -103201,7 +103811,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; @@ -104076,7 +104686,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; @@ -104164,7 +104774,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); @@ -107211,7 +107821,7 @@ function transformES2015(context) { ); } let convertedLoopState; - let enabledSubstitutions; + let enabledSubstitutions = 0 /* None */; return chainBundle(context, transformSourceFile); function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -107304,6 +107914,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 */: @@ -107382,7 +107993,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 */: @@ -107766,12 +108377,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 */: @@ -107980,12 +108593,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 */: @@ -108031,12 +108646,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 */: @@ -110668,7 +111285,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); @@ -112564,6 +113181,7 @@ function transformModule(context) { const moduleInfoMap = []; let currentSourceFile; let currentModuleInfo; + let importsAndRequiresToRewriteOrShim; const noSubstitution = []; let needUMDDynamicImportHelper; return chainBundle(context, transformSourceFile); @@ -112574,6 +113192,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; @@ -113045,7 +113677,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) { @@ -113059,11 +113691,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 */: @@ -113355,13 +113993,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 */: @@ -113692,7 +114344,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"), @@ -114819,6 +115471,7 @@ function transformSystemModule(context) { if (!entry.importClause) { break; } + // falls through case 271 /* ImportEqualsDeclaration */: Debug.assert(importVariableName !== void 0); statements.push( @@ -115453,7 +116106,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)) { @@ -115786,6 +116439,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; @@ -115797,7 +116452,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( @@ -115820,7 +116490,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, @@ -115839,14 +116509,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( @@ -115991,11 +116699,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); @@ -116011,7 +116724,7 @@ function transformECMAScriptModule(context) { synthName ) ), - node.moduleSpecifier, + updatedModuleSpecifier, node.attributes ); setOriginalNode(importDecl, node.exportClause); @@ -116035,7 +116748,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); @@ -116043,18 +116758,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); + } + 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 substitution; + return node; } } @@ -116404,8 +117130,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, @@ -116534,7 +117260,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, @@ -116612,6 +117338,7 @@ function transformDeclarations(context) { let suppressNewDiagnosticContexts; const { factory: factory2 } = context; const host = context.getEmitHost(); + let restoreFallbackNode = () => void 0; const symbolTracker = { trackSymbol, reportInaccessibleThisError, @@ -116623,7 +117350,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; @@ -116960,7 +117699,7 @@ function transformDeclarations(context) { ); } } - function ensureParameter(p, modifierMask, type) { + function ensureParameter(p, modifierMask) { let oldDiag; if (!suppressNewDiagnosticContexts) { oldDiag = getSymbolAccessibilityDiagnostic; @@ -116974,7 +117713,6 @@ function transformDeclarations(context) { resolver.isOptionalParameter(p) ? p.questionToken || factory2.createToken(58 /* QuestionToken */) : void 0, ensureType( p, - type || p.type, /*ignorePrivate*/ true ), @@ -116999,44 +117737,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; } @@ -117052,6 +117780,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 */: @@ -117105,13 +117834,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) { @@ -117143,7 +117866,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)) { @@ -117165,7 +117888,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; @@ -117181,7 +117904,7 @@ function transformDeclarations(context) { decl, decl.modifiers, decl.importClause, - rewriteModuleSpecifier(decl, decl.moduleSpecifier), + rewriteModuleSpecifier2(decl, decl.moduleSpecifier), tryGetResolutionModeOverride(decl.attributes) ); } @@ -117197,7 +117920,7 @@ function transformDeclarations(context) { /*namedBindings*/ void 0 ), - rewriteModuleSpecifier(decl, decl.moduleSpecifier), + rewriteModuleSpecifier2(decl, decl.moduleSpecifier), tryGetResolutionModeOverride(decl.attributes) ); } @@ -117215,7 +117938,7 @@ function transformDeclarations(context) { visibleDefaultBinding, namedBindings ), - rewriteModuleSpecifier(decl, decl.moduleSpecifier), + rewriteModuleSpecifier2(decl, decl.moduleSpecifier), tryGetResolutionModeOverride(decl.attributes) ) : void 0; } @@ -117230,7 +117953,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) ); } @@ -117243,7 +117966,7 @@ function transformDeclarations(context) { decl.modifiers, /*importClause*/ void 0, - rewriteModuleSpecifier(decl, decl.moduleSpecifier), + rewriteModuleSpecifier2(decl, decl.moduleSpecifier), tryGetResolutionModeOverride(decl.attributes) ); } @@ -117362,7 +118085,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( @@ -117389,7 +118112,7 @@ function transformDeclarations(context) { input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), - ensureType(input, input.type), + ensureType(input), /*body*/ void 0 ); @@ -117402,13 +118125,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 )); @@ -117441,7 +118163,7 @@ function transformDeclarations(context) { ensureModifiers(input), input.name, input.questionToken, - ensureType(input, input.type), + ensureType(input), ensureNoInitializer(input) )); case 171 /* PropertySignature */: @@ -117456,7 +118178,7 @@ function transformDeclarations(context) { ensureModifiers(input), input.name, input.questionToken, - ensureType(input, input.type) + ensureType(input) )); case 173 /* MethodSignature */: { if (isPrivateIdentifier(input.name)) { @@ -117472,7 +118194,7 @@ function transformDeclarations(context) { input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), - ensureType(input, input.type) + ensureType(input) )); } case 179 /* CallSignature */: { @@ -117481,7 +118203,7 @@ function transformDeclarations(context) { input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), - ensureType(input, input.type) + ensureType(input) ) ); } @@ -117504,7 +118226,7 @@ function transformDeclarations(context) { input.name, /*exclamationToken*/ void 0, - ensureType(input, input.type), + ensureType(input), ensureNoInitializer(input) )); } @@ -117557,7 +118279,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), @@ -117610,7 +118332,7 @@ function transformDeclarations(context) { input.modifiers, input.isTypeOnly, input.exportClause, - rewriteModuleSpecifier(input, input.moduleSpecifier), + rewriteModuleSpecifier2(input, input.moduleSpecifier), tryGetResolutionModeOverride(input.attributes) ); } @@ -117628,11 +118350,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 ); @@ -117729,7 +118452,7 @@ function transformDeclarations(context) { input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), - ensureType(input, input.type), + ensureType(input), /*body*/ void 0 )); @@ -117860,7 +118583,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 { @@ -117897,7 +118620,7 @@ function transformDeclarations(context) { ensureModifiers(param), param.name, param.questionToken, - ensureType(param, param.type), + ensureType(param), ensureNoInitializer(param) ), param @@ -117918,11 +118641,7 @@ function transformDeclarations(context) { elem.name, /*questionOrExclamationToken*/ void 0, - ensureType( - elem, - /*type*/ - void 0 - ), + ensureType(elem), /*initializer*/ void 0 )); @@ -117946,7 +118665,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 */) { @@ -118072,11 +118792,7 @@ function transformDeclarations(context) { e.name, /*exclamationToken*/ void 0, - ensureType( - e, - /*type*/ - void 0 - ), + ensureType(e), /*initializer*/ void 0 ); @@ -118126,18 +118842,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( @@ -118173,11 +118877,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 */: @@ -118333,7 +119032,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; @@ -119262,7 +119961,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 })); @@ -119547,6 +120247,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) { @@ -119554,14 +120255,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: @@ -119613,6 +120317,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } if (hint === 4 /* Unspecified */) { switch (node.kind) { + // Pseudo-literals case 16 /* TemplateHead */: case 17 /* TemplateMiddle */: case 18 /* TemplateTail */: @@ -119621,20 +120326,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 */: @@ -119656,6 +120367,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitConstructSignature(node); case 181 /* IndexSignature */: return emitIndexSignature(node); + // Types case 182 /* TypePredicate */: return emitTypePredicate(node); case 183 /* TypeReference */: @@ -119674,6 +120386,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 */: @@ -119704,16 +120417,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 */: @@ -119755,6 +120471,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitTryStatement(node); case 259 /* DebuggerStatement */: return emitDebuggerStatement(node); + // Declarations case 260 /* VariableDeclaration */: return emitVariableDeclaration(node); case 261 /* VariableDeclarationList */: @@ -119805,8 +120522,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 */: @@ -119825,6 +120544,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { return emitJsxExpression(node); case 295 /* JsxNamespacedName */: return emitJsxNamespacedName(node); + // Clauses case 296 /* CaseClause */: return emitCaseClause(node); case 297 /* DefaultClause */: @@ -119833,18 +120553,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 */: @@ -119882,6 +120606,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 */: @@ -119891,6 +120616,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); @@ -119909,7 +120635,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)) { @@ -119927,6 +120656,7 @@ function createPrinter(printerOptions = {}, handlers = {}) { } if (hint === 1 /* Expression */) { switch (node.kind) { + // Literals case 9 /* NumericLiteral */: case 10 /* BigIntLiteral */: return emitNumericOrBigIntLiteral(node); @@ -119938,10 +120668,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 */: @@ -120004,21 +120736,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"); } } @@ -121109,15 +121844,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; } @@ -124053,7 +124861,7 @@ var WatchLogLevel = /* @__PURE__ */ ((WatchLogLevel2) => { WatchLogLevel2[WatchLogLevel2["Verbose"] = 2] = "Verbose"; return WatchLogLevel2; })(WatchLogLevel || {}); -function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo2) { +function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo) { setSysLog(watchLogLevel === 2 /* Verbose */ ? log : noop); const plainInvokeFactory = { watchFile: (file, callback, pollingInterval, options) => host.watchFile(file, callback, pollingInterval, options), @@ -124091,23 +124899,23 @@ function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo2) { return typeof host.useCaseSensitiveFileNames === "boolean" ? host.useCaseSensitiveFileNames : host.useCaseSensitiveFileNames(); } function createExcludeWatcherWithLogging(file, flags, options, detailInfo1, detailInfo2) { - log(`ExcludeWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`); + log(`ExcludeWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`); return { - close: () => log(`ExcludeWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`) + close: () => log(`ExcludeWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`) }; } function createFileWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) { - log(`FileWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`); + log(`FileWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`); const watcher = triggerInvokingFactory.watchFile(file, cb, flags, options, detailInfo1, detailInfo2); return { close: () => { - log(`FileWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`); + log(`FileWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`); watcher.close(); } }; } function createDirectoryWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) { - const watchInfo = `DirectoryWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`; + const watchInfo = `DirectoryWatcher:: Added:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`; log(watchInfo); const start = timestamp(); const watcher = triggerInvokingFactory.watchDirectory(file, cb, flags, options, detailInfo1, detailInfo2); @@ -124115,7 +124923,7 @@ function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo2) { log(`Elapsed:: ${elapsed}ms ${watchInfo}`); return { close: () => { - const watchInfo2 = `DirectoryWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`; + const watchInfo2 = `DirectoryWatcher:: Close:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`; log(watchInfo2); const start2 = timestamp(); watcher.close(); @@ -124130,7 +124938,7 @@ function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo2) { void 0, file, (...args) => { - const triggerredInfo = `${key === "watchFile" ? "FileWatcher" : "DirectoryWatcher"}:: Triggered with ${args[0]} ${args[1] !== void 0 ? args[1] : ""}:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2)}`; + const triggerredInfo = `${key === "watchFile" ? "FileWatcher" : "DirectoryWatcher"}:: Triggered with ${args[0]} ${args[1] !== void 0 ? args[1] : ""}:: ${getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)}`; log(triggerredInfo); const start = timestamp(); cb.call( @@ -124147,8 +124955,8 @@ function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo2) { detailInfo2 ); } - function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo3) { - return `WatchInfo: ${file} ${flags} ${JSON.stringify(options)} ${getDetailWatchInfo3 ? getDetailWatchInfo3(detailInfo1, detailInfo2) : detailInfo2 === void 0 ? detailInfo1 : `${detailInfo1} ${detailInfo2}`}`; + function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo2) { + return `WatchInfo: ${file} ${flags} ${JSON.stringify(options)} ${getDetailWatchInfo2 ? getDetailWatchInfo2(detailInfo1, detailInfo2) : detailInfo2 === void 0 ? detailInfo1 : `${detailInfo1} ${detailInfo2}`}`; } } function getFallbackOptions(options) { @@ -124175,7 +124983,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) { @@ -124196,7 +125004,7 @@ function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, ge commonPathComponents.length = sourcePathComponents.length; } }); - if (failed) { + if (failed2) { return ""; } if (!commonPathComponents) { @@ -124712,15 +125520,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"; @@ -124818,7 +125633,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); @@ -124946,20 +125767,20 @@ function shouldProgramCreateNewSourceFiles(program, newOptions) { if (!program) return false; return optionsHaveChanges(program.getCompilerOptions(), newOptions, sourceFileAffectingCompilerOptions); } -function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics, typeScriptVersion3) { +function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics, typeScriptVersion2) { return { rootNames, options, host, oldProgram, configFileParsingDiagnostics, - typeScriptVersion: typeScriptVersion3 + typeScriptVersion: typeScriptVersion2 }; } function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p; const createProgramOptions = isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; - const { rootNames, options, configFileParsingDiagnostics, projectReferences, typeScriptVersion: typeScriptVersion3 } = createProgramOptions; + const { rootNames, options, configFileParsingDiagnostics, projectReferences, typeScriptVersion: typeScriptVersion2 } = createProgramOptions; let { oldProgram } = createProgramOptions; for (const option of commandLineOptionOfCustomType) { if (hasProperty(options, option.name)) { @@ -125093,7 +125914,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; @@ -125338,7 +126159,8 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config getCanonicalFileName, getFileIncludeReasons: () => fileReasons, structureIsReused, - writeFile: writeFile2 + writeFile: writeFile2, + getGlobalTypingsCacheLocation: maybeBind(host, host.getGlobalTypingsCacheLocation) }; onProgramCreateComplete(); verifyCompilerOptions(); @@ -125413,7 +126235,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); @@ -125800,10 +126626,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 */; @@ -125813,7 +126640,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 */; @@ -125904,7 +126735,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) { @@ -126201,6 +127033,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 */: @@ -126332,6 +127165,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 */); @@ -126374,6 +127208,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 */: @@ -126385,6 +127221,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 */: @@ -126498,7 +127335,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; @@ -126515,7 +127366,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)) { @@ -126542,63 +127397,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; @@ -126964,8 +127762,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 }); } } @@ -127242,11 +128040,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(); @@ -127427,7 +128221,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); @@ -127497,7 +128291,7 @@ function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _config function checkDeprecations(deprecatedIn, removedIn, createDiagnostic, fn) { const deprecatedInVersion = new Version(deprecatedIn); const removedInVersion = new Version(removedIn); - const typescriptVersion = new Version(typeScriptVersion3 || versionMajorMinor); + const typescriptVersion = new Version(typeScriptVersion2 || versionMajorMinor); const ignoreDeprecationsVersion = getIgnoreDeprecationsVersion(); const mustBeRemoved = !(removedInVersion.compareTo(typescriptVersion) === 1 /* GreaterThan */); const canBeSilenced = !mustBeRemoved && ignoreDeprecationsVersion.compareTo(deprecatedInVersion) === -1 /* LessThan */; @@ -127754,7 +128548,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); @@ -127789,27 +128587,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; @@ -128005,6 +128807,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); @@ -130262,6 +131067,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)); } @@ -130273,12 +131081,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); @@ -130287,7 +131095,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, @@ -130359,9 +131167,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()); @@ -130402,10 +131210,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), @@ -130469,6 +131277,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(); @@ -130880,6 +131689,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW rootDir, rootPath, rootPathComponents, + isRootWatchable, getCurrentDirectory, resolutionHost.preferNonRecursiveWatch ); @@ -131068,6 +131878,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW rootDir, rootPath, rootPathComponents, + isRootWatchable, getCurrentDirectory, resolutionHost.preferNonRecursiveWatch ); @@ -131211,6 +132022,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*/ @@ -131292,6 +132104,7 @@ function createResolutionCache(resolutionHost, rootDirForResolution, logChangesW resolutionHost.toPath(typeRoot), rootPath, rootPathComponents, + isRootWatchable, getCurrentDirectory, resolutionHost.preferNonRecursiveWatch, (dirPath2) => directoryWatchesOfFailedLookups.has(dirPath2) || dirPathToSymlinkPackageRefCount.has(dirPath2) @@ -131847,6 +132660,7 @@ function getSourceFileVersionAsHashFromText(host, text) { if (pos && text.charCodeAt(pos - 1) === 13 /* carriageReturn */) { pos--; } + // falls through case 13 /* carriageReturn */: break; default: @@ -132048,6 +132862,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; @@ -132136,8 +132951,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(); @@ -132240,6 +133053,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) { @@ -132432,7 +133255,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(); @@ -132446,9 +133275,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); @@ -132500,7 +133328,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) { @@ -133384,6 +134212,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); @@ -133419,7 +134248,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); } @@ -133600,11 +134435,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) { @@ -133924,6 +134755,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 */)) { @@ -134441,6 +135273,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: @@ -134513,7 +135347,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); @@ -134837,7 +135671,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") @@ -134851,7 +135685,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") @@ -134888,10 +135722,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); @@ -135037,16 +135867,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, @@ -135558,39 +136388,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, @@ -135603,17 +136912,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 assertionNode = isJSDocTypeAssertion(initializer) ? getJSDocTypeAssertionType(initializer) : initializer.kind === 234 /* AsExpression */ || initializer.kind === 216 /* TypeAssertionExpression */ ? initializer.type : void 0; + if (assertionNode && !isConstTypeReference(assertionNode) && resolver.canReuseTypeNodeAnnotation(context, node, assertionNode, symbol)) { + result = serializeExistingTypeNode(assertionNode, 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 */: @@ -135628,45 +136959,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, @@ -135678,71 +137014,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( @@ -135753,10 +137137,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) { @@ -135767,14 +137148,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; @@ -135782,43 +137168,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) { @@ -135833,18 +137249,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; @@ -135875,64 +137311,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); + } + } + context.flags = oldFlags; + const typeNode = factory.createTypeLiteralNode(properties); + if (!(context.flags & 1024 /* MultilineObjectLiterals */)) { + setEmitFlags(typeNode, 1 /* SingleLine */); } - return canInferObjectLiteral; + 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; @@ -135947,24 +137533,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 { @@ -135977,9 +137567,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); + }); } } @@ -135991,13 +137593,30 @@ __export(ts_JsTyping_exports, { isTypingUpToDate: () => isTypingUpToDate, loadSafeList: () => loadSafeList, loadTypesMap: () => loadTypesMap, - nodeCoreModuleList: () => nodeCoreModuleList, - nodeCoreModules: () => nodeCoreModules, nonRelativeModuleNameForTypingCache: () => nonRelativeModuleNameForTypingCache, renderPackageNameValidationFailure: () => renderPackageNameValidationFailure, validatePackageName: () => validatePackageName }); +// src/jsTyping/_namespaces/ts.server.ts +var ts_server_exports = {}; +__export(ts_server_exports, { + ActionInvalidate: () => ActionInvalidate, + ActionPackageInstalled: () => ActionPackageInstalled, + ActionSet: () => ActionSet, + ActionWatchTypingLocations: () => ActionWatchTypingLocations, + Arguments: () => Arguments, + EventBeginInstallTypes: () => EventBeginInstallTypes, + EventEndInstallTypes: () => EventEndInstallTypes, + EventInitializationFailed: () => EventInitializationFailed, + EventTypesRegistry: () => EventTypesRegistry, + findArgument: () => findArgument, + hasArgument: () => hasArgument, + indent: () => indent2, + nowString: () => nowString, + stringifyIndented: () => stringifyIndented +}); + // src/jsTyping/shared.ts var ActionSet = "action::set"; var ActionInvalidate = "action::invalidate"; @@ -136041,59 +137660,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", - "inspector/promises", - "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; } @@ -136328,6 +137894,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); } @@ -136393,12 +137960,12 @@ var CompletionTriggerKind = /* @__PURE__ */ ((CompletionTriggerKind2) => { CompletionTriggerKind2[CompletionTriggerKind2["TriggerForIncompleteCompletions"] = 3] = "TriggerForIncompleteCompletions"; return CompletionTriggerKind2; })(CompletionTriggerKind || {}); -var InlayHintKind2 = /* @__PURE__ */ ((InlayHintKind3) => { - InlayHintKind3["Type"] = "Type"; - InlayHintKind3["Parameter"] = "Parameter"; - InlayHintKind3["Enum"] = "Enum"; - return InlayHintKind3; -})(InlayHintKind2 || {}); +var InlayHintKind = /* @__PURE__ */ ((InlayHintKind2) => { + InlayHintKind2["Type"] = "Type"; + InlayHintKind2["Parameter"] = "Parameter"; + InlayHintKind2["Enum"] = "Enum"; + return InlayHintKind2; +})(InlayHintKind || {}); var HighlightSpanKind = /* @__PURE__ */ ((HighlightSpanKind2) => { HighlightSpanKind2["none"] = "none"; HighlightSpanKind2["definition"] = "definition"; @@ -136406,11 +137973,11 @@ var HighlightSpanKind = /* @__PURE__ */ ((HighlightSpanKind2) => { HighlightSpanKind2["writtenReference"] = "writtenReference"; return HighlightSpanKind2; })(HighlightSpanKind || {}); -var IndentStyle = /* @__PURE__ */ ((IndentStyle3) => { - IndentStyle3[IndentStyle3["None"] = 0] = "None"; - IndentStyle3[IndentStyle3["Block"] = 1] = "Block"; - IndentStyle3[IndentStyle3["Smart"] = 2] = "Smart"; - return IndentStyle3; +var IndentStyle = /* @__PURE__ */ ((IndentStyle2) => { + IndentStyle2[IndentStyle2["None"] = 0] = "None"; + IndentStyle2[IndentStyle2["Block"] = 1] = "Block"; + IndentStyle2[IndentStyle2["Smart"] = 2] = "Smart"; + return IndentStyle2; })(IndentStyle || {}); var SemicolonPreference = /* @__PURE__ */ ((SemicolonPreference2) => { SemicolonPreference2["Ignore"] = "ignore"; @@ -136704,6 +138271,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 */; } @@ -137012,6 +138580,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 */: @@ -137049,9 +138618,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); } @@ -137061,9 +138627,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; } @@ -137105,6 +138668,7 @@ function isCompletedNode(n, sourceFile) { if (!n.arguments) { return true; } + // falls through case 213 /* CallExpression */: case 217 /* ParenthesizedExpression */: case 196 /* ParenthesizedType */: @@ -137833,16 +139397,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 */: @@ -138079,7 +139646,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: () => { @@ -138931,28 +140498,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) { @@ -138960,15 +140532,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) { @@ -139097,7 +140673,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); } @@ -139134,7 +140710,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"); @@ -139208,7 +140784,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) { @@ -139270,11 +140852,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) { @@ -139434,6 +141021,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) { @@ -139624,38 +141212,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); } @@ -139726,13 +141333,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; }; @@ -139771,7 +141382,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)) { @@ -139811,7 +141422,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 */ }; } @@ -139829,7 +141444,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) { @@ -140102,6 +141717,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; } @@ -140749,7 +142365,7 @@ function getEncodedSyntacticClassifications(cancellationToken, sourceFile, span) // src/services/documentHighlights.ts var DocumentHighlights; -((DocumentHighlights3) => { +((DocumentHighlights2) => { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { const node = getTouchingPropertyName(sourceFile, position); if (node.parent && (isJsxOpeningElement(node.parent) && node.parent.tagName === node || isJsxClosingElement(node.parent))) { @@ -140759,7 +142375,7 @@ var DocumentHighlights; } return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); } - DocumentHighlights3.getDocumentHighlights = getDocumentHighlights; + DocumentHighlights2.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { return { fileName: sourceFile.fileName, @@ -140912,6 +142528,7 @@ var DocumentHighlights; if (statement.kind === 251 /* ContinueStatement */) { return false; } + // falls through case 248 /* ForStatement */: case 249 /* ForInStatement */: case 250 /* ForOfStatement */: @@ -140957,6 +142574,7 @@ var DocumentHighlights; return [...nodes, container]; } return nodes; + // Syntactically invalid positions that the parser might produce anyway default: return void 0; } @@ -142536,8 +144154,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 */: @@ -143210,6 +144830,7 @@ function addChildrenRecursively(node) { Debug.assertNever(special); } } + // falls through default: if (hasJSDocNodes(node)) { forEach(node.jsDoc, (jsDoc) => { @@ -143372,6 +144993,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); } @@ -143656,6 +145278,7 @@ __export(ts_refactor_exports, { getStatementsToMove: () => getStatementsToMove, getUsageInfo: () => getUsageInfo, inferFunctionReturnType: () => ts_refactor_inferFunctionReturnType_exports, + isInImport: () => isInImport, isRefactorErrorInfo: () => isRefactorErrorInfo, refactorKindBeginsWith: () => refactorKindBeginsWith, registerRefactor: () => registerRefactor @@ -143802,6 +145425,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 */: @@ -144286,7 +145910,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)))) { @@ -144908,6 +146532,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 */: @@ -145089,23 +146714,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); } }); } @@ -145139,16 +146763,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++) { @@ -145367,6 +146981,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); } @@ -146370,6 +147987,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); @@ -146377,6 +147995,7 @@ function entryToFunctionCall(entry) { return callOrNewExpression; } break; + // x.foo(...) case 211 /* PropertyAccessExpression */: const propertyAccessExpression = tryCast(parent2, isPropertyAccessExpression); if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { @@ -146386,6 +148005,7 @@ function entryToFunctionCall(entry) { } } break; + // x["foo"](...) case 212 /* ElementAccessExpression */: const elementAccessExpression = tryCast(parent2, isElementAccessExpression); if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { @@ -146404,12 +148024,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) { @@ -147502,11 +149124,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 */: @@ -149333,6 +150957,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)) { @@ -149341,6 +150966,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)) { @@ -149361,6 +150987,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)) { @@ -149369,6 +150996,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)) { @@ -149681,6 +151309,7 @@ var SourceFileObject = class extends NodeObject { if (!hasSyntacticModifier(node, 31 /* ParameterPropertyModifier */)) { break; } + // falls through case 260 /* VariableDeclaration */: case 208 /* BindingElement */: { const decl = node; @@ -149692,6 +151321,7 @@ var SourceFileObject = class extends NodeObject { visit(decl.initializer); } } + // falls through case 306 /* EnumMember */: case 172 /* PropertyDeclaration */: case 171 /* PropertySignature */: @@ -149726,6 +151356,7 @@ var SourceFileObject = class extends NodeObject { if (getAssignmentDeclarationKind(node) !== 0 /* None */) { addDeclaration(node); } + // falls through default: forEachChild(node, visit); } @@ -149973,7 +151604,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; @@ -150089,7 +151721,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( @@ -150465,6 +152098,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( @@ -150556,14 +152197,14 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h } else { const quotePreference = getQuotePreference(sourceFile, preferences ?? emptyOptions); const providePrefixAndSuffixTextForRename = typeof preferences === "boolean" ? preferences : preferences == null ? void 0 : preferences.providePrefixAndSuffixTextForRename; - return getReferencesWorker2(node, position, { findInStrings, findInComments, providePrefixAndSuffixTextForRename, use: ts_FindAllReferences_exports.FindReferencesUse.Rename }, (entry, originalNode, checker) => ts_FindAllReferences_exports.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false, quotePreference)); + return getReferencesWorker(node, position, { findInStrings, findInComments, providePrefixAndSuffixTextForRename, use: ts_FindAllReferences_exports.FindReferencesUse.Rename }, (entry, originalNode, checker) => ts_FindAllReferences_exports.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false, quotePreference)); } } function getReferencesAtPosition(fileName, position) { synchronizeHostData(); - return getReferencesWorker2(getTouchingPropertyName(getValidSourceFile(fileName), position), position, { use: ts_FindAllReferences_exports.FindReferencesUse.References }, ts_FindAllReferences_exports.toReferenceEntry); + return getReferencesWorker(getTouchingPropertyName(getValidSourceFile(fileName), position), position, { use: ts_FindAllReferences_exports.FindReferencesUse.References }, ts_FindAllReferences_exports.toReferenceEntry); } - function getReferencesWorker2(node, position, options, cb) { + function getReferencesWorker(node, position, options, cb) { synchronizeHostData(); const sourceFiles = options && options.use === ts_FindAllReferences_exports.FindReferencesUse.Rename ? program.getSourceFiles().filter((sourceFile) => !program.isSourceFileDefaultLibrary(sourceFile)) : program.getSourceFiles(); return ts_FindAllReferences_exports.findReferenceOrRenameEntries(program, cancellationToken, sourceFiles, node, position, options, cb); @@ -150613,6 +152254,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h case 197 /* ThisType */: case 80 /* Identifier */: break; + // Cant create the text span default: return void 0; } @@ -150718,22 +152360,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(); @@ -151266,6 +152908,7 @@ function createLanguageService(host, documentRegistry = createDocumentRegistry(h uncommentSelection, provideInlayHints: provideInlayHints2, getSupportedCodeFixes, + preparePasteEditsForFile, getPasteEdits, mapCode: mapCode2 }; @@ -151330,6 +152973,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; } @@ -151484,6 +153128,7 @@ function spanInSourceFileAtLocation(sourceFile, position) { if (isFunctionBlock(node)) { return spanInFunctionBlock(node); } + // falls through case 268 /* ModuleBlock */: return spanInBlock(node); case 299 /* CatchClause */: @@ -151532,6 +153177,7 @@ function spanInSourceFileAtLocation(sourceFile, position) { if (getModuleInstanceState(node) !== 1 /* Instantiated */) { return void 0; } + // falls through case 263 /* ClassDeclaration */: case 266 /* EnumDeclaration */: case 306 /* EnumMember */: @@ -151544,9 +153190,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)); @@ -151567,6 +153215,7 @@ function spanInSourceFileAtLocation(sourceFile, position) { case 32 /* GreaterThanToken */: case 30 /* LessThanToken */: return spanInGreaterThanOrLessThanToken(node); + // Keywords: case 117 /* WhileKeyword */: return spanInWhileKeyword(node); case 93 /* ElseKeyword */: @@ -151717,10 +153366,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]); @@ -151786,6 +153438,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); @@ -151793,6 +153446,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 */: @@ -151805,6 +153459,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; @@ -151854,6 +153509,7 @@ function spanInSourceFileAtLocation(sourceFile, position) { case 214 /* NewExpression */: case 217 /* ParenthesizedExpression */: return spanInPreviousNode(node2); + // Default to parent node default: return spanInNode(node2.parent); } @@ -152387,8 +154043,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 @@ -152405,14 +154063,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) { @@ -152420,9 +154078,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); } } } @@ -152431,15 +154089,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) { @@ -152456,14 +154114,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); } } @@ -152977,19 +154635,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)) { @@ -153030,13 +154768,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); @@ -153107,18 +154845,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); }) @@ -153275,16 +155013,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)); @@ -153556,18 +155294,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); @@ -154366,6 +156104,7 @@ function convertStatement(sourceFile, statement, checker, changes, identifiers, } } } + // falls through default: return false; } @@ -154465,6 +156204,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; @@ -154546,6 +156287,7 @@ function convertExportsDotXEquals_replaceNode(name, exported, useSitesToUnqualif return exportConst(); } } + // falls through case 219 /* ArrowFunction */: return functionExpressionToDeclaration(name, modifiers, exported, useSitesToUnqualify); case 231 /* ClassExpression */: @@ -154594,6 +156336,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([ @@ -154767,19 +156510,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); @@ -154805,20 +156548,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); @@ -154877,18 +156620,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); @@ -154896,15 +156639,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 ]; } @@ -154912,10 +156655,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); @@ -155048,11 +156791,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( @@ -155064,10 +156807,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 ) ]; @@ -155075,7 +156818,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); @@ -155218,10 +156961,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); @@ -155230,10 +156973,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); @@ -155279,25 +157022,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)) { @@ -155363,7 +157106,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, @@ -155382,10 +157125,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( @@ -155421,7 +157165,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)); } }); @@ -155444,7 +157188,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); } @@ -155460,7 +157204,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)); @@ -155494,12 +157238,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); @@ -155562,7 +157385,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 */: @@ -155572,40 +157395,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 }; @@ -155666,7 +157489,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); @@ -155759,7 +157582,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 ); @@ -155772,7 +157595,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 @@ -155948,7 +157771,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; } }); @@ -156377,6 +158201,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); } @@ -156477,7 +158303,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 }); } @@ -156672,8 +158498,7 @@ function doAddExistingFix(changes, sourceFile, clause, defaultImport, namedImpor ...namedImports.map((i) => factory.createBindingElement( /*dotDotDotToken*/ void 0, - /*propertyName*/ - void 0, + i.propertyName, i.name )) ]) @@ -156684,12 +158509,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; } @@ -156705,8 +158525,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) ) ), @@ -156801,8 +158620,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) ) ), @@ -156840,11 +158658,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) { @@ -156896,8 +158713,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, @@ -156910,20 +158727,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))) { @@ -157005,7 +158822,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, @@ -157069,19 +158886,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) { @@ -157157,20 +158974,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); @@ -157186,20 +159003,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()); }) }); @@ -157244,25 +159061,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; @@ -157402,20 +159219,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); @@ -157450,8 +159267,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, @@ -157468,7 +159285,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); @@ -157476,10 +159293,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); @@ -157568,17 +159385,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; @@ -157593,7 +159410,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) { @@ -157792,7 +159609,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( @@ -157804,11 +159621,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 @@ -157816,7 +159633,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, @@ -157826,7 +159643,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); @@ -157853,21 +159670,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 */) { @@ -157906,7 +159723,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) { @@ -157919,7 +159736,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*/ @@ -157929,7 +159746,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, @@ -157944,7 +159761,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, @@ -157963,7 +159780,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; @@ -158284,8 +160101,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, @@ -158436,17 +160254,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); @@ -158465,9 +160283,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); @@ -158500,7 +160318,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; @@ -158703,17 +160521,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*/ @@ -158726,7 +160546,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) { @@ -158755,11 +160575,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, @@ -158767,18 +160587,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); @@ -158805,23 +160625,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; @@ -158847,18 +160667,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); @@ -158878,9 +160698,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) { @@ -158892,7 +160712,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; @@ -158905,23 +160725,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); @@ -159001,20 +160821,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)); @@ -159024,20 +160844,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); }) @@ -159064,15 +160884,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); @@ -159080,10 +160900,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); }) @@ -159102,12 +160922,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; @@ -159133,7 +160953,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 = { @@ -159155,12 +160975,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 = []; @@ -159175,7 +160995,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)); @@ -159238,10 +161058,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; @@ -159249,14 +161069,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); @@ -159293,7 +161113,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, @@ -159303,7 +161123,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(); @@ -159392,7 +161212,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: @@ -159632,18 +161452,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); @@ -159670,6 +161490,7 @@ function doChange27(changes, sourceFile, start, length2, errorCode) { } return; } + // falls through case 247 /* WhileStatement */: case 248 /* ForStatement */: changes.delete(sourceFile, container); @@ -159694,16 +161515,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); @@ -159722,13 +161543,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(); @@ -159741,20 +161562,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); }); } @@ -159810,21 +161631,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); }) @@ -159848,14 +161669,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, @@ -159871,7 +161692,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 ]; @@ -159892,8 +161713,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)); @@ -159907,7 +161728,7 @@ registerCodeFix({ }, getAllCodeActions: (context) => { const changes = withContext(context, 0 /* Full */, (f) => { - eachDiagnostic(context, errorCodes47, (diag2) => { + eachDiagnostic(context, errorCodes48, (diag2) => { f.addTypeAnnotation(diag2); }); }); @@ -159921,7 +161742,7 @@ function addCodeAction(fixName8, fixes, context, typePrintMode, cb) { fixName8, changes.textChanges, changes.result, - fixId36, + fixId37, Diagnostics.Add_all_missing_type_annotations )); } @@ -160677,7 +162498,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; @@ -160686,6 +162507,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 */) { @@ -160741,26 +162566,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); @@ -160813,21 +162638,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) { @@ -160863,8 +162688,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 @@ -160898,7 +162723,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); @@ -160918,13 +162743,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); }); } @@ -160934,6 +162759,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; @@ -160972,6 +162798,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)) { @@ -161012,12 +162839,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); @@ -161025,6 +162854,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)) { @@ -161032,12 +162862,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); @@ -161419,6 +163251,7 @@ function inferTypeFromReferences(program, references, cancellationToken) { break; } } + // falls through default: return inferTypeFromContextualType(node, usage); } @@ -161446,16 +163279,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 */: @@ -161467,7 +163309,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 */: @@ -161493,6 +163339,7 @@ function inferTypeFromReferences(program, references, cancellationToken) { usage.isNumberOrString = true; } break; + // AssignmentOperators case 64 /* EqualsToken */: case 35 /* EqualsEqualsToken */: case 37 /* EqualsEqualsEqualsToken */: @@ -161508,6 +163355,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( @@ -161855,13 +163703,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(); @@ -161872,14 +163720,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); @@ -161915,13 +163763,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())) { @@ -161942,21 +163790,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"); @@ -162012,11 +163860,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); @@ -162040,8 +163887,7 @@ function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, sourceFile, con let typeNode2 = checker.typeToTypeNode( type, enclosingDeclaration, - /*flags*/ - void 0, + flags, /*internalFlags*/ void 0, getNoopSymbolTrackerWithResolver(context) @@ -162368,7 +164214,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) { @@ -162378,6 +164230,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)) { @@ -162969,9 +164857,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; @@ -162983,7 +164871,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) { @@ -163106,20 +164994,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); @@ -163196,19 +165084,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); }) @@ -163235,24 +165123,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; @@ -163263,18 +165151,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); @@ -163297,9 +165185,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); @@ -163308,7 +165196,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); @@ -163347,18 +165235,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."); @@ -163367,20 +165255,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); }) @@ -163425,12 +165313,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) { @@ -163439,30 +165327,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) { @@ -163487,20 +165375,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); }) }); @@ -163549,22 +165437,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))) { @@ -163575,7 +165463,7 @@ registerCodeFix({ }); })); }, - fixIds: [fixId51] + fixIds: [fixId52] }); function getInfo21(sourceFile, pos, program) { var _a; @@ -163593,26 +165481,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); }) @@ -163628,25 +165516,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(); @@ -163738,6 +165626,8 @@ var SortText = { return sortText + "1"; } }; +var allCommitCharacters = [".", ",", ";"]; +var noCommaCommitCharacters = [".", ";"]; var CompletionSource = /* @__PURE__ */ ((CompletionSource2) => { CompletionSource2["ThisProperty"] = "ThisProperty/"; CompletionSource2["ClassMemberSnippet"] = "ClassMemberSnippet/"; @@ -163844,7 +165734,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; @@ -164342,7 +166232,8 @@ function completionInfoFromData(sourceFile, host, program, compilerOptions, log, importStatementCompletion, insideJsDocTagTypeExpression, symbolToSortTextMap, - hasUnresolvedAutoImports + hasUnresolvedAutoImports, + defaultCommitCharacters } = completionData; let literals = completionData.literals; const checker = program.getTypeChecker(); @@ -164460,7 +166351,7 @@ function completionInfoFromData(sourceFile, host, program, compilerOptions, log, isNewIdentifierLocation, optionalReplacementSpan: getOptionalReplacementSpan(location), entries, - defaultCommitCharacters: getDefaultCommitCharacters(isNewIdentifierLocation) + defaultCommitCharacters: defaultCommitCharacters ?? getDefaultCommitCharacters(isNewIdentifierLocation) }; } function isCheckedFile(sourceFile, compilerOptions) { @@ -164795,9 +166686,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); @@ -165359,7 +167254,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(); @@ -165429,15 +167324,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); @@ -165754,6 +167660,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 */: @@ -165859,6 +167766,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) { @@ -165878,7 +167786,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 */) { @@ -165939,6 +167847,7 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, if (!binaryExpressionMayBeOpenTag(parent2)) { break; } + // falls through case 285 /* JsxSelfClosingElement */: case 284 /* JsxElement */: case 286 /* JsxOpeningElement */: @@ -165980,7 +167889,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); @@ -166037,7 +167946,8 @@ function getCompletionData(program, log, sourceFile, compilerOptions, position, isRightOfDotOrQuestionDot: isRightOfDot || isRightOfQuestionDot, importStatementCompletion, hasUnresolvedAutoImports, - flags + flags, + defaultCommitCharacters }; function isTagWithTypeExpression(tag) { switch (tag.kind) { @@ -166072,7 +167982,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); @@ -166142,9 +168055,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) { @@ -166283,7 +168200,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'."); } @@ -166445,18 +168362,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), @@ -166549,41 +168459,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))); @@ -166811,6 +168801,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 */: @@ -166833,6 +168824,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; @@ -166867,14 +168861,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< | @@ -166885,6 +168883,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 */: @@ -166895,7 +168894,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( @@ -167111,6 +169110,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; @@ -167388,9 +169388,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: @@ -167624,20 +169626,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) { @@ -167709,7 +169728,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)) { @@ -167896,6 +169915,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 */: @@ -167981,7 +170001,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) => { @@ -168021,7 +170041,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; @@ -168052,8 +170072,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 { @@ -168064,7 +170085,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( @@ -168074,6 +170095,7 @@ function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, p extensionOptions, program, host, + moduleSpecifierResolutionHost, scriptPath ); } else { @@ -168083,6 +170105,7 @@ function getCompletionEntriesForRelativeModules(literalValue, scriptDirectory, p extensionOptions, program, host, + moduleSpecifierResolutionHost, /*moduleSpecifierIsRelative*/ true, scriptPath @@ -168108,7 +170131,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()); @@ -168120,6 +170143,7 @@ function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment extensionOptions, program, host, + moduleSpecifierResolutionHost, /*moduleSpecifierIsRelative*/ true, exclude @@ -168127,7 +170151,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 = ""; @@ -168152,7 +170176,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; } } @@ -168180,7 +170204,7 @@ function getCompletionEntriesForDirectoryFragment(fragment, scriptDirectory, ext getBaseFileName(filePath), program, extensionOptions, - /*isExportsWildcard*/ + /*isExportsOrImportsWildcard*/ false ); result.add(nameAndKind(name, "script" /* scriptElement */, extension)); @@ -168197,7 +170221,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) }; @@ -168211,7 +170235,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 */) { @@ -168221,13 +170245,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); @@ -168236,40 +170260,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)) }); } } @@ -168277,7 +170304,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; @@ -168291,6 +170318,7 @@ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, p extensionOptions, program, host, + moduleSpecifierResolutionHost, /*moduleSpecifierIsRelative*/ false, /*exclude*/ @@ -168300,7 +170328,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)) { @@ -168311,7 +170339,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) { @@ -168329,6 +170357,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)) { @@ -168338,6 +170386,7 @@ function getCompletionEntriesForNonRelativeModules(fragment, scriptPath, mode, p extensionOptions, program, host, + moduleSpecifierResolutionHost, /*moduleSpecifierIsRelative*/ false, /*exclude*/ @@ -168345,58 +170394,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") { @@ -168414,25 +170482,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; } - const pathPrefix = path.slice(0, path.length - 1); - const remainingFragment = tryRemovePrefix(fragment, pathPrefix); + if (typeof parsedPath === "string") { + return justPathMappingName(path, "script" /* scriptElement */); + } + 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; } @@ -168445,35 +170516,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); }); } @@ -168493,7 +170596,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); @@ -168514,13 +170617,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; @@ -168557,6 +170661,7 @@ function getCompletionEntriesFromTypings(host, program, scriptPath, fragmentDire extensionOptions, program, host, + moduleSpecifierResolutionHost, /*moduleSpecifierIsRelative*/ false, /*exclude*/ @@ -168702,6 +170807,7 @@ function getImportersForExport(sourceFiles, sourceFilesSet, allDirectImports, { break; case 80 /* Identifier */: break; + // TODO: GH#23879 case 271 /* ImportEqualsDeclaration */: handleNamespaceImport( direct, @@ -169308,7 +171414,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))) { @@ -169596,6 +171702,7 @@ function declarationIsWriteAccess(decl) { case 306 /* EnumMember */: case 281 /* ExportSpecifier */: case 273 /* ImportClause */: + // default import case 271 /* ImportEqualsDeclaration */: case 276 /* ImportSpecifier */: case 264 /* InterfaceDeclaration */: @@ -169982,6 +172089,7 @@ var Core; Debug.assert(node.parent.name === node); return 2 /* Class */; } + // falls through default: return 0 /* None */; } @@ -170313,6 +172421,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 */: @@ -170738,6 +172847,7 @@ var Core; searchSpaceNode = searchSpaceNode.parent; break; } + // falls through case 172 /* PropertyDeclaration */: case 171 /* PropertySignature */: case 176 /* Constructor */: @@ -170750,9 +172860,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; } @@ -170953,10 +173066,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); @@ -171092,6 +173205,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) { @@ -171536,6 +173650,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 */: @@ -171739,11 +173855,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); @@ -172512,6 +174625,7 @@ function getCommentHavingNodes(declaration) { if (isJSDocOverloadTag(declaration.parent)) { return [declaration.parent.parent]; } + // falls through default: return getJSDocCommentsAndTags(declaration); } @@ -173849,6 +175963,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 */); } @@ -175599,6 +177714,7 @@ __export(ts_textChanges_exports, { assignPositionsToNode: () => assignPositionsToNode, createWriter: () => createWriter, deleteNode: () => deleteNode, + getAdjustedEndPosition: () => getAdjustedEndPosition, isThisTypeAnnotatable: () => isThisTypeAnnotatable, isValidLocationToAddComment: () => isValidLocationToAddComment }); @@ -176098,7 +178214,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 { @@ -177674,19 +179793,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 */; } @@ -177750,12 +179884,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; } @@ -177815,6 +179957,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: @@ -177982,6 +180127,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; } @@ -178443,6 +180591,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); @@ -178455,6 +180604,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 */: @@ -178484,6 +180637,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 */: @@ -179641,6 +181795,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, { @@ -179648,10 +181844,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; @@ -179679,11 +181875,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, @@ -179739,14349 +181937,16 @@ function pasteEdits(targetFile, pastedText, pasteLocations, copiedFrom, host, pr ); }); } - -// src/server/_namespaces/ts.ts -var ts_exports2 = {}; -__export(ts_exports2, { - ANONYMOUS: () => ANONYMOUS, - AccessFlags: () => AccessFlags, - AssertionLevel: () => AssertionLevel, - AssignmentDeclarationKind: () => AssignmentDeclarationKind, - AssignmentKind: () => AssignmentKind, - Associativity: () => Associativity, - BreakpointResolver: () => ts_BreakpointResolver_exports, - BuilderFileEmit: () => BuilderFileEmit, - BuilderProgramKind: () => BuilderProgramKind, - BuilderState: () => BuilderState, - CallHierarchy: () => ts_CallHierarchy_exports, - CharacterCodes: () => CharacterCodes, - CheckFlags: () => CheckFlags, - CheckMode: () => CheckMode, - ClassificationType: () => ClassificationType, - ClassificationTypeNames: () => ClassificationTypeNames, - CommentDirectiveType: () => CommentDirectiveType, - Comparison: () => Comparison, - CompletionInfoFlags: () => CompletionInfoFlags, - CompletionTriggerKind: () => CompletionTriggerKind, - Completions: () => ts_Completions_exports, - ContainerFlags: () => ContainerFlags, - ContextFlags: () => ContextFlags, - Debug: () => Debug, - DiagnosticCategory: () => DiagnosticCategory, - Diagnostics: () => Diagnostics, - DocumentHighlights: () => DocumentHighlights, - ElementFlags: () => ElementFlags, - EmitFlags: () => EmitFlags, - EmitHint: () => EmitHint, - EmitOnly: () => EmitOnly, - EndOfLineState: () => EndOfLineState, - ExitStatus: () => ExitStatus, - ExportKind: () => ExportKind, - Extension: () => Extension, - ExternalEmitHelpers: () => ExternalEmitHelpers, - FileIncludeKind: () => FileIncludeKind, - FilePreprocessingDiagnosticsKind: () => FilePreprocessingDiagnosticsKind, - FileSystemEntryKind: () => FileSystemEntryKind, - FileWatcherEventKind: () => FileWatcherEventKind, - FindAllReferences: () => ts_FindAllReferences_exports, - FlattenLevel: () => FlattenLevel, - FlowFlags: () => FlowFlags, - ForegroundColorEscapeSequences: () => ForegroundColorEscapeSequences, - FunctionFlags: () => FunctionFlags, - GeneratedIdentifierFlags: () => GeneratedIdentifierFlags, - GetLiteralTextFlags: () => GetLiteralTextFlags, - GoToDefinition: () => ts_GoToDefinition_exports, - HighlightSpanKind: () => HighlightSpanKind, - IdentifierNameMap: () => IdentifierNameMap, - ImportKind: () => ImportKind, - ImportsNotUsedAsValues: () => ImportsNotUsedAsValues, - IndentStyle: () => IndentStyle, - IndexFlags: () => IndexFlags, - IndexKind: () => IndexKind, - InferenceFlags: () => InferenceFlags, - InferencePriority: () => InferencePriority, - InlayHintKind: () => InlayHintKind2, - InlayHints: () => ts_InlayHints_exports, - InternalEmitFlags: () => InternalEmitFlags, - InternalNodeBuilderFlags: () => InternalNodeBuilderFlags, - InternalSymbolName: () => InternalSymbolName, - IntersectionFlags: () => IntersectionFlags, - InvalidatedProjectKind: () => InvalidatedProjectKind, - JSDocParsingMode: () => JSDocParsingMode, - JsDoc: () => ts_JsDoc_exports, - JsTyping: () => ts_JsTyping_exports, - JsxEmit: () => JsxEmit, - JsxFlags: () => JsxFlags, - JsxReferenceKind: () => JsxReferenceKind, - LanguageFeatureMinimumTarget: () => LanguageFeatureMinimumTarget, - LanguageServiceMode: () => LanguageServiceMode, - LanguageVariant: () => LanguageVariant, - LexicalEnvironmentFlags: () => LexicalEnvironmentFlags, - ListFormat: () => ListFormat, - LogLevel: () => LogLevel, - MapCode: () => ts_MapCode_exports, - MemberOverrideStatus: () => MemberOverrideStatus, - ModifierFlags: () => ModifierFlags, - ModuleDetectionKind: () => ModuleDetectionKind, - ModuleInstanceState: () => ModuleInstanceState, - ModuleKind: () => ModuleKind, - ModuleResolutionKind: () => ModuleResolutionKind, - ModuleSpecifierEnding: () => ModuleSpecifierEnding, - NavigateTo: () => ts_NavigateTo_exports, - NavigationBar: () => ts_NavigationBar_exports, - NewLineKind: () => NewLineKind, - NodeBuilderFlags: () => NodeBuilderFlags, - NodeCheckFlags: () => NodeCheckFlags, - NodeFactoryFlags: () => NodeFactoryFlags, - NodeFlags: () => NodeFlags, - NodeResolutionFeatures: () => NodeResolutionFeatures, - ObjectFlags: () => ObjectFlags, - OperationCanceledException: () => OperationCanceledException, - OperatorPrecedence: () => OperatorPrecedence, - OrganizeImports: () => ts_OrganizeImports_exports, - OrganizeImportsMode: () => OrganizeImportsMode, - OuterExpressionKinds: () => OuterExpressionKinds, - OutliningElementsCollector: () => ts_OutliningElementsCollector_exports, - OutliningSpanKind: () => OutliningSpanKind, - OutputFileType: () => OutputFileType, - PackageJsonAutoImportPreference: () => PackageJsonAutoImportPreference, - PackageJsonDependencyGroup: () => PackageJsonDependencyGroup, - PatternMatchKind: () => PatternMatchKind, - PollingInterval: () => PollingInterval, - PollingWatchKind: () => PollingWatchKind, - PragmaKindFlags: () => PragmaKindFlags, - PredicateSemantics: () => PredicateSemantics, - PrivateIdentifierKind: () => PrivateIdentifierKind, - ProcessLevel: () => ProcessLevel, - ProgramUpdateLevel: () => ProgramUpdateLevel, - QuotePreference: () => QuotePreference, - RegularExpressionFlags: () => RegularExpressionFlags, - RelationComparisonResult: () => RelationComparisonResult, - Rename: () => ts_Rename_exports, - ScriptElementKind: () => ScriptElementKind, - ScriptElementKindModifier: () => ScriptElementKindModifier, - ScriptKind: () => ScriptKind, - ScriptSnapshot: () => ScriptSnapshot, - ScriptTarget: () => ScriptTarget, - SemanticClassificationFormat: () => SemanticClassificationFormat, - SemanticMeaning: () => SemanticMeaning, - SemicolonPreference: () => SemicolonPreference, - SignatureCheckMode: () => SignatureCheckMode, - SignatureFlags: () => SignatureFlags, - SignatureHelp: () => ts_SignatureHelp_exports, - SignatureInfo: () => SignatureInfo, - SignatureKind: () => SignatureKind, - SmartSelectionRange: () => ts_SmartSelectionRange_exports, - SnippetKind: () => SnippetKind, - StatisticType: () => StatisticType, - StructureIsReused: () => StructureIsReused, - SymbolAccessibility: () => SymbolAccessibility, - SymbolDisplay: () => ts_SymbolDisplay_exports, - SymbolDisplayPartKind: () => SymbolDisplayPartKind, - SymbolFlags: () => SymbolFlags, - SymbolFormatFlags: () => SymbolFormatFlags, - SyntaxKind: () => SyntaxKind, - Ternary: () => Ternary, - ThrottledCancellationToken: () => ThrottledCancellationToken, - TokenClass: () => TokenClass, - TokenFlags: () => TokenFlags, - TransformFlags: () => TransformFlags, - TypeFacts: () => TypeFacts, - TypeFlags: () => TypeFlags, - TypeFormatFlags: () => TypeFormatFlags, - TypeMapKind: () => TypeMapKind, - TypePredicateKind: () => TypePredicateKind, - TypeReferenceSerializationKind: () => TypeReferenceSerializationKind, - UnionReduction: () => UnionReduction, - UpToDateStatusType: () => UpToDateStatusType, - VarianceFlags: () => VarianceFlags, - Version: () => Version, - VersionRange: () => VersionRange, - WatchDirectoryFlags: () => WatchDirectoryFlags, - WatchDirectoryKind: () => WatchDirectoryKind, - WatchFileKind: () => WatchFileKind, - WatchLogLevel: () => WatchLogLevel, - WatchType: () => WatchType, - accessPrivateIdentifier: () => accessPrivateIdentifier, - addEmitFlags: () => addEmitFlags, - addEmitHelper: () => addEmitHelper, - addEmitHelpers: () => addEmitHelpers, - addInternalEmitFlags: () => addInternalEmitFlags, - addNodeFactoryPatcher: () => addNodeFactoryPatcher, - addObjectAllocatorPatcher: () => addObjectAllocatorPatcher, - addRange: () => addRange, - addRelatedInfo: () => addRelatedInfo, - addSyntheticLeadingComment: () => addSyntheticLeadingComment, - addSyntheticTrailingComment: () => addSyntheticTrailingComment, - addToSeen: () => addToSeen, - advancedAsyncSuperHelper: () => advancedAsyncSuperHelper, - affectsDeclarationPathOptionDeclarations: () => affectsDeclarationPathOptionDeclarations, - affectsEmitOptionDeclarations: () => affectsEmitOptionDeclarations, - allKeysStartWithDot: () => allKeysStartWithDot, - altDirectorySeparator: () => altDirectorySeparator, - and: () => and, - append: () => append, - appendIfUnique: () => appendIfUnique, - arrayFrom: () => arrayFrom, - arrayIsEqualTo: () => arrayIsEqualTo, - arrayIsHomogeneous: () => arrayIsHomogeneous, - arrayOf: () => arrayOf, - arrayReverseIterator: () => arrayReverseIterator, - arrayToMap: () => arrayToMap, - arrayToMultiMap: () => arrayToMultiMap, - arrayToNumericMap: () => arrayToNumericMap, - assertType: () => assertType, - assign: () => assign, - asyncSuperHelper: () => asyncSuperHelper, - attachFileToDiagnostics: () => attachFileToDiagnostics, - base64decode: () => base64decode, - base64encode: () => base64encode, - binarySearch: () => binarySearch, - binarySearchKey: () => binarySearchKey, - bindSourceFile: () => bindSourceFile, - breakIntoCharacterSpans: () => breakIntoCharacterSpans, - breakIntoWordSpans: () => breakIntoWordSpans, - buildLinkParts: () => buildLinkParts, - buildOpts: () => buildOpts, - buildOverload: () => buildOverload, - bundlerModuleNameResolver: () => bundlerModuleNameResolver, - canBeConvertedToAsync: () => canBeConvertedToAsync, - canEmitTsBuildInfo: () => canEmitTsBuildInfo, - canHaveDecorators: () => canHaveDecorators, - canHaveExportModifier: () => canHaveExportModifier, - canHaveFlowNode: () => canHaveFlowNode, - canHaveIllegalDecorators: () => canHaveIllegalDecorators, - canHaveIllegalModifiers: () => canHaveIllegalModifiers, - canHaveIllegalType: () => canHaveIllegalType, - canHaveIllegalTypeParameters: () => canHaveIllegalTypeParameters, - canHaveJSDoc: () => canHaveJSDoc, - canHaveLocals: () => canHaveLocals, - canHaveModifiers: () => canHaveModifiers, - canHaveModuleSpecifier: () => canHaveModuleSpecifier, - canHaveSymbol: () => canHaveSymbol, - canIncludeBindAndCheckDiagnostics: () => canIncludeBindAndCheckDiagnostics, - canJsonReportNoInputFiles: () => canJsonReportNoInputFiles, - canProduceDiagnostics: () => canProduceDiagnostics, - canUsePropertyAccess: () => canUsePropertyAccess, - canWatchAffectingLocation: () => canWatchAffectingLocation, - canWatchAtTypes: () => canWatchAtTypes, - canWatchDirectoryOrFile: () => canWatchDirectoryOrFile, - cartesianProduct: () => cartesianProduct, - cast: () => cast, - chainBundle: () => chainBundle, - chainDiagnosticMessages: () => chainDiagnosticMessages, - changeAnyExtension: () => changeAnyExtension, - changeCompilerHostLikeToUseCache: () => changeCompilerHostLikeToUseCache, - changeExtension: () => changeExtension, - changeFullExtension: () => changeFullExtension, - changesAffectModuleResolution: () => changesAffectModuleResolution, - changesAffectingProgramStructure: () => changesAffectingProgramStructure, - characterCodeToRegularExpressionFlag: () => characterCodeToRegularExpressionFlag, - childIsDecorated: () => childIsDecorated, - classElementOrClassElementParameterIsDecorated: () => classElementOrClassElementParameterIsDecorated, - classHasClassThisAssignment: () => classHasClassThisAssignment, - classHasDeclaredOrExplicitlyAssignedName: () => classHasDeclaredOrExplicitlyAssignedName, - classHasExplicitlyAssignedName: () => classHasExplicitlyAssignedName, - classOrConstructorParameterIsDecorated: () => classOrConstructorParameterIsDecorated, - classicNameResolver: () => classicNameResolver, - classifier: () => ts_classifier_exports, - cleanExtendedConfigCache: () => cleanExtendedConfigCache, - clear: () => clear, - clearMap: () => clearMap, - clearSharedExtendedConfigFileWatcher: () => clearSharedExtendedConfigFileWatcher, - climbPastPropertyAccess: () => climbPastPropertyAccess, - clone: () => clone, - cloneCompilerOptions: () => cloneCompilerOptions, - closeFileWatcher: () => closeFileWatcher, - closeFileWatcherOf: () => closeFileWatcherOf, - codefix: () => ts_codefix_exports, - collapseTextChangeRangesAcrossMultipleVersions: () => collapseTextChangeRangesAcrossMultipleVersions, - collectExternalModuleInfo: () => collectExternalModuleInfo, - combine: () => combine, - combinePaths: () => combinePaths, - commandLineOptionOfCustomType: () => commandLineOptionOfCustomType, - commentPragmas: () => commentPragmas, - commonOptionsWithBuild: () => commonOptionsWithBuild, - compact: () => compact, - compareBooleans: () => compareBooleans, - compareDataObjects: () => compareDataObjects, - compareDiagnostics: () => compareDiagnostics, - compareEmitHelpers: () => compareEmitHelpers, - compareNumberOfDirectorySeparators: () => compareNumberOfDirectorySeparators, - comparePaths: () => comparePaths, - comparePathsCaseInsensitive: () => comparePathsCaseInsensitive, - comparePathsCaseSensitive: () => comparePathsCaseSensitive, - comparePatternKeys: () => comparePatternKeys, - compareProperties: () => compareProperties, - compareStringsCaseInsensitive: () => compareStringsCaseInsensitive, - compareStringsCaseInsensitiveEslintCompatible: () => compareStringsCaseInsensitiveEslintCompatible, - compareStringsCaseSensitive: () => compareStringsCaseSensitive, - compareStringsCaseSensitiveUI: () => compareStringsCaseSensitiveUI, - compareTextSpans: () => compareTextSpans, - compareValues: () => compareValues, - compilerOptionsAffectDeclarationPath: () => compilerOptionsAffectDeclarationPath, - compilerOptionsAffectEmit: () => compilerOptionsAffectEmit, - compilerOptionsAffectSemanticDiagnostics: () => compilerOptionsAffectSemanticDiagnostics, - compilerOptionsDidYouMeanDiagnostics: () => compilerOptionsDidYouMeanDiagnostics, - compilerOptionsIndicateEsModules: () => compilerOptionsIndicateEsModules, - computeCommonSourceDirectoryOfFilenames: () => computeCommonSourceDirectoryOfFilenames, - computeLineAndCharacterOfPosition: () => computeLineAndCharacterOfPosition, - computeLineOfPosition: () => computeLineOfPosition, - computeLineStarts: () => computeLineStarts, - computePositionOfLineAndCharacter: () => computePositionOfLineAndCharacter, - computeSignatureWithDiagnostics: () => computeSignatureWithDiagnostics, - computeSuggestionDiagnostics: () => computeSuggestionDiagnostics, - computedOptions: () => computedOptions, - concatenate: () => concatenate, - concatenateDiagnosticMessageChains: () => concatenateDiagnosticMessageChains, - consumesNodeCoreModules: () => consumesNodeCoreModules, - contains: () => contains, - containsIgnoredPath: () => containsIgnoredPath, - containsObjectRestOrSpread: () => containsObjectRestOrSpread, - containsParseError: () => containsParseError, - containsPath: () => containsPath, - convertCompilerOptionsForTelemetry: () => convertCompilerOptionsForTelemetry, - convertCompilerOptionsFromJson: () => convertCompilerOptionsFromJson, - convertJsonOption: () => convertJsonOption, - convertToBase64: () => convertToBase64, - convertToJson: () => convertToJson, - convertToObject: () => convertToObject, - convertToOptionsWithAbsolutePaths: () => convertToOptionsWithAbsolutePaths, - convertToRelativePath: () => convertToRelativePath, - convertToTSConfig: () => convertToTSConfig, - convertTypeAcquisitionFromJson: () => convertTypeAcquisitionFromJson, - copyComments: () => copyComments, - copyEntries: () => copyEntries, - copyLeadingComments: () => copyLeadingComments, - copyProperties: () => copyProperties, - copyTrailingAsLeadingComments: () => copyTrailingAsLeadingComments, - copyTrailingComments: () => copyTrailingComments, - couldStartTrivia: () => couldStartTrivia, - countWhere: () => countWhere, - createAbstractBuilder: () => createAbstractBuilder, - createAccessorPropertyBackingField: () => createAccessorPropertyBackingField, - createAccessorPropertyGetRedirector: () => createAccessorPropertyGetRedirector, - createAccessorPropertySetRedirector: () => createAccessorPropertySetRedirector, - createBaseNodeFactory: () => createBaseNodeFactory, - createBinaryExpressionTrampoline: () => createBinaryExpressionTrampoline, - createBuilderProgram: () => createBuilderProgram, - createBuilderProgramUsingIncrementalBuildInfo: () => createBuilderProgramUsingIncrementalBuildInfo, - createBuilderStatusReporter: () => createBuilderStatusReporter, - createCacheableExportInfoMap: () => createCacheableExportInfoMap, - createCachedDirectoryStructureHost: () => createCachedDirectoryStructureHost, - createClassifier: () => createClassifier, - createCommentDirectivesMap: () => createCommentDirectivesMap, - createCompilerDiagnostic: () => createCompilerDiagnostic, - createCompilerDiagnosticForInvalidCustomType: () => createCompilerDiagnosticForInvalidCustomType, - createCompilerDiagnosticFromMessageChain: () => createCompilerDiagnosticFromMessageChain, - createCompilerHost: () => createCompilerHost, - createCompilerHostFromProgramHost: () => createCompilerHostFromProgramHost, - createCompilerHostWorker: () => createCompilerHostWorker, - createDetachedDiagnostic: () => createDetachedDiagnostic, - createDiagnosticCollection: () => createDiagnosticCollection, - createDiagnosticForFileFromMessageChain: () => createDiagnosticForFileFromMessageChain, - createDiagnosticForNode: () => createDiagnosticForNode, - createDiagnosticForNodeArray: () => createDiagnosticForNodeArray, - createDiagnosticForNodeArrayFromMessageChain: () => createDiagnosticForNodeArrayFromMessageChain, - createDiagnosticForNodeFromMessageChain: () => createDiagnosticForNodeFromMessageChain, - createDiagnosticForNodeInSourceFile: () => createDiagnosticForNodeInSourceFile, - createDiagnosticForRange: () => createDiagnosticForRange, - createDiagnosticMessageChainFromDiagnostic: () => createDiagnosticMessageChainFromDiagnostic, - createDiagnosticReporter: () => createDiagnosticReporter, - createDocumentPositionMapper: () => createDocumentPositionMapper, - createDocumentRegistry: () => createDocumentRegistry, - createDocumentRegistryInternal: () => createDocumentRegistryInternal, - createEmitAndSemanticDiagnosticsBuilderProgram: () => createEmitAndSemanticDiagnosticsBuilderProgram, - createEmitHelperFactory: () => createEmitHelperFactory, - createEmptyExports: () => createEmptyExports, - createEvaluator: () => createEvaluator, - createExpressionForJsxElement: () => createExpressionForJsxElement, - createExpressionForJsxFragment: () => createExpressionForJsxFragment, - createExpressionForObjectLiteralElementLike: () => createExpressionForObjectLiteralElementLike, - createExpressionForPropertyName: () => createExpressionForPropertyName, - createExpressionFromEntityName: () => createExpressionFromEntityName, - createExternalHelpersImportDeclarationIfNeeded: () => createExternalHelpersImportDeclarationIfNeeded, - createFileDiagnostic: () => createFileDiagnostic, - createFileDiagnosticFromMessageChain: () => createFileDiagnosticFromMessageChain, - createFlowNode: () => createFlowNode, - createForOfBindingStatement: () => createForOfBindingStatement, - createFutureSourceFile: () => createFutureSourceFile, - createGetCanonicalFileName: () => createGetCanonicalFileName, - createGetIsolatedDeclarationErrors: () => createGetIsolatedDeclarationErrors, - createGetSourceFile: () => createGetSourceFile, - createGetSymbolAccessibilityDiagnosticForNode: () => createGetSymbolAccessibilityDiagnosticForNode, - createGetSymbolAccessibilityDiagnosticForNodeName: () => createGetSymbolAccessibilityDiagnosticForNodeName, - createGetSymbolWalker: () => createGetSymbolWalker, - createIncrementalCompilerHost: () => createIncrementalCompilerHost, - createIncrementalProgram: () => createIncrementalProgram, - createJsxFactoryExpression: () => createJsxFactoryExpression, - createLanguageService: () => createLanguageService, - createLanguageServiceSourceFile: () => createLanguageServiceSourceFile, - createMemberAccessForPropertyName: () => createMemberAccessForPropertyName, - createModeAwareCache: () => createModeAwareCache, - createModeAwareCacheKey: () => createModeAwareCacheKey, - createModeMismatchDetails: () => createModeMismatchDetails, - createModuleNotFoundChain: () => createModuleNotFoundChain, - createModuleResolutionCache: () => createModuleResolutionCache, - createModuleResolutionLoader: () => createModuleResolutionLoader, - createModuleResolutionLoaderUsingGlobalCache: () => createModuleResolutionLoaderUsingGlobalCache, - createModuleSpecifierResolutionHost: () => createModuleSpecifierResolutionHost, - createMultiMap: () => createMultiMap, - createNameResolver: () => createNameResolver, - createNodeConverters: () => createNodeConverters, - createNodeFactory: () => createNodeFactory, - createOptionNameMap: () => createOptionNameMap, - createOverload: () => createOverload, - createPackageJsonImportFilter: () => createPackageJsonImportFilter, - createPackageJsonInfo: () => createPackageJsonInfo, - createParenthesizerRules: () => createParenthesizerRules, - createPatternMatcher: () => createPatternMatcher, - createPrinter: () => createPrinter, - createPrinterWithDefaults: () => createPrinterWithDefaults, - createPrinterWithRemoveComments: () => createPrinterWithRemoveComments, - createPrinterWithRemoveCommentsNeverAsciiEscape: () => createPrinterWithRemoveCommentsNeverAsciiEscape, - createPrinterWithRemoveCommentsOmitTrailingSemicolon: () => createPrinterWithRemoveCommentsOmitTrailingSemicolon, - createProgram: () => createProgram, - createProgramHost: () => createProgramHost, - createPropertyNameNodeForIdentifierOrLiteral: () => createPropertyNameNodeForIdentifierOrLiteral, - createQueue: () => createQueue, - createRange: () => createRange, - createRedirectedBuilderProgram: () => createRedirectedBuilderProgram, - createResolutionCache: () => createResolutionCache, - createRuntimeTypeSerializer: () => createRuntimeTypeSerializer, - createScanner: () => createScanner, - createSemanticDiagnosticsBuilderProgram: () => createSemanticDiagnosticsBuilderProgram, - createSet: () => createSet, - createSolutionBuilder: () => createSolutionBuilder, - createSolutionBuilderHost: () => createSolutionBuilderHost, - createSolutionBuilderWithWatch: () => createSolutionBuilderWithWatch, - createSolutionBuilderWithWatchHost: () => createSolutionBuilderWithWatchHost, - createSortedArray: () => createSortedArray, - createSourceFile: () => createSourceFile, - createSourceMapGenerator: () => createSourceMapGenerator, - createSourceMapSource: () => createSourceMapSource, - createSuperAccessVariableStatement: () => createSuperAccessVariableStatement, - createSymbolTable: () => createSymbolTable, - createSymlinkCache: () => createSymlinkCache, - createSyntacticTypeNodeBuilder: () => createSyntacticTypeNodeBuilder, - createSystemWatchFunctions: () => createSystemWatchFunctions, - createTextChange: () => createTextChange, - createTextChangeFromStartLength: () => createTextChangeFromStartLength, - createTextChangeRange: () => createTextChangeRange, - createTextRangeFromNode: () => createTextRangeFromNode, - createTextRangeFromSpan: () => createTextRangeFromSpan, - createTextSpan: () => createTextSpan, - createTextSpanFromBounds: () => createTextSpanFromBounds, - createTextSpanFromNode: () => createTextSpanFromNode, - createTextSpanFromRange: () => createTextSpanFromRange, - createTextSpanFromStringLiteralLikeContent: () => createTextSpanFromStringLiteralLikeContent, - createTextWriter: () => createTextWriter, - createTokenRange: () => createTokenRange, - createTypeChecker: () => createTypeChecker, - createTypeReferenceDirectiveResolutionCache: () => createTypeReferenceDirectiveResolutionCache, - createTypeReferenceResolutionLoader: () => createTypeReferenceResolutionLoader, - createWatchCompilerHost: () => createWatchCompilerHost2, - createWatchCompilerHostOfConfigFile: () => createWatchCompilerHostOfConfigFile, - createWatchCompilerHostOfFilesAndCompilerOptions: () => createWatchCompilerHostOfFilesAndCompilerOptions, - createWatchFactory: () => createWatchFactory, - createWatchHost: () => createWatchHost, - createWatchProgram: () => createWatchProgram, - createWatchStatusReporter: () => createWatchStatusReporter, - createWriteFileMeasuringIO: () => createWriteFileMeasuringIO, - declarationNameToString: () => declarationNameToString, - decodeMappings: () => decodeMappings, - decodedTextSpanIntersectsWith: () => decodedTextSpanIntersectsWith, - deduplicate: () => deduplicate, - defaultInitCompilerOptions: () => defaultInitCompilerOptions, - defaultMaximumTruncationLength: () => defaultMaximumTruncationLength, - deno: () => deno_exports, - diagnosticCategoryName: () => diagnosticCategoryName, - diagnosticToString: () => diagnosticToString, - diagnosticsEqualityComparer: () => diagnosticsEqualityComparer, - directoryProbablyExists: () => directoryProbablyExists, - directorySeparator: () => directorySeparator, - displayPart: () => displayPart, - displayPartsToString: () => displayPartsToString, - disposeEmitNodes: () => disposeEmitNodes, - documentSpansEqual: () => documentSpansEqual, - dumpTracingLegend: () => dumpTracingLegend, - elementAt: () => elementAt, - elideNodes: () => elideNodes, - emitDetachedComments: () => emitDetachedComments, - emitFiles: () => emitFiles, - emitFilesAndReportErrors: () => emitFilesAndReportErrors, - emitFilesAndReportErrorsAndGetExitStatus: () => emitFilesAndReportErrorsAndGetExitStatus, - emitModuleKindIsNonNodeESM: () => emitModuleKindIsNonNodeESM, - emitNewLineBeforeLeadingCommentOfPosition: () => emitNewLineBeforeLeadingCommentOfPosition, - emitResolverSkipsTypeChecking: () => emitResolverSkipsTypeChecking, - emitSkippedWithNoDiagnostics: () => emitSkippedWithNoDiagnostics, - emptyArray: () => emptyArray, - emptyFileSystemEntries: () => emptyFileSystemEntries, - emptyMap: () => emptyMap, - emptyOptions: () => emptyOptions, - endsWith: () => endsWith, - ensurePathIsNonModuleName: () => ensurePathIsNonModuleName, - ensureScriptKind: () => ensureScriptKind, - ensureTrailingDirectorySeparator: () => ensureTrailingDirectorySeparator, - entityNameToString: () => entityNameToString, - enumerateInsertsAndDeletes: () => enumerateInsertsAndDeletes, - equalOwnProperties: () => equalOwnProperties, - equateStringsCaseInsensitive: () => equateStringsCaseInsensitive, - equateStringsCaseSensitive: () => equateStringsCaseSensitive, - equateValues: () => equateValues, - escapeJsxAttributeString: () => escapeJsxAttributeString, - escapeLeadingUnderscores: () => escapeLeadingUnderscores, - escapeNonAsciiString: () => escapeNonAsciiString, - escapeSnippetText: () => escapeSnippetText, - escapeString: () => escapeString, - escapeTemplateSubstitution: () => escapeTemplateSubstitution, - evaluatorResult: () => evaluatorResult, - every: () => every, - executeCommandLine: () => executeCommandLine, - expandPreOrPostfixIncrementOrDecrementExpression: () => expandPreOrPostfixIncrementOrDecrementExpression, - explainFiles: () => explainFiles, - explainIfFileIsRedirectAndImpliedFormat: () => explainIfFileIsRedirectAndImpliedFormat, - exportAssignmentIsAlias: () => exportAssignmentIsAlias, - expressionResultIsUnused: () => expressionResultIsUnused, - extend: () => extend, - extensionFromPath: () => extensionFromPath, - extensionIsTS: () => extensionIsTS, - extensionsNotSupportingExtensionlessResolution: () => extensionsNotSupportingExtensionlessResolution, - externalHelpersModuleNameText: () => externalHelpersModuleNameText, - factory: () => factory, - fileContainsPackageImport: () => fileContainsPackageImport, - fileExtensionIs: () => fileExtensionIs, - fileExtensionIsOneOf: () => fileExtensionIsOneOf, - fileIncludeReasonToDiagnostics: () => fileIncludeReasonToDiagnostics, - fileShouldUseJavaScriptRequire: () => fileShouldUseJavaScriptRequire, - filter: () => filter, - filterMutate: () => filterMutate, - filterSemanticDiagnostics: () => filterSemanticDiagnostics, - find: () => find, - findAncestor: () => findAncestor, - findBestPatternMatch: () => findBestPatternMatch, - findChildOfKind: () => findChildOfKind, - findComputedPropertyNameCacheAssignment: () => findComputedPropertyNameCacheAssignment, - findConfigFile: () => findConfigFile, - findConstructorDeclaration: () => findConstructorDeclaration, - findContainingList: () => findContainingList, - findDiagnosticForNode: () => findDiagnosticForNode, - findFirstNonJsxWhitespaceToken: () => findFirstNonJsxWhitespaceToken, - findIndex: () => findIndex, - findLast: () => findLast, - findLastIndex: () => findLastIndex, - findListItemInfo: () => findListItemInfo, - findModifier: () => findModifier, - findNextToken: () => findNextToken, - findPackageJson: () => findPackageJson, - findPackageJsons: () => findPackageJsons, - findPrecedingMatchingToken: () => findPrecedingMatchingToken, - findPrecedingToken: () => findPrecedingToken, - findSuperStatementIndexPath: () => findSuperStatementIndexPath, - findTokenOnLeftOfPosition: () => findTokenOnLeftOfPosition, - findUseStrictPrologue: () => findUseStrictPrologue, - first: () => first, - firstDefined: () => firstDefined, - firstDefinedIterator: () => firstDefinedIterator, - firstIterator: () => firstIterator, - firstOrOnly: () => firstOrOnly, - firstOrUndefined: () => firstOrUndefined, - firstOrUndefinedIterator: () => firstOrUndefinedIterator, - fixupCompilerOptions: () => fixupCompilerOptions, - flatMap: () => flatMap, - flatMapIterator: () => flatMapIterator, - flatMapToMutable: () => flatMapToMutable, - flatten: () => flatten, - flattenCommaList: () => flattenCommaList, - flattenDestructuringAssignment: () => flattenDestructuringAssignment, - flattenDestructuringBinding: () => flattenDestructuringBinding, - flattenDiagnosticMessageText: () => flattenDiagnosticMessageText, - forEach: () => forEach, - forEachAncestor: () => forEachAncestor, - forEachAncestorDirectory: () => forEachAncestorDirectory, - forEachChild: () => forEachChild, - forEachChildRecursively: () => forEachChildRecursively, - forEachEmittedFile: () => forEachEmittedFile, - forEachEnclosingBlockScopeContainer: () => forEachEnclosingBlockScopeContainer, - forEachEntry: () => forEachEntry, - forEachExternalModuleToImportFrom: () => forEachExternalModuleToImportFrom, - forEachImportClauseDeclaration: () => forEachImportClauseDeclaration, - forEachKey: () => forEachKey, - forEachLeadingCommentRange: () => forEachLeadingCommentRange, - forEachNameInAccessChainWalkingLeft: () => forEachNameInAccessChainWalkingLeft, - forEachNameOfDefaultExport: () => forEachNameOfDefaultExport, - forEachPropertyAssignment: () => forEachPropertyAssignment, - forEachResolvedProjectReference: () => forEachResolvedProjectReference, - forEachReturnStatement: () => forEachReturnStatement, - forEachRight: () => forEachRight, - forEachTrailingCommentRange: () => forEachTrailingCommentRange, - forEachTsConfigPropArray: () => forEachTsConfigPropArray, - forEachUnique: () => forEachUnique, - forEachYieldExpression: () => forEachYieldExpression, - formatColorAndReset: () => formatColorAndReset, - formatDiagnostic: () => formatDiagnostic, - formatDiagnostics: () => formatDiagnostics, - formatDiagnosticsWithColorAndContext: () => formatDiagnosticsWithColorAndContext, - formatGeneratedName: () => formatGeneratedName, - formatGeneratedNamePart: () => formatGeneratedNamePart, - formatLocation: () => formatLocation, - formatMessage: () => formatMessage, - formatStringFromArgs: () => formatStringFromArgs, - formatting: () => ts_formatting_exports, - generateDjb2Hash: () => generateDjb2Hash, - generateTSConfig: () => generateTSConfig, - getAdjustedReferenceLocation: () => getAdjustedReferenceLocation, - getAdjustedRenameLocation: () => getAdjustedRenameLocation, - getAliasDeclarationFromName: () => getAliasDeclarationFromName, - getAllAccessorDeclarations: () => getAllAccessorDeclarations, - getAllDecoratorsOfClass: () => getAllDecoratorsOfClass, - getAllDecoratorsOfClassElement: () => getAllDecoratorsOfClassElement, - getAllJSDocTags: () => getAllJSDocTags, - getAllJSDocTagsOfKind: () => getAllJSDocTagsOfKind, - getAllKeys: () => getAllKeys, - getAllProjectOutputs: () => getAllProjectOutputs, - getAllSuperTypeNodes: () => getAllSuperTypeNodes, - getAllowJSCompilerOption: () => getAllowJSCompilerOption, - getAllowSyntheticDefaultImports: () => getAllowSyntheticDefaultImports, - getAncestor: () => getAncestor, - getAnyExtensionFromPath: () => getAnyExtensionFromPath, - getAreDeclarationMapsEnabled: () => getAreDeclarationMapsEnabled, - getAssignedExpandoInitializer: () => getAssignedExpandoInitializer, - getAssignedName: () => getAssignedName, - getAssignmentDeclarationKind: () => getAssignmentDeclarationKind, - getAssignmentDeclarationPropertyAccessKind: () => getAssignmentDeclarationPropertyAccessKind, - getAssignmentTargetKind: () => getAssignmentTargetKind, - getAutomaticTypeDirectiveNames: () => getAutomaticTypeDirectiveNames, - getBaseFileName: () => getBaseFileName, - getBinaryOperatorPrecedence: () => getBinaryOperatorPrecedence, - getBuildInfo: () => getBuildInfo, - getBuildInfoFileVersionMap: () => getBuildInfoFileVersionMap, - getBuildInfoText: () => getBuildInfoText, - getBuildOrderFromAnyBuildOrder: () => getBuildOrderFromAnyBuildOrder, - getBuilderCreationParameters: () => getBuilderCreationParameters, - getBuilderFileEmit: () => getBuilderFileEmit, - getCanonicalDiagnostic: () => getCanonicalDiagnostic, - getCheckFlags: () => getCheckFlags, - getClassExtendsHeritageElement: () => getClassExtendsHeritageElement, - getClassLikeDeclarationOfSymbol: () => getClassLikeDeclarationOfSymbol, - getCombinedLocalAndExportSymbolFlags: () => getCombinedLocalAndExportSymbolFlags, - getCombinedModifierFlags: () => getCombinedModifierFlags, - getCombinedNodeFlags: () => getCombinedNodeFlags, - getCombinedNodeFlagsAlwaysIncludeJSDoc: () => getCombinedNodeFlagsAlwaysIncludeJSDoc, - getCommentRange: () => getCommentRange, - getCommonSourceDirectory: () => getCommonSourceDirectory, - getCommonSourceDirectoryOfConfig: () => getCommonSourceDirectoryOfConfig, - getCompilerOptionValue: () => getCompilerOptionValue, - getCompilerOptionsDiffValue: () => getCompilerOptionsDiffValue, - getConditions: () => getConditions, - getConfigFileParsingDiagnostics: () => getConfigFileParsingDiagnostics, - getConstantValue: () => getConstantValue, - getContainerFlags: () => getContainerFlags, - getContainerNode: () => getContainerNode, - getContainingClass: () => getContainingClass, - getContainingClassExcludingClassDecorators: () => getContainingClassExcludingClassDecorators, - getContainingClassStaticBlock: () => getContainingClassStaticBlock, - getContainingFunction: () => getContainingFunction, - getContainingFunctionDeclaration: () => getContainingFunctionDeclaration, - getContainingFunctionOrClassStaticBlock: () => getContainingFunctionOrClassStaticBlock, - getContainingNodeArray: () => getContainingNodeArray, - getContainingObjectLiteralElement: () => getContainingObjectLiteralElement, - getContextualTypeFromParent: () => getContextualTypeFromParent, - getContextualTypeFromParentOrAncestorTypeNode: () => getContextualTypeFromParentOrAncestorTypeNode, - getDeclarationDiagnostics: () => getDeclarationDiagnostics, - getDeclarationEmitExtensionForPath: () => getDeclarationEmitExtensionForPath, - getDeclarationEmitOutputFilePath: () => getDeclarationEmitOutputFilePath, - getDeclarationEmitOutputFilePathWorker: () => getDeclarationEmitOutputFilePathWorker, - getDeclarationFileExtension: () => getDeclarationFileExtension, - getDeclarationFromName: () => getDeclarationFromName, - getDeclarationModifierFlagsFromSymbol: () => getDeclarationModifierFlagsFromSymbol, - getDeclarationOfKind: () => getDeclarationOfKind, - getDeclarationsOfKind: () => getDeclarationsOfKind, - getDeclaredExpandoInitializer: () => getDeclaredExpandoInitializer, - getDecorators: () => getDecorators, - getDefaultCompilerOptions: () => getDefaultCompilerOptions2, - getDefaultFormatCodeSettings: () => getDefaultFormatCodeSettings, - getDefaultLibFileName: () => getDefaultLibFileName, - getDefaultLibFilePath: () => getDefaultLibFilePath, - getDefaultLikeExportInfo: () => getDefaultLikeExportInfo, - getDefaultLikeExportNameFromDeclaration: () => getDefaultLikeExportNameFromDeclaration, - getDefaultResolutionModeForFileWorker: () => getDefaultResolutionModeForFileWorker, - getDiagnosticText: () => getDiagnosticText, - getDiagnosticsWithinSpan: () => getDiagnosticsWithinSpan, - getDirectoryPath: () => getDirectoryPath, - getDirectoryToWatchFailedLookupLocation: () => getDirectoryToWatchFailedLookupLocation, - getDirectoryToWatchFailedLookupLocationFromTypeRoot: () => getDirectoryToWatchFailedLookupLocationFromTypeRoot, - getDocumentPositionMapper: () => getDocumentPositionMapper, - getDocumentSpansEqualityComparer: () => getDocumentSpansEqualityComparer, - getESModuleInterop: () => getESModuleInterop, - getEditsForFileRename: () => getEditsForFileRename, - getEffectiveBaseTypeNode: () => getEffectiveBaseTypeNode, - getEffectiveConstraintOfTypeParameter: () => getEffectiveConstraintOfTypeParameter, - getEffectiveContainerForJSDocTemplateTag: () => getEffectiveContainerForJSDocTemplateTag, - getEffectiveImplementsTypeNodes: () => getEffectiveImplementsTypeNodes, - getEffectiveInitializer: () => getEffectiveInitializer, - getEffectiveJSDocHost: () => getEffectiveJSDocHost, - getEffectiveModifierFlags: () => getEffectiveModifierFlags, - getEffectiveModifierFlagsAlwaysIncludeJSDoc: () => getEffectiveModifierFlagsAlwaysIncludeJSDoc, - getEffectiveModifierFlagsNoCache: () => getEffectiveModifierFlagsNoCache, - getEffectiveReturnTypeNode: () => getEffectiveReturnTypeNode, - getEffectiveSetAccessorTypeAnnotationNode: () => getEffectiveSetAccessorTypeAnnotationNode, - getEffectiveTypeAnnotationNode: () => getEffectiveTypeAnnotationNode, - getEffectiveTypeParameterDeclarations: () => getEffectiveTypeParameterDeclarations, - getEffectiveTypeRoots: () => getEffectiveTypeRoots, - getElementOrPropertyAccessArgumentExpressionOrName: () => getElementOrPropertyAccessArgumentExpressionOrName, - getElementOrPropertyAccessName: () => getElementOrPropertyAccessName, - getElementsOfBindingOrAssignmentPattern: () => getElementsOfBindingOrAssignmentPattern, - getEmitDeclarations: () => getEmitDeclarations, - getEmitFlags: () => getEmitFlags, - getEmitHelpers: () => getEmitHelpers, - getEmitModuleDetectionKind: () => getEmitModuleDetectionKind, - getEmitModuleFormatOfFileWorker: () => getEmitModuleFormatOfFileWorker, - getEmitModuleKind: () => getEmitModuleKind, - getEmitModuleResolutionKind: () => getEmitModuleResolutionKind, - getEmitScriptTarget: () => getEmitScriptTarget, - getEmitStandardClassFields: () => getEmitStandardClassFields, - getEnclosingBlockScopeContainer: () => getEnclosingBlockScopeContainer, - getEnclosingContainer: () => getEnclosingContainer, - getEncodedSemanticClassifications: () => getEncodedSemanticClassifications, - getEncodedSyntacticClassifications: () => getEncodedSyntacticClassifications, - getEndLinePosition: () => getEndLinePosition, - getEntityNameFromTypeNode: () => getEntityNameFromTypeNode, - getEntrypointsFromPackageJsonInfo: () => getEntrypointsFromPackageJsonInfo, - getErrorCountForSummary: () => getErrorCountForSummary, - getErrorSpanForNode: () => getErrorSpanForNode, - getErrorSummaryText: () => getErrorSummaryText, - getEscapedTextOfIdentifierOrLiteral: () => getEscapedTextOfIdentifierOrLiteral, - getEscapedTextOfJsxAttributeName: () => getEscapedTextOfJsxAttributeName, - getEscapedTextOfJsxNamespacedName: () => getEscapedTextOfJsxNamespacedName, - getExpandoInitializer: () => getExpandoInitializer, - getExportAssignmentExpression: () => getExportAssignmentExpression, - getExportInfoMap: () => getExportInfoMap, - getExportNeedsImportStarHelper: () => getExportNeedsImportStarHelper, - getExpressionAssociativity: () => getExpressionAssociativity, - getExpressionPrecedence: () => getExpressionPrecedence, - getExternalHelpersModuleName: () => getExternalHelpersModuleName, - getExternalModuleImportEqualsDeclarationExpression: () => getExternalModuleImportEqualsDeclarationExpression, - getExternalModuleName: () => getExternalModuleName, - getExternalModuleNameFromDeclaration: () => getExternalModuleNameFromDeclaration, - getExternalModuleNameFromPath: () => getExternalModuleNameFromPath, - getExternalModuleNameLiteral: () => getExternalModuleNameLiteral, - getExternalModuleRequireArgument: () => getExternalModuleRequireArgument, - getFallbackOptions: () => getFallbackOptions, - getFileEmitOutput: () => getFileEmitOutput, - getFileMatcherPatterns: () => getFileMatcherPatterns, - getFileNamesFromConfigSpecs: () => getFileNamesFromConfigSpecs, - getFileWatcherEventKind: () => getFileWatcherEventKind, - getFilesInErrorForSummary: () => getFilesInErrorForSummary, - getFirstConstructorWithBody: () => getFirstConstructorWithBody, - getFirstIdentifier: () => getFirstIdentifier, - getFirstNonSpaceCharacterPosition: () => getFirstNonSpaceCharacterPosition, - getFirstProjectOutput: () => getFirstProjectOutput, - getFixableErrorSpanExpression: () => getFixableErrorSpanExpression, - getFormatCodeSettingsForWriting: () => getFormatCodeSettingsForWriting, - getFullWidth: () => getFullWidth, - getFunctionFlags: () => getFunctionFlags, - getHeritageClause: () => getHeritageClause, - getHostSignatureFromJSDoc: () => getHostSignatureFromJSDoc, - getIdentifierAutoGenerate: () => getIdentifierAutoGenerate, - getIdentifierGeneratedImportReference: () => getIdentifierGeneratedImportReference, - getIdentifierTypeArguments: () => getIdentifierTypeArguments, - getImmediatelyInvokedFunctionExpression: () => getImmediatelyInvokedFunctionExpression, - getImpliedNodeFormatForEmitWorker: () => getImpliedNodeFormatForEmitWorker, - getImpliedNodeFormatForFile: () => getImpliedNodeFormatForFile, - getImpliedNodeFormatForFileWorker: () => getImpliedNodeFormatForFileWorker, - getImportNeedsImportDefaultHelper: () => getImportNeedsImportDefaultHelper, - getImportNeedsImportStarHelper: () => getImportNeedsImportStarHelper, - getIndentString: () => getIndentString, - getInferredLibraryNameResolveFrom: () => getInferredLibraryNameResolveFrom, - getInitializedVariables: () => getInitializedVariables, - getInitializerOfBinaryExpression: () => getInitializerOfBinaryExpression, - getInitializerOfBindingOrAssignmentElement: () => getInitializerOfBindingOrAssignmentElement, - getInterfaceBaseTypeNodes: () => getInterfaceBaseTypeNodes, - getInternalEmitFlags: () => getInternalEmitFlags, - getInvokedExpression: () => getInvokedExpression, - getIsFileExcluded: () => getIsFileExcluded, - getIsolatedModules: () => getIsolatedModules, - getJSDocAugmentsTag: () => getJSDocAugmentsTag, - getJSDocClassTag: () => getJSDocClassTag, - getJSDocCommentRanges: () => getJSDocCommentRanges, - getJSDocCommentsAndTags: () => getJSDocCommentsAndTags, - getJSDocDeprecatedTag: () => getJSDocDeprecatedTag, - getJSDocDeprecatedTagNoCache: () => getJSDocDeprecatedTagNoCache, - getJSDocEnumTag: () => getJSDocEnumTag, - getJSDocHost: () => getJSDocHost, - getJSDocImplementsTags: () => getJSDocImplementsTags, - getJSDocOverloadTags: () => getJSDocOverloadTags, - getJSDocOverrideTagNoCache: () => getJSDocOverrideTagNoCache, - getJSDocParameterTags: () => getJSDocParameterTags, - getJSDocParameterTagsNoCache: () => getJSDocParameterTagsNoCache, - getJSDocPrivateTag: () => getJSDocPrivateTag, - getJSDocPrivateTagNoCache: () => getJSDocPrivateTagNoCache, - getJSDocProtectedTag: () => getJSDocProtectedTag, - getJSDocProtectedTagNoCache: () => getJSDocProtectedTagNoCache, - getJSDocPublicTag: () => getJSDocPublicTag, - getJSDocPublicTagNoCache: () => getJSDocPublicTagNoCache, - getJSDocReadonlyTag: () => getJSDocReadonlyTag, - getJSDocReadonlyTagNoCache: () => getJSDocReadonlyTagNoCache, - getJSDocReturnTag: () => getJSDocReturnTag, - getJSDocReturnType: () => getJSDocReturnType, - getJSDocRoot: () => getJSDocRoot, - getJSDocSatisfiesExpressionType: () => getJSDocSatisfiesExpressionType, - getJSDocSatisfiesTag: () => getJSDocSatisfiesTag, - getJSDocTags: () => getJSDocTags, - getJSDocTemplateTag: () => getJSDocTemplateTag, - getJSDocThisTag: () => getJSDocThisTag, - getJSDocType: () => getJSDocType, - getJSDocTypeAliasName: () => getJSDocTypeAliasName, - getJSDocTypeAssertionType: () => getJSDocTypeAssertionType, - getJSDocTypeParameterDeclarations: () => getJSDocTypeParameterDeclarations, - getJSDocTypeParameterTags: () => getJSDocTypeParameterTags, - getJSDocTypeParameterTagsNoCache: () => getJSDocTypeParameterTagsNoCache, - getJSDocTypeTag: () => getJSDocTypeTag, - getJSXImplicitImportBase: () => getJSXImplicitImportBase, - getJSXRuntimeImport: () => getJSXRuntimeImport, - getJSXTransformEnabled: () => getJSXTransformEnabled, - getKeyForCompilerOptions: () => getKeyForCompilerOptions, - getLanguageVariant: () => getLanguageVariant, - getLastChild: () => getLastChild, - getLeadingCommentRanges: () => getLeadingCommentRanges, - getLeadingCommentRangesOfNode: () => getLeadingCommentRangesOfNode, - getLeftmostAccessExpression: () => getLeftmostAccessExpression, - getLeftmostExpression: () => getLeftmostExpression, - getLibraryNameFromLibFileName: () => getLibraryNameFromLibFileName, - getLineAndCharacterOfPosition: () => getLineAndCharacterOfPosition, - getLineInfo: () => getLineInfo, - getLineOfLocalPosition: () => getLineOfLocalPosition, - getLineStartPositionForPosition: () => getLineStartPositionForPosition, - getLineStarts: () => getLineStarts, - getLinesBetweenPositionAndNextNonWhitespaceCharacter: () => getLinesBetweenPositionAndNextNonWhitespaceCharacter, - getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter: () => getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter, - getLinesBetweenPositions: () => getLinesBetweenPositions, - getLinesBetweenRangeEndAndRangeStart: () => getLinesBetweenRangeEndAndRangeStart, - getLinesBetweenRangeEndPositions: () => getLinesBetweenRangeEndPositions, - getLiteralText: () => getLiteralText, - getLocalNameForExternalImport: () => getLocalNameForExternalImport, - getLocalSymbolForExportDefault: () => getLocalSymbolForExportDefault, - getLocaleSpecificMessage: () => getLocaleSpecificMessage, - getLocaleTimeString: () => getLocaleTimeString, - getMappedContextSpan: () => getMappedContextSpan, - getMappedDocumentSpan: () => getMappedDocumentSpan, - getMappedLocation: () => getMappedLocation, - getMatchedFileSpec: () => getMatchedFileSpec, - getMatchedIncludeSpec: () => getMatchedIncludeSpec, - getMeaningFromDeclaration: () => getMeaningFromDeclaration, - getMeaningFromLocation: () => getMeaningFromLocation, - getMembersOfDeclaration: () => getMembersOfDeclaration, - getModeForFileReference: () => getModeForFileReference, - getModeForResolutionAtIndex: () => getModeForResolutionAtIndex, - getModeForUsageLocation: () => getModeForUsageLocation, - getModifiedTime: () => getModifiedTime, - getModifiers: () => getModifiers, - getModuleInstanceState: () => getModuleInstanceState, - getModuleNameStringLiteralAt: () => getModuleNameStringLiteralAt, - getModuleSpecifierEndingPreference: () => getModuleSpecifierEndingPreference, - getModuleSpecifierResolverHost: () => getModuleSpecifierResolverHost, - getNameForExportedSymbol: () => getNameForExportedSymbol, - getNameFromImportAttribute: () => getNameFromImportAttribute, - getNameFromIndexInfo: () => getNameFromIndexInfo, - getNameFromPropertyName: () => getNameFromPropertyName, - getNameOfAccessExpression: () => getNameOfAccessExpression, - getNameOfCompilerOptionValue: () => getNameOfCompilerOptionValue, - getNameOfDeclaration: () => getNameOfDeclaration, - getNameOfExpando: () => getNameOfExpando, - getNameOfJSDocTypedef: () => getNameOfJSDocTypedef, - getNameOfScriptTarget: () => getNameOfScriptTarget, - getNameOrArgument: () => getNameOrArgument, - getNameTable: () => getNameTable, - getNamespaceDeclarationNode: () => getNamespaceDeclarationNode, - getNewLineCharacter: () => getNewLineCharacter, - getNewLineKind: () => getNewLineKind, - getNewLineOrDefaultFromHost: () => getNewLineOrDefaultFromHost, - getNewTargetContainer: () => getNewTargetContainer, - getNextJSDocCommentLocation: () => getNextJSDocCommentLocation, - getNodeChildren: () => getNodeChildren, - getNodeForGeneratedName: () => getNodeForGeneratedName, - getNodeId: () => getNodeId, - getNodeKind: () => getNodeKind, - getNodeModifiers: () => getNodeModifiers, - getNodeModulePathParts: () => getNodeModulePathParts, - getNonAssignedNameOfDeclaration: () => getNonAssignedNameOfDeclaration, - getNonAssignmentOperatorForCompoundAssignment: () => getNonAssignmentOperatorForCompoundAssignment, - getNonAugmentationDeclaration: () => getNonAugmentationDeclaration, - getNonDecoratorTokenPosOfNode: () => getNonDecoratorTokenPosOfNode, - getNonIncrementalBuildInfoRoots: () => getNonIncrementalBuildInfoRoots, - getNonModifierTokenPosOfNode: () => getNonModifierTokenPosOfNode, - getNormalizedAbsolutePath: () => getNormalizedAbsolutePath, - getNormalizedAbsolutePathWithoutRoot: () => getNormalizedAbsolutePathWithoutRoot, - getNormalizedPathComponents: () => getNormalizedPathComponents, - getObjectFlags: () => getObjectFlags, - getOperatorAssociativity: () => getOperatorAssociativity, - getOperatorPrecedence: () => getOperatorPrecedence, - getOptionFromName: () => getOptionFromName, - getOptionsForLibraryResolution: () => getOptionsForLibraryResolution, - getOptionsNameMap: () => getOptionsNameMap, - getOrCreateEmitNode: () => getOrCreateEmitNode, - getOrUpdate: () => getOrUpdate, - getOriginalNode: () => getOriginalNode, - getOriginalNodeId: () => getOriginalNodeId, - getOutputDeclarationFileName: () => getOutputDeclarationFileName, - getOutputDeclarationFileNameWorker: () => getOutputDeclarationFileNameWorker, - getOutputExtension: () => getOutputExtension, - getOutputFileNames: () => getOutputFileNames, - getOutputJSFileNameWorker: () => getOutputJSFileNameWorker, - getOutputPathsFor: () => getOutputPathsFor, - getOwnEmitOutputFilePath: () => getOwnEmitOutputFilePath, - getOwnKeys: () => getOwnKeys, - getOwnValues: () => getOwnValues, - getPackageJsonTypesVersionsPaths: () => getPackageJsonTypesVersionsPaths, - getPackageNameFromTypesPackageName: () => getPackageNameFromTypesPackageName, - getPackageScopeForPath: () => getPackageScopeForPath, - getParameterSymbolFromJSDoc: () => getParameterSymbolFromJSDoc, - getParentNodeInSpan: () => getParentNodeInSpan, - getParseTreeNode: () => getParseTreeNode, - getParsedCommandLineOfConfigFile: () => getParsedCommandLineOfConfigFile, - getPathComponents: () => getPathComponents, - getPathFromPathComponents: () => getPathFromPathComponents, - getPathUpdater: () => getPathUpdater, - getPathsBasePath: () => getPathsBasePath, - getPatternFromSpec: () => getPatternFromSpec, - getPendingEmitKindWithSeen: () => getPendingEmitKindWithSeen, - getPositionOfLineAndCharacter: () => getPositionOfLineAndCharacter, - getPossibleGenericSignatures: () => getPossibleGenericSignatures, - getPossibleOriginalInputExtensionForExtension: () => getPossibleOriginalInputExtensionForExtension, - getPossibleTypeArgumentsInfo: () => getPossibleTypeArgumentsInfo, - getPreEmitDiagnostics: () => getPreEmitDiagnostics, - getPrecedingNonSpaceCharacterPosition: () => getPrecedingNonSpaceCharacterPosition, - getPrivateIdentifier: () => getPrivateIdentifier, - getProperties: () => getProperties, - getProperty: () => getProperty, - getPropertyArrayElementValue: () => getPropertyArrayElementValue, - getPropertyAssignmentAliasLikeExpression: () => getPropertyAssignmentAliasLikeExpression, - getPropertyNameForPropertyNameNode: () => getPropertyNameForPropertyNameNode, - getPropertyNameFromType: () => getPropertyNameFromType, - getPropertyNameOfBindingOrAssignmentElement: () => getPropertyNameOfBindingOrAssignmentElement, - getPropertySymbolFromBindingElement: () => getPropertySymbolFromBindingElement, - getPropertySymbolsFromContextualType: () => getPropertySymbolsFromContextualType, - getQuoteFromPreference: () => getQuoteFromPreference, - getQuotePreference: () => getQuotePreference, - getRangesWhere: () => getRangesWhere, - getRefactorContextSpan: () => getRefactorContextSpan, - getReferencedFileLocation: () => getReferencedFileLocation, - getRegexFromPattern: () => getRegexFromPattern, - getRegularExpressionForWildcard: () => getRegularExpressionForWildcard, - getRegularExpressionsForWildcards: () => getRegularExpressionsForWildcards, - getRelativePathFromDirectory: () => getRelativePathFromDirectory, - getRelativePathFromFile: () => getRelativePathFromFile, - getRelativePathToDirectoryOrUrl: () => getRelativePathToDirectoryOrUrl, - getRenameLocation: () => getRenameLocation, - getReplacementSpanForContextToken: () => getReplacementSpanForContextToken, - getResolutionDiagnostic: () => getResolutionDiagnostic, - getResolutionModeOverride: () => getResolutionModeOverride, - getResolveJsonModule: () => getResolveJsonModule, - getResolvePackageJsonExports: () => getResolvePackageJsonExports, - getResolvePackageJsonImports: () => getResolvePackageJsonImports, - getResolvedExternalModuleName: () => getResolvedExternalModuleName, - getResolvedModuleFromResolution: () => getResolvedModuleFromResolution, - getResolvedTypeReferenceDirectiveFromResolution: () => getResolvedTypeReferenceDirectiveFromResolution, - getRestIndicatorOfBindingOrAssignmentElement: () => getRestIndicatorOfBindingOrAssignmentElement, - getRestParameterElementType: () => getRestParameterElementType, - getRightMostAssignedExpression: () => getRightMostAssignedExpression, - getRootDeclaration: () => getRootDeclaration, - getRootDirectoryOfResolutionCache: () => getRootDirectoryOfResolutionCache, - getRootLength: () => getRootLength, - getScriptKind: () => getScriptKind, - getScriptKindFromFileName: () => getScriptKindFromFileName, - getScriptTargetFeatures: () => getScriptTargetFeatures, - getSelectedEffectiveModifierFlags: () => getSelectedEffectiveModifierFlags, - getSelectedSyntacticModifierFlags: () => getSelectedSyntacticModifierFlags, - getSemanticClassifications: () => getSemanticClassifications, - getSemanticJsxChildren: () => getSemanticJsxChildren, - getSetAccessorTypeAnnotationNode: () => getSetAccessorTypeAnnotationNode, - getSetAccessorValueParameter: () => getSetAccessorValueParameter, - getSetExternalModuleIndicator: () => getSetExternalModuleIndicator, - getShebang: () => getShebang, - getSingleVariableOfVariableStatement: () => getSingleVariableOfVariableStatement, - getSnapshotText: () => getSnapshotText, - getSnippetElement: () => getSnippetElement, - getSourceFileOfModule: () => getSourceFileOfModule, - getSourceFileOfNode: () => getSourceFileOfNode, - getSourceFilePathInNewDir: () => getSourceFilePathInNewDir, - getSourceFileVersionAsHashFromText: () => getSourceFileVersionAsHashFromText, - getSourceFilesToEmit: () => getSourceFilesToEmit, - getSourceMapRange: () => getSourceMapRange, - getSourceMapper: () => getSourceMapper, - getSourceTextOfNodeFromSourceFile: () => getSourceTextOfNodeFromSourceFile, - getSpanOfTokenAtPosition: () => getSpanOfTokenAtPosition, - getSpellingSuggestion: () => getSpellingSuggestion, - getStartPositionOfLine: () => getStartPositionOfLine, - getStartPositionOfRange: () => getStartPositionOfRange, - getStartsOnNewLine: () => getStartsOnNewLine, - getStaticPropertiesAndClassStaticBlock: () => getStaticPropertiesAndClassStaticBlock, - getStrictOptionValue: () => getStrictOptionValue, - getStringComparer: () => getStringComparer, - getSubPatternFromSpec: () => getSubPatternFromSpec, - getSuperCallFromStatement: () => getSuperCallFromStatement, - getSuperContainer: () => getSuperContainer, - getSupportedCodeFixes: () => getSupportedCodeFixes, - getSupportedExtensions: () => getSupportedExtensions, - getSupportedExtensionsWithJsonIfResolveJsonModule: () => getSupportedExtensionsWithJsonIfResolveJsonModule, - getSwitchedType: () => getSwitchedType, - getSymbolId: () => getSymbolId, - getSymbolNameForPrivateIdentifier: () => getSymbolNameForPrivateIdentifier, - getSymbolTarget: () => getSymbolTarget, - getSyntacticClassifications: () => getSyntacticClassifications, - getSyntacticModifierFlags: () => getSyntacticModifierFlags, - getSyntacticModifierFlagsNoCache: () => getSyntacticModifierFlagsNoCache, - getSynthesizedDeepClone: () => getSynthesizedDeepClone, - getSynthesizedDeepCloneWithReplacements: () => getSynthesizedDeepCloneWithReplacements, - getSynthesizedDeepClones: () => getSynthesizedDeepClones, - getSynthesizedDeepClonesWithReplacements: () => getSynthesizedDeepClonesWithReplacements, - getSyntheticLeadingComments: () => getSyntheticLeadingComments, - getSyntheticTrailingComments: () => getSyntheticTrailingComments, - getTargetLabel: () => getTargetLabel, - getTargetOfBindingOrAssignmentElement: () => getTargetOfBindingOrAssignmentElement, - getTemporaryModuleResolutionState: () => getTemporaryModuleResolutionState, - getTextOfConstantValue: () => getTextOfConstantValue, - getTextOfIdentifierOrLiteral: () => getTextOfIdentifierOrLiteral, - getTextOfJSDocComment: () => getTextOfJSDocComment, - getTextOfJsxAttributeName: () => getTextOfJsxAttributeName, - getTextOfJsxNamespacedName: () => getTextOfJsxNamespacedName, - getTextOfNode: () => getTextOfNode, - getTextOfNodeFromSourceText: () => getTextOfNodeFromSourceText, - getTextOfPropertyName: () => getTextOfPropertyName, - getThisContainer: () => getThisContainer, - getThisParameter: () => getThisParameter, - getTokenAtPosition: () => getTokenAtPosition, - getTokenPosOfNode: () => getTokenPosOfNode, - getTokenSourceMapRange: () => getTokenSourceMapRange, - getTouchingPropertyName: () => getTouchingPropertyName, - getTouchingToken: () => getTouchingToken, - getTrailingCommentRanges: () => getTrailingCommentRanges, - getTrailingSemicolonDeferringWriter: () => getTrailingSemicolonDeferringWriter, - getTransformers: () => getTransformers, - getTsBuildInfoEmitOutputFilePath: () => getTsBuildInfoEmitOutputFilePath, - getTsConfigObjectLiteralExpression: () => getTsConfigObjectLiteralExpression, - getTsConfigPropArrayElementValue: () => getTsConfigPropArrayElementValue, - getTypeAnnotationNode: () => getTypeAnnotationNode, - getTypeArgumentOrTypeParameterList: () => getTypeArgumentOrTypeParameterList, - getTypeKeywordOfTypeOnlyImport: () => getTypeKeywordOfTypeOnlyImport, - getTypeNode: () => getTypeNode, - getTypeNodeIfAccessible: () => getTypeNodeIfAccessible, - getTypeParameterFromJsDoc: () => getTypeParameterFromJsDoc, - getTypeParameterOwner: () => getTypeParameterOwner, - getTypesPackageName: () => getTypesPackageName, - getUILocale: () => getUILocale, - getUniqueName: () => getUniqueName, - getUniqueSymbolId: () => getUniqueSymbolId, - getUseDefineForClassFields: () => getUseDefineForClassFields, - getWatchErrorSummaryDiagnosticMessage: () => getWatchErrorSummaryDiagnosticMessage, - getWatchFactory: () => getWatchFactory, - group: () => group, - groupBy: () => groupBy, - guessIndentation: () => guessIndentation, - handleNoEmitOptions: () => handleNoEmitOptions, - handleWatchOptionsConfigDirTemplateSubstitution: () => handleWatchOptionsConfigDirTemplateSubstitution, - hasAbstractModifier: () => hasAbstractModifier, - hasAccessorModifier: () => hasAccessorModifier, - hasAmbientModifier: () => hasAmbientModifier, - hasChangesInResolutions: () => hasChangesInResolutions, - hasContextSensitiveParameters: () => hasContextSensitiveParameters, - hasDecorators: () => hasDecorators, - hasDocComment: () => hasDocComment, - hasDynamicName: () => hasDynamicName, - hasEffectiveModifier: () => hasEffectiveModifier, - hasEffectiveModifiers: () => hasEffectiveModifiers, - hasEffectiveReadonlyModifier: () => hasEffectiveReadonlyModifier, - hasExtension: () => hasExtension, - hasImplementationTSFileExtension: () => hasImplementationTSFileExtension, - hasIndexSignature: () => hasIndexSignature, - hasInferredType: () => hasInferredType, - hasInitializer: () => hasInitializer, - hasInvalidEscape: () => hasInvalidEscape, - hasJSDocNodes: () => hasJSDocNodes, - hasJSDocParameterTags: () => hasJSDocParameterTags, - hasJSFileExtension: () => hasJSFileExtension, - hasJsonModuleEmitEnabled: () => hasJsonModuleEmitEnabled, - hasOnlyExpressionInitializer: () => hasOnlyExpressionInitializer, - hasOverrideModifier: () => hasOverrideModifier, - hasPossibleExternalModuleReference: () => hasPossibleExternalModuleReference, - hasProperty: () => hasProperty, - hasPropertyAccessExpressionWithName: () => hasPropertyAccessExpressionWithName, - hasQuestionToken: () => hasQuestionToken, - hasRecordedExternalHelpers: () => hasRecordedExternalHelpers, - hasResolutionModeOverride: () => hasResolutionModeOverride, - hasRestParameter: () => hasRestParameter, - hasScopeMarker: () => hasScopeMarker, - hasStaticModifier: () => hasStaticModifier, - hasSyntacticModifier: () => hasSyntacticModifier, - hasSyntacticModifiers: () => hasSyntacticModifiers, - hasTSFileExtension: () => hasTSFileExtension, - hasTabstop: () => hasTabstop, - hasTrailingDirectorySeparator: () => hasTrailingDirectorySeparator, - hasType: () => hasType, - hasTypeArguments: () => hasTypeArguments, - hasZeroOrOneAsteriskCharacter: () => hasZeroOrOneAsteriskCharacter, - hostGetCanonicalFileName: () => hostGetCanonicalFileName, - hostUsesCaseSensitiveFileNames: () => hostUsesCaseSensitiveFileNames, - idText: () => idText, - identifierIsThisKeyword: () => identifierIsThisKeyword, - identifierToKeywordKind: () => identifierToKeywordKind, - identity: () => identity, - identitySourceMapConsumer: () => identitySourceMapConsumer, - ignoreSourceNewlines: () => ignoreSourceNewlines, - ignoredPaths: () => ignoredPaths, - importFromModuleSpecifier: () => importFromModuleSpecifier, - importSyntaxAffectsModuleResolution: () => importSyntaxAffectsModuleResolution, - indexOfAnyCharCode: () => indexOfAnyCharCode, - indexOfNode: () => indexOfNode, - indicesOf: () => indicesOf, - inferredTypesContainingFile: () => inferredTypesContainingFile, - injectClassNamedEvaluationHelperBlockIfMissing: () => injectClassNamedEvaluationHelperBlockIfMissing, - injectClassThisAssignmentIfMissing: () => injectClassThisAssignmentIfMissing, - insertImports: () => insertImports, - insertSorted: () => insertSorted, - insertStatementAfterCustomPrologue: () => insertStatementAfterCustomPrologue, - insertStatementAfterStandardPrologue: () => insertStatementAfterStandardPrologue, - insertStatementsAfterCustomPrologue: () => insertStatementsAfterCustomPrologue, - insertStatementsAfterStandardPrologue: () => insertStatementsAfterStandardPrologue, - intersperse: () => intersperse, - intrinsicTagNameToString: () => intrinsicTagNameToString, - introducesArgumentsExoticObject: () => introducesArgumentsExoticObject, - inverseJsxOptionMap: () => inverseJsxOptionMap, - isAbstractConstructorSymbol: () => isAbstractConstructorSymbol, - isAbstractModifier: () => isAbstractModifier, - isAccessExpression: () => isAccessExpression, - isAccessibilityModifier: () => isAccessibilityModifier, - isAccessor: () => isAccessor, - isAccessorModifier: () => isAccessorModifier, - isAliasableExpression: () => isAliasableExpression, - isAmbientModule: () => isAmbientModule, - isAmbientPropertyDeclaration: () => isAmbientPropertyDeclaration, - isAnyDirectorySeparator: () => isAnyDirectorySeparator, - isAnyImportOrBareOrAccessedRequire: () => isAnyImportOrBareOrAccessedRequire, - isAnyImportOrReExport: () => isAnyImportOrReExport, - isAnyImportOrRequireStatement: () => isAnyImportOrRequireStatement, - isAnyImportSyntax: () => isAnyImportSyntax, - isAnySupportedFileExtension: () => isAnySupportedFileExtension, - isApplicableVersionedTypesKey: () => isApplicableVersionedTypesKey, - isArgumentExpressionOfElementAccess: () => isArgumentExpressionOfElementAccess, - isArray: () => isArray, - isArrayBindingElement: () => isArrayBindingElement, - isArrayBindingOrAssignmentElement: () => isArrayBindingOrAssignmentElement, - isArrayBindingOrAssignmentPattern: () => isArrayBindingOrAssignmentPattern, - isArrayBindingPattern: () => isArrayBindingPattern, - isArrayLiteralExpression: () => isArrayLiteralExpression, - isArrayLiteralOrObjectLiteralDestructuringPattern: () => isArrayLiteralOrObjectLiteralDestructuringPattern, - isArrayTypeNode: () => isArrayTypeNode, - isArrowFunction: () => isArrowFunction, - isAsExpression: () => isAsExpression, - isAssertClause: () => isAssertClause, - isAssertEntry: () => isAssertEntry, - isAssertionExpression: () => isAssertionExpression, - isAssertsKeyword: () => isAssertsKeyword, - isAssignmentDeclaration: () => isAssignmentDeclaration, - isAssignmentExpression: () => isAssignmentExpression, - isAssignmentOperator: () => isAssignmentOperator, - isAssignmentPattern: () => isAssignmentPattern, - isAssignmentTarget: () => isAssignmentTarget, - isAsteriskToken: () => isAsteriskToken, - isAsyncFunction: () => isAsyncFunction, - isAsyncModifier: () => isAsyncModifier, - isAutoAccessorPropertyDeclaration: () => isAutoAccessorPropertyDeclaration, - isAwaitExpression: () => isAwaitExpression, - isAwaitKeyword: () => isAwaitKeyword, - isBigIntLiteral: () => isBigIntLiteral, - isBinaryExpression: () => isBinaryExpression, - isBinaryLogicalOperator: () => isBinaryLogicalOperator, - isBinaryOperatorToken: () => isBinaryOperatorToken, - isBindableObjectDefinePropertyCall: () => isBindableObjectDefinePropertyCall, - isBindableStaticAccessExpression: () => isBindableStaticAccessExpression, - isBindableStaticElementAccessExpression: () => isBindableStaticElementAccessExpression, - isBindableStaticNameExpression: () => isBindableStaticNameExpression, - isBindingElement: () => isBindingElement, - isBindingElementOfBareOrAccessedRequire: () => isBindingElementOfBareOrAccessedRequire, - isBindingName: () => isBindingName, - isBindingOrAssignmentElement: () => isBindingOrAssignmentElement, - isBindingOrAssignmentPattern: () => isBindingOrAssignmentPattern, - isBindingPattern: () => isBindingPattern, - isBlock: () => isBlock, - isBlockLike: () => isBlockLike, - isBlockOrCatchScoped: () => isBlockOrCatchScoped, - isBlockScope: () => isBlockScope, - isBlockScopedContainerTopLevel: () => isBlockScopedContainerTopLevel, - isBooleanLiteral: () => isBooleanLiteral, - isBreakOrContinueStatement: () => isBreakOrContinueStatement, - isBreakStatement: () => isBreakStatement, - isBuild: () => isBuild, - isBuildInfoFile: () => isBuildInfoFile, - isBuilderProgram: () => isBuilderProgram, - isBundle: () => isBundle, - isCallChain: () => isCallChain, - isCallExpression: () => isCallExpression, - isCallExpressionTarget: () => isCallExpressionTarget, - isCallLikeExpression: () => isCallLikeExpression, - isCallLikeOrFunctionLikeExpression: () => isCallLikeOrFunctionLikeExpression, - isCallOrNewExpression: () => isCallOrNewExpression, - isCallOrNewExpressionTarget: () => isCallOrNewExpressionTarget, - isCallSignatureDeclaration: () => isCallSignatureDeclaration, - isCallToHelper: () => isCallToHelper, - isCaseBlock: () => isCaseBlock, - isCaseClause: () => isCaseClause, - isCaseKeyword: () => isCaseKeyword, - isCaseOrDefaultClause: () => isCaseOrDefaultClause, - isCatchClause: () => isCatchClause, - isCatchClauseVariableDeclaration: () => isCatchClauseVariableDeclaration, - isCatchClauseVariableDeclarationOrBindingElement: () => isCatchClauseVariableDeclarationOrBindingElement, - isCheckJsEnabledForFile: () => isCheckJsEnabledForFile, - isCircularBuildOrder: () => isCircularBuildOrder, - isClassDeclaration: () => isClassDeclaration, - isClassElement: () => isClassElement, - isClassExpression: () => isClassExpression, - isClassInstanceProperty: () => isClassInstanceProperty, - isClassLike: () => isClassLike, - isClassMemberModifier: () => isClassMemberModifier, - isClassNamedEvaluationHelperBlock: () => isClassNamedEvaluationHelperBlock, - isClassOrTypeElement: () => isClassOrTypeElement, - isClassStaticBlockDeclaration: () => isClassStaticBlockDeclaration, - isClassThisAssignmentBlock: () => isClassThisAssignmentBlock, - isColonToken: () => isColonToken, - isCommaExpression: () => isCommaExpression, - isCommaListExpression: () => isCommaListExpression, - isCommaSequence: () => isCommaSequence, - isCommaToken: () => isCommaToken, - isComment: () => isComment, - isCommonJsExportPropertyAssignment: () => isCommonJsExportPropertyAssignment, - isCommonJsExportedExpression: () => isCommonJsExportedExpression, - isCompoundAssignment: () => isCompoundAssignment, - isComputedNonLiteralName: () => isComputedNonLiteralName, - isComputedPropertyName: () => isComputedPropertyName, - isConciseBody: () => isConciseBody, - isConditionalExpression: () => isConditionalExpression, - isConditionalTypeNode: () => isConditionalTypeNode, - isConstAssertion: () => isConstAssertion, - isConstTypeReference: () => isConstTypeReference, - isConstructSignatureDeclaration: () => isConstructSignatureDeclaration, - isConstructorDeclaration: () => isConstructorDeclaration, - isConstructorTypeNode: () => isConstructorTypeNode, - isContextualKeyword: () => isContextualKeyword, - isContinueStatement: () => isContinueStatement, - isCustomPrologue: () => isCustomPrologue, - isDebuggerStatement: () => isDebuggerStatement, - isDeclaration: () => isDeclaration, - isDeclarationBindingElement: () => isDeclarationBindingElement, - isDeclarationFileName: () => isDeclarationFileName, - isDeclarationName: () => isDeclarationName, - isDeclarationNameOfEnumOrNamespace: () => isDeclarationNameOfEnumOrNamespace, - isDeclarationReadonly: () => isDeclarationReadonly, - isDeclarationStatement: () => isDeclarationStatement, - isDeclarationWithTypeParameterChildren: () => isDeclarationWithTypeParameterChildren, - isDeclarationWithTypeParameters: () => isDeclarationWithTypeParameters, - isDecorator: () => isDecorator, - isDecoratorTarget: () => isDecoratorTarget, - isDefaultClause: () => isDefaultClause, - isDefaultImport: () => isDefaultImport, - isDefaultModifier: () => isDefaultModifier, - isDefaultedExpandoInitializer: () => isDefaultedExpandoInitializer, - isDeleteExpression: () => isDeleteExpression, - isDeleteTarget: () => isDeleteTarget, - isDeprecatedDeclaration: () => isDeprecatedDeclaration, - isDestructuringAssignment: () => isDestructuringAssignment, - isDiskPathRoot: () => isDiskPathRoot, - isDoStatement: () => isDoStatement, - isDocumentRegistryEntry: () => isDocumentRegistryEntry, - isDotDotDotToken: () => isDotDotDotToken, - isDottedName: () => isDottedName, - isDynamicName: () => isDynamicName, - isEffectiveExternalModule: () => isEffectiveExternalModule, - isEffectiveStrictModeSourceFile: () => isEffectiveStrictModeSourceFile, - isElementAccessChain: () => isElementAccessChain, - isElementAccessExpression: () => isElementAccessExpression, - isEmittedFileOfProgram: () => isEmittedFileOfProgram, - isEmptyArrayLiteral: () => isEmptyArrayLiteral, - isEmptyBindingElement: () => isEmptyBindingElement, - isEmptyBindingPattern: () => isEmptyBindingPattern, - isEmptyObjectLiteral: () => isEmptyObjectLiteral, - isEmptyStatement: () => isEmptyStatement, - isEmptyStringLiteral: () => isEmptyStringLiteral, - isEntityName: () => isEntityName, - isEntityNameExpression: () => isEntityNameExpression, - isEnumConst: () => isEnumConst, - isEnumDeclaration: () => isEnumDeclaration, - isEnumMember: () => isEnumMember, - isEqualityOperatorKind: () => isEqualityOperatorKind, - isEqualsGreaterThanToken: () => isEqualsGreaterThanToken, - isExclamationToken: () => isExclamationToken, - isExcludedFile: () => isExcludedFile, - isExclusivelyTypeOnlyImportOrExport: () => isExclusivelyTypeOnlyImportOrExport, - isExpandoPropertyDeclaration: () => isExpandoPropertyDeclaration, - isExportAssignment: () => isExportAssignment, - isExportDeclaration: () => isExportDeclaration, - isExportModifier: () => isExportModifier, - isExportName: () => isExportName, - isExportNamespaceAsDefaultDeclaration: () => isExportNamespaceAsDefaultDeclaration, - isExportOrDefaultModifier: () => isExportOrDefaultModifier, - isExportSpecifier: () => isExportSpecifier, - isExportsIdentifier: () => isExportsIdentifier, - isExportsOrModuleExportsOrAlias: () => isExportsOrModuleExportsOrAlias, - isExpression: () => isExpression, - isExpressionNode: () => isExpressionNode, - isExpressionOfExternalModuleImportEqualsDeclaration: () => isExpressionOfExternalModuleImportEqualsDeclaration, - isExpressionOfOptionalChainRoot: () => isExpressionOfOptionalChainRoot, - isExpressionStatement: () => isExpressionStatement, - isExpressionWithTypeArguments: () => isExpressionWithTypeArguments, - isExpressionWithTypeArgumentsInClassExtendsClause: () => isExpressionWithTypeArgumentsInClassExtendsClause, - isExternalModule: () => isExternalModule, - isExternalModuleAugmentation: () => isExternalModuleAugmentation, - isExternalModuleImportEqualsDeclaration: () => isExternalModuleImportEqualsDeclaration, - isExternalModuleIndicator: () => isExternalModuleIndicator, - isExternalModuleNameRelative: () => isExternalModuleNameRelative, - isExternalModuleReference: () => isExternalModuleReference, - isExternalModuleSymbol: () => isExternalModuleSymbol, - isExternalOrCommonJsModule: () => isExternalOrCommonJsModule, - isFileLevelReservedGeneratedIdentifier: () => isFileLevelReservedGeneratedIdentifier, - isFileLevelUniqueName: () => isFileLevelUniqueName, - isFileProbablyExternalModule: () => isFileProbablyExternalModule, - isFirstDeclarationOfSymbolParameter: () => isFirstDeclarationOfSymbolParameter, - isFixablePromiseHandler: () => isFixablePromiseHandler, - isForInOrOfStatement: () => isForInOrOfStatement, - isForInStatement: () => isForInStatement, - isForInitializer: () => isForInitializer, - isForOfStatement: () => isForOfStatement, - isForStatement: () => isForStatement, - isFullSourceFile: () => isFullSourceFile, - isFunctionBlock: () => isFunctionBlock, - isFunctionBody: () => isFunctionBody, - isFunctionDeclaration: () => isFunctionDeclaration, - isFunctionExpression: () => isFunctionExpression, - isFunctionExpressionOrArrowFunction: () => isFunctionExpressionOrArrowFunction, - isFunctionLike: () => isFunctionLike, - isFunctionLikeDeclaration: () => isFunctionLikeDeclaration, - isFunctionLikeKind: () => isFunctionLikeKind, - isFunctionLikeOrClassStaticBlockDeclaration: () => isFunctionLikeOrClassStaticBlockDeclaration, - isFunctionOrConstructorTypeNode: () => isFunctionOrConstructorTypeNode, - isFunctionOrModuleBlock: () => isFunctionOrModuleBlock, - isFunctionSymbol: () => isFunctionSymbol, - isFunctionTypeNode: () => isFunctionTypeNode, - isGeneratedIdentifier: () => isGeneratedIdentifier, - isGeneratedPrivateIdentifier: () => isGeneratedPrivateIdentifier, - isGetAccessor: () => isGetAccessor, - isGetAccessorDeclaration: () => isGetAccessorDeclaration, - isGetOrSetAccessorDeclaration: () => isGetOrSetAccessorDeclaration, - isGlobalScopeAugmentation: () => isGlobalScopeAugmentation, - isGlobalSourceFile: () => isGlobalSourceFile, - isGrammarError: () => isGrammarError, - isHeritageClause: () => isHeritageClause, - isHoistedFunction: () => isHoistedFunction, - isHoistedVariableStatement: () => isHoistedVariableStatement, - isIdentifier: () => isIdentifier, - isIdentifierANonContextualKeyword: () => isIdentifierANonContextualKeyword, - isIdentifierName: () => isIdentifierName, - isIdentifierOrThisTypeNode: () => isIdentifierOrThisTypeNode, - isIdentifierPart: () => isIdentifierPart, - isIdentifierStart: () => isIdentifierStart, - isIdentifierText: () => isIdentifierText, - isIdentifierTypePredicate: () => isIdentifierTypePredicate, - isIdentifierTypeReference: () => isIdentifierTypeReference, - isIfStatement: () => isIfStatement, - isIgnoredFileFromWildCardWatching: () => isIgnoredFileFromWildCardWatching, - isImplicitGlob: () => isImplicitGlob, - isImportAttribute: () => isImportAttribute, - isImportAttributeName: () => isImportAttributeName, - isImportAttributes: () => isImportAttributes, - isImportCall: () => isImportCall, - isImportClause: () => isImportClause, - isImportDeclaration: () => isImportDeclaration, - isImportEqualsDeclaration: () => isImportEqualsDeclaration, - isImportKeyword: () => isImportKeyword, - isImportMeta: () => isImportMeta, - isImportOrExportSpecifier: () => isImportOrExportSpecifier, - isImportOrExportSpecifierName: () => isImportOrExportSpecifierName, - isImportSpecifier: () => isImportSpecifier, - isImportTypeAssertionContainer: () => isImportTypeAssertionContainer, - isImportTypeNode: () => isImportTypeNode, - isImportableFile: () => isImportableFile, - isInComment: () => isInComment, - isInCompoundLikeAssignment: () => isInCompoundLikeAssignment, - isInExpressionContext: () => isInExpressionContext, - isInJSDoc: () => isInJSDoc, - isInJSFile: () => isInJSFile, - isInJSXText: () => isInJSXText, - isInJsonFile: () => isInJsonFile, - isInNonReferenceComment: () => isInNonReferenceComment, - isInReferenceComment: () => isInReferenceComment, - isInRightSideOfInternalImportEqualsDeclaration: () => isInRightSideOfInternalImportEqualsDeclaration, - isInString: () => isInString, - isInTemplateString: () => isInTemplateString, - isInTopLevelContext: () => isInTopLevelContext, - isInTypeQuery: () => isInTypeQuery, - isIncrementalBuildInfo: () => isIncrementalBuildInfo, - isIncrementalBundleEmitBuildInfo: () => isIncrementalBundleEmitBuildInfo, - isIncrementalCompilation: () => isIncrementalCompilation, - isIndexSignatureDeclaration: () => isIndexSignatureDeclaration, - isIndexedAccessTypeNode: () => isIndexedAccessTypeNode, - isInferTypeNode: () => isInferTypeNode, - isInfinityOrNaNString: () => isInfinityOrNaNString, - isInitializedProperty: () => isInitializedProperty, - isInitializedVariable: () => isInitializedVariable, - isInsideJsxElement: () => isInsideJsxElement, - isInsideJsxElementOrAttribute: () => isInsideJsxElementOrAttribute, - isInsideNodeModules: () => isInsideNodeModules, - isInsideTemplateLiteral: () => isInsideTemplateLiteral, - isInstanceOfExpression: () => isInstanceOfExpression, - isInstantiatedModule: () => isInstantiatedModule, - isInterfaceDeclaration: () => isInterfaceDeclaration, - isInternalDeclaration: () => isInternalDeclaration, - isInternalModuleImportEqualsDeclaration: () => isInternalModuleImportEqualsDeclaration, - isInternalName: () => isInternalName, - isIntersectionTypeNode: () => isIntersectionTypeNode, - isIntrinsicJsxName: () => isIntrinsicJsxName, - isIterationStatement: () => isIterationStatement, - isJSDoc: () => isJSDoc, - isJSDocAllType: () => isJSDocAllType, - isJSDocAugmentsTag: () => isJSDocAugmentsTag, - isJSDocAuthorTag: () => isJSDocAuthorTag, - isJSDocCallbackTag: () => isJSDocCallbackTag, - isJSDocClassTag: () => isJSDocClassTag, - isJSDocCommentContainingNode: () => isJSDocCommentContainingNode, - isJSDocConstructSignature: () => isJSDocConstructSignature, - isJSDocDeprecatedTag: () => isJSDocDeprecatedTag, - isJSDocEnumTag: () => isJSDocEnumTag, - isJSDocFunctionType: () => isJSDocFunctionType, - isJSDocImplementsTag: () => isJSDocImplementsTag, - isJSDocImportTag: () => isJSDocImportTag, - isJSDocIndexSignature: () => isJSDocIndexSignature, - isJSDocLikeText: () => isJSDocLikeText, - isJSDocLink: () => isJSDocLink, - isJSDocLinkCode: () => isJSDocLinkCode, - isJSDocLinkLike: () => isJSDocLinkLike, - isJSDocLinkPlain: () => isJSDocLinkPlain, - isJSDocMemberName: () => isJSDocMemberName, - isJSDocNameReference: () => isJSDocNameReference, - isJSDocNamepathType: () => isJSDocNamepathType, - isJSDocNamespaceBody: () => isJSDocNamespaceBody, - isJSDocNode: () => isJSDocNode, - isJSDocNonNullableType: () => isJSDocNonNullableType, - isJSDocNullableType: () => isJSDocNullableType, - isJSDocOptionalParameter: () => isJSDocOptionalParameter, - isJSDocOptionalType: () => isJSDocOptionalType, - isJSDocOverloadTag: () => isJSDocOverloadTag, - isJSDocOverrideTag: () => isJSDocOverrideTag, - isJSDocParameterTag: () => isJSDocParameterTag, - isJSDocPrivateTag: () => isJSDocPrivateTag, - isJSDocPropertyLikeTag: () => isJSDocPropertyLikeTag, - isJSDocPropertyTag: () => isJSDocPropertyTag, - isJSDocProtectedTag: () => isJSDocProtectedTag, - isJSDocPublicTag: () => isJSDocPublicTag, - isJSDocReadonlyTag: () => isJSDocReadonlyTag, - isJSDocReturnTag: () => isJSDocReturnTag, - isJSDocSatisfiesExpression: () => isJSDocSatisfiesExpression, - isJSDocSatisfiesTag: () => isJSDocSatisfiesTag, - isJSDocSeeTag: () => isJSDocSeeTag, - isJSDocSignature: () => isJSDocSignature, - isJSDocTag: () => isJSDocTag, - isJSDocTemplateTag: () => isJSDocTemplateTag, - isJSDocThisTag: () => isJSDocThisTag, - isJSDocThrowsTag: () => isJSDocThrowsTag, - isJSDocTypeAlias: () => isJSDocTypeAlias, - isJSDocTypeAssertion: () => isJSDocTypeAssertion, - isJSDocTypeExpression: () => isJSDocTypeExpression, - isJSDocTypeLiteral: () => isJSDocTypeLiteral, - isJSDocTypeTag: () => isJSDocTypeTag, - isJSDocTypedefTag: () => isJSDocTypedefTag, - isJSDocUnknownTag: () => isJSDocUnknownTag, - isJSDocUnknownType: () => isJSDocUnknownType, - isJSDocVariadicType: () => isJSDocVariadicType, - isJSXTagName: () => isJSXTagName, - isJsonEqual: () => isJsonEqual, - isJsonSourceFile: () => isJsonSourceFile, - isJsxAttribute: () => isJsxAttribute, - isJsxAttributeLike: () => isJsxAttributeLike, - isJsxAttributeName: () => isJsxAttributeName, - isJsxAttributes: () => isJsxAttributes, - isJsxChild: () => isJsxChild, - isJsxClosingElement: () => isJsxClosingElement, - isJsxClosingFragment: () => isJsxClosingFragment, - isJsxElement: () => isJsxElement, - isJsxExpression: () => isJsxExpression, - isJsxFragment: () => isJsxFragment, - isJsxNamespacedName: () => isJsxNamespacedName, - isJsxOpeningElement: () => isJsxOpeningElement, - isJsxOpeningFragment: () => isJsxOpeningFragment, - isJsxOpeningLikeElement: () => isJsxOpeningLikeElement, - isJsxOpeningLikeElementTagName: () => isJsxOpeningLikeElementTagName, - isJsxSelfClosingElement: () => isJsxSelfClosingElement, - isJsxSpreadAttribute: () => isJsxSpreadAttribute, - isJsxTagNameExpression: () => isJsxTagNameExpression, - isJsxText: () => isJsxText, - isJumpStatementTarget: () => isJumpStatementTarget, - isKeyword: () => isKeyword, - isKeywordOrPunctuation: () => isKeywordOrPunctuation, - isKnownSymbol: () => isKnownSymbol, - isLabelName: () => isLabelName, - isLabelOfLabeledStatement: () => isLabelOfLabeledStatement, - isLabeledStatement: () => isLabeledStatement, - isLateVisibilityPaintedStatement: () => isLateVisibilityPaintedStatement, - isLeftHandSideExpression: () => isLeftHandSideExpression, - isLet: () => isLet, - isLineBreak: () => isLineBreak, - isLiteralComputedPropertyDeclarationName: () => isLiteralComputedPropertyDeclarationName, - isLiteralExpression: () => isLiteralExpression, - isLiteralExpressionOfObject: () => isLiteralExpressionOfObject, - isLiteralImportTypeNode: () => isLiteralImportTypeNode, - isLiteralKind: () => isLiteralKind, - isLiteralNameOfPropertyDeclarationOrIndexAccess: () => isLiteralNameOfPropertyDeclarationOrIndexAccess, - isLiteralTypeLiteral: () => isLiteralTypeLiteral, - isLiteralTypeNode: () => isLiteralTypeNode, - isLocalName: () => isLocalName, - isLogicalOperator: () => isLogicalOperator, - isLogicalOrCoalescingAssignmentExpression: () => isLogicalOrCoalescingAssignmentExpression, - isLogicalOrCoalescingAssignmentOperator: () => isLogicalOrCoalescingAssignmentOperator, - isLogicalOrCoalescingBinaryExpression: () => isLogicalOrCoalescingBinaryExpression, - isLogicalOrCoalescingBinaryOperator: () => isLogicalOrCoalescingBinaryOperator, - isMappedTypeNode: () => isMappedTypeNode, - isMemberName: () => isMemberName, - isMetaProperty: () => isMetaProperty, - isMethodDeclaration: () => isMethodDeclaration, - isMethodOrAccessor: () => isMethodOrAccessor, - isMethodSignature: () => isMethodSignature, - isMinusToken: () => isMinusToken, - isMissingDeclaration: () => isMissingDeclaration, - isMissingPackageJsonInfo: () => isMissingPackageJsonInfo, - isModifier: () => isModifier, - isModifierKind: () => isModifierKind, - isModifierLike: () => isModifierLike, - isModuleAugmentationExternal: () => isModuleAugmentationExternal, - isModuleBlock: () => isModuleBlock, - isModuleBody: () => isModuleBody, - isModuleDeclaration: () => isModuleDeclaration, - isModuleExportName: () => isModuleExportName, - isModuleExportsAccessExpression: () => isModuleExportsAccessExpression, - isModuleIdentifier: () => isModuleIdentifier, - isModuleName: () => isModuleName, - isModuleOrEnumDeclaration: () => isModuleOrEnumDeclaration, - isModuleReference: () => isModuleReference, - isModuleSpecifierLike: () => isModuleSpecifierLike, - isModuleWithStringLiteralName: () => isModuleWithStringLiteralName, - isNameOfFunctionDeclaration: () => isNameOfFunctionDeclaration, - isNameOfModuleDeclaration: () => isNameOfModuleDeclaration, - isNamedDeclaration: () => isNamedDeclaration, - isNamedEvaluation: () => isNamedEvaluation, - isNamedEvaluationSource: () => isNamedEvaluationSource, - isNamedExportBindings: () => isNamedExportBindings, - isNamedExports: () => isNamedExports, - isNamedImportBindings: () => isNamedImportBindings, - isNamedImports: () => isNamedImports, - isNamedImportsOrExports: () => isNamedImportsOrExports, - isNamedTupleMember: () => isNamedTupleMember, - isNamespaceBody: () => isNamespaceBody, - isNamespaceExport: () => isNamespaceExport, - isNamespaceExportDeclaration: () => isNamespaceExportDeclaration, - isNamespaceImport: () => isNamespaceImport, - isNamespaceReexportDeclaration: () => isNamespaceReexportDeclaration, - isNewExpression: () => isNewExpression, - isNewExpressionTarget: () => isNewExpressionTarget, - isNoSubstitutionTemplateLiteral: () => isNoSubstitutionTemplateLiteral, - isNodeArray: () => isNodeArray, - isNodeArrayMultiLine: () => isNodeArrayMultiLine, - isNodeDescendantOf: () => isNodeDescendantOf, - isNodeKind: () => isNodeKind, - isNodeLikeSystem: () => isNodeLikeSystem, - isNodeModulesDirectory: () => isNodeModulesDirectory, - isNodeWithPossibleHoistedDeclaration: () => isNodeWithPossibleHoistedDeclaration, - isNonContextualKeyword: () => isNonContextualKeyword, - isNonGlobalAmbientModule: () => isNonGlobalAmbientModule, - isNonNullAccess: () => isNonNullAccess, - isNonNullChain: () => isNonNullChain, - isNonNullExpression: () => isNonNullExpression, - isNonStaticMethodOrAccessorWithPrivateName: () => isNonStaticMethodOrAccessorWithPrivateName, - isNotEmittedStatement: () => isNotEmittedStatement, - isNullishCoalesce: () => isNullishCoalesce, - isNumber: () => isNumber, - isNumericLiteral: () => isNumericLiteral, - isNumericLiteralName: () => isNumericLiteralName, - isObjectBindingElementWithoutPropertyName: () => isObjectBindingElementWithoutPropertyName, - isObjectBindingOrAssignmentElement: () => isObjectBindingOrAssignmentElement, - isObjectBindingOrAssignmentPattern: () => isObjectBindingOrAssignmentPattern, - isObjectBindingPattern: () => isObjectBindingPattern, - isObjectLiteralElement: () => isObjectLiteralElement, - isObjectLiteralElementLike: () => isObjectLiteralElementLike, - isObjectLiteralExpression: () => isObjectLiteralExpression, - isObjectLiteralMethod: () => isObjectLiteralMethod, - isObjectLiteralOrClassExpressionMethodOrAccessor: () => isObjectLiteralOrClassExpressionMethodOrAccessor, - isObjectTypeDeclaration: () => isObjectTypeDeclaration, - isOmittedExpression: () => isOmittedExpression, - isOptionalChain: () => isOptionalChain, - isOptionalChainRoot: () => isOptionalChainRoot, - isOptionalDeclaration: () => isOptionalDeclaration, - isOptionalJSDocPropertyLikeTag: () => isOptionalJSDocPropertyLikeTag, - isOptionalTypeNode: () => isOptionalTypeNode, - isOuterExpression: () => isOuterExpression, - isOutermostOptionalChain: () => isOutermostOptionalChain, - isOverrideModifier: () => isOverrideModifier, - isPackageJsonInfo: () => isPackageJsonInfo, - isPackedArrayLiteral: () => isPackedArrayLiteral, - isParameter: () => isParameter, - isParameterPropertyDeclaration: () => isParameterPropertyDeclaration, - isParameterPropertyModifier: () => isParameterPropertyModifier, - isParenthesizedExpression: () => isParenthesizedExpression, - isParenthesizedTypeNode: () => isParenthesizedTypeNode, - isParseTreeNode: () => isParseTreeNode, - isPartOfParameterDeclaration: () => isPartOfParameterDeclaration, - isPartOfTypeNode: () => isPartOfTypeNode, - isPartOfTypeQuery: () => isPartOfTypeQuery, - isPartiallyEmittedExpression: () => isPartiallyEmittedExpression, - isPatternMatch: () => isPatternMatch, - isPinnedComment: () => isPinnedComment, - isPlainJsFile: () => isPlainJsFile, - isPlusToken: () => isPlusToken, - isPossiblyTypeArgumentPosition: () => isPossiblyTypeArgumentPosition, - isPostfixUnaryExpression: () => isPostfixUnaryExpression, - isPrefixUnaryExpression: () => isPrefixUnaryExpression, - isPrimitiveLiteralValue: () => isPrimitiveLiteralValue, - isPrivateIdentifier: () => isPrivateIdentifier, - isPrivateIdentifierClassElementDeclaration: () => isPrivateIdentifierClassElementDeclaration, - isPrivateIdentifierPropertyAccessExpression: () => isPrivateIdentifierPropertyAccessExpression, - isPrivateIdentifierSymbol: () => isPrivateIdentifierSymbol, - isProgramUptoDate: () => isProgramUptoDate, - isPrologueDirective: () => isPrologueDirective, - isPropertyAccessChain: () => isPropertyAccessChain, - isPropertyAccessEntityNameExpression: () => isPropertyAccessEntityNameExpression, - isPropertyAccessExpression: () => isPropertyAccessExpression, - isPropertyAccessOrQualifiedName: () => isPropertyAccessOrQualifiedName, - isPropertyAccessOrQualifiedNameOrImportTypeNode: () => isPropertyAccessOrQualifiedNameOrImportTypeNode, - isPropertyAssignment: () => isPropertyAssignment, - isPropertyDeclaration: () => isPropertyDeclaration, - isPropertyName: () => isPropertyName, - isPropertyNameLiteral: () => isPropertyNameLiteral, - isPropertySignature: () => isPropertySignature, - isPrototypeAccess: () => isPrototypeAccess, - isPrototypePropertyAssignment: () => isPrototypePropertyAssignment, - isPunctuation: () => isPunctuation, - isPushOrUnshiftIdentifier: () => isPushOrUnshiftIdentifier, - isQualifiedName: () => isQualifiedName, - isQuestionDotToken: () => isQuestionDotToken, - isQuestionOrExclamationToken: () => isQuestionOrExclamationToken, - isQuestionOrPlusOrMinusToken: () => isQuestionOrPlusOrMinusToken, - isQuestionToken: () => isQuestionToken, - isReadonlyKeyword: () => isReadonlyKeyword, - isReadonlyKeywordOrPlusOrMinusToken: () => isReadonlyKeywordOrPlusOrMinusToken, - isRecognizedTripleSlashComment: () => isRecognizedTripleSlashComment, - isReferenceFileLocation: () => isReferenceFileLocation, - isReferencedFile: () => isReferencedFile, - isRegularExpressionLiteral: () => isRegularExpressionLiteral, - isRequireCall: () => isRequireCall, - isRequireVariableStatement: () => isRequireVariableStatement, - isRestParameter: () => isRestParameter, - isRestTypeNode: () => isRestTypeNode, - isReturnStatement: () => isReturnStatement, - isReturnStatementWithFixablePromiseHandler: () => isReturnStatementWithFixablePromiseHandler, - isRightSideOfAccessExpression: () => isRightSideOfAccessExpression, - isRightSideOfInstanceofExpression: () => isRightSideOfInstanceofExpression, - isRightSideOfPropertyAccess: () => isRightSideOfPropertyAccess, - isRightSideOfQualifiedName: () => isRightSideOfQualifiedName, - isRightSideOfQualifiedNameOrPropertyAccess: () => isRightSideOfQualifiedNameOrPropertyAccess, - isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName: () => isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName, - isRootedDiskPath: () => isRootedDiskPath, - isSameEntityName: () => isSameEntityName, - isSatisfiesExpression: () => isSatisfiesExpression, - isSemicolonClassElement: () => isSemicolonClassElement, - isSetAccessor: () => isSetAccessor, - isSetAccessorDeclaration: () => isSetAccessorDeclaration, - isShiftOperatorOrHigher: () => isShiftOperatorOrHigher, - isShorthandAmbientModuleSymbol: () => isShorthandAmbientModuleSymbol, - isShorthandPropertyAssignment: () => isShorthandPropertyAssignment, - isSideEffectImport: () => isSideEffectImport, - isSignedNumericLiteral: () => isSignedNumericLiteral, - isSimpleCopiableExpression: () => isSimpleCopiableExpression, - isSimpleInlineableExpression: () => isSimpleInlineableExpression, - isSimpleParameterList: () => isSimpleParameterList, - isSingleOrDoubleQuote: () => isSingleOrDoubleQuote, - isSourceElement: () => isSourceElement, - isSourceFile: () => isSourceFile, - isSourceFileFromLibrary: () => isSourceFileFromLibrary, - isSourceFileJS: () => isSourceFileJS, - isSourceFileNotJson: () => isSourceFileNotJson, - isSourceMapping: () => isSourceMapping, - isSpecialPropertyDeclaration: () => isSpecialPropertyDeclaration, - isSpreadAssignment: () => isSpreadAssignment, - isSpreadElement: () => isSpreadElement, - isStatement: () => isStatement, - isStatementButNotDeclaration: () => isStatementButNotDeclaration, - isStatementOrBlock: () => isStatementOrBlock, - isStatementWithLocals: () => isStatementWithLocals, - isStatic: () => isStatic, - isStaticModifier: () => isStaticModifier, - isString: () => isString, - isStringANonContextualKeyword: () => isStringANonContextualKeyword, - isStringAndEmptyAnonymousObjectIntersection: () => isStringAndEmptyAnonymousObjectIntersection, - isStringDoubleQuoted: () => isStringDoubleQuoted, - isStringLiteral: () => isStringLiteral, - isStringLiteralLike: () => isStringLiteralLike, - isStringLiteralOrJsxExpression: () => isStringLiteralOrJsxExpression, - isStringLiteralOrTemplate: () => isStringLiteralOrTemplate, - isStringOrNumericLiteralLike: () => isStringOrNumericLiteralLike, - isStringOrRegularExpressionOrTemplateLiteral: () => isStringOrRegularExpressionOrTemplateLiteral, - isStringTextContainingNode: () => isStringTextContainingNode, - isSuperCall: () => isSuperCall, - isSuperKeyword: () => isSuperKeyword, - isSuperProperty: () => isSuperProperty, - isSupportedSourceFileName: () => isSupportedSourceFileName, - isSwitchStatement: () => isSwitchStatement, - isSyntaxList: () => isSyntaxList, - isSyntheticExpression: () => isSyntheticExpression, - isSyntheticReference: () => isSyntheticReference, - isTagName: () => isTagName, - isTaggedTemplateExpression: () => isTaggedTemplateExpression, - isTaggedTemplateTag: () => isTaggedTemplateTag, - isTemplateExpression: () => isTemplateExpression, - isTemplateHead: () => isTemplateHead, - isTemplateLiteral: () => isTemplateLiteral, - isTemplateLiteralKind: () => isTemplateLiteralKind, - isTemplateLiteralToken: () => isTemplateLiteralToken, - isTemplateLiteralTypeNode: () => isTemplateLiteralTypeNode, - isTemplateLiteralTypeSpan: () => isTemplateLiteralTypeSpan, - isTemplateMiddle: () => isTemplateMiddle, - isTemplateMiddleOrTemplateTail: () => isTemplateMiddleOrTemplateTail, - isTemplateSpan: () => isTemplateSpan, - isTemplateTail: () => isTemplateTail, - isTextWhiteSpaceLike: () => isTextWhiteSpaceLike, - isThis: () => isThis, - isThisContainerOrFunctionBlock: () => isThisContainerOrFunctionBlock, - isThisIdentifier: () => isThisIdentifier, - isThisInTypeQuery: () => isThisInTypeQuery, - isThisInitializedDeclaration: () => isThisInitializedDeclaration, - isThisInitializedObjectBindingExpression: () => isThisInitializedObjectBindingExpression, - isThisProperty: () => isThisProperty, - isThisTypeNode: () => isThisTypeNode, - isThisTypeParameter: () => isThisTypeParameter, - isThisTypePredicate: () => isThisTypePredicate, - isThrowStatement: () => isThrowStatement, - isToken: () => isToken, - isTokenKind: () => isTokenKind, - isTraceEnabled: () => isTraceEnabled, - isTransientSymbol: () => isTransientSymbol, - isTrivia: () => isTrivia, - isTryStatement: () => isTryStatement, - isTupleTypeNode: () => isTupleTypeNode, - isTypeAlias: () => isTypeAlias, - isTypeAliasDeclaration: () => isTypeAliasDeclaration, - isTypeAssertionExpression: () => isTypeAssertionExpression, - isTypeDeclaration: () => isTypeDeclaration, - isTypeElement: () => isTypeElement, - isTypeKeyword: () => isTypeKeyword, - isTypeKeywordTokenOrIdentifier: () => isTypeKeywordTokenOrIdentifier, - isTypeLiteralNode: () => isTypeLiteralNode, - isTypeNode: () => isTypeNode, - isTypeNodeKind: () => isTypeNodeKind, - isTypeOfExpression: () => isTypeOfExpression, - isTypeOnlyExportDeclaration: () => isTypeOnlyExportDeclaration, - isTypeOnlyImportDeclaration: () => isTypeOnlyImportDeclaration, - isTypeOnlyImportOrExportDeclaration: () => isTypeOnlyImportOrExportDeclaration, - isTypeOperatorNode: () => isTypeOperatorNode, - isTypeParameterDeclaration: () => isTypeParameterDeclaration, - isTypePredicateNode: () => isTypePredicateNode, - isTypeQueryNode: () => isTypeQueryNode, - isTypeReferenceNode: () => isTypeReferenceNode, - isTypeReferenceType: () => isTypeReferenceType, - isTypeUsableAsPropertyName: () => isTypeUsableAsPropertyName, - isUMDExportSymbol: () => isUMDExportSymbol, - isUnaryExpression: () => isUnaryExpression, - isUnaryExpressionWithWrite: () => isUnaryExpressionWithWrite, - isUnicodeIdentifierStart: () => isUnicodeIdentifierStart, - isUnionTypeNode: () => isUnionTypeNode, - isUrl: () => isUrl, - isValidBigIntString: () => isValidBigIntString, - isValidESSymbolDeclaration: () => isValidESSymbolDeclaration, - isValidTypeOnlyAliasUseSite: () => isValidTypeOnlyAliasUseSite, - isValueSignatureDeclaration: () => isValueSignatureDeclaration, - isVarAwaitUsing: () => isVarAwaitUsing, - isVarConst: () => isVarConst, - isVarConstLike: () => isVarConstLike, - isVarUsing: () => isVarUsing, - isVariableDeclaration: () => isVariableDeclaration, - isVariableDeclarationInVariableStatement: () => isVariableDeclarationInVariableStatement, - isVariableDeclarationInitializedToBareOrAccessedRequire: () => isVariableDeclarationInitializedToBareOrAccessedRequire, - isVariableDeclarationInitializedToRequire: () => isVariableDeclarationInitializedToRequire, - isVariableDeclarationList: () => isVariableDeclarationList, - isVariableLike: () => isVariableLike, - isVariableLikeOrAccessor: () => isVariableLikeOrAccessor, - isVariableStatement: () => isVariableStatement, - isVoidExpression: () => isVoidExpression, - isWatchSet: () => isWatchSet, - isWhileStatement: () => isWhileStatement, - isWhiteSpaceLike: () => isWhiteSpaceLike, - isWhiteSpaceSingleLine: () => isWhiteSpaceSingleLine, - isWithStatement: () => isWithStatement, - isWriteAccess: () => isWriteAccess, - isWriteOnlyAccess: () => isWriteOnlyAccess, - isYieldExpression: () => isYieldExpression, - jsxModeNeedsExplicitImport: () => jsxModeNeedsExplicitImport, - keywordPart: () => keywordPart, - last: () => last, - lastOrUndefined: () => lastOrUndefined, - length: () => length, - libMap: () => libMap, - libs: () => libs, - lineBreakPart: () => lineBreakPart, - loadModuleFromGlobalCache: () => loadModuleFromGlobalCache, - loadWithModeAwareCache: () => loadWithModeAwareCache, - makeIdentifierFromModuleName: () => makeIdentifierFromModuleName, - makeImport: () => makeImport, - makeStringLiteral: () => makeStringLiteral, - mangleScopedPackageName: () => mangleScopedPackageName, - map: () => map, - mapAllOrFail: () => mapAllOrFail, - mapDefined: () => mapDefined, - mapDefinedIterator: () => mapDefinedIterator, - mapEntries: () => mapEntries, - mapIterator: () => mapIterator, - mapOneOrMany: () => mapOneOrMany, - mapToDisplayParts: () => mapToDisplayParts, - matchFiles: () => matchFiles, - matchPatternOrExact: () => matchPatternOrExact, - matchedText: () => matchedText, - matchesExclude: () => matchesExclude, - maxBy: () => maxBy, - maybeBind: () => maybeBind, - maybeSetLocalizedDiagnosticMessages: () => maybeSetLocalizedDiagnosticMessages, - memoize: () => memoize, - memoizeOne: () => memoizeOne, - min: () => min, - minAndMax: () => minAndMax, - missingFileModifiedTime: () => missingFileModifiedTime, - modifierToFlag: () => modifierToFlag, - modifiersToFlags: () => modifiersToFlags, - moduleExportNameIsDefault: () => moduleExportNameIsDefault, - moduleExportNameTextEscaped: () => moduleExportNameTextEscaped, - moduleExportNameTextUnescaped: () => moduleExportNameTextUnescaped, - moduleOptionDeclaration: () => moduleOptionDeclaration, - moduleResolutionIsEqualTo: () => moduleResolutionIsEqualTo, - moduleResolutionNameAndModeGetter: () => moduleResolutionNameAndModeGetter, - moduleResolutionOptionDeclarations: () => moduleResolutionOptionDeclarations, - moduleResolutionSupportsPackageJsonExportsAndImports: () => moduleResolutionSupportsPackageJsonExportsAndImports, - moduleResolutionUsesNodeModules: () => moduleResolutionUsesNodeModules, - moduleSpecifierToValidIdentifier: () => moduleSpecifierToValidIdentifier, - moduleSpecifiers: () => ts_moduleSpecifiers_exports, - moduleSymbolToValidIdentifier: () => moduleSymbolToValidIdentifier, - moveEmitHelpers: () => moveEmitHelpers, - moveRangeEnd: () => moveRangeEnd, - moveRangePastDecorators: () => moveRangePastDecorators, - moveRangePastModifiers: () => moveRangePastModifiers, - moveRangePos: () => moveRangePos, - moveSyntheticComments: () => moveSyntheticComments, - mutateMap: () => mutateMap, - mutateMapSkippingNewValues: () => mutateMapSkippingNewValues, - needsParentheses: () => needsParentheses, - needsScopeMarker: () => needsScopeMarker, - newCaseClauseTracker: () => newCaseClauseTracker, - newPrivateEnvironment: () => newPrivateEnvironment, - noEmitNotification: () => noEmitNotification, - noEmitSubstitution: () => noEmitSubstitution, - noTransformers: () => noTransformers, - noTruncationMaximumTruncationLength: () => noTruncationMaximumTruncationLength, - nodeCanBeDecorated: () => nodeCanBeDecorated, - nodeHasName: () => nodeHasName, - nodeIsDecorated: () => nodeIsDecorated, - nodeIsMissing: () => nodeIsMissing, - nodeIsPresent: () => nodeIsPresent, - nodeIsSynthesized: () => nodeIsSynthesized, - nodeModuleNameResolver: () => nodeModuleNameResolver, - nodeModulesPathPart: () => nodeModulesPathPart, - nodeNextJsonConfigResolver: () => nodeNextJsonConfigResolver, - nodeOrChildIsDecorated: () => nodeOrChildIsDecorated, - nodeOverlapsWithStartEnd: () => nodeOverlapsWithStartEnd, - nodePosToString: () => nodePosToString, - nodeSeenTracker: () => nodeSeenTracker, - nodeStartsNewLexicalEnvironment: () => nodeStartsNewLexicalEnvironment, - noop: () => noop, - noopFileWatcher: () => noopFileWatcher, - normalizePath: () => normalizePath, - normalizeSlashes: () => normalizeSlashes, - normalizeSpans: () => normalizeSpans, - not: () => not, - notImplemented: () => notImplemented, - notImplementedResolver: () => notImplementedResolver, - nullNodeConverters: () => nullNodeConverters, - nullParenthesizerRules: () => nullParenthesizerRules, - nullTransformationContext: () => nullTransformationContext, - objectAllocator: () => objectAllocator, - operatorPart: () => operatorPart, - optionDeclarations: () => optionDeclarations, - optionMapToObject: () => optionMapToObject, - optionsAffectingProgramStructure: () => optionsAffectingProgramStructure, - optionsForBuild: () => optionsForBuild, - optionsForWatch: () => optionsForWatch, - optionsHaveChanges: () => optionsHaveChanges, - or: () => or, - orderedRemoveItem: () => orderedRemoveItem, - orderedRemoveItemAt: () => orderedRemoveItemAt, - packageIdToPackageName: () => packageIdToPackageName, - packageIdToString: () => packageIdToString, - parameterIsThisKeyword: () => parameterIsThisKeyword, - parameterNamePart: () => parameterNamePart, - parseBaseNodeFactory: () => parseBaseNodeFactory, - parseBigInt: () => parseBigInt, - parseBuildCommand: () => parseBuildCommand, - parseCommandLine: () => parseCommandLine, - parseCommandLineWorker: () => parseCommandLineWorker, - parseConfigFileTextToJson: () => parseConfigFileTextToJson, - parseConfigFileWithSystem: () => parseConfigFileWithSystem, - parseConfigHostFromCompilerHostLike: () => parseConfigHostFromCompilerHostLike, - parseCustomTypeOption: () => parseCustomTypeOption, - parseIsolatedEntityName: () => parseIsolatedEntityName, - parseIsolatedJSDocComment: () => parseIsolatedJSDocComment, - parseJSDocTypeExpressionForTests: () => parseJSDocTypeExpressionForTests, - parseJsonConfigFileContent: () => parseJsonConfigFileContent, - parseJsonSourceFileConfigFileContent: () => parseJsonSourceFileConfigFileContent, - parseJsonText: () => parseJsonText, - parseListTypeOption: () => parseListTypeOption, - parseNodeFactory: () => parseNodeFactory, - parseNodeModuleFromPath: () => parseNodeModuleFromPath, - parsePackageName: () => parsePackageName, - parsePseudoBigInt: () => parsePseudoBigInt, - parseValidBigInt: () => parseValidBigInt, - pasteEdits: () => ts_PasteEdits_exports, - patchWriteFileEnsuringDirectory: () => patchWriteFileEnsuringDirectory, - pathContainsNodeModules: () => pathContainsNodeModules, - pathIsAbsolute: () => pathIsAbsolute, - pathIsBareSpecifier: () => pathIsBareSpecifier, - pathIsRelative: () => pathIsRelative, - patternText: () => patternText, - performIncrementalCompilation: () => performIncrementalCompilation, - performance: () => ts_performance_exports, - positionBelongsToNode: () => positionBelongsToNode, - positionIsASICandidate: () => positionIsASICandidate, - positionIsSynthesized: () => positionIsSynthesized, - positionsAreOnSameLine: () => positionsAreOnSameLine, - preProcessFile: () => preProcessFile, - probablyUsesSemicolons: () => probablyUsesSemicolons, - processCommentPragmas: () => processCommentPragmas, - processPragmasIntoFields: () => processPragmasIntoFields, - processTaggedTemplateExpression: () => processTaggedTemplateExpression, - programContainsEsModules: () => programContainsEsModules, - programContainsModules: () => programContainsModules, - projectReferenceIsEqualTo: () => projectReferenceIsEqualTo, - propertyNamePart: () => propertyNamePart, - pseudoBigIntToString: () => pseudoBigIntToString, - punctuationPart: () => punctuationPart, - pushIfUnique: () => pushIfUnique, - quote: () => quote, - quotePreferenceFromString: () => quotePreferenceFromString, - rangeContainsPosition: () => rangeContainsPosition, - rangeContainsPositionExclusive: () => rangeContainsPositionExclusive, - rangeContainsRange: () => rangeContainsRange, - rangeContainsRangeExclusive: () => rangeContainsRangeExclusive, - rangeContainsStartEnd: () => rangeContainsStartEnd, - rangeEndIsOnSameLineAsRangeStart: () => rangeEndIsOnSameLineAsRangeStart, - rangeEndPositionsAreOnSameLine: () => rangeEndPositionsAreOnSameLine, - rangeEquals: () => rangeEquals, - rangeIsOnSingleLine: () => rangeIsOnSingleLine, - rangeOfNode: () => rangeOfNode, - rangeOfTypeParameters: () => rangeOfTypeParameters, - rangeOverlapsWithStartEnd: () => rangeOverlapsWithStartEnd, - rangeStartIsOnSameLineAsRangeEnd: () => rangeStartIsOnSameLineAsRangeEnd, - rangeStartPositionsAreOnSameLine: () => rangeStartPositionsAreOnSameLine, - readBuilderProgram: () => readBuilderProgram, - readConfigFile: () => readConfigFile, - readJson: () => readJson, - readJsonConfigFile: () => readJsonConfigFile, - readJsonOrUndefined: () => readJsonOrUndefined, - reduceEachLeadingCommentRange: () => reduceEachLeadingCommentRange, - reduceEachTrailingCommentRange: () => reduceEachTrailingCommentRange, - reduceLeft: () => reduceLeft, - reduceLeftIterator: () => reduceLeftIterator, - reducePathComponents: () => reducePathComponents, - refactor: () => ts_refactor_exports, - regExpEscape: () => regExpEscape, - regularExpressionFlagToCharacterCode: () => regularExpressionFlagToCharacterCode, - relativeComplement: () => relativeComplement, - removeAllComments: () => removeAllComments, - removeEmitHelper: () => removeEmitHelper, - removeExtension: () => removeExtension, - removeFileExtension: () => removeFileExtension, - removeIgnoredPath: () => removeIgnoredPath, - removeMinAndVersionNumbers: () => removeMinAndVersionNumbers, - removePrefix: () => removePrefix, - removeSuffix: () => removeSuffix, - removeTrailingDirectorySeparator: () => removeTrailingDirectorySeparator, - repeatString: () => repeatString, - replaceElement: () => replaceElement, - replaceFirstStar: () => replaceFirstStar, - resolutionExtensionIsTSOrJson: () => resolutionExtensionIsTSOrJson, - resolveConfigFileProjectName: () => resolveConfigFileProjectName, - resolveJSModule: () => resolveJSModule, - resolveLibrary: () => resolveLibrary, - resolveModuleName: () => resolveModuleName, - resolveModuleNameFromCache: () => resolveModuleNameFromCache, - resolvePackageNameToPackageJson: () => resolvePackageNameToPackageJson, - resolvePath: () => resolvePath, - resolveProjectReferencePath: () => resolveProjectReferencePath, - resolveTripleslashReference: () => resolveTripleslashReference, - resolveTypeReferenceDirective: () => resolveTypeReferenceDirective, - resolvingEmptyArray: () => resolvingEmptyArray, - returnFalse: () => returnFalse, - returnNoopFileWatcher: () => returnNoopFileWatcher, - returnTrue: () => returnTrue, - returnUndefined: () => returnUndefined, - returnsPromise: () => returnsPromise, - sameFlatMap: () => sameFlatMap, - sameMap: () => sameMap, - sameMapping: () => sameMapping, - scanTokenAtPosition: () => scanTokenAtPosition, - scanner: () => scanner, - semanticDiagnosticsOptionDeclarations: () => semanticDiagnosticsOptionDeclarations, - serializeCompilerOptions: () => serializeCompilerOptions, - server: () => ts_server_exports3, - servicesVersion: () => servicesVersion, - setCommentRange: () => setCommentRange, - setConfigFileInOptions: () => setConfigFileInOptions, - setConstantValue: () => setConstantValue, - setEmitFlags: () => setEmitFlags, - setGetSourceFileAsHashVersioned: () => setGetSourceFileAsHashVersioned, - setIdentifierAutoGenerate: () => setIdentifierAutoGenerate, - setIdentifierGeneratedImportReference: () => setIdentifierGeneratedImportReference, - setIdentifierTypeArguments: () => setIdentifierTypeArguments, - setInternalEmitFlags: () => setInternalEmitFlags, - setLocalizedDiagnosticMessages: () => setLocalizedDiagnosticMessages, - setNodeChildren: () => setNodeChildren, - setNodeFlags: () => setNodeFlags, - setObjectAllocator: () => setObjectAllocator, - setOriginalNode: () => setOriginalNode, - setParent: () => setParent, - setParentRecursive: () => setParentRecursive, - setPrivateIdentifier: () => setPrivateIdentifier, - setSnippetElement: () => setSnippetElement, - setSourceMapRange: () => setSourceMapRange, - setStackTraceLimit: () => setStackTraceLimit, - setStartsOnNewLine: () => setStartsOnNewLine, - setSyntheticLeadingComments: () => setSyntheticLeadingComments, - setSyntheticTrailingComments: () => setSyntheticTrailingComments, - setSys: () => setSys, - setSysLog: () => setSysLog, - setTextRange: () => setTextRange, - setTextRangeEnd: () => setTextRangeEnd, - setTextRangePos: () => setTextRangePos, - setTextRangePosEnd: () => setTextRangePosEnd, - setTextRangePosWidth: () => setTextRangePosWidth, - setTokenSourceMapRange: () => setTokenSourceMapRange, - setTypeNode: () => setTypeNode, - setUILocale: () => setUILocale, - setValueDeclaration: () => setValueDeclaration, - shouldAllowImportingTsExtension: () => shouldAllowImportingTsExtension, - shouldPreserveConstEnums: () => shouldPreserveConstEnums, - shouldUseUriStyleNodeCoreModules: () => shouldUseUriStyleNodeCoreModules, - showModuleSpecifier: () => showModuleSpecifier, - signatureHasRestParameter: () => signatureHasRestParameter, - signatureToDisplayParts: () => signatureToDisplayParts, - single: () => single, - singleElementArray: () => singleElementArray, - singleIterator: () => singleIterator, - singleOrMany: () => singleOrMany, - singleOrUndefined: () => singleOrUndefined, - skipAlias: () => skipAlias, - skipConstraint: () => skipConstraint, - skipOuterExpressions: () => skipOuterExpressions, - skipParentheses: () => skipParentheses, - skipPartiallyEmittedExpressions: () => skipPartiallyEmittedExpressions, - skipTrivia: () => skipTrivia, - skipTypeChecking: () => skipTypeChecking, - skipTypeCheckingIgnoringNoCheck: () => skipTypeCheckingIgnoringNoCheck, - skipTypeParentheses: () => skipTypeParentheses, - skipWhile: () => skipWhile, - sliceAfter: () => sliceAfter, - some: () => some, - sortAndDeduplicate: () => sortAndDeduplicate, - sortAndDeduplicateDiagnostics: () => sortAndDeduplicateDiagnostics, - sourceFileAffectingCompilerOptions: () => sourceFileAffectingCompilerOptions, - sourceFileMayBeEmitted: () => sourceFileMayBeEmitted, - sourceMapCommentRegExp: () => sourceMapCommentRegExp, - sourceMapCommentRegExpDontCareLineStart: () => sourceMapCommentRegExpDontCareLineStart, - spacePart: () => spacePart, - spanMap: () => spanMap, - startEndContainsRange: () => startEndContainsRange, - startEndOverlapsWithStartEnd: () => startEndOverlapsWithStartEnd, - startOnNewLine: () => startOnNewLine, - startTracing: () => startTracing, - startsWith: () => startsWith, - startsWithDirectory: () => startsWithDirectory, - startsWithUnderscore: () => startsWithUnderscore, - startsWithUseStrict: () => startsWithUseStrict, - stringContainsAt: () => stringContainsAt, - stringToToken: () => stringToToken, - stripQuotes: () => stripQuotes, - supportedDeclarationExtensions: () => supportedDeclarationExtensions, - supportedJSExtensionsFlat: () => supportedJSExtensionsFlat, - supportedLocaleDirectories: () => supportedLocaleDirectories, - supportedTSExtensionsFlat: () => supportedTSExtensionsFlat, - supportedTSImplementationExtensions: () => supportedTSImplementationExtensions, - suppressLeadingAndTrailingTrivia: () => suppressLeadingAndTrailingTrivia, - suppressLeadingTrivia: () => suppressLeadingTrivia, - suppressTrailingTrivia: () => suppressTrailingTrivia, - symbolEscapedNameNoDefault: () => symbolEscapedNameNoDefault, - symbolName: () => symbolName, - symbolNameNoDefault: () => symbolNameNoDefault, - symbolToDisplayParts: () => symbolToDisplayParts, - sys: () => sys, - sysLog: () => sysLog, - tagNamesAreEquivalent: () => tagNamesAreEquivalent, - takeWhile: () => takeWhile, - targetOptionDeclaration: () => targetOptionDeclaration, - testFormatSettings: () => testFormatSettings, - textChangeRangeIsUnchanged: () => textChangeRangeIsUnchanged, - textChangeRangeNewSpan: () => textChangeRangeNewSpan, - textChanges: () => ts_textChanges_exports, - textOrKeywordPart: () => textOrKeywordPart, - textPart: () => textPart, - textRangeContainsPositionInclusive: () => textRangeContainsPositionInclusive, - textRangeContainsTextSpan: () => textRangeContainsTextSpan, - textRangeIntersectsWithTextSpan: () => textRangeIntersectsWithTextSpan, - textSpanContainsPosition: () => textSpanContainsPosition, - textSpanContainsTextRange: () => textSpanContainsTextRange, - textSpanContainsTextSpan: () => textSpanContainsTextSpan, - textSpanEnd: () => textSpanEnd, - textSpanIntersection: () => textSpanIntersection, - textSpanIntersectsWith: () => textSpanIntersectsWith, - textSpanIntersectsWithPosition: () => textSpanIntersectsWithPosition, - textSpanIntersectsWithTextSpan: () => textSpanIntersectsWithTextSpan, - textSpanIsEmpty: () => textSpanIsEmpty, - textSpanOverlap: () => textSpanOverlap, - textSpanOverlapsWith: () => textSpanOverlapsWith, - textSpansEqual: () => textSpansEqual, - textToKeywordObj: () => textToKeywordObj, - timestamp: () => timestamp, - toArray: () => toArray, - toBuilderFileEmit: () => toBuilderFileEmit, - toBuilderStateFileInfoForMultiEmit: () => toBuilderStateFileInfoForMultiEmit, - toEditorSettings: () => toEditorSettings, - toFileNameLowerCase: () => toFileNameLowerCase, - toPath: () => toPath, - toProgramEmitPending: () => toProgramEmitPending, - toSorted: () => toSorted, - tokenIsIdentifierOrKeyword: () => tokenIsIdentifierOrKeyword, - tokenIsIdentifierOrKeywordOrGreaterThan: () => tokenIsIdentifierOrKeywordOrGreaterThan, - tokenToString: () => tokenToString, - trace: () => trace, - tracing: () => tracing, - tracingEnabled: () => tracingEnabled, - transferSourceFileChildren: () => transferSourceFileChildren, - transform: () => transform, - transformClassFields: () => transformClassFields, - transformDeclarations: () => transformDeclarations, - transformECMAScriptModule: () => transformECMAScriptModule, - transformES2015: () => transformES2015, - transformES2016: () => transformES2016, - transformES2017: () => transformES2017, - transformES2018: () => transformES2018, - transformES2019: () => transformES2019, - transformES2020: () => transformES2020, - transformES2021: () => transformES2021, - transformESDecorators: () => transformESDecorators, - transformESNext: () => transformESNext, - transformGenerators: () => transformGenerators, - transformImpliedNodeFormatDependentModule: () => transformImpliedNodeFormatDependentModule, - transformJsx: () => transformJsx, - transformLegacyDecorators: () => transformLegacyDecorators, - transformModule: () => transformModule, - transformNamedEvaluation: () => transformNamedEvaluation, - transformNodes: () => transformNodes, - transformSystemModule: () => transformSystemModule, - transformTypeScript: () => transformTypeScript, - transpile: () => transpile, - transpileDeclaration: () => transpileDeclaration, - transpileModule: () => transpileModule, - transpileOptionValueCompilerOptions: () => transpileOptionValueCompilerOptions, - tryAddToSet: () => tryAddToSet, - tryAndIgnoreErrors: () => tryAndIgnoreErrors, - tryCast: () => tryCast, - tryDirectoryExists: () => tryDirectoryExists, - tryExtractTSExtension: () => tryExtractTSExtension, - tryFileExists: () => tryFileExists, - tryGetClassExtendingExpressionWithTypeArguments: () => tryGetClassExtendingExpressionWithTypeArguments, - tryGetClassImplementingOrExtendingExpressionWithTypeArguments: () => tryGetClassImplementingOrExtendingExpressionWithTypeArguments, - tryGetDirectories: () => tryGetDirectories, - tryGetExtensionFromPath: () => tryGetExtensionFromPath2, - tryGetImportFromModuleSpecifier: () => tryGetImportFromModuleSpecifier, - tryGetJSDocSatisfiesTypeNode: () => tryGetJSDocSatisfiesTypeNode, - tryGetModuleNameFromFile: () => tryGetModuleNameFromFile, - tryGetModuleSpecifierFromDeclaration: () => tryGetModuleSpecifierFromDeclaration, - tryGetNativePerformanceHooks: () => tryGetNativePerformanceHooks, - tryGetPropertyAccessOrIdentifierToString: () => tryGetPropertyAccessOrIdentifierToString, - tryGetPropertyNameOfBindingOrAssignmentElement: () => tryGetPropertyNameOfBindingOrAssignmentElement, - tryGetSourceMappingURL: () => tryGetSourceMappingURL, - tryGetTextOfPropertyName: () => tryGetTextOfPropertyName, - tryParseJson: () => tryParseJson, - tryParsePattern: () => tryParsePattern, - tryParsePatterns: () => tryParsePatterns, - tryParseRawSourceMap: () => tryParseRawSourceMap, - tryReadDirectory: () => tryReadDirectory, - tryReadFile: () => tryReadFile, - tryRemoveDirectoryPrefix: () => tryRemoveDirectoryPrefix, - tryRemoveExtension: () => tryRemoveExtension, - tryRemovePrefix: () => tryRemovePrefix, - tryRemoveSuffix: () => tryRemoveSuffix, - typeAcquisitionDeclarations: () => typeAcquisitionDeclarations, - typeAliasNamePart: () => typeAliasNamePart, - typeDirectiveIsEqualTo: () => typeDirectiveIsEqualTo, - typeKeywords: () => typeKeywords, - typeParameterNamePart: () => typeParameterNamePart, - typeToDisplayParts: () => typeToDisplayParts, - unchangedPollThresholds: () => unchangedPollThresholds, - unchangedTextChangeRange: () => unchangedTextChangeRange, - unescapeLeadingUnderscores: () => unescapeLeadingUnderscores, - unmangleScopedPackageName: () => unmangleScopedPackageName, - unorderedRemoveItem: () => unorderedRemoveItem, - unreachableCodeIsError: () => unreachableCodeIsError, - unsetNodeChildren: () => unsetNodeChildren, - unusedLabelIsError: () => unusedLabelIsError, - unwrapInnermostStatementOfLabel: () => unwrapInnermostStatementOfLabel, - unwrapParenthesizedExpression: () => unwrapParenthesizedExpression, - updateErrorForNoInputFiles: () => updateErrorForNoInputFiles, - updateLanguageServiceSourceFile: () => updateLanguageServiceSourceFile, - updateMissingFilePathsWatch: () => updateMissingFilePathsWatch, - updateResolutionField: () => updateResolutionField, - updateSharedExtendedConfigFileWatcher: () => updateSharedExtendedConfigFileWatcher, - updateSourceFile: () => updateSourceFile, - updateWatchingWildcardDirectories: () => updateWatchingWildcardDirectories, - usingSingleLineStringWriter: () => usingSingleLineStringWriter, - utf16EncodeAsString: () => utf16EncodeAsString, - validateLocaleAndSetLanguage: () => validateLocaleAndSetLanguage, - version: () => version, - versionMajorMinor: () => versionMajorMinor, - visitArray: () => visitArray, - visitCommaListElements: () => visitCommaListElements, - visitEachChild: () => visitEachChild, - visitFunctionBody: () => visitFunctionBody, - visitIterationBody: () => visitIterationBody, - visitLexicalEnvironment: () => visitLexicalEnvironment, - visitNode: () => visitNode, - visitNodes: () => visitNodes2, - visitParameterList: () => visitParameterList, - walkUpBindingElementsAndPatterns: () => walkUpBindingElementsAndPatterns, - walkUpOuterExpressions: () => walkUpOuterExpressions, - walkUpParenthesizedExpressions: () => walkUpParenthesizedExpressions, - walkUpParenthesizedTypes: () => walkUpParenthesizedTypes, - walkUpParenthesizedTypesAndGetParentAndChild: () => walkUpParenthesizedTypesAndGetParentAndChild, - whitespaceOrMapCommentRegExp: () => whitespaceOrMapCommentRegExp, - writeCommentRange: () => writeCommentRange, - writeFile: () => writeFile, - writeFileEnsuringDirectories: () => writeFileEnsuringDirectories, - zipWith: () => zipWith -}); - -// src/deprecatedCompat/deprecate.ts -var enableDeprecationWarnings = true; -var typeScriptVersion2; -function getTypeScriptVersion() { - return typeScriptVersion2 ?? (typeScriptVersion2 = new Version(version)); -} -function formatDeprecationMessage(name, error2, errorAfter, since, message) { - let deprecationMessage = error2 ? "DeprecationError: " : "DeprecationWarning: "; - deprecationMessage += `'${name}' `; - deprecationMessage += since ? `has been deprecated since v${since}` : "is deprecated"; - deprecationMessage += error2 ? " and can no longer be used." : errorAfter ? ` and will no longer be usable after v${errorAfter}.` : "."; - deprecationMessage += message ? ` ${formatStringFromArgs(message, [name])}` : ""; - return deprecationMessage; -} -function createErrorDeprecation(name, errorAfter, since, message) { - const deprecationMessage = formatDeprecationMessage( - name, - /*error*/ - true, - errorAfter, - since, - message - ); - return () => { - throw new TypeError(deprecationMessage); - }; -} -function createWarningDeprecation(name, errorAfter, since, message) { - let hasWrittenDeprecation = false; - return () => { - if (enableDeprecationWarnings && !hasWrittenDeprecation) { - Debug.log.warn(formatDeprecationMessage( - name, - /*error*/ - false, - errorAfter, - since, - message - )); - hasWrittenDeprecation = true; - } - }; -} -function createDeprecation(name, options = {}) { - const version2 = typeof options.typeScriptVersion === "string" ? new Version(options.typeScriptVersion) : options.typeScriptVersion ?? getTypeScriptVersion(); - const errorAfter = typeof options.errorAfter === "string" ? new Version(options.errorAfter) : options.errorAfter; - const warnAfter = typeof options.warnAfter === "string" ? new Version(options.warnAfter) : options.warnAfter; - const since = typeof options.since === "string" ? new Version(options.since) : options.since ?? warnAfter; - const error2 = options.error || errorAfter && version2.compareTo(errorAfter) >= 0; - const warn = !warnAfter || version2.compareTo(warnAfter) >= 0; - return error2 ? createErrorDeprecation(name, errorAfter, since, options.message) : warn ? createWarningDeprecation(name, errorAfter, since, options.message) : noop; -} -function wrapFunction(deprecation, func) { - return function() { - deprecation(); - return func.apply(this, arguments); - }; -} -function deprecate(func, options) { - const deprecation = createDeprecation((options == null ? void 0 : options.name) ?? Debug.getFunctionName(func), options); - return wrapFunction(deprecation, func); -} - -// src/deprecatedCompat/deprecations.ts -function createOverload(name, overloads, binder2, deprecations) { - Object.defineProperty(call, "name", { ...Object.getOwnPropertyDescriptor(call, "name"), value: name }); - if (deprecations) { - for (const key of Object.keys(deprecations)) { - const index = +key; - if (!isNaN(index) && hasProperty(overloads, `${index}`)) { - overloads[index] = deprecate(overloads[index], { ...deprecations[index], name }); - } - } - } - const bind = createBinder2(overloads, binder2); - return call; - function call(...args) { - const index = bind(args); - const fn = index !== void 0 ? overloads[index] : void 0; - if (typeof fn === "function") { - return fn(...args); - } - throw new TypeError("Invalid arguments"); - } -} -function createBinder2(overloads, binder2) { - return (args) => { - for (let i = 0; hasProperty(overloads, `${i}`) && hasProperty(binder2, `${i}`); i++) { - const fn = binder2[i]; - if (fn(args)) { - return i; - } - } - }; -} -function buildOverload(name) { - return { - overload: (overloads) => ({ - bind: (binder2) => ({ - finish: () => createOverload(name, overloads, binder2), - deprecate: (deprecations) => ({ - finish: () => createOverload(name, overloads, binder2, deprecations) - }) - }) - }) - }; -} - -// src/server/_namespaces/ts.server.ts -var ts_server_exports3 = {}; -__export(ts_server_exports3, { - ActionInvalidate: () => ActionInvalidate, - ActionPackageInstalled: () => ActionPackageInstalled, - ActionSet: () => ActionSet, - ActionWatchTypingLocations: () => ActionWatchTypingLocations, - Arguments: () => Arguments, - AutoImportProviderProject: () => AutoImportProviderProject, - AuxiliaryProject: () => AuxiliaryProject, - CharRangeSection: () => CharRangeSection, - CloseFileWatcherEvent: () => CloseFileWatcherEvent, - CommandNames: () => CommandNames, - ConfigFileDiagEvent: () => ConfigFileDiagEvent, - ConfiguredProject: () => ConfiguredProject2, - ConfiguredProjectLoadKind: () => ConfiguredProjectLoadKind, - CreateDirectoryWatcherEvent: () => CreateDirectoryWatcherEvent, - CreateFileWatcherEvent: () => CreateFileWatcherEvent, - Errors: () => Errors, - EventBeginInstallTypes: () => EventBeginInstallTypes, - EventEndInstallTypes: () => EventEndInstallTypes, - EventInitializationFailed: () => EventInitializationFailed, - EventTypesRegistry: () => EventTypesRegistry, - ExternalProject: () => ExternalProject, - GcTimer: () => GcTimer, - InferredProject: () => InferredProject2, - LargeFileReferencedEvent: () => LargeFileReferencedEvent, - LineIndex: () => LineIndex, - LineLeaf: () => LineLeaf, - LineNode: () => LineNode, - LogLevel: () => LogLevel2, - Msg: () => Msg, - OpenFileInfoTelemetryEvent: () => OpenFileInfoTelemetryEvent, - Project: () => Project2, - ProjectInfoTelemetryEvent: () => ProjectInfoTelemetryEvent, - ProjectKind: () => ProjectKind, - ProjectLanguageServiceStateEvent: () => ProjectLanguageServiceStateEvent, - ProjectLoadingFinishEvent: () => ProjectLoadingFinishEvent, - ProjectLoadingStartEvent: () => ProjectLoadingStartEvent, - ProjectService: () => ProjectService2, - ProjectsUpdatedInBackgroundEvent: () => ProjectsUpdatedInBackgroundEvent, - ScriptInfo: () => ScriptInfo, - ScriptVersionCache: () => ScriptVersionCache, - Session: () => Session3, - TextStorage: () => TextStorage, - ThrottledOperations: () => ThrottledOperations, - TypingsInstallerAdapter: () => TypingsInstallerAdapter, - allFilesAreJsOrDts: () => allFilesAreJsOrDts, - allRootFilesAreJsOrDts: () => allRootFilesAreJsOrDts, - asNormalizedPath: () => asNormalizedPath, - convertCompilerOptions: () => convertCompilerOptions, - convertFormatOptions: () => convertFormatOptions, - convertScriptKindName: () => convertScriptKindName, - convertTypeAcquisition: () => convertTypeAcquisition, - convertUserPreferences: () => convertUserPreferences, - convertWatchOptions: () => convertWatchOptions, - countEachFileTypes: () => countEachFileTypes, - createInstallTypingsRequest: () => createInstallTypingsRequest, - createModuleSpecifierCache: () => createModuleSpecifierCache, - createNormalizedPathMap: () => createNormalizedPathMap, - createPackageJsonCache: () => createPackageJsonCache, - createSortedArray: () => createSortedArray2, - emptyArray: () => emptyArray2, - findArgument: () => findArgument, - formatDiagnosticToProtocol: () => formatDiagnosticToProtocol, - formatMessage: () => formatMessage2, - getBaseConfigFileName: () => getBaseConfigFileName, - getLocationInNewDocument: () => getLocationInNewDocument, - hasArgument: () => hasArgument, - hasNoTypeScriptSource: () => hasNoTypeScriptSource, - indent: () => indent2, - isBackgroundProject: () => isBackgroundProject, - isConfigFile: () => isConfigFile, - isConfiguredProject: () => isConfiguredProject, - isDynamicFileName: () => isDynamicFileName, - isExternalProject: () => isExternalProject, - isInferredProject: () => isInferredProject, - isInferredProjectName: () => isInferredProjectName, - isProjectDeferredClose: () => isProjectDeferredClose, - makeAutoImportProviderProjectName: () => makeAutoImportProviderProjectName, - makeAuxiliaryProjectName: () => makeAuxiliaryProjectName, - makeInferredProjectName: () => makeInferredProjectName, - maxFileSize: () => maxFileSize, - maxProgramSizeForNonTsFiles: () => maxProgramSizeForNonTsFiles, - normalizedPathToPath: () => normalizedPathToPath, - nowString: () => nowString, - nullCancellationToken: () => nullCancellationToken, - nullTypingsInstaller: () => nullTypingsInstaller, - protocol: () => ts_server_protocol_exports, - stringifyIndented: () => stringifyIndented, - toEvent: () => toEvent, - toNormalizedPath: () => toNormalizedPath, - tryConvertScriptKindName: () => tryConvertScriptKindName, - typingsInstaller: () => ts_server_typingsInstaller_exports, - updateProjectIfDirty: () => updateProjectIfDirty -}); - -// src/typingsInstallerCore/_namespaces/ts.server.typingsInstaller.ts -var ts_server_typingsInstaller_exports = {}; -__export(ts_server_typingsInstaller_exports, { - TypingsInstaller: () => TypingsInstaller, - getNpmCommandForInstallation: () => getNpmCommandForInstallation, - installNpmPackages: () => installNpmPackages, - typingsName: () => typingsName -}); - -// src/typingsInstallerCore/typingsInstaller.ts -var nullLog = { - isEnabled: () => false, - writeLine: noop -}; -function typingToFileName(cachePath, packageName, installTypingHost, log) { - try { - const result = resolveModuleName(packageName, combinePaths(cachePath, "index.d.ts"), { moduleResolution: 2 /* Node10 */ }, installTypingHost); - return result.resolvedModule && result.resolvedModule.resolvedFileName; - } catch (e) { - if (log.isEnabled()) { - log.writeLine(`Failed to resolve ${packageName} in folder '${cachePath}': ${e.message}`); - } - return void 0; - } -} -function installNpmPackages(npmPath, tsVersion, packageNames, install) { - let hasError = false; - for (let remaining = packageNames.length; remaining > 0; ) { - const result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining); - remaining = result.remaining; - hasError = install(result.command) || hasError; - } - return hasError; -} -function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining) { - const sliceStart = packageNames.length - remaining; - let command, toSlice = remaining; - while (true) { - command = `${npmPath} install --ignore-scripts ${(toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" ")} --save-dev --user-agent="typesInstaller/${tsVersion}"`; - if (command.length < 8e3) { - break; - } - toSlice = toSlice - Math.floor(toSlice / 2); - } - return { command, remaining: remaining - toSlice }; -} -var TypingsInstaller = class { - constructor(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log = nullLog) { - this.installTypingHost = installTypingHost; - this.globalCachePath = globalCachePath; - this.safeListPath = safeListPath; - this.typesMapLocation = typesMapLocation; - this.throttleLimit = throttleLimit; - this.log = log; - this.packageNameToTypingLocation = /* @__PURE__ */ new Map(); - this.missingTypingsSet = /* @__PURE__ */ new Set(); - this.knownCachesSet = /* @__PURE__ */ new Set(); - this.projectWatchers = /* @__PURE__ */ new Map(); - this.pendingRunRequests = []; - this.installRunCount = 1; - this.inFlightRequestCount = 0; - // eslint-disable-line @typescript-eslint/unified-signatures - this.latestDistTag = "latest"; - const isLoggingEnabled = this.log.isEnabled(); - if (isLoggingEnabled) { - this.log.writeLine(`Global cache location '${globalCachePath}', safe file path '${safeListPath}', types map path ${typesMapLocation}`); - } - this.processCacheLocation(this.globalCachePath); - } - /** @internal */ - handleRequest(req) { - switch (req.kind) { - case "discover": - this.install(req); - break; - case "closeProject": - this.closeProject(req); - break; - case "typesRegistry": { - const typesRegistry = {}; - this.typesRegistry.forEach((value, key) => { - typesRegistry[key] = value; - }); - const response = { kind: EventTypesRegistry, typesRegistry }; - this.sendResponse(response); - break; - } - case "installPackage": { - this.installPackage(req); - break; - } - default: - Debug.assertNever(req); - } - } - closeProject(req) { - this.closeWatchers(req.projectName); - } - closeWatchers(projectName) { - if (this.log.isEnabled()) { - this.log.writeLine(`Closing file watchers for project '${projectName}'`); - } - const watchers = this.projectWatchers.get(projectName); - if (!watchers) { - if (this.log.isEnabled()) { - this.log.writeLine(`No watchers are registered for project '${projectName}'`); - } - return; - } - this.projectWatchers.delete(projectName); - this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files: [] }); - if (this.log.isEnabled()) { - this.log.writeLine(`Closing file watchers for project '${projectName}' - done.`); - } - } - install(req) { - if (this.log.isEnabled()) { - this.log.writeLine(`Got install request${stringifyIndented(req)}`); - } - if (req.cachePath) { - if (this.log.isEnabled()) { - this.log.writeLine(`Request specifies cache path '${req.cachePath}', loading cached information...`); - } - this.processCacheLocation(req.cachePath); - } - if (this.safeList === void 0) { - this.initializeSafeList(); - } - const discoverTypingsResult = ts_JsTyping_exports.discoverTypings( - this.installTypingHost, - this.log.isEnabled() ? (s) => this.log.writeLine(s) : void 0, - req.fileNames, - req.projectRootPath, - this.safeList, - this.packageNameToTypingLocation, - req.typeAcquisition, - req.unresolvedImports, - this.typesRegistry, - req.compilerOptions - ); - this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch); - if (discoverTypingsResult.newTypingNames.length) { - this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames); - } else { - this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths)); - if (this.log.isEnabled()) { - this.log.writeLine(`No new typings were requested as a result of typings discovery`); - } - } - } - /** @internal */ - installPackage(req) { - const { fileName, packageName, projectName, projectRootPath, id } = req; - const cwd = forEachAncestorDirectory(getDirectoryPath(fileName), (directory) => { - if (this.installTypingHost.fileExists(combinePaths(directory, "package.json"))) { - return directory; - } - }) || projectRootPath; - if (cwd) { - this.installWorker(-1, [packageName], cwd, (success) => { - const message = success ? `Package ${packageName} installed.` : `There was an error installing ${packageName}.`; - const response = { - kind: ActionPackageInstalled, - projectName, - id, - success, - message - }; - this.sendResponse(response); - }); - } else { - const response = { - kind: ActionPackageInstalled, - projectName, - id, - success: false, - message: "Could not determine a project root path." - }; - this.sendResponse(response); - } - } - initializeSafeList() { - if (this.typesMapLocation) { - const safeListFromMap = ts_JsTyping_exports.loadTypesMap(this.installTypingHost, this.typesMapLocation); - if (safeListFromMap) { - this.log.writeLine(`Loaded safelist from types map file '${this.typesMapLocation}'`); - this.safeList = safeListFromMap; - return; - } - this.log.writeLine(`Failed to load safelist from types map file '${this.typesMapLocation}'`); - } - this.safeList = ts_JsTyping_exports.loadSafeList(this.installTypingHost, this.safeListPath); - } - processCacheLocation(cacheLocation) { - if (this.log.isEnabled()) { - this.log.writeLine(`Processing cache location '${cacheLocation}'`); - } - if (this.knownCachesSet.has(cacheLocation)) { - if (this.log.isEnabled()) { - this.log.writeLine(`Cache location was already processed...`); - } - return; - } - const packageJson = combinePaths(cacheLocation, "package.json"); - const packageLockJson = combinePaths(cacheLocation, "package-lock.json"); - if (this.log.isEnabled()) { - this.log.writeLine(`Trying to find '${packageJson}'...`); - } - if (this.installTypingHost.fileExists(packageJson) && this.installTypingHost.fileExists(packageLockJson)) { - const npmConfig = JSON.parse(this.installTypingHost.readFile(packageJson)); - const npmLock = JSON.parse(this.installTypingHost.readFile(packageLockJson)); - if (this.log.isEnabled()) { - this.log.writeLine(`Loaded content of '${packageJson}':${stringifyIndented(npmConfig)}`); - this.log.writeLine(`Loaded content of '${packageLockJson}':${stringifyIndented(npmLock)}`); - } - if (npmConfig.devDependencies && npmLock.dependencies) { - for (const key in npmConfig.devDependencies) { - if (!hasProperty(npmLock.dependencies, key)) { - continue; - } - const packageName = getBaseFileName(key); - if (!packageName) { - continue; - } - const typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log); - if (!typingFile) { - this.missingTypingsSet.add(packageName); - continue; - } - const existingTypingFile = this.packageNameToTypingLocation.get(packageName); - if (existingTypingFile) { - if (existingTypingFile.typingLocation === typingFile) { - continue; - } - if (this.log.isEnabled()) { - this.log.writeLine(`New typing for package ${packageName} from '${typingFile}' conflicts with existing typing file '${existingTypingFile}'`); - } - } - if (this.log.isEnabled()) { - this.log.writeLine(`Adding entry into typings cache: '${packageName}' => '${typingFile}'`); - } - const info = getProperty(npmLock.dependencies, key); - const version2 = info && info.version; - if (!version2) { - continue; - } - const newTyping = { typingLocation: typingFile, version: new Version(version2) }; - this.packageNameToTypingLocation.set(packageName, newTyping); - } - } - } - if (this.log.isEnabled()) { - this.log.writeLine(`Finished processing cache location '${cacheLocation}'`); - } - this.knownCachesSet.add(cacheLocation); - } - filterTypings(typingsToInstall) { - return mapDefined(typingsToInstall, (typing) => { - const typingKey = mangleScopedPackageName(typing); - if (this.missingTypingsSet.has(typingKey)) { - if (this.log.isEnabled()) this.log.writeLine(`'${typing}':: '${typingKey}' is in missingTypingsSet - skipping...`); - return void 0; - } - const validationResult = ts_JsTyping_exports.validatePackageName(typing); - if (validationResult !== ts_JsTyping_exports.NameValidationResult.Ok) { - this.missingTypingsSet.add(typingKey); - if (this.log.isEnabled()) this.log.writeLine(ts_JsTyping_exports.renderPackageNameValidationFailure(validationResult, typing)); - return void 0; - } - if (!this.typesRegistry.has(typingKey)) { - if (this.log.isEnabled()) this.log.writeLine(`'${typing}':: Entry for package '${typingKey}' does not exist in local types registry - skipping...`); - return void 0; - } - if (this.packageNameToTypingLocation.get(typingKey) && ts_JsTyping_exports.isTypingUpToDate(this.packageNameToTypingLocation.get(typingKey), this.typesRegistry.get(typingKey))) { - if (this.log.isEnabled()) this.log.writeLine(`'${typing}':: '${typingKey}' already has an up-to-date typing - skipping...`); - return void 0; - } - return typingKey; - }); - } - ensurePackageDirectoryExists(directory) { - const npmConfigPath = combinePaths(directory, "package.json"); - if (this.log.isEnabled()) { - this.log.writeLine(`Npm config file: ${npmConfigPath}`); - } - if (!this.installTypingHost.fileExists(npmConfigPath)) { - if (this.log.isEnabled()) { - this.log.writeLine(`Npm config file: '${npmConfigPath}' is missing, creating new one...`); - } - this.ensureDirectoryExists(directory, this.installTypingHost); - this.installTypingHost.writeFile(npmConfigPath, '{ "private": true }'); - } - } - installTypings(req, cachePath, currentlyCachedTypings, typingsToInstall) { - if (this.log.isEnabled()) { - this.log.writeLine(`Installing typings ${JSON.stringify(typingsToInstall)}`); - } - const filteredTypings = this.filterTypings(typingsToInstall); - if (filteredTypings.length === 0) { - if (this.log.isEnabled()) { - this.log.writeLine(`All typings are known to be missing or invalid - no need to install more typings`); - } - this.sendResponse(this.createSetTypings(req, currentlyCachedTypings)); - return; - } - this.ensurePackageDirectoryExists(cachePath); - const requestId = this.installRunCount; - this.installRunCount++; - this.sendResponse({ - kind: EventBeginInstallTypes, - eventId: requestId, - typingsInstallerVersion: version, - projectName: req.projectName - }); - const scopedTypings = filteredTypings.map(typingsName); - this.installTypingsAsync(requestId, scopedTypings, cachePath, (ok) => { - try { - if (!ok) { - if (this.log.isEnabled()) { - this.log.writeLine(`install request failed, marking packages as missing to prevent repeated requests: ${JSON.stringify(filteredTypings)}`); - } - for (const typing of filteredTypings) { - this.missingTypingsSet.add(typing); - } - return; - } - if (this.log.isEnabled()) { - this.log.writeLine(`Installed typings ${JSON.stringify(scopedTypings)}`); - } - const installedTypingFiles = []; - for (const packageName of filteredTypings) { - const typingFile = typingToFileName(cachePath, packageName, this.installTypingHost, this.log); - if (!typingFile) { - this.missingTypingsSet.add(packageName); - continue; - } - const distTags = this.typesRegistry.get(packageName); - const newVersion = new Version(distTags[`ts${versionMajorMinor}`] || distTags[this.latestDistTag]); - const newTyping = { typingLocation: typingFile, version: newVersion }; - this.packageNameToTypingLocation.set(packageName, newTyping); - installedTypingFiles.push(typingFile); - } - if (this.log.isEnabled()) { - this.log.writeLine(`Installed typing files ${JSON.stringify(installedTypingFiles)}`); - } - this.sendResponse(this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles))); - } finally { - const response = { - kind: EventEndInstallTypes, - eventId: requestId, - projectName: req.projectName, - packagesToInstall: scopedTypings, - installSuccess: ok, - typingsInstallerVersion: version - }; - this.sendResponse(response); - } - }); - } - ensureDirectoryExists(directory, host) { - const directoryName = getDirectoryPath(directory); - if (!host.directoryExists(directoryName)) { - this.ensureDirectoryExists(directoryName, host); - } - if (!host.directoryExists(directory)) { - host.createDirectory(directory); - } - } - watchFiles(projectName, files) { - if (!files.length) { - this.closeWatchers(projectName); - return; - } - const existing = this.projectWatchers.get(projectName); - const newSet = new Set(files); - if (!existing || forEachKey(newSet, (s) => !existing.has(s)) || forEachKey(existing, (s) => !newSet.has(s))) { - this.projectWatchers.set(projectName, newSet); - this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files }); - } else { - this.sendResponse({ kind: ActionWatchTypingLocations, projectName, files: void 0 }); - } - } - createSetTypings(request, typings) { - return { - projectName: request.projectName, - typeAcquisition: request.typeAcquisition, - compilerOptions: request.compilerOptions, - typings, - unresolvedImports: request.unresolvedImports, - kind: ActionSet - }; - } - installTypingsAsync(requestId, packageNames, cwd, onRequestCompleted) { - this.pendingRunRequests.unshift({ requestId, packageNames, cwd, onRequestCompleted }); - this.executeWithThrottling(); - } - executeWithThrottling() { - while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) { - this.inFlightRequestCount++; - const request = this.pendingRunRequests.pop(); - this.installWorker(request.requestId, request.packageNames, request.cwd, (ok) => { - this.inFlightRequestCount--; - request.onRequestCompleted(ok); - this.executeWithThrottling(); - }); - } - } -}; -function typingsName(packageName) { - return `@types/${packageName}@ts${versionMajorMinor}`; -} - -// src/server/utilitiesPublic.ts -var LogLevel2 = /* @__PURE__ */ ((LogLevel3) => { - LogLevel3[LogLevel3["terse"] = 0] = "terse"; - LogLevel3[LogLevel3["normal"] = 1] = "normal"; - LogLevel3[LogLevel3["requestTime"] = 2] = "requestTime"; - LogLevel3[LogLevel3["verbose"] = 3] = "verbose"; - return LogLevel3; -})(LogLevel2 || {}); -var emptyArray2 = createSortedArray2(); -var Msg = /* @__PURE__ */ ((Msg2) => { - Msg2["Err"] = "Err"; - Msg2["Info"] = "Info"; - Msg2["Perf"] = "Perf"; - return Msg2; -})(Msg || {}); -function createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, cachePath) { - return { - projectName: project.getProjectName(), - fileNames: project.getFileNames( - /*excludeFilesFromExternalLibraries*/ - true, - /*excludeConfigFiles*/ - true - ).concat(project.getExcludedFiles()), - compilerOptions: project.getCompilationSettings(), - typeAcquisition, - unresolvedImports, - projectRootPath: project.getCurrentDirectory(), - cachePath, - kind: "discover" - }; -} -var Errors; -((Errors2) => { - function ThrowNoProject() { - throw new Error("No Project."); - } - Errors2.ThrowNoProject = ThrowNoProject; - function ThrowProjectLanguageServiceDisabled() { - throw new Error("The project's language service is disabled."); - } - Errors2.ThrowProjectLanguageServiceDisabled = ThrowProjectLanguageServiceDisabled; - function ThrowProjectDoesNotContainDocument(fileName, project) { - throw new Error(`Project '${project.getProjectName()}' does not contain document '${fileName}'`); - } - Errors2.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument; -})(Errors || (Errors = {})); -function toNormalizedPath(fileName) { - return normalizePath(fileName); -} -function normalizedPathToPath(normalizedPath, currentDirectory, getCanonicalFileName) { - const f = isRootedDiskPath(normalizedPath) ? normalizedPath : getNormalizedAbsolutePath(normalizedPath, currentDirectory); - return getCanonicalFileName(f); -} -function asNormalizedPath(fileName) { - return fileName; -} -function createNormalizedPathMap() { - const map2 = /* @__PURE__ */ new Map(); - return { - get(path) { - return map2.get(path); - }, - set(path, value) { - map2.set(path, value); - }, - contains(path) { - return map2.has(path); - }, - remove(path) { - map2.delete(path); - } - }; -} -function isInferredProjectName(name) { - return /dev\/null\/inferredProject\d+\*/.test(name); -} -function makeInferredProjectName(counter) { - return `/dev/null/inferredProject${counter}*`; -} -function makeAutoImportProviderProjectName(counter) { - return `/dev/null/autoImportProviderProject${counter}*`; -} -function makeAuxiliaryProjectName(counter) { - return `/dev/null/auxiliaryProject${counter}*`; -} -function createSortedArray2() { - return []; -} - -// src/server/utilities.ts -var ThrottledOperations = class _ThrottledOperations { - constructor(host, logger) { - this.host = host; - this.pendingTimeouts = /* @__PURE__ */ new Map(); - this.logger = logger.hasLevel(3 /* verbose */) ? logger : void 0; - } - /** - * Wait `number` milliseconds and then invoke `cb`. If, while waiting, schedule - * is called again with the same `operationId`, cancel this operation in favor - * of the new one. (Note that the amount of time the canceled operation had been - * waiting does not affect the amount of time that the new operation waits.) - */ - schedule(operationId, delay, cb) { - const pendingTimeout = this.pendingTimeouts.get(operationId); - if (pendingTimeout) { - this.host.clearTimeout(pendingTimeout); - } - this.pendingTimeouts.set(operationId, this.host.setTimeout(_ThrottledOperations.run, delay, operationId, this, cb)); - if (this.logger) { - this.logger.info(`Scheduled: ${operationId}${pendingTimeout ? ", Cancelled earlier one" : ""}`); - } - } - cancel(operationId) { - const pendingTimeout = this.pendingTimeouts.get(operationId); - if (!pendingTimeout) return false; - this.host.clearTimeout(pendingTimeout); - return this.pendingTimeouts.delete(operationId); - } - static run(operationId, self, cb) { - self.pendingTimeouts.delete(operationId); - if (self.logger) { - self.logger.info(`Running: ${operationId}`); - } - cb(); - } -}; -var GcTimer = class _GcTimer { - constructor(host, delay, logger) { - this.host = host; - this.delay = delay; - this.logger = logger; - } - scheduleCollect() { - if (!this.host.gc || this.timerId !== void 0) { - return; - } - this.timerId = this.host.setTimeout(_GcTimer.run, this.delay, this); - } - static run(self) { - self.timerId = void 0; - const log = self.logger.hasLevel(2 /* requestTime */); - const before = log && self.host.getMemoryUsage(); - self.host.gc(); - if (log) { - const after = self.host.getMemoryUsage(); - self.logger.perftrc(`GC::before ${before}, after ${after}`); - } - } -}; -function getBaseConfigFileName(configFilePath) { - const base = getBaseFileName(configFilePath); - return base === "tsconfig.json" || base === "jsconfig.json" ? base : void 0; -} - -// src/server/_namespaces/ts.server.protocol.ts -var ts_server_protocol_exports = {}; -__export(ts_server_protocol_exports, { - ClassificationType: () => ClassificationType, - CommandTypes: () => CommandTypes, - CompletionTriggerKind: () => CompletionTriggerKind, - IndentStyle: () => IndentStyle2, - JsxEmit: () => JsxEmit2, - ModuleKind: () => ModuleKind2, - ModuleResolutionKind: () => ModuleResolutionKind2, - NewLineKind: () => NewLineKind2, - OrganizeImportsMode: () => OrganizeImportsMode, - PollingWatchKind: () => PollingWatchKind2, - ScriptTarget: () => ScriptTarget11, - SemicolonPreference: () => SemicolonPreference, - WatchDirectoryKind: () => WatchDirectoryKind2, - WatchFileKind: () => WatchFileKind2 -}); - -// src/server/protocol.ts -var CommandTypes = /* @__PURE__ */ ((CommandTypes2) => { - CommandTypes2["JsxClosingTag"] = "jsxClosingTag"; - CommandTypes2["LinkedEditingRange"] = "linkedEditingRange"; - CommandTypes2["Brace"] = "brace"; - CommandTypes2["BraceFull"] = "brace-full"; - CommandTypes2["BraceCompletion"] = "braceCompletion"; - CommandTypes2["GetSpanOfEnclosingComment"] = "getSpanOfEnclosingComment"; - CommandTypes2["Change"] = "change"; - CommandTypes2["Close"] = "close"; - CommandTypes2["Completions"] = "completions"; - CommandTypes2["CompletionInfo"] = "completionInfo"; - CommandTypes2["CompletionsFull"] = "completions-full"; - CommandTypes2["CompletionDetails"] = "completionEntryDetails"; - CommandTypes2["CompletionDetailsFull"] = "completionEntryDetails-full"; - CommandTypes2["CompileOnSaveAffectedFileList"] = "compileOnSaveAffectedFileList"; - CommandTypes2["CompileOnSaveEmitFile"] = "compileOnSaveEmitFile"; - CommandTypes2["Configure"] = "configure"; - CommandTypes2["Definition"] = "definition"; - CommandTypes2["DefinitionFull"] = "definition-full"; - CommandTypes2["DefinitionAndBoundSpan"] = "definitionAndBoundSpan"; - CommandTypes2["DefinitionAndBoundSpanFull"] = "definitionAndBoundSpan-full"; - CommandTypes2["Implementation"] = "implementation"; - CommandTypes2["ImplementationFull"] = "implementation-full"; - CommandTypes2["EmitOutput"] = "emit-output"; - CommandTypes2["Exit"] = "exit"; - CommandTypes2["FileReferences"] = "fileReferences"; - CommandTypes2["FileReferencesFull"] = "fileReferences-full"; - CommandTypes2["Format"] = "format"; - CommandTypes2["Formatonkey"] = "formatonkey"; - CommandTypes2["FormatFull"] = "format-full"; - CommandTypes2["FormatonkeyFull"] = "formatonkey-full"; - CommandTypes2["FormatRangeFull"] = "formatRange-full"; - CommandTypes2["Geterr"] = "geterr"; - CommandTypes2["GeterrForProject"] = "geterrForProject"; - CommandTypes2["SemanticDiagnosticsSync"] = "semanticDiagnosticsSync"; - CommandTypes2["SyntacticDiagnosticsSync"] = "syntacticDiagnosticsSync"; - CommandTypes2["SuggestionDiagnosticsSync"] = "suggestionDiagnosticsSync"; - CommandTypes2["NavBar"] = "navbar"; - CommandTypes2["NavBarFull"] = "navbar-full"; - CommandTypes2["Navto"] = "navto"; - CommandTypes2["NavtoFull"] = "navto-full"; - CommandTypes2["NavTree"] = "navtree"; - CommandTypes2["NavTreeFull"] = "navtree-full"; - CommandTypes2["DocumentHighlights"] = "documentHighlights"; - CommandTypes2["DocumentHighlightsFull"] = "documentHighlights-full"; - CommandTypes2["Open"] = "open"; - CommandTypes2["Quickinfo"] = "quickinfo"; - CommandTypes2["QuickinfoFull"] = "quickinfo-full"; - CommandTypes2["References"] = "references"; - CommandTypes2["ReferencesFull"] = "references-full"; - CommandTypes2["Reload"] = "reload"; - CommandTypes2["Rename"] = "rename"; - CommandTypes2["RenameInfoFull"] = "rename-full"; - CommandTypes2["RenameLocationsFull"] = "renameLocations-full"; - CommandTypes2["Saveto"] = "saveto"; - CommandTypes2["SignatureHelp"] = "signatureHelp"; - CommandTypes2["SignatureHelpFull"] = "signatureHelp-full"; - CommandTypes2["FindSourceDefinition"] = "findSourceDefinition"; - CommandTypes2["Status"] = "status"; - CommandTypes2["TypeDefinition"] = "typeDefinition"; - CommandTypes2["ProjectInfo"] = "projectInfo"; - CommandTypes2["ReloadProjects"] = "reloadProjects"; - CommandTypes2["Unknown"] = "unknown"; - CommandTypes2["OpenExternalProject"] = "openExternalProject"; - CommandTypes2["OpenExternalProjects"] = "openExternalProjects"; - CommandTypes2["CloseExternalProject"] = "closeExternalProject"; - CommandTypes2["SynchronizeProjectList"] = "synchronizeProjectList"; - CommandTypes2["ApplyChangedToOpenFiles"] = "applyChangedToOpenFiles"; - CommandTypes2["UpdateOpen"] = "updateOpen"; - CommandTypes2["EncodedSyntacticClassificationsFull"] = "encodedSyntacticClassifications-full"; - CommandTypes2["EncodedSemanticClassificationsFull"] = "encodedSemanticClassifications-full"; - CommandTypes2["Cleanup"] = "cleanup"; - CommandTypes2["GetOutliningSpans"] = "getOutliningSpans"; - CommandTypes2["GetOutliningSpansFull"] = "outliningSpans"; - CommandTypes2["TodoComments"] = "todoComments"; - CommandTypes2["Indentation"] = "indentation"; - CommandTypes2["DocCommentTemplate"] = "docCommentTemplate"; - CommandTypes2["CompilerOptionsDiagnosticsFull"] = "compilerOptionsDiagnostics-full"; - CommandTypes2["NameOrDottedNameSpan"] = "nameOrDottedNameSpan"; - CommandTypes2["BreakpointStatement"] = "breakpointStatement"; - CommandTypes2["CompilerOptionsForInferredProjects"] = "compilerOptionsForInferredProjects"; - CommandTypes2["GetCodeFixes"] = "getCodeFixes"; - CommandTypes2["GetCodeFixesFull"] = "getCodeFixes-full"; - CommandTypes2["GetCombinedCodeFix"] = "getCombinedCodeFix"; - CommandTypes2["GetCombinedCodeFixFull"] = "getCombinedCodeFix-full"; - CommandTypes2["ApplyCodeActionCommand"] = "applyCodeActionCommand"; - CommandTypes2["GetSupportedCodeFixes"] = "getSupportedCodeFixes"; - CommandTypes2["GetApplicableRefactors"] = "getApplicableRefactors"; - CommandTypes2["GetEditsForRefactor"] = "getEditsForRefactor"; - CommandTypes2["GetMoveToRefactoringFileSuggestions"] = "getMoveToRefactoringFileSuggestions"; - CommandTypes2["GetPasteEdits"] = "getPasteEdits"; - CommandTypes2["GetEditsForRefactorFull"] = "getEditsForRefactor-full"; - CommandTypes2["OrganizeImports"] = "organizeImports"; - CommandTypes2["OrganizeImportsFull"] = "organizeImports-full"; - CommandTypes2["GetEditsForFileRename"] = "getEditsForFileRename"; - CommandTypes2["GetEditsForFileRenameFull"] = "getEditsForFileRename-full"; - CommandTypes2["ConfigurePlugin"] = "configurePlugin"; - CommandTypes2["SelectionRange"] = "selectionRange"; - CommandTypes2["SelectionRangeFull"] = "selectionRange-full"; - CommandTypes2["ToggleLineComment"] = "toggleLineComment"; - CommandTypes2["ToggleLineCommentFull"] = "toggleLineComment-full"; - CommandTypes2["ToggleMultilineComment"] = "toggleMultilineComment"; - CommandTypes2["ToggleMultilineCommentFull"] = "toggleMultilineComment-full"; - CommandTypes2["CommentSelection"] = "commentSelection"; - CommandTypes2["CommentSelectionFull"] = "commentSelection-full"; - CommandTypes2["UncommentSelection"] = "uncommentSelection"; - CommandTypes2["UncommentSelectionFull"] = "uncommentSelection-full"; - CommandTypes2["PrepareCallHierarchy"] = "prepareCallHierarchy"; - CommandTypes2["ProvideCallHierarchyIncomingCalls"] = "provideCallHierarchyIncomingCalls"; - CommandTypes2["ProvideCallHierarchyOutgoingCalls"] = "provideCallHierarchyOutgoingCalls"; - CommandTypes2["ProvideInlayHints"] = "provideInlayHints"; - CommandTypes2["WatchChange"] = "watchChange"; - CommandTypes2["MapCode"] = "mapCode"; - return CommandTypes2; -})(CommandTypes || {}); -var WatchFileKind2 = /* @__PURE__ */ ((WatchFileKind3) => { - WatchFileKind3["FixedPollingInterval"] = "FixedPollingInterval"; - WatchFileKind3["PriorityPollingInterval"] = "PriorityPollingInterval"; - WatchFileKind3["DynamicPriorityPolling"] = "DynamicPriorityPolling"; - WatchFileKind3["FixedChunkSizePolling"] = "FixedChunkSizePolling"; - WatchFileKind3["UseFsEvents"] = "UseFsEvents"; - WatchFileKind3["UseFsEventsOnParentDirectory"] = "UseFsEventsOnParentDirectory"; - return WatchFileKind3; -})(WatchFileKind2 || {}); -var WatchDirectoryKind2 = /* @__PURE__ */ ((WatchDirectoryKind3) => { - WatchDirectoryKind3["UseFsEvents"] = "UseFsEvents"; - WatchDirectoryKind3["FixedPollingInterval"] = "FixedPollingInterval"; - WatchDirectoryKind3["DynamicPriorityPolling"] = "DynamicPriorityPolling"; - WatchDirectoryKind3["FixedChunkSizePolling"] = "FixedChunkSizePolling"; - return WatchDirectoryKind3; -})(WatchDirectoryKind2 || {}); -var PollingWatchKind2 = /* @__PURE__ */ ((PollingWatchKind3) => { - PollingWatchKind3["FixedInterval"] = "FixedInterval"; - PollingWatchKind3["PriorityInterval"] = "PriorityInterval"; - PollingWatchKind3["DynamicPriority"] = "DynamicPriority"; - PollingWatchKind3["FixedChunkSize"] = "FixedChunkSize"; - return PollingWatchKind3; -})(PollingWatchKind2 || {}); -var IndentStyle2 = /* @__PURE__ */ ((IndentStyle3) => { - IndentStyle3["None"] = "None"; - IndentStyle3["Block"] = "Block"; - IndentStyle3["Smart"] = "Smart"; - return IndentStyle3; -})(IndentStyle2 || {}); -var JsxEmit2 = /* @__PURE__ */ ((JsxEmit3) => { - JsxEmit3["None"] = "none"; - JsxEmit3["Preserve"] = "preserve"; - JsxEmit3["ReactNative"] = "react-native"; - JsxEmit3["React"] = "react"; - JsxEmit3["ReactJSX"] = "react-jsx"; - JsxEmit3["ReactJSXDev"] = "react-jsxdev"; - return JsxEmit3; -})(JsxEmit2 || {}); -var ModuleKind2 = /* @__PURE__ */ ((ModuleKind3) => { - ModuleKind3["None"] = "none"; - ModuleKind3["CommonJS"] = "commonjs"; - ModuleKind3["AMD"] = "amd"; - ModuleKind3["UMD"] = "umd"; - ModuleKind3["System"] = "system"; - ModuleKind3["ES6"] = "es6"; - ModuleKind3["ES2015"] = "es2015"; - ModuleKind3["ES2020"] = "es2020"; - ModuleKind3["ES2022"] = "es2022"; - ModuleKind3["ESNext"] = "esnext"; - ModuleKind3["Node16"] = "node16"; - ModuleKind3["NodeNext"] = "nodenext"; - ModuleKind3["Preserve"] = "preserve"; - return ModuleKind3; -})(ModuleKind2 || {}); -var ModuleResolutionKind2 = /* @__PURE__ */ ((ModuleResolutionKind3) => { - ModuleResolutionKind3["Classic"] = "classic"; - ModuleResolutionKind3["Node"] = "node"; - ModuleResolutionKind3["NodeJs"] = "node"; - ModuleResolutionKind3["Node10"] = "node10"; - ModuleResolutionKind3["Node16"] = "node16"; - ModuleResolutionKind3["NodeNext"] = "nodenext"; - ModuleResolutionKind3["Bundler"] = "bundler"; - return ModuleResolutionKind3; -})(ModuleResolutionKind2 || {}); -var NewLineKind2 = /* @__PURE__ */ ((NewLineKind3) => { - NewLineKind3["Crlf"] = "Crlf"; - NewLineKind3["Lf"] = "Lf"; - return NewLineKind3; -})(NewLineKind2 || {}); -var ScriptTarget11 = /* @__PURE__ */ ((ScriptTarget12) => { - ScriptTarget12["ES3"] = "es3"; - ScriptTarget12["ES5"] = "es5"; - ScriptTarget12["ES6"] = "es6"; - ScriptTarget12["ES2015"] = "es2015"; - ScriptTarget12["ES2016"] = "es2016"; - ScriptTarget12["ES2017"] = "es2017"; - ScriptTarget12["ES2018"] = "es2018"; - ScriptTarget12["ES2019"] = "es2019"; - ScriptTarget12["ES2020"] = "es2020"; - ScriptTarget12["ES2021"] = "es2021"; - ScriptTarget12["ES2022"] = "es2022"; - ScriptTarget12["ES2023"] = "es2023"; - ScriptTarget12["ESNext"] = "esnext"; - ScriptTarget12["JSON"] = "json"; - ScriptTarget12["Latest"] = "esnext" /* ESNext */; - return ScriptTarget12; -})(ScriptTarget11 || {}); -{ -} - -// src/server/scriptInfo.ts -var TextStorage = class { - constructor(host, info, initialVersion) { - this.host = host; - this.info = info; - /** - * True if the text is for the file thats open in the editor - */ - this.isOpen = false; - /** - * True if the text present is the text from the file on the disk - */ - this.ownFileText = false; - /** - * True when reloading contents of file from the disk is pending - */ - this.pendingReloadFromDisk = false; - this.version = initialVersion || 0; - } - getVersion() { - return this.svc ? `SVC-${this.version}-${this.svc.getSnapshotVersion()}` : `Text-${this.version}`; - } - hasScriptVersionCache_TestOnly() { - return this.svc !== void 0; - } - resetSourceMapInfo() { - this.info.sourceFileLike = void 0; - this.info.closeSourceMapFileWatcher(); - this.info.sourceMapFilePath = void 0; - this.info.declarationInfoPath = void 0; - this.info.sourceInfos = void 0; - this.info.documentPositionMapper = void 0; - } - /** Public for testing */ - useText(newText) { - this.svc = void 0; - this.text = newText; - this.textSnapshot = void 0; - this.lineMap = void 0; - this.fileSize = void 0; - this.resetSourceMapInfo(); - this.version++; - } - edit(start, end, newText) { - this.switchToScriptVersionCache().edit(start, end - start, newText); - this.ownFileText = false; - this.text = void 0; - this.textSnapshot = void 0; - this.lineMap = void 0; - this.fileSize = void 0; - this.resetSourceMapInfo(); - } - /** - * Set the contents as newText - * returns true if text changed - */ - reload(newText) { - Debug.assert(newText !== void 0); - this.pendingReloadFromDisk = false; - if (!this.text && this.svc) { - this.text = getSnapshotText(this.svc.getSnapshot()); - } - if (this.text !== newText) { - this.useText(newText); - this.ownFileText = false; - return true; - } - return false; - } - /** - * Reads the contents from tempFile(if supplied) or own file and sets it as contents - * returns true if text changed - */ - reloadWithFileText(tempFileName) { - const { text: newText, fileSize } = tempFileName || !this.info.isDynamicOrHasMixedContent() ? this.getFileTextAndSize(tempFileName) : { text: "", fileSize: void 0 }; - const reloaded = this.reload(newText); - this.fileSize = fileSize; - this.ownFileText = !tempFileName || tempFileName === this.info.fileName; - if (this.ownFileText && this.info.mTime === missingFileModifiedTime.getTime()) { - this.info.mTime = (this.host.getModifiedTime(this.info.fileName) || missingFileModifiedTime).getTime(); - } - return reloaded; - } - /** - * Schedule reload from the disk if its not already scheduled and its not own text - * returns true when scheduling reload - */ - scheduleReloadIfNeeded() { - return !this.pendingReloadFromDisk && !this.ownFileText ? this.pendingReloadFromDisk = true : false; - } - delayReloadFromFileIntoText() { - this.pendingReloadFromDisk = true; - } - /** - * For telemetry purposes, we would like to be able to report the size of the file. - * However, we do not want telemetry to require extra file I/O so we report a size - * that may be stale (e.g. may not reflect change made on disk since the last reload). - * NB: Will read from disk if the file contents have never been loaded because - * telemetry falsely indicating size 0 would be counter-productive. - */ - getTelemetryFileSize() { - return !!this.fileSize ? this.fileSize : !!this.text ? this.text.length : !!this.svc ? this.svc.getSnapshot().getLength() : this.getSnapshot().getLength(); - } - getSnapshot() { - var _a; - return ((_a = this.tryUseScriptVersionCache()) == null ? void 0 : _a.getSnapshot()) || (this.textSnapshot ?? (this.textSnapshot = ScriptSnapshot.fromString(Debug.checkDefined(this.text)))); - } - getAbsolutePositionAndLineText(oneBasedLine) { - const svc = this.tryUseScriptVersionCache(); - if (svc) return svc.getAbsolutePositionAndLineText(oneBasedLine); - const lineMap = this.getLineMap(); - return oneBasedLine <= lineMap.length ? { - absolutePosition: lineMap[oneBasedLine - 1], - lineText: this.text.substring(lineMap[oneBasedLine - 1], lineMap[oneBasedLine]) - } : { - absolutePosition: this.text.length, - lineText: void 0 - }; - } - /** - * @param line 0 based index - */ - lineToTextSpan(line) { - const svc = this.tryUseScriptVersionCache(); - if (svc) return svc.lineToTextSpan(line); - const lineMap = this.getLineMap(); - const start = lineMap[line]; - const end = line + 1 < lineMap.length ? lineMap[line + 1] : this.text.length; - return createTextSpanFromBounds(start, end); - } - /** - * @param line 1 based index - * @param offset 1 based index - */ - lineOffsetToPosition(line, offset, allowEdits) { - const svc = this.tryUseScriptVersionCache(); - return svc ? svc.lineOffsetToPosition(line, offset) : computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text, allowEdits); - } - positionToLineOffset(position) { - const svc = this.tryUseScriptVersionCache(); - if (svc) return svc.positionToLineOffset(position); - const { line, character } = computeLineAndCharacterOfPosition(this.getLineMap(), position); - return { line: line + 1, offset: character + 1 }; - } - getFileTextAndSize(tempFileName) { - let text; - const fileName = tempFileName || this.info.fileName; - const getText = () => text === void 0 ? text = this.host.readFile(fileName) || "" : text; - if (!hasTSFileExtension(this.info.fileName)) { - const fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; - if (fileSize > maxFileSize) { - Debug.assert(!!this.info.containingProjects.length); - const service = this.info.containingProjects[0].projectService; - service.logger.info(`Skipped loading contents of large file ${fileName} for info ${this.info.fileName}: fileSize: ${fileSize}`); - this.info.containingProjects[0].projectService.sendLargeFileReferencedEvent(fileName, fileSize); - return { text: "", fileSize }; - } - } - return { text: getText() }; - } - /** @internal */ - switchToScriptVersionCache() { - if (!this.svc || this.pendingReloadFromDisk) { - this.svc = ScriptVersionCache.fromString(this.getOrLoadText()); - this.textSnapshot = void 0; - this.version++; - } - return this.svc; - } - tryUseScriptVersionCache() { - if (!this.svc || this.pendingReloadFromDisk) { - this.getOrLoadText(); - } - if (this.isOpen) { - if (!this.svc && !this.textSnapshot) { - this.svc = ScriptVersionCache.fromString(Debug.checkDefined(this.text)); - this.textSnapshot = void 0; - } - return this.svc; - } - return this.svc; - } - getOrLoadText() { - if (this.text === void 0 || this.pendingReloadFromDisk) { - Debug.assert(!this.svc || this.pendingReloadFromDisk, "ScriptVersionCache should not be set when reloading from disk"); - this.reloadWithFileText(); - } - return this.text; - } - getLineMap() { - Debug.assert(!this.svc, "ScriptVersionCache should not be set"); - return this.lineMap || (this.lineMap = computeLineStarts(Debug.checkDefined(this.text))); - } - getLineInfo() { - const svc = this.tryUseScriptVersionCache(); - if (svc) { - return { - getLineCount: () => svc.getLineCount(), - getLineText: (line) => svc.getAbsolutePositionAndLineText(line + 1).lineText - }; - } - const lineMap = this.getLineMap(); - return getLineInfo(this.text, lineMap); - } -}; -function isDynamicFileName(fileName) { - return fileName[0] === "^" || (fileName.includes("walkThroughSnippet:/") || fileName.includes("untitled:/")) && getBaseFileName(fileName)[0] === "^" || fileName.includes(":^") && !fileName.includes(directorySeparator); -} -var ScriptInfo = class { - constructor(host, fileName, scriptKind, hasMixedContent, path, initialVersion) { - this.host = host; - this.fileName = fileName; - this.scriptKind = scriptKind; - this.hasMixedContent = hasMixedContent; - this.path = path; - /** - * All projects that include this file - */ - this.containingProjects = []; - this.isDynamic = isDynamicFileName(fileName); - this.textStorage = new TextStorage(host, this, initialVersion); - if (hasMixedContent || this.isDynamic) { - this.realpath = this.path; - } - this.scriptKind = scriptKind ? scriptKind : getScriptKindFromFileName(fileName); - } - /** @internal */ - isDynamicOrHasMixedContent() { - return this.hasMixedContent || this.isDynamic; - } - isScriptOpen() { - return this.textStorage.isOpen; - } - open(newText) { - this.textStorage.isOpen = true; - if (newText !== void 0 && this.textStorage.reload(newText)) { - this.markContainingProjectsAsDirty(); - } - } - close(fileExists = true) { - this.textStorage.isOpen = false; - if (fileExists && this.textStorage.scheduleReloadIfNeeded()) { - this.markContainingProjectsAsDirty(); - } - } - getSnapshot() { - return this.textStorage.getSnapshot(); - } - ensureRealPath() { - if (this.realpath === void 0) { - this.realpath = this.path; - if (this.host.realpath) { - Debug.assert(!!this.containingProjects.length); - const project = this.containingProjects[0]; - const realpath = this.host.realpath(this.path); - if (realpath) { - this.realpath = project.toPath(realpath); - if (this.realpath !== this.path) { - project.projectService.realpathToScriptInfos.add(this.realpath, this); - } - } - } - } - } - /** @internal */ - getRealpathIfDifferent() { - return this.realpath && this.realpath !== this.path ? this.realpath : void 0; - } - /** - * @internal - * Does not compute realpath; uses precomputed result. Use `ensureRealPath` - * first if a definite result is needed. - */ - isSymlink() { - return this.realpath && this.realpath !== this.path; - } - getFormatCodeSettings() { - return this.formatSettings; - } - getPreferences() { - return this.preferences; - } - attachToProject(project) { - const isNew = !this.isAttached(project); - if (isNew) { - this.containingProjects.push(project); - if (!project.getCompilerOptions().preserveSymlinks) { - this.ensureRealPath(); - } - project.onFileAddedOrRemoved(this.isSymlink()); - } - return isNew; - } - isAttached(project) { - switch (this.containingProjects.length) { - case 0: - return false; - case 1: - return this.containingProjects[0] === project; - case 2: - return this.containingProjects[0] === project || this.containingProjects[1] === project; - default: - return contains(this.containingProjects, project); - } - } - detachFromProject(project) { - switch (this.containingProjects.length) { - case 0: - return; - case 1: - if (this.containingProjects[0] === project) { - project.onFileAddedOrRemoved(this.isSymlink()); - this.containingProjects.pop(); - } - break; - case 2: - if (this.containingProjects[0] === project) { - project.onFileAddedOrRemoved(this.isSymlink()); - this.containingProjects[0] = this.containingProjects.pop(); - } else if (this.containingProjects[1] === project) { - project.onFileAddedOrRemoved(this.isSymlink()); - this.containingProjects.pop(); - } - break; - default: - if (orderedRemoveItem(this.containingProjects, project)) { - project.onFileAddedOrRemoved(this.isSymlink()); - } - break; - } - } - detachAllProjects() { - for (const p of this.containingProjects) { - if (isConfiguredProject(p)) { - p.getCachedDirectoryStructureHost().addOrDeleteFile(this.fileName, this.path, 2 /* Deleted */); - } - const existingRoot = p.getRootFilesMap().get(this.path); - p.removeFile( - this, - /*fileExists*/ - false, - /*detachFromProject*/ - false - ); - p.onFileAddedOrRemoved(this.isSymlink()); - if (existingRoot && !isInferredProject(p)) { - p.addMissingFileRoot(existingRoot.fileName); - } - } - clear(this.containingProjects); - } - getDefaultProject() { - switch (this.containingProjects.length) { - case 0: - return Errors.ThrowNoProject(); - case 1: - return isProjectDeferredClose(this.containingProjects[0]) || isBackgroundProject(this.containingProjects[0]) ? Errors.ThrowNoProject() : this.containingProjects[0]; - default: - let firstConfiguredProject; - let firstInferredProject; - let firstNonSourceOfProjectReferenceRedirect; - let defaultConfiguredProject; - for (let index = 0; index < this.containingProjects.length; index++) { - const project = this.containingProjects[index]; - if (isConfiguredProject(project)) { - if (project.deferredClose) continue; - if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) { - if (defaultConfiguredProject === void 0 && index !== this.containingProjects.length - 1) { - defaultConfiguredProject = project.projectService.findDefaultConfiguredProject(this) || false; - } - if (defaultConfiguredProject === project) return project; - if (!firstNonSourceOfProjectReferenceRedirect) firstNonSourceOfProjectReferenceRedirect = project; - } - if (!firstConfiguredProject) firstConfiguredProject = project; - } else if (isExternalProject(project)) { - return project; - } else if (!firstInferredProject && isInferredProject(project)) { - firstInferredProject = project; - } - } - return (defaultConfiguredProject || firstNonSourceOfProjectReferenceRedirect || firstConfiguredProject || firstInferredProject) ?? Errors.ThrowNoProject(); - } - } - registerFileUpdate() { - for (const p of this.containingProjects) { - p.registerFileUpdate(this.path); - } - } - setOptions(formatSettings, preferences) { - if (formatSettings) { - if (!this.formatSettings) { - this.formatSettings = getDefaultFormatCodeSettings(this.host.newLine); - assign(this.formatSettings, formatSettings); - } else { - this.formatSettings = { ...this.formatSettings, ...formatSettings }; - } - } - if (preferences) { - if (!this.preferences) { - this.preferences = emptyOptions; - } - this.preferences = { ...this.preferences, ...preferences }; - } - } - getLatestVersion() { - this.textStorage.getSnapshot(); - return this.textStorage.getVersion(); - } - saveTo(fileName) { - this.host.writeFile(fileName, getSnapshotText(this.textStorage.getSnapshot())); - } - /** @internal */ - delayReloadNonMixedContentFile() { - Debug.assert(!this.isDynamicOrHasMixedContent()); - this.textStorage.delayReloadFromFileIntoText(); - this.markContainingProjectsAsDirty(); - } - reloadFromFile(tempFileName) { - if (this.textStorage.reloadWithFileText(tempFileName)) { - this.markContainingProjectsAsDirty(); - return true; - } - return false; - } - editContent(start, end, newText) { - this.textStorage.edit(start, end, newText); - this.markContainingProjectsAsDirty(); - } - markContainingProjectsAsDirty() { - for (const p of this.containingProjects) { - p.markFileAsDirty(this.path); - } - } - isOrphan() { - return this.deferredDelete || !forEach(this.containingProjects, (p) => !p.isOrphan()); - } - /** @internal */ - isContainedByBackgroundProject() { - return some( - this.containingProjects, - isBackgroundProject - ); - } - /** - * @param line 1 based index - */ - lineToTextSpan(line) { - return this.textStorage.lineToTextSpan(line); - } - // eslint-disable-line @typescript-eslint/unified-signatures - lineOffsetToPosition(line, offset, allowEdits) { - return this.textStorage.lineOffsetToPosition(line, offset, allowEdits); - } - positionToLineOffset(position) { - failIfInvalidPosition(position); - const location = this.textStorage.positionToLineOffset(position); - failIfInvalidLocation(location); - return location; - } - isJavaScript() { - return this.scriptKind === 1 /* JS */ || this.scriptKind === 2 /* JSX */; - } - /** @internal */ - closeSourceMapFileWatcher() { - if (this.sourceMapFilePath && !isString(this.sourceMapFilePath)) { - closeFileWatcherOf(this.sourceMapFilePath); - this.sourceMapFilePath = void 0; - } - } -}; -function failIfInvalidPosition(position) { - Debug.assert(typeof position === "number", `Expected position ${position} to be a number.`); - Debug.assert(position >= 0, `Expected position to be non-negative.`); -} -function failIfInvalidLocation(location) { - Debug.assert(typeof location.line === "number", `Expected line ${location.line} to be a number.`); - Debug.assert(typeof location.offset === "number", `Expected offset ${location.offset} to be a number.`); - 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"}`); -} - -// src/server/project.ts -var ProjectKind = /* @__PURE__ */ ((ProjectKind2) => { - ProjectKind2[ProjectKind2["Inferred"] = 0] = "Inferred"; - ProjectKind2[ProjectKind2["Configured"] = 1] = "Configured"; - ProjectKind2[ProjectKind2["External"] = 2] = "External"; - ProjectKind2[ProjectKind2["AutoImportProvider"] = 3] = "AutoImportProvider"; - ProjectKind2[ProjectKind2["Auxiliary"] = 4] = "Auxiliary"; - return ProjectKind2; -})(ProjectKind || {}); -function countEachFileTypes(infos, includeSizes = false) { - const result = { - js: 0, - jsSize: 0, - jsx: 0, - jsxSize: 0, - ts: 0, - tsSize: 0, - tsx: 0, - tsxSize: 0, - dts: 0, - dtsSize: 0, - deferred: 0, - deferredSize: 0 - }; - for (const info of infos) { - const fileSize = includeSizes ? info.textStorage.getTelemetryFileSize() : 0; - switch (info.scriptKind) { - case 1 /* JS */: - result.js += 1; - result.jsSize += fileSize; - break; - case 2 /* JSX */: - result.jsx += 1; - result.jsxSize += fileSize; - break; - case 3 /* TS */: - if (isDeclarationFileName(info.fileName)) { - result.dts += 1; - result.dtsSize += fileSize; - } else { - result.ts += 1; - result.tsSize += fileSize; - } - break; - case 4 /* TSX */: - result.tsx += 1; - result.tsxSize += fileSize; - break; - case 7 /* Deferred */: - result.deferred += 1; - result.deferredSize += fileSize; - break; - } - } - return result; -} -function hasOneOrMoreJsAndNoTsFiles(project) { - const counts2 = countEachFileTypes(project.getScriptInfos()); - return counts2.js > 0 && counts2.ts === 0 && counts2.tsx === 0; -} -function allRootFilesAreJsOrDts(project) { - const counts2 = countEachFileTypes(project.getRootScriptInfos()); - return counts2.ts === 0 && counts2.tsx === 0; -} -function allFilesAreJsOrDts(project) { - const counts2 = countEachFileTypes(project.getScriptInfos()); - return counts2.ts === 0 && counts2.tsx === 0; -} -function hasNoTypeScriptSource(fileNames) { - return !fileNames.some((fileName) => fileExtensionIs(fileName, ".ts" /* Ts */) && !isDeclarationFileName(fileName) || fileExtensionIs(fileName, ".tsx" /* Tsx */)); -} -function isGeneratedFileWatcher(watch) { - return watch.generatedFilePath !== void 0; -} -function setIsEqualTo(arr1, arr2) { - if (arr1 === arr2) { - return true; - } - if ((arr1 || emptyArray2).length === 0 && (arr2 || emptyArray2).length === 0) { - return true; - } - const set = /* @__PURE__ */ new Map(); - let unique = 0; - for (const v of arr1) { - if (set.get(v) !== true) { - set.set(v, true); - unique++; - } - } - for (const v of arr2) { - const isSet = set.get(v); - if (isSet === void 0) { - return false; - } - if (isSet === true) { - set.set(v, false); - unique--; - } - } - return unique === 0; -} -function typeAcquisitionChanged(opt1, opt2) { - return opt1.enable !== opt2.enable || !setIsEqualTo(opt1.include, opt2.include) || !setIsEqualTo(opt1.exclude, opt2.exclude); -} -function compilerOptionsChanged(opt1, opt2) { - return getAllowJSCompilerOption(opt1) !== getAllowJSCompilerOption(opt2); -} -function unresolvedImportsChanged(imports1, imports2) { - if (imports1 === imports2) { - return false; - } - return !arrayIsEqualTo(imports1, imports2); -} -var Project2 = class _Project { - /** @internal */ - constructor(projectName, projectKind, projectService, documentRegistry, 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; - this.rootFilesMap = /* @__PURE__ */ new Map(); - /** @internal */ - this.plugins = []; - /** - * This is map from files to unresolved imports in it - * Maop does not contain entries for files that do not have unresolved imports - * This helps in containing the set of files to invalidate - * - * @internal - */ - this.cachedUnresolvedImportsPerFile = /* @__PURE__ */ new Map(); - this.hasAddedorRemovedFiles = false; - this.hasAddedOrRemovedSymlinks = false; - /** - * Last version that was reported. - */ - this.lastReportedVersion = 0; - /** - * Current project's program version. (incremented everytime new program is created that is not complete reuse from the old one) - * This property is changed in 'updateGraph' based on the set of files in program - * @internal - */ - this.projectProgramVersion = 0; - /** - * Current version of the project state. It is changed when: - * - new root file was added/removed - * - edit happen in some file that is currently included in the project. - * This property is different from projectStructureVersion since in most cases edits don't affect set of files in the project - * @internal - */ - this.projectStateVersion = 0; - this.isInitialLoadPending = returnFalse; - /** @internal */ - this.dirty = false; - /** @internal */ - this.typingFiles = emptyArray2; - this.moduleSpecifierCache = createModuleSpecifierCache(this); - /** @internal */ - this.createHash = maybeBind(this.projectService.host, this.projectService.host.createHash); - /** @internal */ - this.globalCacheResolutionModuleName = ts_JsTyping_exports.nonRelativeModuleNameForTypingCache; - /** @internal */ - this.updateFromProjectInProgress = false; - this.projectName = projectName; - this.directoryStructureHost = directoryStructureHost; - this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory); - this.getCanonicalFileName = this.projectService.toCanonicalFileName; - this.jsDocParsingMode = this.projectService.jsDocParsingMode; - this.cancellationToken = new ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds); - if (!this.compilerOptions) { - this.compilerOptions = getDefaultCompilerOptions2(); - this.compilerOptions.allowNonTsExtensions = true; - this.compilerOptions.allowJs = true; - } else if (hasExplicitListOfFiles || getAllowJSCompilerOption(this.compilerOptions) || this.projectService.hasDeferredExtension()) { - this.compilerOptions.allowNonTsExtensions = true; - } - switch (projectService.serverMode) { - case 0 /* Semantic */: - this.languageServiceEnabled = true; - break; - case 1 /* PartialSemantic */: - this.languageServiceEnabled = true; - this.compilerOptions.noResolve = true; - this.compilerOptions.types = []; - break; - case 2 /* Syntactic */: - this.languageServiceEnabled = false; - this.compilerOptions.noResolve = true; - this.compilerOptions.types = []; - break; - default: - Debug.assertNever(projectService.serverMode); - } - this.setInternalCompilerOptionsForEmittingJsFiles(); - const host = this.projectService.host; - if (this.projectService.logger.loggingEnabled()) { - this.trace = (s) => this.writeLog(s); - } else if (host.trace) { - this.trace = (s) => host.trace(s); - } - this.realpath = maybeBind(host, host.realpath); - this.preferNonRecursiveWatch = this.projectService.canUseWatchEvents || host.preferNonRecursiveWatch; - this.resolutionCache = createResolutionCache( - this, - this.currentDirectory, - /*logChangesWhenResolvingModule*/ - true - ); - this.languageService = createLanguageService(this, this.documentRegistry, this.projectService.serverMode); - if (lastFileExceededProgramSize) { - this.disableLanguageService(lastFileExceededProgramSize); - } - this.markAsDirty(); - if (!isBackgroundProject(this)) { - this.projectService.pendingEnsureProjectForOpenFiles = true; - } - this.projectService.onProjectCreation(this); - } - /** @internal */ - getResolvedProjectReferenceToRedirect(_fileName) { - return void 0; - } - isNonTsProject() { - updateProjectIfDirty(this); - return allFilesAreJsOrDts(this); - } - isJsOnlyProject() { - updateProjectIfDirty(this); - return hasOneOrMoreJsAndNoTsFiles(this); - } - static resolveModule(moduleName, initialDir, host, log) { - return _Project.importServicePluginSync({ name: moduleName }, [initialDir], host, log).resolvedModule; - } - /** @internal */ - static importServicePluginSync(pluginConfigEntry, searchPaths, host, log) { - Debug.assertIsDefined(host.require); - let errorLogs; - let resolvedModule; - for (const initialDir of searchPaths) { - const resolvedPath = normalizeSlashes(host.resolvePath(combinePaths(initialDir, "node_modules"))); - log(`Loading ${pluginConfigEntry.name} from ${initialDir} (resolved to ${resolvedPath})`); - const result = host.require(resolvedPath, pluginConfigEntry.name); - if (!result.error) { - resolvedModule = result.module; - break; - } - const err = result.error.stack || result.error.message || JSON.stringify(result.error); - (errorLogs ?? (errorLogs = [])).push(`Failed to load module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`); - } - return { pluginConfigEntry, resolvedModule, errorLogs }; - } - /** @internal */ - static async importServicePluginAsync(pluginConfigEntry, searchPaths, host, log) { - Debug.assertIsDefined(host.importPlugin); - let errorLogs; - let resolvedModule; - for (const initialDir of searchPaths) { - const resolvedPath = combinePaths(initialDir, "node_modules"); - log(`Dynamically importing ${pluginConfigEntry.name} from ${initialDir} (resolved to ${resolvedPath})`); - let result; - try { - result = await host.importPlugin(resolvedPath, pluginConfigEntry.name); - } catch (e) { - result = { module: void 0, error: e }; - } - if (!result.error) { - resolvedModule = result.module; - break; - } - const err = result.error.stack || result.error.message || JSON.stringify(result.error); - (errorLogs ?? (errorLogs = [])).push(`Failed to dynamically import module '${pluginConfigEntry.name}' from ${resolvedPath}: ${err}`); - } - return { pluginConfigEntry, resolvedModule, errorLogs }; - } - isKnownTypesPackageName(name) { - return this.projectService.typingsInstaller.isKnownTypesPackageName(name); - } - installPackage(options) { - return this.projectService.typingsInstaller.installPackage({ ...options, projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) }); - } - /** @internal */ - getGlobalTypingsCacheLocation() { - return this.getGlobalCache(); - } - /** @internal */ - getSymlinkCache() { - if (!this.symlinks) { - this.symlinks = createSymlinkCache(this.getCurrentDirectory(), this.getCanonicalFileName); - } - if (this.program && !this.symlinks.hasProcessedResolutions()) { - this.symlinks.setSymlinksFromResolutions( - this.program.forEachResolvedModule, - this.program.forEachResolvedTypeReferenceDirective, - this.program.getAutomaticTypeDirectiveResolutions() - ); - } - return this.symlinks; - } - // Method of LanguageServiceHost - getCompilationSettings() { - return this.compilerOptions; - } - // Method to support public API - getCompilerOptions() { - return this.getCompilationSettings(); - } - getNewLine() { - return this.projectService.host.newLine; - } - getProjectVersion() { - return this.projectStateVersion.toString(); - } - getProjectReferences() { - return void 0; - } - getScriptFileNames() { - if (!this.rootFilesMap.size) { - return emptyArray; - } - let result; - this.rootFilesMap.forEach((value) => { - if (this.languageServiceEnabled || value.info && value.info.isScriptOpen()) { - (result || (result = [])).push(value.fileName); - } - }); - return addRange(result, this.typingFiles) || emptyArray; - } - getOrCreateScriptInfoAndAttachToProject(fileName) { - const scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClient( - fileName, - this.currentDirectory, - this.directoryStructureHost, - /*deferredDeleteOk*/ - false - ); - if (scriptInfo) { - const existingValue = this.rootFilesMap.get(scriptInfo.path); - if (existingValue && existingValue.info !== scriptInfo) { - existingValue.info = scriptInfo; - } - scriptInfo.attachToProject(this); - } - return scriptInfo; - } - getScriptKind(fileName) { - const info = this.projectService.getScriptInfoForPath(this.toPath(fileName)); - return info && info.scriptKind; - } - getScriptVersion(filename) { - const info = this.projectService.getOrCreateScriptInfoNotOpenedByClient( - filename, - this.currentDirectory, - this.directoryStructureHost, - /*deferredDeleteOk*/ - false - ); - return info && info.getLatestVersion(); - } - getScriptSnapshot(filename) { - const scriptInfo = this.getOrCreateScriptInfoAndAttachToProject(filename); - if (scriptInfo) { - return scriptInfo.getSnapshot(); - } - } - getCancellationToken() { - return this.cancellationToken; - } - getCurrentDirectory() { - return this.currentDirectory; - } - getDefaultLibFileName() { - const nodeModuleBinDir = getDirectoryPath(normalizePath(this.projectService.getExecutingFilePath())); - return combinePaths(nodeModuleBinDir, getDefaultLibFileName(this.compilerOptions)); - } - useCaseSensitiveFileNames() { - return this.projectService.host.useCaseSensitiveFileNames; - } - readDirectory(path, extensions, exclude, include, depth) { - return this.directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); - } - readFile(fileName) { - return this.projectService.host.readFile(fileName); - } - writeFile(fileName, content) { - return this.projectService.host.writeFile(fileName, content); - } - fileExists(file) { - const path = this.toPath(file); - return !!this.projectService.getScriptInfoForPath(path) || !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); - } - /** @internal */ - resolveModuleNameLiterals(moduleLiterals, containingFile, redirectedReference, options, containingSourceFile, reusedNames) { - return this.resolutionCache.resolveModuleNameLiterals(moduleLiterals, containingFile, redirectedReference, options, containingSourceFile, reusedNames); - } - /** @internal */ - getModuleResolutionCache() { - return this.resolutionCache.getModuleResolutionCache(); - } - /** @internal */ - resolveTypeReferenceDirectiveReferences(typeDirectiveReferences, containingFile, redirectedReference, options, containingSourceFile, reusedNames) { - return this.resolutionCache.resolveTypeReferenceDirectiveReferences( - typeDirectiveReferences, - containingFile, - redirectedReference, - options, - containingSourceFile, - reusedNames - ); - } - /** @internal */ - resolveLibrary(libraryName, resolveFrom, options, libFileName) { - return this.resolutionCache.resolveLibrary(libraryName, resolveFrom, options, libFileName); - } - directoryExists(path) { - return this.directoryStructureHost.directoryExists(path); - } - getDirectories(path) { - return this.directoryStructureHost.getDirectories(path); - } - /** @internal */ - getCachedDirectoryStructureHost() { - return void 0; - } - /** @internal */ - toPath(fileName) { - return toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName); - } - /** @internal */ - watchDirectoryOfFailedLookupLocation(directory, cb, flags) { - return this.projectService.watchFactory.watchDirectory( - directory, - cb, - flags, - this.projectService.getWatchOptions(this), - WatchType.FailedLookupLocations, - this - ); - } - /** @internal */ - watchAffectingFileLocation(file, cb) { - return this.projectService.watchFactory.watchFile( - file, - cb, - 2e3 /* High */, - this.projectService.getWatchOptions(this), - WatchType.AffectingFileLocation, - this - ); - } - /** @internal */ - clearInvalidateResolutionOfFailedLookupTimer() { - return this.projectService.throttledOperations.cancel(`${this.getProjectName()}FailedLookupInvalidation`); - } - /** @internal */ - scheduleInvalidateResolutionsOfFailedLookupLocations() { - this.projectService.throttledOperations.schedule( - `${this.getProjectName()}FailedLookupInvalidation`, - /*delay*/ - 1e3, - () => { - if (this.resolutionCache.invalidateResolutionsOfFailedLookupLocations()) { - this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); - } - } - ); - } - /** @internal */ - invalidateResolutionsOfFailedLookupLocations() { - if (this.clearInvalidateResolutionOfFailedLookupTimer() && this.resolutionCache.invalidateResolutionsOfFailedLookupLocations()) { - this.markAsDirty(); - this.projectService.delayEnsureProjectForOpenFiles(); - } - } - /** @internal */ - onInvalidatedResolution() { - this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); - } - /** @internal */ - watchTypeRootsDirectory(directory, cb, flags) { - return this.projectService.watchFactory.watchDirectory( - directory, - cb, - flags, - this.projectService.getWatchOptions(this), - WatchType.TypeRoots, - this - ); - } - /** @internal */ - hasChangedAutomaticTypeDirectiveNames() { - return this.resolutionCache.hasChangedAutomaticTypeDirectiveNames(); - } - /** @internal */ - onChangedAutomaticTypeDirectiveNames() { - 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); - } - /** @internal */ - writeLog(s) { - this.projectService.logger.info(s); - } - log(s) { - this.writeLog(s); - } - error(s) { - this.projectService.logger.msg(s, "Err" /* Err */); - } - setInternalCompilerOptionsForEmittingJsFiles() { - if (this.projectKind === 0 /* Inferred */ || this.projectKind === 2 /* External */) { - this.compilerOptions.noEmitForJsFiles = true; - } - } - /** - * Get the errors that dont have any file name associated - */ - getGlobalProjectErrors() { - return filter(this.projectErrors, (diagnostic) => !diagnostic.file) || emptyArray2; - } - /** - * Get all the project errors - */ - getAllProjectErrors() { - return this.projectErrors || emptyArray2; - } - setProjectErrors(projectErrors) { - this.projectErrors = projectErrors; - } - getLanguageService(ensureSynchronized = true) { - if (ensureSynchronized) { - updateProjectIfDirty(this); - } - return this.languageService; - } - /** @internal */ - getSourceMapper() { - return this.getLanguageService().getSourceMapper(); - } - /** @internal */ - clearSourceMapperCache() { - this.languageService.clearSourceMapperCache(); - } - /** @internal */ - getDocumentPositionMapper(generatedFileName, sourceFileName) { - return this.projectService.getDocumentPositionMapper(this, generatedFileName, sourceFileName); - } - /** @internal */ - getSourceFileLike(fileName) { - return this.projectService.getSourceFileLike(fileName, this); - } - /** @internal */ - shouldEmitFile(scriptInfo) { - return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent() && !this.program.isSourceOfProjectReferenceRedirect(scriptInfo.path); - } - getCompileOnSaveAffectedFileList(scriptInfo) { - if (!this.languageServiceEnabled) { - return []; - } - updateProjectIfDirty(this); - this.builderState = BuilderState.create( - this.program, - this.builderState, - /*disableUseFileVersionAsSignature*/ - true - ); - return mapDefined( - BuilderState.getFilesAffectedBy( - this.builderState, - this.program, - scriptInfo.path, - this.cancellationToken, - this.projectService.host - ), - (sourceFile) => this.shouldEmitFile(this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : void 0 - ); - } - /** - * Returns true if emit was conducted - */ - emitFile(scriptInfo, writeFile2) { - if (!this.languageServiceEnabled || !this.shouldEmitFile(scriptInfo)) { - return { emitSkipped: true, diagnostics: emptyArray2 }; - } - const { emitSkipped, diagnostics, outputFiles } = this.getLanguageService().getEmitOutput(scriptInfo.fileName); - if (!emitSkipped) { - for (const outputFile of outputFiles) { - const outputFileAbsoluteFileName = getNormalizedAbsolutePath(outputFile.name, this.currentDirectory); - writeFile2(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); - } - if (this.builderState && getEmitDeclarations(this.compilerOptions)) { - const dtsFiles = outputFiles.filter((f) => isDeclarationFileName(f.name)); - if (dtsFiles.length === 1) { - const sourceFile = this.program.getSourceFile(scriptInfo.fileName); - const signature = this.projectService.host.createHash ? this.projectService.host.createHash(dtsFiles[0].text) : generateDjb2Hash(dtsFiles[0].text); - BuilderState.updateSignatureOfFile(this.builderState, signature, sourceFile.resolvedPath); - } - } - } - return { emitSkipped, diagnostics }; - } - enableLanguageService() { - if (this.languageServiceEnabled || this.projectService.serverMode === 2 /* Syntactic */) { - return; - } - this.languageServiceEnabled = true; - this.lastFileExceededProgramSize = void 0; - this.projectService.onUpdateLanguageServiceStateForProject( - this, - /*languageServiceEnabled*/ - true - ); - } - /** @internal */ - cleanupProgram() { - if (this.program) { - for (const f of this.program.getSourceFiles()) { - this.detachScriptInfoIfNotRoot(f.fileName); - } - this.program.forEachResolvedProjectReference((ref) => this.detachScriptInfoFromProject(ref.sourceFile.fileName)); - this.program = void 0; - } - } - disableLanguageService(lastFileExceededProgramSize) { - if (!this.languageServiceEnabled) { - return; - } - Debug.assert(this.projectService.serverMode !== 2 /* Syntactic */); - this.languageService.cleanupSemanticCache(); - this.languageServiceEnabled = false; - this.cleanupProgram(); - this.lastFileExceededProgramSize = lastFileExceededProgramSize; - this.builderState = void 0; - if (this.autoImportProviderHost) { - this.autoImportProviderHost.close(); - } - this.autoImportProviderHost = void 0; - this.resolutionCache.closeTypeRootsWatch(); - this.clearGeneratedFileWatch(); - this.projectService.verifyDocumentRegistry(); - this.projectService.onUpdateLanguageServiceStateForProject( - this, - /*languageServiceEnabled*/ - false - ); - } - getProjectName() { - return this.projectName; - } - removeLocalTypingsFromTypeAcquisition(newTypeAcquisition) { - if (!newTypeAcquisition.enable || !newTypeAcquisition.include) { - return newTypeAcquisition; - } - return { ...newTypeAcquisition, include: this.removeExistingTypings(newTypeAcquisition.include) }; - } - getExternalFiles(updateLevel) { - return toSorted(flatMap(this.plugins, (plugin) => { - if (typeof plugin.module.getExternalFiles !== "function") return; - try { - return plugin.module.getExternalFiles(this, updateLevel || 0 /* Update */); - } catch (e) { - this.projectService.logger.info(`A plugin threw an exception in getExternalFiles: ${e}`); - if (e.stack) { - this.projectService.logger.info(e.stack); - } - } - })); - } - getSourceFile(path) { - if (!this.program) { - return void 0; - } - return this.program.getSourceFileByPath(path); - } - /** @internal */ - getSourceFileOrConfigFile(path) { - const options = this.program.getCompilerOptions(); - return path === options.configFilePath ? options.configFile : this.getSourceFile(path); - } - close() { - var _a; - if (this.typingsCache) this.projectService.typingsInstaller.onProjectClosed(this); - this.typingsCache = void 0; - this.closeWatchingTypingLocations(); - this.cleanupProgram(); - forEach(this.externalFiles, (externalFile) => this.detachScriptInfoIfNotRoot(externalFile)); - this.rootFilesMap.forEach((root) => { - var _a2; - return (_a2 = root.info) == null ? void 0 : _a2.detachFromProject(this); - }); - this.projectService.pendingEnsureProjectForOpenFiles = true; - this.rootFilesMap = void 0; - this.externalFiles = void 0; - this.program = void 0; - this.builderState = void 0; - this.resolutionCache.clear(); - this.resolutionCache = void 0; - this.cachedUnresolvedImportsPerFile = void 0; - (_a = this.packageJsonWatches) == null ? void 0 : _a.forEach((watcher) => { - watcher.projects.delete(this); - watcher.close(); - }); - this.packageJsonWatches = void 0; - this.moduleSpecifierCache.clear(); - this.moduleSpecifierCache = void 0; - this.directoryStructureHost = void 0; - this.exportMapCache = void 0; - this.projectErrors = void 0; - this.plugins.length = 0; - if (this.missingFilesMap) { - clearMap(this.missingFilesMap, closeFileWatcher); - this.missingFilesMap = void 0; - } - this.clearGeneratedFileWatch(); - this.clearInvalidateResolutionOfFailedLookupTimer(); - if (this.autoImportProviderHost) { - this.autoImportProviderHost.close(); - } - this.autoImportProviderHost = void 0; - if (this.noDtsResolutionProject) { - this.noDtsResolutionProject.close(); - } - this.noDtsResolutionProject = void 0; - this.languageService.dispose(); - this.languageService = void 0; - } - detachScriptInfoIfNotRoot(uncheckedFilename) { - const info = this.projectService.getScriptInfo(uncheckedFilename); - if (info && !this.isRoot(info)) { - info.detachFromProject(this); - } - } - isClosed() { - return this.rootFilesMap === void 0; - } - hasRoots() { - var _a; - return !!((_a = this.rootFilesMap) == null ? void 0 : _a.size); - } - /** @internal */ - isOrphan() { - return false; - } - getRootFiles() { - return this.rootFilesMap && arrayFrom(mapDefinedIterator(this.rootFilesMap.values(), (value) => { - var _a; - return (_a = value.info) == null ? void 0 : _a.fileName; - })); - } - /** @internal */ - getRootFilesMap() { - return this.rootFilesMap; - } - getRootScriptInfos() { - return arrayFrom(mapDefinedIterator(this.rootFilesMap.values(), (value) => value.info)); - } - getScriptInfos() { - if (!this.languageServiceEnabled) { - return this.getRootScriptInfos(); - } - return map(this.program.getSourceFiles(), (sourceFile) => { - const scriptInfo = this.projectService.getScriptInfoForPath(sourceFile.resolvedPath); - Debug.assert(!!scriptInfo, "getScriptInfo", () => `scriptInfo for a file '${sourceFile.fileName}' Path: '${sourceFile.path}' / '${sourceFile.resolvedPath}' is missing.`); - return scriptInfo; - }); - } - getExcludedFiles() { - return emptyArray2; - } - getFileNames(excludeFilesFromExternalLibraries, excludeConfigFiles) { - if (!this.program) { - return []; - } - if (!this.languageServiceEnabled) { - let rootFiles = this.getRootFiles(); - if (this.compilerOptions) { - const defaultLibrary = getDefaultLibFilePath(this.compilerOptions); - if (defaultLibrary) { - (rootFiles || (rootFiles = [])).push(asNormalizedPath(defaultLibrary)); - } - } - return rootFiles; - } - const result = []; - for (const f of this.program.getSourceFiles()) { - if (excludeFilesFromExternalLibraries && this.program.isSourceFileFromExternalLibrary(f)) { - continue; - } - result.push(asNormalizedPath(f.fileName)); - } - if (!excludeConfigFiles) { - const configFile = this.program.getCompilerOptions().configFile; - if (configFile) { - result.push(asNormalizedPath(configFile.fileName)); - if (configFile.extendedSourceFiles) { - for (const f of configFile.extendedSourceFiles) { - result.push(asNormalizedPath(f)); - } - } - } - } - return result; - } - /** @internal */ - getFileNamesWithRedirectInfo(includeProjectReferenceRedirectInfo) { - return this.getFileNames().map((fileName) => ({ - fileName, - isSourceOfProjectReferenceRedirect: includeProjectReferenceRedirectInfo && this.isSourceOfProjectReferenceRedirect(fileName) - })); - } - hasConfigFile(configFilePath) { - if (this.program && this.languageServiceEnabled) { - const configFile = this.program.getCompilerOptions().configFile; - if (configFile) { - if (configFilePath === asNormalizedPath(configFile.fileName)) { - return true; - } - if (configFile.extendedSourceFiles) { - for (const f of configFile.extendedSourceFiles) { - if (configFilePath === asNormalizedPath(f)) { - return true; - } - } - } - } - } - return false; - } - containsScriptInfo(info) { - if (this.isRoot(info)) return true; - if (!this.program) return false; - const file = this.program.getSourceFileByPath(info.path); - return !!file && file.resolvedPath === info.path; - } - containsFile(filename, requireOpen) { - const info = this.projectService.getScriptInfoForNormalizedPath(filename); - if (info && (info.isScriptOpen() || !requireOpen)) { - return this.containsScriptInfo(info); - } - return false; - } - isRoot(info) { - var _a, _b; - return ((_b = (_a = this.rootFilesMap) == null ? void 0 : _a.get(info.path)) == null ? void 0 : _b.info) === info; - } - // add a root file to project - addRoot(info, fileName) { - Debug.assert(!this.isRoot(info)); - this.rootFilesMap.set(info.path, { fileName: fileName || info.fileName, info }); - info.attachToProject(this); - this.markAsDirty(); - } - // add a root file that doesnt exist on host - addMissingFileRoot(fileName) { - const path = this.projectService.toPath(fileName); - this.rootFilesMap.set(path, { fileName }); - this.markAsDirty(); - } - removeFile(info, fileExists, detachFromProject) { - if (this.isRoot(info)) { - this.removeRoot(info); - } - if (fileExists) { - this.resolutionCache.removeResolutionsOfFile(info.path); - } else { - this.resolutionCache.invalidateResolutionOfFile(info.path); - } - this.cachedUnresolvedImportsPerFile.delete(info.path); - if (detachFromProject) { - info.detachFromProject(this); - } - this.markAsDirty(); - } - registerFileUpdate(fileName) { - (this.updatedFileNames || (this.updatedFileNames = /* @__PURE__ */ new Set())).add(fileName); - } - /** @internal */ - markFileAsDirty(changedFile) { - this.markAsDirty(); - if (this.exportMapCache && !this.exportMapCache.isEmpty()) { - (this.changedFilesForExportMapCache || (this.changedFilesForExportMapCache = /* @__PURE__ */ new Set())).add(changedFile); - } - } - /** @internal */ - markAsDirty() { - if (!this.dirty) { - this.projectStateVersion++; - this.dirty = true; - } - } - /** @internal */ - markAutoImportProviderAsDirty() { - var _a; - if (!this.autoImportProviderHost) this.autoImportProviderHost = void 0; - (_a = this.autoImportProviderHost) == null ? void 0 : _a.markAsDirty(); - } - /** @internal */ - onAutoImportProviderSettingsChanged() { - var _a; - if (this.autoImportProviderHost === false) { - this.autoImportProviderHost = void 0; - } else { - (_a = this.autoImportProviderHost) == null ? void 0 : _a.markAsDirty(); - } - } - /** @internal */ - onPackageJsonChange() { - this.moduleSpecifierCache.clear(); - if (this.autoImportProviderHost) { - this.autoImportProviderHost.markAsDirty(); - } - } - /** @internal */ - onFileAddedOrRemoved(isSymlink) { - this.hasAddedorRemovedFiles = true; - if (isSymlink) { - this.hasAddedOrRemovedSymlinks = true; - } - } - /** @internal */ - onDiscoveredSymlink() { - this.hasAddedOrRemovedSymlinks = true; - } - /** @internal */ - onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath, newSourceFileByResolvedPath) { - if (!newSourceFileByResolvedPath || oldSourceFile.resolvedPath === oldSourceFile.path && newSourceFileByResolvedPath.resolvedPath !== oldSourceFile.path) { - this.detachScriptInfoFromProject(oldSourceFile.fileName, hasSourceFileByPath); - } - } - /** @internal */ - updateFromProject() { - updateProjectIfDirty(this); - } - /** - * Updates set of files that contribute to this project - * @returns: true if set of files in the project stays the same and false - otherwise. - */ - updateGraph() { - var _a, _b; - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "updateGraph", { name: this.projectName, kind: ProjectKind[this.projectKind] }); - this.resolutionCache.startRecordingFilesWithChangedResolutions(); - const hasNewProgram = this.updateGraphWorker(); - const hasAddedorRemovedFiles = this.hasAddedorRemovedFiles; - this.hasAddedorRemovedFiles = false; - this.hasAddedOrRemovedSymlinks = false; - const changedFiles = this.resolutionCache.finishRecordingFilesWithChangedResolutions() || emptyArray2; - for (const file of changedFiles) { - this.cachedUnresolvedImportsPerFile.delete(file); - } - if (this.languageServiceEnabled && this.projectService.serverMode === 0 /* Semantic */ && !this.isOrphan()) { - if (hasNewProgram || changedFiles.length) { - this.lastCachedUnresolvedImportsList = getUnresolvedImports(this.program, this.cachedUnresolvedImportsPerFile); - } - this.enqueueInstallTypingsForProject(hasAddedorRemovedFiles); - } else { - this.lastCachedUnresolvedImportsList = void 0; - } - const isFirstProgramLoad = this.projectProgramVersion === 0 && hasNewProgram; - if (hasNewProgram) { - this.projectProgramVersion++; - } - if (hasAddedorRemovedFiles) { - this.markAutoImportProviderAsDirty(); - } - if (isFirstProgramLoad) { - this.getPackageJsonAutoImportProvider(); - } - (_b = tracing) == null ? void 0 : _b.pop(); - return !hasNewProgram; - } - /** @internal */ - enqueueInstallTypingsForProject(forceRefresh) { - const typeAcquisition = this.getTypeAcquisition(); - if (!typeAcquisition || !typeAcquisition.enable || this.projectService.typingsInstaller === nullTypingsInstaller) { - return; - } - const entry = this.typingsCache; - if (forceRefresh || !entry || typeAcquisitionChanged(typeAcquisition, entry.typeAcquisition) || compilerOptionsChanged(this.getCompilationSettings(), entry.compilerOptions) || unresolvedImportsChanged(this.lastCachedUnresolvedImportsList, entry.unresolvedImports)) { - this.typingsCache = { - compilerOptions: this.getCompilationSettings(), - typeAcquisition, - unresolvedImports: this.lastCachedUnresolvedImportsList - }; - this.projectService.typingsInstaller.enqueueInstallTypingsRequest(this, typeAcquisition, this.lastCachedUnresolvedImportsList); - } - } - /** @internal */ - updateTypingFiles(compilerOptions, typeAcquisition, unresolvedImports, newTypings) { - this.typingsCache = { - compilerOptions, - typeAcquisition, - unresolvedImports - }; - const typingFiles = !typeAcquisition || !typeAcquisition.enable ? emptyArray2 : toSorted(newTypings); - if (enumerateInsertsAndDeletes( - typingFiles, - this.typingFiles, - getStringComparer(!this.useCaseSensitiveFileNames()), - /*inserted*/ - noop, - (removed) => this.detachScriptInfoFromProject(removed) - )) { - this.typingFiles = typingFiles; - this.resolutionCache.setFilesWithInvalidatedNonRelativeUnresolvedImports(this.cachedUnresolvedImportsPerFile); - this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); - } - } - closeWatchingTypingLocations() { - if (this.typingWatchers) clearMap(this.typingWatchers, closeFileWatcher); - this.typingWatchers = void 0; - } - onTypingInstallerWatchInvoke() { - this.typingWatchers.isInvoked = true; - this.projectService.updateTypingsForProject({ projectName: this.getProjectName(), kind: ActionInvalidate }); - } - /** @internal */ - watchTypingLocations(files) { - if (!files) { - this.typingWatchers.isInvoked = false; - return; - } - if (!files.length) { - this.closeWatchingTypingLocations(); - return; - } - const toRemove = new Map(this.typingWatchers); - if (!this.typingWatchers) this.typingWatchers = /* @__PURE__ */ new Map(); - this.typingWatchers.isInvoked = false; - const createProjectWatcher = (path, typingsWatcherType) => { - const canonicalPath = this.toPath(path); - toRemove.delete(canonicalPath); - if (!this.typingWatchers.has(canonicalPath)) { - this.typingWatchers.set( - canonicalPath, - typingsWatcherType === "FileWatcher" /* FileWatcher */ ? this.projectService.watchFactory.watchFile( - path, - () => !this.typingWatchers.isInvoked ? this.onTypingInstallerWatchInvoke() : this.writeLog(`TypingWatchers already invoked`), - 2e3 /* High */, - this.projectService.getWatchOptions(this), - WatchType.TypingInstallerLocationFile, - this - ) : this.projectService.watchFactory.watchDirectory( - path, - (f) => { - if (this.typingWatchers.isInvoked) return this.writeLog(`TypingWatchers already invoked`); - if (!fileExtensionIs(f, ".json" /* Json */)) return this.writeLog(`Ignoring files that are not *.json`); - if (comparePaths(f, combinePaths(this.projectService.typingsInstaller.globalTypingsCacheLocation, "package.json"), !this.useCaseSensitiveFileNames())) return this.writeLog(`Ignoring package.json change at global typings location`); - this.onTypingInstallerWatchInvoke(); - }, - 1 /* Recursive */, - this.projectService.getWatchOptions(this), - WatchType.TypingInstallerLocationDirectory, - this - ) - ); - } - }; - for (const file of files) { - const basename = getBaseFileName(file); - if (basename === "package.json" || basename === "bower.json") { - createProjectWatcher(file, "FileWatcher" /* FileWatcher */); - continue; - } - if (containsPath(this.currentDirectory, file, this.currentDirectory, !this.useCaseSensitiveFileNames())) { - const subDirectory = file.indexOf(directorySeparator, this.currentDirectory.length + 1); - if (subDirectory !== -1) { - createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */); - } else { - createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); - } - continue; - } - if (containsPath(this.projectService.typingsInstaller.globalTypingsCacheLocation, file, this.currentDirectory, !this.useCaseSensitiveFileNames())) { - createProjectWatcher(this.projectService.typingsInstaller.globalTypingsCacheLocation, "DirectoryWatcher" /* DirectoryWatcher */); - continue; - } - createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */); - } - toRemove.forEach((watch, path) => { - watch.close(); - this.typingWatchers.delete(path); - }); - } - /** @internal */ - getCurrentProgram() { - return this.program; - } - removeExistingTypings(include) { - if (!include.length) return include; - const existing = getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost); - return filter(include, (i) => !existing.includes(i)); - } - updateGraphWorker() { - var _a, _b; - const oldProgram = this.languageService.getCurrentProgram(); - Debug.assert(oldProgram === this.program); - Debug.assert(!this.isClosed(), "Called update graph worker of closed project"); - this.writeLog(`Starting updateGraphWorker: Project: ${this.getProjectName()}`); - const start = timestamp(); - const { hasInvalidatedResolutions, hasInvalidatedLibResolutions } = this.resolutionCache.createHasInvalidatedResolutions(returnFalse, returnFalse); - this.hasInvalidatedResolutions = hasInvalidatedResolutions; - this.hasInvalidatedLibResolutions = hasInvalidatedLibResolutions; - this.resolutionCache.startCachingPerDirectoryResolution(); - this.dirty = false; - this.updateFromProjectInProgress = true; - this.program = this.languageService.getProgram(); - this.updateFromProjectInProgress = false; - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "finishCachingPerDirectoryResolution"); - this.resolutionCache.finishCachingPerDirectoryResolution(this.program, oldProgram); - (_b = tracing) == null ? void 0 : _b.pop(); - Debug.assert(oldProgram === void 0 || this.program !== void 0); - let hasNewProgram = false; - if (this.program && (!oldProgram || this.program !== oldProgram && this.program.structureIsReused !== 2 /* Completely */)) { - hasNewProgram = true; - this.rootFilesMap.forEach((value, path) => { - var _a2; - const file = this.program.getSourceFileByPath(path); - const info = value.info; - if (!file || ((_a2 = value.info) == null ? void 0 : _a2.path) === file.resolvedPath) return; - value.info = this.projectService.getScriptInfo(file.fileName); - Debug.assert(value.info.isAttached(this)); - info == null ? void 0 : info.detachFromProject(this); - }); - updateMissingFilePathsWatch( - this.program, - this.missingFilesMap || (this.missingFilesMap = /* @__PURE__ */ new Map()), - // Watch the missing files - (missingFilePath, missingFileName) => this.addMissingFileWatcher(missingFilePath, missingFileName) - ); - if (this.generatedFilesMap) { - const outPath = this.compilerOptions.outFile; - if (isGeneratedFileWatcher(this.generatedFilesMap)) { - if (!outPath || !this.isValidGeneratedFileWatcher( - removeFileExtension(outPath) + ".d.ts" /* Dts */, - this.generatedFilesMap - )) { - this.clearGeneratedFileWatch(); - } - } else { - if (outPath) { - this.clearGeneratedFileWatch(); - } else { - this.generatedFilesMap.forEach((watcher, source) => { - const sourceFile = this.program.getSourceFileByPath(source); - if (!sourceFile || sourceFile.resolvedPath !== source || !this.isValidGeneratedFileWatcher( - getDeclarationEmitOutputFilePathWorker(sourceFile.fileName, this.compilerOptions, this.program), - watcher - )) { - closeFileWatcherOf(watcher); - this.generatedFilesMap.delete(source); - } - }); - } - } - } - if (this.languageServiceEnabled && this.projectService.serverMode === 0 /* Semantic */) { - this.resolutionCache.updateTypeRootsWatch(); - } - } - this.projectService.verifyProgram(this); - if (this.exportMapCache && !this.exportMapCache.isEmpty()) { - this.exportMapCache.releaseSymbols(); - if (this.hasAddedorRemovedFiles || oldProgram && !this.program.structureIsReused) { - this.exportMapCache.clear(); - } else if (this.changedFilesForExportMapCache && oldProgram && this.program) { - forEachKey(this.changedFilesForExportMapCache, (fileName) => { - const oldSourceFile = oldProgram.getSourceFileByPath(fileName); - const sourceFile = this.program.getSourceFileByPath(fileName); - if (!oldSourceFile || !sourceFile) { - this.exportMapCache.clear(); - return true; - } - return this.exportMapCache.onFileChanged(oldSourceFile, sourceFile, !!this.getTypeAcquisition().enable); - }); - } - } - if (this.changedFilesForExportMapCache) { - this.changedFilesForExportMapCache.clear(); - } - if (this.hasAddedOrRemovedSymlinks || this.program && !this.program.structureIsReused && this.getCompilerOptions().preserveSymlinks) { - this.symlinks = void 0; - this.moduleSpecifierCache.clear(); - } - const oldExternalFiles = this.externalFiles || emptyArray2; - this.externalFiles = this.getExternalFiles(); - enumerateInsertsAndDeletes( - this.externalFiles, - oldExternalFiles, - getStringComparer(!this.useCaseSensitiveFileNames()), - // Ensure a ScriptInfo is created for new external files. This is performed indirectly - // by the host for files in the program when the program is retrieved above but - // the program doesn't contain external files so this must be done explicitly. - (inserted) => { - const scriptInfo = this.projectService.getOrCreateScriptInfoNotOpenedByClient( - inserted, - this.currentDirectory, - this.directoryStructureHost, - /*deferredDeleteOk*/ - false - ); - scriptInfo == null ? void 0 : scriptInfo.attachToProject(this); - }, - (removed) => this.detachScriptInfoFromProject(removed) - ); - const elapsed = timestamp() - start; - this.sendPerformanceEvent("UpdateGraph", elapsed); - this.writeLog(`Finishing updateGraphWorker: Project: ${this.getProjectName()} projectStateVersion: ${this.projectStateVersion} projectProgramVersion: ${this.projectProgramVersion} structureChanged: ${hasNewProgram}${this.program ? ` structureIsReused:: ${StructureIsReused[this.program.structureIsReused]}` : ""} Elapsed: ${elapsed}ms`); - if (this.projectService.logger.isTestLogger) { - if (this.program !== oldProgram) { - this.print( - /*writeProjectFileNames*/ - true, - this.hasAddedorRemovedFiles, - /*writeFileVersionAndText*/ - true - ); - } else { - this.writeLog(`Same program as before`); - } - } else if (this.hasAddedorRemovedFiles) { - this.print( - /*writeProjectFileNames*/ - true, - /*writeFileExplaination*/ - true, - /*writeFileVersionAndText*/ - false - ); - } else if (this.program !== oldProgram) { - this.writeLog(`Different program with same set of files`); - } - this.projectService.verifyDocumentRegistry(); - return hasNewProgram; - } - /** @internal */ - sendPerformanceEvent(kind, durationMs) { - this.projectService.sendPerformanceEvent(kind, durationMs); - } - detachScriptInfoFromProject(uncheckedFileName, noRemoveResolution) { - const scriptInfoToDetach = this.projectService.getScriptInfo(uncheckedFileName); - if (scriptInfoToDetach) { - scriptInfoToDetach.detachFromProject(this); - if (!noRemoveResolution) { - this.resolutionCache.removeResolutionsOfFile(scriptInfoToDetach.path); - } - } - } - addMissingFileWatcher(missingFilePath, missingFileName) { - var _a; - if (isConfiguredProject(this)) { - const configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(missingFilePath); - if ((_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config) == null ? void 0 : _a.projects.has(this.canonicalConfigFilePath)) return noopFileWatcher; - } - const fileWatcher = this.projectService.watchFactory.watchFile( - getNormalizedAbsolutePath(missingFileName, this.currentDirectory), - (fileName, eventKind) => { - if (isConfiguredProject(this)) { - this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind); - } - if (eventKind === 0 /* Created */ && this.missingFilesMap.has(missingFilePath)) { - this.missingFilesMap.delete(missingFilePath); - fileWatcher.close(); - this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); - } - }, - 500 /* Medium */, - this.projectService.getWatchOptions(this), - WatchType.MissingFile, - this - ); - return fileWatcher; - } - isWatchedMissingFile(path) { - return !!this.missingFilesMap && this.missingFilesMap.has(path); - } - /** @internal */ - addGeneratedFileWatch(generatedFile, sourceFile) { - if (this.compilerOptions.outFile) { - if (!this.generatedFilesMap) { - this.generatedFilesMap = this.createGeneratedFileWatcher(generatedFile); - } - } else { - const path = this.toPath(sourceFile); - if (this.generatedFilesMap) { - if (isGeneratedFileWatcher(this.generatedFilesMap)) { - Debug.fail(`${this.projectName} Expected to not have --out watcher for generated file with options: ${JSON.stringify(this.compilerOptions)}`); - return; - } - if (this.generatedFilesMap.has(path)) return; - } else { - this.generatedFilesMap = /* @__PURE__ */ new Map(); - } - this.generatedFilesMap.set(path, this.createGeneratedFileWatcher(generatedFile)); - } - } - createGeneratedFileWatcher(generatedFile) { - return { - generatedFilePath: this.toPath(generatedFile), - watcher: this.projectService.watchFactory.watchFile( - generatedFile, - () => { - this.clearSourceMapperCache(); - this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); - }, - 2e3 /* High */, - this.projectService.getWatchOptions(this), - WatchType.MissingGeneratedFile, - this - ) - }; - } - isValidGeneratedFileWatcher(generateFile, watcher) { - return this.toPath(generateFile) === watcher.generatedFilePath; - } - clearGeneratedFileWatch() { - if (this.generatedFilesMap) { - if (isGeneratedFileWatcher(this.generatedFilesMap)) { - closeFileWatcherOf(this.generatedFilesMap); - } else { - clearMap(this.generatedFilesMap, closeFileWatcherOf); - } - this.generatedFilesMap = void 0; - } - } - getScriptInfoForNormalizedPath(fileName) { - const scriptInfo = this.projectService.getScriptInfoForPath(this.toPath(fileName)); - if (scriptInfo && !scriptInfo.isAttached(this)) { - return Errors.ThrowProjectDoesNotContainDocument(fileName, this); - } - return scriptInfo; - } - getScriptInfo(uncheckedFileName) { - return this.projectService.getScriptInfo(uncheckedFileName); - } - filesToString(writeProjectFileNames) { - return this.filesToStringWorker( - writeProjectFileNames, - /*writeFileExplaination*/ - true, - /*writeFileVersionAndText*/ - false - ); - } - filesToStringWorker(writeProjectFileNames, writeFileExplaination, writeFileVersionAndText) { - if (this.isInitialLoadPending()) return " Files (0) InitialLoadPending\n"; - if (!this.program) return " Files (0) NoProgram\n"; - const sourceFiles = this.program.getSourceFiles(); - let strBuilder = ` Files (${sourceFiles.length}) -`; - if (writeProjectFileNames) { - for (const file of sourceFiles) { - strBuilder += ` ${file.fileName}${writeFileVersionAndText ? ` ${file.version} ${JSON.stringify(file.text)}` : ""} -`; - } - if (writeFileExplaination) { - strBuilder += "\n\n"; - explainFiles(this.program, (s) => strBuilder += ` ${s} -`); - } - } - return strBuilder; - } - /** @internal */ - print(writeProjectFileNames, writeFileExplaination, writeFileVersionAndText) { - var _a; - this.writeLog(`Project '${this.projectName}' (${ProjectKind[this.projectKind]})`); - this.writeLog(this.filesToStringWorker( - writeProjectFileNames && this.projectService.logger.hasLevel(3 /* verbose */), - writeFileExplaination && this.projectService.logger.hasLevel(3 /* verbose */), - writeFileVersionAndText && this.projectService.logger.hasLevel(3 /* verbose */) - )); - this.writeLog("-----------------------------------------------"); - if (this.autoImportProviderHost) { - this.autoImportProviderHost.print( - /*writeProjectFileNames*/ - false, - /*writeFileExplaination*/ - false, - /*writeFileVersionAndText*/ - false - ); - } - (_a = this.noDtsResolutionProject) == null ? void 0 : _a.print( - /*writeProjectFileNames*/ - false, - /*writeFileExplaination*/ - false, - /*writeFileVersionAndText*/ - false - ); - } - setCompilerOptions(compilerOptions) { - var _a; - if (compilerOptions) { - compilerOptions.allowNonTsExtensions = true; - const oldOptions = this.compilerOptions; - this.compilerOptions = compilerOptions; - this.setInternalCompilerOptionsForEmittingJsFiles(); - (_a = this.noDtsResolutionProject) == null ? void 0 : _a.setCompilerOptions(this.getCompilerOptionsForNoDtsResolutionProject()); - if (changesAffectModuleResolution(oldOptions, compilerOptions)) { - this.cachedUnresolvedImportsPerFile.clear(); - this.lastCachedUnresolvedImportsList = void 0; - this.resolutionCache.onChangesAffectModuleResolution(); - this.moduleSpecifierCache.clear(); - } - this.markAsDirty(); - } - } - /** @internal */ - setWatchOptions(watchOptions) { - this.watchOptions = watchOptions; - } - /** @internal */ - getWatchOptions() { - return this.watchOptions; - } - setTypeAcquisition(newTypeAcquisition) { - if (newTypeAcquisition) { - this.typeAcquisition = this.removeLocalTypingsFromTypeAcquisition(newTypeAcquisition); - } - } - getTypeAcquisition() { - return this.typeAcquisition || {}; - } - /** @internal */ - getChangesSinceVersion(lastKnownVersion, includeProjectReferenceRedirectInfo) { - var _a, _b; - const includeProjectReferenceRedirectInfoIfRequested = includeProjectReferenceRedirectInfo ? (files) => arrayFrom(files.entries(), ([fileName, isSourceOfProjectReferenceRedirect]) => ({ - fileName, - isSourceOfProjectReferenceRedirect - })) : (files) => arrayFrom(files.keys()); - if (!this.isInitialLoadPending()) { - updateProjectIfDirty(this); - } - const info = { - projectName: this.getProjectName(), - version: this.projectProgramVersion, - isInferred: isInferredProject(this), - options: this.getCompilationSettings(), - languageServiceDisabled: !this.languageServiceEnabled, - lastFileExceededProgramSize: this.lastFileExceededProgramSize - }; - const updatedFileNames = this.updatedFileNames; - this.updatedFileNames = void 0; - if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { - if (this.projectProgramVersion === this.lastReportedVersion && !updatedFileNames) { - return { info, projectErrors: this.getGlobalProjectErrors() }; - } - const lastReportedFileNames = this.lastReportedFileNames; - const externalFiles = ((_a = this.externalFiles) == null ? void 0 : _a.map((f) => ({ - fileName: toNormalizedPath(f), - isSourceOfProjectReferenceRedirect: false - }))) || emptyArray2; - const currentFiles = arrayToMap( - this.getFileNamesWithRedirectInfo(!!includeProjectReferenceRedirectInfo).concat(externalFiles), - (info2) => info2.fileName, - (info2) => info2.isSourceOfProjectReferenceRedirect - ); - const added = /* @__PURE__ */ new Map(); - const removed = /* @__PURE__ */ new Map(); - const updated = updatedFileNames ? arrayFrom(updatedFileNames.keys()) : []; - const updatedRedirects = []; - forEachEntry(currentFiles, (isSourceOfProjectReferenceRedirect, fileName) => { - if (!lastReportedFileNames.has(fileName)) { - added.set(fileName, isSourceOfProjectReferenceRedirect); - } else if (includeProjectReferenceRedirectInfo && isSourceOfProjectReferenceRedirect !== lastReportedFileNames.get(fileName)) { - updatedRedirects.push({ - fileName, - isSourceOfProjectReferenceRedirect - }); - } - }); - forEachEntry(lastReportedFileNames, (isSourceOfProjectReferenceRedirect, fileName) => { - if (!currentFiles.has(fileName)) { - removed.set(fileName, isSourceOfProjectReferenceRedirect); - } - }); - this.lastReportedFileNames = currentFiles; - this.lastReportedVersion = this.projectProgramVersion; - return { - info, - changes: { - added: includeProjectReferenceRedirectInfoIfRequested(added), - removed: includeProjectReferenceRedirectInfoIfRequested(removed), - updated: includeProjectReferenceRedirectInfo ? updated.map((fileName) => ({ - fileName, - isSourceOfProjectReferenceRedirect: this.isSourceOfProjectReferenceRedirect(fileName) - })) : updated, - updatedRedirects: includeProjectReferenceRedirectInfo ? updatedRedirects : void 0 - }, - projectErrors: this.getGlobalProjectErrors() - }; - } else { - const projectFileNames = this.getFileNamesWithRedirectInfo(!!includeProjectReferenceRedirectInfo); - const externalFiles = ((_b = this.externalFiles) == null ? void 0 : _b.map((f) => ({ - fileName: toNormalizedPath(f), - isSourceOfProjectReferenceRedirect: false - }))) || emptyArray2; - const allFiles = projectFileNames.concat(externalFiles); - this.lastReportedFileNames = arrayToMap( - allFiles, - (info2) => info2.fileName, - (info2) => info2.isSourceOfProjectReferenceRedirect - ); - this.lastReportedVersion = this.projectProgramVersion; - return { - info, - files: includeProjectReferenceRedirectInfo ? allFiles : allFiles.map((f) => f.fileName), - projectErrors: this.getGlobalProjectErrors() - }; - } - } - // remove a root file from project - removeRoot(info) { - this.rootFilesMap.delete(info.path); - } - /** @internal */ - isSourceOfProjectReferenceRedirect(fileName) { - return !!this.program && this.program.isSourceOfProjectReferenceRedirect(fileName); - } - /** @internal */ - getGlobalPluginSearchPaths() { - return [ - ...this.projectService.pluginProbeLocations, - // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ - combinePaths(this.projectService.getExecutingFilePath(), "../../..") - ]; - } - enableGlobalPlugins(options) { - if (!this.projectService.globalPlugins.length) return; - const host = this.projectService.host; - if (!host.require && !host.importPlugin) { - this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); - return; - } - const searchPaths = this.getGlobalPluginSearchPaths(); - for (const globalPluginName of this.projectService.globalPlugins) { - if (!globalPluginName) continue; - if (options.plugins && options.plugins.some((p) => p.name === globalPluginName)) continue; - this.projectService.logger.info(`Loading global plugin ${globalPluginName}`); - this.enablePlugin({ name: globalPluginName, global: true }, searchPaths); - } - } - enablePlugin(pluginConfigEntry, searchPaths) { - this.projectService.requestEnablePlugin(this, pluginConfigEntry, searchPaths); - } - /** @internal */ - enableProxy(pluginModuleFactory, configEntry) { - try { - if (typeof pluginModuleFactory !== "function") { - this.projectService.logger.info(`Skipped loading plugin ${configEntry.name} because it did not expose a proper factory function`); - return; - } - const info = { - config: configEntry, - project: this, - languageService: this.languageService, - languageServiceHost: this, - serverHost: this.projectService.host, - session: this.projectService.session - }; - const pluginModule = pluginModuleFactory({ typescript: ts_exports2 }); - const newLS = pluginModule.create(info); - for (const k of Object.keys(this.languageService)) { - if (!(k in newLS)) { - this.projectService.logger.info(`Plugin activation warning: Missing proxied method ${k} in created LS. Patching.`); - newLS[k] = this.languageService[k]; - } - } - this.projectService.logger.info(`Plugin validation succeeded`); - this.languageService = newLS; - this.plugins.push({ name: configEntry.name, module: pluginModule }); - } catch (e) { - this.projectService.logger.info(`Plugin activation failed: ${e}`); - } - } - /** @internal */ - onPluginConfigurationChanged(pluginName, configuration) { - this.plugins.filter((plugin) => plugin.name === pluginName).forEach((plugin) => { - if (plugin.module.onConfigurationChanged) { - plugin.module.onConfigurationChanged(configuration); - } - }); - } - /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ - refreshDiagnostics() { - this.projectService.sendProjectsUpdatedInBackgroundEvent(); - } - /** @internal */ - getPackageJsonsVisibleToFile(fileName, rootDir) { - if (this.projectService.serverMode !== 0 /* Semantic */) return emptyArray2; - return this.projectService.getPackageJsonsVisibleToFile(fileName, this, rootDir); - } - /** @internal */ - getNearestAncestorDirectoryWithPackageJson(fileName) { - return this.projectService.getNearestAncestorDirectoryWithPackageJson(fileName); - } - /** @internal */ - getPackageJsonsForAutoImport(rootDir) { - return this.getPackageJsonsVisibleToFile(combinePaths(this.currentDirectory, inferredTypesContainingFile), rootDir); - } - /** @internal */ - getPackageJsonCache() { - return this.projectService.packageJsonCache; - } - /** @internal */ - getCachedExportInfoMap() { - return this.exportMapCache || (this.exportMapCache = createCacheableExportInfoMap(this)); - } - /** @internal */ - clearCachedExportInfoMap() { - var _a; - (_a = this.exportMapCache) == null ? void 0 : _a.clear(); - } - /** @internal */ - getModuleSpecifierCache() { - return this.moduleSpecifierCache; - } - /** @internal */ - includePackageJsonAutoImports() { - if (this.projectService.includePackageJsonAutoImports() === 0 /* Off */ || !this.languageServiceEnabled || isInsideNodeModules(this.currentDirectory) || !this.isDefaultProjectForOpenFiles()) { - return 0 /* Off */; - } - return this.projectService.includePackageJsonAutoImports(); - } - /** @internal */ - getHostForAutoImportProvider() { - var _a, _b; - if (this.program) { - return { - fileExists: this.program.fileExists, - directoryExists: this.program.directoryExists, - realpath: this.program.realpath || ((_a = this.projectService.host.realpath) == null ? void 0 : _a.bind(this.projectService.host)), - getCurrentDirectory: this.getCurrentDirectory.bind(this), - readFile: this.projectService.host.readFile.bind(this.projectService.host), - getDirectories: this.projectService.host.getDirectories.bind(this.projectService.host), - trace: (_b = this.projectService.host.trace) == null ? void 0 : _b.bind(this.projectService.host), - useCaseSensitiveFileNames: this.program.useCaseSensitiveFileNames(), - readDirectory: this.projectService.host.readDirectory.bind(this.projectService.host) - }; - } - return this.projectService.host; - } - /** @internal */ - getPackageJsonAutoImportProvider() { - var _a, _b, _c; - if (this.autoImportProviderHost === false) { - return void 0; - } - if (this.projectService.serverMode !== 0 /* Semantic */) { - this.autoImportProviderHost = false; - return void 0; - } - if (this.autoImportProviderHost) { - updateProjectIfDirty(this.autoImportProviderHost); - if (this.autoImportProviderHost.isEmpty()) { - this.autoImportProviderHost.close(); - this.autoImportProviderHost = void 0; - return void 0; - } - return this.autoImportProviderHost.getCurrentProgram(); - } - const dependencySelection = this.includePackageJsonAutoImports(); - 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); - if (this.autoImportProviderHost) { - updateProjectIfDirty(this.autoImportProviderHost); - this.sendPerformanceEvent("CreatePackageJsonAutoImportProvider", timestamp() - start); - (_b = tracing) == null ? void 0 : _b.pop(); - return this.autoImportProviderHost.getCurrentProgram(); - } - (_c = tracing) == null ? void 0 : _c.pop(); - } - } - isDefaultProjectForOpenFiles() { - return !!forEachEntry( - this.projectService.openFiles, - (_projectRootPath, path) => this.projectService.tryGetDefaultProjectForFile(this.projectService.getScriptInfoForPath(path)) === this - ); - } - /** @internal */ - watchNodeModulesForPackageJsonChanges(directoryPath) { - return this.projectService.watchPackageJsonsInNodeModules(directoryPath, this); - } - /** @internal */ - getIncompleteCompletionsCache() { - return this.projectService.getIncompleteCompletionsCache(); - } - /** @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); - } - if (this.noDtsResolutionProject.rootFile !== rootFile) { - this.projectService.setFileNamesOfAutpImportProviderOrAuxillaryProject(this.noDtsResolutionProject, [rootFile]); - this.noDtsResolutionProject.rootFile = rootFile; - } - return this.noDtsResolutionProject; - } - /** @internal */ - runWithTemporaryFileUpdate(rootFile, updatedText, cb) { - var _a, _b, _c, _d; - const originalProgram = this.program; - const rootSourceFile = Debug.checkDefined((_a = this.program) == null ? void 0 : _a.getSourceFile(rootFile), "Expected file to be part of program"); - const originalText = Debug.checkDefined(rootSourceFile.getFullText()); - (_b = this.getScriptInfo(rootFile)) == null ? void 0 : _b.editContent(0, originalText.length, updatedText); - this.updateGraph(); - try { - cb(this.program, originalProgram, (_c = this.program) == null ? void 0 : _c.getSourceFile(rootFile)); - } finally { - (_d = this.getScriptInfo(rootFile)) == null ? void 0 : _d.editContent(0, updatedText.length, originalText); - } - } - getCompilerOptionsForNoDtsResolutionProject() { - return { - ...this.getCompilerOptions(), - noDtsResolution: true, - allowJs: true, - maxNodeModuleJsDepth: 3, - diagnostics: false, - skipLibCheck: true, - sourceMap: false, - types: emptyArray, - lib: emptyArray, - noLib: true - }; - } -}; -function getUnresolvedImports(program, cachedUnresolvedImportsPerFile) { - var _a, _b; - const sourceFiles = program.getSourceFiles(); - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "getUnresolvedImports", { count: sourceFiles.length }); - const ambientModules = program.getTypeChecker().getAmbientModules().map((mod) => stripQuotes(mod.getName())); - const result = sortAndDeduplicate(flatMap(sourceFiles, (sourceFile) => extractUnresolvedImportsFromSourceFile( - program, - sourceFile, - ambientModules, - cachedUnresolvedImportsPerFile - ))); - (_b = tracing) == null ? void 0 : _b.pop(); - return result; -} -function extractUnresolvedImportsFromSourceFile(program, file, ambientModules, cachedUnresolvedImportsPerFile) { - return getOrUpdate(cachedUnresolvedImportsPerFile, file.path, () => { - let unresolvedImports; - program.forEachResolvedModule(({ resolvedModule }, name) => { - if ((!resolvedModule || !resolutionExtensionIsTSOrJson(resolvedModule.extension)) && !isExternalModuleNameRelative(name) && !ambientModules.some((m) => m === name)) { - unresolvedImports = append(unresolvedImports, parsePackageName(name).packageName); - } - }, file); - return unresolvedImports || emptyArray2; - }); -} -var InferredProject2 = class extends Project2 { - /** @internal */ - constructor(projectService, documentRegistry, compilerOptions, watchOptions, projectRootPath, currentDirectory, typeAcquisition) { - super( - projectService.newInferredProjectName(), - 0 /* Inferred */, - projectService, - documentRegistry, - // TODO: GH#18217 - /*files*/ - void 0, - /*lastFileExceededProgramSize*/ - void 0, - compilerOptions, - /*compileOnSaveEnabled*/ - false, - watchOptions, - projectService.host, - currentDirectory - ); - this._isJsInferredProject = false; - this.typeAcquisition = typeAcquisition; - this.projectRootPath = projectRootPath && projectService.toCanonicalFileName(projectRootPath); - if (!projectRootPath && !projectService.useSingleInferredProject) { - this.canonicalCurrentDirectory = projectService.toCanonicalFileName(this.currentDirectory); - } - this.enableGlobalPlugins(this.getCompilerOptions()); - } - toggleJsInferredProject(isJsInferredProject) { - if (isJsInferredProject !== this._isJsInferredProject) { - this._isJsInferredProject = isJsInferredProject; - this.setCompilerOptions(); - } - } - setCompilerOptions(options) { - if (!options && !this.getCompilationSettings()) { - return; - } - const newOptions = cloneCompilerOptions(options || this.getCompilationSettings()); - if (this._isJsInferredProject && typeof newOptions.maxNodeModuleJsDepth !== "number") { - newOptions.maxNodeModuleJsDepth = 2; - } else if (!this._isJsInferredProject) { - newOptions.maxNodeModuleJsDepth = void 0; - } - newOptions.allowJs = true; - super.setCompilerOptions(newOptions); - } - addRoot(info) { - Debug.assert(info.isScriptOpen()); - this.projectService.startWatchingConfigFilesForInferredProjectRoot(info); - if (!this._isJsInferredProject && info.isJavaScript()) { - this.toggleJsInferredProject( - /*isJsInferredProject*/ - true - ); - } else if (this.isOrphan() && this._isJsInferredProject && !info.isJavaScript()) { - this.toggleJsInferredProject( - /*isJsInferredProject*/ - false - ); - } - super.addRoot(info); - } - removeRoot(info) { - this.projectService.stopWatchingConfigFilesForScriptInfo(info); - super.removeRoot(info); - if (!this.isOrphan() && this._isJsInferredProject && info.isJavaScript()) { - if (every(this.getRootScriptInfos(), (rootInfo) => !rootInfo.isJavaScript())) { - this.toggleJsInferredProject( - /*isJsInferredProject*/ - false - ); - } - } - } - /** @internal */ - isOrphan() { - return !this.hasRoots(); - } - isProjectWithSingleRoot() { - return !this.projectRootPath && !this.projectService.useSingleInferredProject || this.getRootScriptInfos().length === 1; - } - close() { - forEach(this.getRootScriptInfos(), (info) => this.projectService.stopWatchingConfigFilesForScriptInfo(info)); - super.close(); - } - getTypeAcquisition() { - return this.typeAcquisition || { - enable: allRootFilesAreJsOrDts(this), - include: emptyArray, - exclude: emptyArray - }; - } -}; -var AuxiliaryProject = class extends Project2 { - constructor(projectService, documentRegistry, compilerOptions, currentDirectory) { - super( - projectService.newAuxiliaryProjectName(), - 4 /* Auxiliary */, - projectService, - documentRegistry, - /*hasExplicitListOfFiles*/ - false, - /*lastFileExceededProgramSize*/ - void 0, - compilerOptions, - /*compileOnSaveEnabled*/ - false, - /*watchOptions*/ - void 0, - projectService.host, - currentDirectory - ); - } - isOrphan() { - return true; - } - scheduleInvalidateResolutionsOfFailedLookupLocations() { - return; - } -}; -var _AutoImportProviderProject = class _AutoImportProviderProject extends Project2 { - /** @internal */ - constructor(hostProject, initialRootNames, documentRegistry, compilerOptions) { - super( - hostProject.projectService.newAutoImportProviderProjectName(), - 3 /* AutoImportProvider */, - hostProject.projectService, - documentRegistry, - /*hasExplicitListOfFiles*/ - false, - /*lastFileExceededProgramSize*/ - void 0, - compilerOptions, - /*compileOnSaveEnabled*/ - false, - hostProject.getWatchOptions(), - hostProject.projectService.host, - hostProject.currentDirectory - ); - this.hostProject = hostProject; - this.rootFileNames = initialRootNames; - this.useSourceOfProjectReferenceRedirect = maybeBind(this.hostProject, this.hostProject.useSourceOfProjectReferenceRedirect); - this.getParsedCommandLine = maybeBind(this.hostProject, this.hostProject.getParsedCommandLine); - } - /** @internal */ - static getRootFileNames(dependencySelection, hostProject, host, compilerOptions) { - var _a, _b; - if (!dependencySelection) { - return emptyArray; - } - const program = hostProject.getCurrentProgram(); - if (!program) { - return emptyArray; - } - const start = timestamp(); - let dependencyNames; - let rootNames; - const rootFileName = combinePaths(hostProject.currentDirectory, inferredTypesContainingFile); - const packageJsons = hostProject.getPackageJsonsForAutoImport(combinePaths(hostProject.currentDirectory, rootFileName)); - for (const packageJson of packageJsons) { - (_a = packageJson.dependencies) == null ? void 0 : _a.forEach((_, dependenyName) => addDependency(dependenyName)); - (_b = packageJson.peerDependencies) == null ? void 0 : _b.forEach((_, dependencyName) => addDependency(dependencyName)); - } - let dependenciesAdded = 0; - if (dependencyNames) { - const symlinkCache = hostProject.getSymlinkCache(); - for (const name of arrayFrom(dependencyNames.keys())) { - if (dependencySelection === 2 /* Auto */ && dependenciesAdded > this.maxDependencies) { - hostProject.log(`AutoImportProviderProject: attempted to add more than ${this.maxDependencies} dependencies. Aborting.`); - return emptyArray; - } - const packageJson = resolvePackageNameToPackageJson( - name, - hostProject.currentDirectory, - compilerOptions, - host, - program.getModuleResolutionCache() - ); - if (packageJson) { - const entrypoints = getRootNamesFromPackageJson(packageJson, program, symlinkCache); - if (entrypoints) { - dependenciesAdded += addRootNames(entrypoints); - continue; - } - } - const done = forEach([hostProject.currentDirectory, hostProject.getGlobalTypingsCacheLocation()], (directory) => { - if (directory) { - const typesPackageJson = resolvePackageNameToPackageJson( - `@types/${name}`, - directory, - compilerOptions, - host, - program.getModuleResolutionCache() - ); - if (typesPackageJson) { - const entrypoints = getRootNamesFromPackageJson(typesPackageJson, program, symlinkCache); - dependenciesAdded += addRootNames(entrypoints); - return true; - } - } - }); - if (done) continue; - if (packageJson && compilerOptions.allowJs && compilerOptions.maxNodeModuleJsDepth) { - const entrypoints = getRootNamesFromPackageJson( - packageJson, - program, - symlinkCache, - /*resolveJs*/ - true - ); - dependenciesAdded += addRootNames(entrypoints); - } - } - } - const references = program.getResolvedProjectReferences(); - let referencesAddded = 0; - if ((references == null ? void 0 : references.length) && hostProject.projectService.getHostPreferences().includeCompletionsForModuleExports) { - references.forEach((ref) => { - if (ref == null ? void 0 : ref.commandLine.options.outFile) { - referencesAddded += addRootNames(filterEntrypoints([ - changeExtension(ref.commandLine.options.outFile, ".d.ts") - ])); - } else if (ref) { - const getCommonSourceDirectory2 = memoize( - () => getCommonSourceDirectoryOfConfig( - ref.commandLine, - !hostProject.useCaseSensitiveFileNames() - ) - ); - referencesAddded += addRootNames(filterEntrypoints(mapDefined( - ref.commandLine.fileNames, - (fileName) => !isDeclarationFileName(fileName) && !fileExtensionIs(fileName, ".json" /* Json */) && !program.getSourceFile(fileName) ? getOutputDeclarationFileName( - fileName, - ref.commandLine, - !hostProject.useCaseSensitiveFileNames(), - getCommonSourceDirectory2 - ) : void 0 - ))); - } - }); - } - if (rootNames == null ? void 0 : rootNames.size) { - hostProject.log(`AutoImportProviderProject: found ${rootNames.size} root files in ${dependenciesAdded} dependencies ${referencesAddded} referenced projects in ${timestamp() - start} ms`); - } - return rootNames ? arrayFrom(rootNames.values()) : emptyArray; - function addRootNames(entrypoints) { - if (!(entrypoints == null ? void 0 : entrypoints.length)) return 0; - rootNames ?? (rootNames = /* @__PURE__ */ new Set()); - entrypoints.forEach((entry) => rootNames.add(entry)); - return 1; - } - function addDependency(dependency) { - if (!startsWith(dependency, "@types/")) { - (dependencyNames || (dependencyNames = /* @__PURE__ */ new Set())).add(dependency); - } - } - function getRootNamesFromPackageJson(packageJson, program2, symlinkCache, resolveJs) { - var _a2; - const entrypoints = getEntrypointsFromPackageJsonInfo( - packageJson, - compilerOptions, - host, - program2.getModuleResolutionCache(), - resolveJs - ); - if (entrypoints) { - const real = (_a2 = host.realpath) == null ? void 0 : _a2.call(host, packageJson.packageDirectory); - const realPath2 = real ? hostProject.toPath(real) : void 0; - const isSymlink = realPath2 && realPath2 !== hostProject.toPath(packageJson.packageDirectory); - if (isSymlink) { - symlinkCache.setSymlinkedDirectory(packageJson.packageDirectory, { - real: ensureTrailingDirectorySeparator(real), - realPath: ensureTrailingDirectorySeparator(realPath2) - }); - } - return filterEntrypoints(entrypoints, isSymlink ? (entrypoint) => entrypoint.replace(packageJson.packageDirectory, real) : void 0); - } - } - function filterEntrypoints(entrypoints, symlinkName) { - return mapDefined(entrypoints, (entrypoint) => { - const resolvedFileName = symlinkName ? symlinkName(entrypoint) : entrypoint; - if (!program.getSourceFile(resolvedFileName) && !(symlinkName && program.getSourceFile(entrypoint))) { - return resolvedFileName; - } - }); - } - } - /** @internal */ - static create(dependencySelection, hostProject, host, documentRegistry) { - if (dependencySelection === 0 /* Off */) { - return void 0; - } - const compilerOptions = { - ...hostProject.getCompilerOptions(), - ...this.compilerOptionsOverrides - }; - const rootNames = this.getRootFileNames(dependencySelection, hostProject, host, compilerOptions); - if (!rootNames.length) { - return void 0; - } - return new _AutoImportProviderProject(hostProject, rootNames, documentRegistry, compilerOptions); - } - /** @internal */ - isEmpty() { - return !some(this.rootFileNames); - } - /** @internal */ - isOrphan() { - return true; - } - updateGraph() { - let rootFileNames = this.rootFileNames; - if (!rootFileNames) { - rootFileNames = _AutoImportProviderProject.getRootFileNames( - this.hostProject.includePackageJsonAutoImports(), - this.hostProject, - this.hostProject.getHostForAutoImportProvider(), - this.getCompilationSettings() - ); - } - this.projectService.setFileNamesOfAutpImportProviderOrAuxillaryProject(this, rootFileNames); - this.rootFileNames = rootFileNames; - const oldProgram = this.getCurrentProgram(); - const hasSameSetOfFiles = super.updateGraph(); - if (oldProgram && oldProgram !== this.getCurrentProgram()) { - this.hostProject.clearCachedExportInfoMap(); - } - return hasSameSetOfFiles; - } - /** @internal */ - scheduleInvalidateResolutionsOfFailedLookupLocations() { - return; - } - hasRoots() { - var _a; - return !!((_a = this.rootFileNames) == null ? void 0 : _a.length); - } - /** @internal */ - markAsDirty() { - this.rootFileNames = void 0; - super.markAsDirty(); - } - getScriptFileNames() { - return this.rootFileNames || emptyArray; - } - getLanguageService() { - throw new Error("AutoImportProviderProject language service should never be used. To get the program, use `project.getCurrentProgram()`."); - } - /** @internal */ - onAutoImportProviderSettingsChanged() { - throw new Error("AutoImportProviderProject is an auto import provider; use `markAsDirty()` instead."); - } - /** @internal */ - onPackageJsonChange() { - throw new Error("package.json changes should be notified on an AutoImportProvider's host project"); - } - getHostForAutoImportProvider() { - throw new Error("AutoImportProviderProject cannot provide its own host; use `hostProject.getModuleResolutionHostForAutomImportProvider()` instead."); - } - getProjectReferences() { - return this.hostProject.getProjectReferences(); - } - /** @internal */ - includePackageJsonAutoImports() { - return 0 /* Off */; - } - /** @internal */ - getSymlinkCache() { - return this.hostProject.getSymlinkCache(); - } - /** @internal */ - getModuleResolutionCache() { - var _a; - return (_a = this.hostProject.getCurrentProgram()) == null ? void 0 : _a.getModuleResolutionCache(); - } -}; -_AutoImportProviderProject.maxDependencies = 10; -/** @internal */ -_AutoImportProviderProject.compilerOptionsOverrides = { - diagnostics: false, - skipLibCheck: true, - sourceMap: false, - types: emptyArray, - lib: emptyArray, - noLib: true -}; -var AutoImportProviderProject = _AutoImportProviderProject; -var ConfiguredProject2 = class extends Project2 { - /** @internal */ - constructor(configFileName, canonicalConfigFilePath, projectService, documentRegistry, cachedDirectoryStructureHost, pendingUpdateReason) { - super( - configFileName, - 1 /* Configured */, - projectService, - documentRegistry, - /*hasExplicitListOfFiles*/ - false, - /*lastFileExceededProgramSize*/ - void 0, - /*compilerOptions*/ - {}, - /*compileOnSaveEnabled*/ - false, - /*watchOptions*/ - void 0, - cachedDirectoryStructureHost, - getDirectoryPath(configFileName) - ); - this.canonicalConfigFilePath = canonicalConfigFilePath; - /** @internal */ - this.openFileWatchTriggered = /* @__PURE__ */ new Map(); - /** @internal */ - this.canConfigFileJsonReportNoInputFiles = false; - /** @internal */ - this.isInitialLoadPending = returnTrue; - /** @internal */ - this.sendLoadingProjectFinish = false; - this.pendingUpdateLevel = 2 /* Full */; - this.pendingUpdateReason = pendingUpdateReason; - } - /** @internal */ - setCompilerHost(host) { - this.compilerHost = host; - } - /** @internal */ - getCompilerHost() { - return this.compilerHost; - } - /** @internal */ - useSourceOfProjectReferenceRedirect() { - return this.languageServiceEnabled; - } - /** @internal */ - getParsedCommandLine(fileName) { - const configFileName = asNormalizedPath(normalizePath(fileName)); - const canonicalConfigFilePath = asNormalizedPath(this.projectService.toCanonicalFileName(configFileName)); - let configFileExistenceInfo = this.projectService.configFileExistenceInfoCache.get(canonicalConfigFilePath); - if (!configFileExistenceInfo) { - this.projectService.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { exists: this.projectService.host.fileExists(configFileName) }); - } - this.projectService.ensureParsedConfigUptoDate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, this); - if (this.languageServiceEnabled && this.projectService.serverMode === 0 /* Semantic */) { - this.projectService.watchWildcards(configFileName, configFileExistenceInfo, this); - } - return configFileExistenceInfo.exists ? configFileExistenceInfo.config.parsedCommandLine : void 0; - } - /** @internal */ - onReleaseParsedCommandLine(fileName) { - this.releaseParsedConfig(asNormalizedPath(this.projectService.toCanonicalFileName(asNormalizedPath(normalizePath(fileName))))); - } - releaseParsedConfig(canonicalConfigFilePath) { - this.projectService.stopWatchingWildCards(canonicalConfigFilePath, this); - this.projectService.releaseParsedConfig(canonicalConfigFilePath, this); - } - /** - * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph - * @returns: true if set of files in the project stays the same and false - otherwise. - */ - updateGraph() { - if (this.deferredClose) return false; - const isDirty = this.dirty; - this.isInitialLoadPending = returnFalse; - const updateLevel = this.pendingUpdateLevel; - this.pendingUpdateLevel = 0 /* Update */; - let result; - switch (updateLevel) { - case 1 /* RootNamesAndUpdate */: - this.openFileWatchTriggered.clear(); - result = this.projectService.reloadFileNamesOfConfiguredProject(this); - break; - case 2 /* Full */: - this.openFileWatchTriggered.clear(); - const reason = Debug.checkDefined(this.pendingUpdateReason); - this.projectService.reloadConfiguredProject(this, reason); - result = true; - break; - default: - result = super.updateGraph(); - } - this.compilerHost = void 0; - this.projectService.sendProjectLoadingFinishEvent(this); - this.projectService.sendProjectTelemetry(this); - if (updateLevel === 2 /* Full */ || // Already sent event through reload - result && // Not new program - (!isDirty || !this.triggerFileForConfigFileDiag || this.getCurrentProgram().structureIsReused === 2 /* Completely */)) { - this.triggerFileForConfigFileDiag = void 0; - } else if (!this.triggerFileForConfigFileDiag) { - this.projectService.sendConfigFileDiagEvent( - this, - /*triggerFile*/ - void 0, - /*force*/ - false - ); - } - return result; - } - /** @internal */ - getCachedDirectoryStructureHost() { - return this.directoryStructureHost; - } - getConfigFilePath() { - return asNormalizedPath(this.getProjectName()); - } - getProjectReferences() { - return this.projectReferences; - } - updateReferences(refs) { - this.projectReferences = refs; - this.potentialProjectReferences = void 0; - } - /** @internal */ - setPotentialProjectReference(canonicalConfigPath) { - Debug.assert(this.isInitialLoadPending()); - (this.potentialProjectReferences || (this.potentialProjectReferences = /* @__PURE__ */ new Set())).add(canonicalConfigPath); - } - /** @internal */ - getResolvedProjectReferenceToRedirect(fileName) { - const program = this.getCurrentProgram(); - return program && program.getResolvedProjectReferenceToRedirect(fileName); - } - /** @internal */ - forEachResolvedProjectReference(cb) { - var _a; - return (_a = this.getCurrentProgram()) == null ? void 0 : _a.forEachResolvedProjectReference(cb); - } - /** @internal */ - enablePluginsWithOptions(options) { - var _a; - this.plugins.length = 0; - if (!((_a = options.plugins) == null ? void 0 : _a.length) && !this.projectService.globalPlugins.length) return; - const host = this.projectService.host; - if (!host.require && !host.importPlugin) { - this.projectService.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); - return; - } - const searchPaths = this.getGlobalPluginSearchPaths(); - if (this.projectService.allowLocalPluginLoads) { - const local = getDirectoryPath(this.canonicalConfigFilePath); - this.projectService.logger.info(`Local plugin loading enabled; adding ${local} to search paths`); - searchPaths.unshift(local); - } - if (options.plugins) { - for (const pluginConfigEntry of options.plugins) { - this.enablePlugin(pluginConfigEntry, searchPaths); - } - } - return this.enableGlobalPlugins(options); - } - /** - * Get the errors that dont have any file name associated - */ - getGlobalProjectErrors() { - return filter(this.projectErrors, (diagnostic) => !diagnostic.file) || emptyArray2; - } - /** - * Get all the project errors - */ - getAllProjectErrors() { - return this.projectErrors || emptyArray2; - } - setProjectErrors(projectErrors) { - this.projectErrors = projectErrors; - } - close() { - this.projectService.configFileExistenceInfoCache.forEach((_configFileExistenceInfo, canonicalConfigFilePath) => this.releaseParsedConfig(canonicalConfigFilePath)); - this.projectErrors = void 0; - this.openFileWatchTriggered.clear(); - this.compilerHost = void 0; - super.close(); - } - /** @internal */ - markAsDirty() { - if (this.deferredClose) return; - super.markAsDirty(); - } - /** @internal */ - isSolution() { - return this.getRootFilesMap().size === 0 && !this.canConfigFileJsonReportNoInputFiles; - } - /** @internal */ - isOrphan() { - return !!this.deferredClose; - } - getEffectiveTypeRoots() { - return getEffectiveTypeRoots(this.getCompilationSettings(), this) || []; - } - /** @internal */ - updateErrorOnNoInputFiles(fileNames) { - updateErrorForNoInputFiles(fileNames, this.getConfigFilePath(), this.getCompilerOptions().configFile.configFileSpecs, this.projectErrors, this.canConfigFileJsonReportNoInputFiles); - } -}; -var ExternalProject = class extends Project2 { - /** @internal */ - constructor(externalProjectName, projectService, documentRegistry, compilerOptions, lastFileExceededProgramSize, compileOnSaveEnabled, projectFilePath, watchOptions) { - super( - externalProjectName, - 2 /* External */, - projectService, - documentRegistry, - /*hasExplicitListOfFiles*/ - true, - lastFileExceededProgramSize, - compilerOptions, - compileOnSaveEnabled, - watchOptions, - projectService.host, - getDirectoryPath(projectFilePath || normalizeSlashes(externalProjectName)) - ); - this.externalProjectName = externalProjectName; - this.compileOnSaveEnabled = compileOnSaveEnabled; - this.excludedFiles = []; - this.enableGlobalPlugins(this.getCompilerOptions()); - } - updateGraph() { - const result = super.updateGraph(); - this.projectService.sendProjectTelemetry(this); - return result; - } - getExcludedFiles() { - return this.excludedFiles; - } -}; -function isInferredProject(project) { - return project.projectKind === 0 /* Inferred */; -} -function isConfiguredProject(project) { - return project.projectKind === 1 /* Configured */; -} -function isExternalProject(project) { - return project.projectKind === 2 /* External */; -} -function isBackgroundProject(project) { - return project.projectKind === 3 /* AutoImportProvider */ || project.projectKind === 4 /* Auxiliary */; -} -function isProjectDeferredClose(project) { - return isConfiguredProject(project) && !!project.deferredClose; -} - -// src/server/editorServices.ts -var maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; -var maxFileSize = 4 * 1024 * 1024; -var ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; -var ProjectLoadingStartEvent = "projectLoadingStart"; -var ProjectLoadingFinishEvent = "projectLoadingFinish"; -var LargeFileReferencedEvent = "largeFileReferenced"; -var ConfigFileDiagEvent = "configFileDiag"; -var ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; -var ProjectInfoTelemetryEvent = "projectInfo"; -var OpenFileInfoTelemetryEvent = "openFileInfo"; -var CreateFileWatcherEvent = "createFileWatcher"; -var CreateDirectoryWatcherEvent = "createDirectoryWatcher"; -var CloseFileWatcherEvent = "closeFileWatcher"; -var ensureProjectForOpenFileSchedule = "*ensureProjectForOpenFiles*"; -function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) { - const map2 = /* @__PURE__ */ new Map(); - for (const option of commandLineOptions) { - if (typeof option.type === "object") { - const optionMap = option.type; - optionMap.forEach((value) => { - Debug.assert(typeof value === "number"); - }); - map2.set(option.name, optionMap); - } - } - return map2; -} -var compilerOptionConverters = prepareConvertersForEnumLikeCompilerOptions(optionDeclarations); -var watchOptionsConverters = prepareConvertersForEnumLikeCompilerOptions(optionsForWatch); -var indentStyle = new Map(Object.entries({ - none: 0 /* None */, - block: 1 /* Block */, - smart: 2 /* Smart */ -})); -var defaultTypeSafeList = { - "jquery": { - // jquery files can have names like "jquery-1.10.2.min.js" (or "jquery.intellisense.js") - match: /jquery(-[\d.]+)?(\.intellisense)?(\.min)?\.js$/i, - types: ["jquery"] - }, - "WinJS": { - // e.g. c:/temp/UWApp1/lib/winjs-4.0.1/js/base.js - match: /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i, - // If the winjs/base.js file is found.. - exclude: [["^", 1, "/.*"]], - // ..then exclude all files under the winjs folder - types: ["winjs"] - // And fetch the @types package for WinJS - }, - "Kendo": { - // e.g. /Kendo3/wwwroot/lib/kendo/kendo.all.min.js - match: /^(.*\/kendo(-ui)?)\/kendo\.all(\.min)?\.js$/i, - exclude: [["^", 1, "/.*"]], - types: ["kendo-ui"] - }, - "Office Nuget": { - // e.g. /scripts/Office/1/excel-15.debug.js - match: /^(.*\/office\/1)\/excel-\d+\.debug\.js$/i, - // Office NuGet package is installed under a "1/office" folder - exclude: [["^", 1, "/.*"]], - // Exclude that whole folder if the file indicated above is found in it - types: ["office"] - // @types package to fetch instead - }, - "References": { - match: /^(.*\/_references\.js)$/i, - exclude: [["^", 1, "$"]] - } -}; -function convertFormatOptions(protocolOptions) { - if (isString(protocolOptions.indentStyle)) { - protocolOptions.indentStyle = indentStyle.get(protocolOptions.indentStyle.toLowerCase()); - Debug.assert(protocolOptions.indentStyle !== void 0); - } - return protocolOptions; -} -function convertCompilerOptions(protocolOptions) { - compilerOptionConverters.forEach((mappedValues, id) => { - const propertyValue = protocolOptions[id]; - if (isString(propertyValue)) { - protocolOptions[id] = mappedValues.get(propertyValue.toLowerCase()); - } - }); - return protocolOptions; -} -function convertWatchOptions(protocolOptions, currentDirectory) { - let watchOptions; - let errors; - optionsForWatch.forEach((option) => { - const propertyValue = protocolOptions[option.name]; - if (propertyValue === void 0) return; - const mappedValues = watchOptionsConverters.get(option.name); - (watchOptions || (watchOptions = {}))[option.name] = mappedValues ? isString(propertyValue) ? mappedValues.get(propertyValue.toLowerCase()) : propertyValue : convertJsonOption(option, propertyValue, currentDirectory || "", errors || (errors = [])); - }); - return watchOptions && { watchOptions, errors }; -} -function convertTypeAcquisition(protocolOptions) { - let result; - typeAcquisitionDeclarations.forEach((option) => { - const propertyValue = protocolOptions[option.name]; - if (propertyValue === void 0) return; - (result || (result = {}))[option.name] = propertyValue; - }); - return result; -} -function tryConvertScriptKindName(scriptKindName) { - return isString(scriptKindName) ? convertScriptKindName(scriptKindName) : scriptKindName; -} -function convertScriptKindName(scriptKindName) { - switch (scriptKindName) { - case "JS": - return 1 /* JS */; - case "JSX": - return 2 /* JSX */; - case "TS": - return 3 /* TS */; - case "TSX": - return 4 /* TSX */; - default: - return 0 /* Unknown */; - } -} -function convertUserPreferences(preferences) { - const { lazyConfiguredProjectsFromExternalProject: _, ...userPreferences } = preferences; - return userPreferences; -} -var fileNamePropertyReader = { - getFileName: (x) => x, - getScriptKind: (fileName, extraFileExtensions) => { - let result; - if (extraFileExtensions) { - const fileExtension = getAnyExtensionFromPath(fileName); - if (fileExtension) { - some(extraFileExtensions, (info) => { - if (info.extension === fileExtension) { - result = info.scriptKind; - return true; - } - return false; - }); - } - } - return result; - }, - hasMixedContent: (fileName, extraFileExtensions) => some(extraFileExtensions, (ext) => ext.isMixedContent && fileExtensionIs(fileName, ext.extension)) -}; -var externalFilePropertyReader = { - getFileName: (x) => x.fileName, - getScriptKind: (x) => tryConvertScriptKindName(x.scriptKind), - // TODO: GH#18217 - hasMixedContent: (x) => !!x.hasMixedContent -}; -function findProjectByName(projectName, projects) { - for (const proj of projects) { - if (proj.getProjectName() === projectName) { - return proj; - } - } -} -var nullTypingsInstaller = { - isKnownTypesPackageName: returnFalse, - // Should never be called because we never provide a types registry. - installPackage: notImplemented, - enqueueInstallTypingsRequest: noop, - attach: noop, - onProjectClosed: noop, - globalTypingsCacheLocation: void 0 - // TODO: GH#18217 -}; -var noopConfigFileWatcher = { close: noop }; -function getConfigFileNameFromCache(info, cache) { - if (!cache || isAncestorConfigFileInfo(info)) return void 0; - return cache.get(info.path); -} -function isOpenScriptInfo(infoOrFileNameOrConfig) { - return !!infoOrFileNameOrConfig.containingProjects; -} -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"; - return ConfiguredProjectLoadKind2; -})(ConfiguredProjectLoadKind || {}); -function forEachAncestorProject(info, project, cb, kind, reason, allowDeferredClosed, reloadedProjects, delayReloadedConfiguredProjects) { - 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 (!configFileName) return; - const ancestor = project.projectService.findCreateOrReloadConfiguredProject( - configFileName, - kind, - reason, - allowDeferredClosed, - /*triggerFile*/ - void 0, - reloadedProjects, - /*delayLoad*/ - true, - delayReloadedConfiguredProjects - ); - if (!ancestor) return; - if (ancestor.project.isInitialLoadPending() && project.getCompilerOptions().composite) { - ancestor.project.setPotentialProjectReference(project.canonicalConfigFilePath); - } - const result = cb(ancestor.project); - 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; - } - } - 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), - 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; - } -} -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 forEachPotentialProjectReference(project, cb) { - return project.potentialProjectReferences && forEachKey(project.potentialProjectReferences, cb); -} -function forEachAnyProjectReferenceKind(project, cb, cbProjectRef, cbPotentialProjectRef) { - return project.getCurrentProgram() ? project.forEachResolvedProjectReference(cb) : project.isInitialLoadPending() ? forEachPotentialProjectReference(project, cbPotentialProjectRef) : forEach(project.getProjectReferences(), cbProjectRef); -} -function callbackRefProject(project, cb, refPath) { - const refProject = refPath && project.projectService.configuredProjects.get(refPath); - return refProject && cb(refProject); -} -function forEachReferencedProject(project, cb) { - return forEachAnyProjectReferenceKind( - project, - (resolvedRef) => callbackRefProject(project, cb, resolvedRef.sourceFile.path), - (projectRef) => callbackRefProject(project, cb, project.toPath(resolveProjectReferencePath(projectRef))), - (potentialProjectRef) => callbackRefProject(project, cb, potentialProjectRef) - ); -} -function getDetailWatchInfo(watchType, project) { - return `${isString(project) ? `Config: ${project} ` : project ? `Project: ${project.getProjectName()} ` : ""}WatchType: ${watchType}`; -} -function isScriptInfoWatchedFromNodeModules(info) { - return !info.isScriptOpen() && info.mTime !== void 0; -} -function updateProjectIfDirty(project) { - project.invalidateResolutionsOfFailedLookupLocations(); - return project.dirty && !project.updateGraph(); -} -function updateWithTriggerFile(project, triggerFile, isReload) { - if (!isReload) { - project.invalidateResolutionsOfFailedLookupLocations(); - if (!project.dirty) return false; - } - project.triggerFileForConfigFileDiag = triggerFile; - const updateLevel = project.pendingUpdateLevel; - project.updateGraph(); - if (!project.triggerFileForConfigFileDiag && !isReload) return updateLevel === 2 /* Full */; - const sent = project.projectService.sendConfigFileDiagEvent(project, triggerFile, isReload); - project.triggerFileForConfigFileDiag = void 0; - return sent; -} -function updateConfiguredProject(project, triggerFile) { - if (triggerFile) { - if (updateWithTriggerFile( - project, - triggerFile, - /*isReload*/ - false - )) return true; - } else { - updateProjectIfDirty(project); - } - return false; -} -function fileOpenReason(info) { - return `Creating possible configured project for ${info.fileName} to open`; -} -function reloadReason(reason) { - return `User requested reload projects: ${reason}`; -} -function setProjectOptionsUsed(project) { - if (isConfiguredProject(project)) { - project.projectOptions = true; - } -} -function createProjectNameFactoryWithCounter(nameFactory) { - let nextId = 1; - return () => nameFactory(nextId++); -} -function getHostWatcherMap() { - return { idToCallbacks: /* @__PURE__ */ new Map(), pathToId: /* @__PURE__ */ new Map() }; -} -function getCanUseWatchEvents(service, canUseWatchEvents) { - return !!canUseWatchEvents && !!service.eventHandler && !!service.session; -} -function createWatchFactoryHostUsingWatchEvents(service, canUseWatchEvents) { - if (!getCanUseWatchEvents(service, canUseWatchEvents)) return void 0; - const watchedFiles = getHostWatcherMap(); - const watchedDirectories = getHostWatcherMap(); - const watchedDirectoriesRecursive = getHostWatcherMap(); - let ids = 1; - service.session.addProtocolHandler("watchChange" /* WatchChange */, (req) => { - onWatchChange(req.arguments); - return { responseRequired: false }; - }); - return { - watchFile: watchFile2, - watchDirectory, - getCurrentDirectory: () => service.host.getCurrentDirectory(), - useCaseSensitiveFileNames: service.host.useCaseSensitiveFileNames - }; - function watchFile2(path, callback) { - return getOrCreateFileWatcher( - watchedFiles, - path, - callback, - (id) => ({ eventName: CreateFileWatcherEvent, data: { id, path } }) - ); - } - function watchDirectory(path, callback, recursive) { - return getOrCreateFileWatcher( - recursive ? watchedDirectoriesRecursive : watchedDirectories, - path, - callback, - (id) => ({ - eventName: CreateDirectoryWatcherEvent, - data: { - id, - path, - recursive: !!recursive, - // Special case node_modules as we watch it for changes to closed script infos as well - ignoreUpdate: !path.endsWith("/node_modules") ? true : void 0 - } - }) - ); - } - function getOrCreateFileWatcher({ pathToId, idToCallbacks }, path, callback, event) { - const key = service.toPath(path); - let id = pathToId.get(key); - if (!id) pathToId.set(key, id = ids++); - let callbacks = idToCallbacks.get(id); - if (!callbacks) { - idToCallbacks.set(id, callbacks = /* @__PURE__ */ new Set()); - service.eventHandler(event(id)); - } - callbacks.add(callback); - return { - close() { - const callbacks2 = idToCallbacks.get(id); - if (!(callbacks2 == null ? void 0 : callbacks2.delete(callback))) return; - if (callbacks2.size) return; - idToCallbacks.delete(id); - pathToId.delete(key); - service.eventHandler({ eventName: CloseFileWatcherEvent, data: { id } }); - } - }; - } - function onWatchChange(args) { - if (isArray(args)) args.forEach(onWatchChangeRequestArgs); - else onWatchChangeRequestArgs(args); - } - function onWatchChangeRequestArgs({ id, created, deleted, updated }) { - onWatchEventType(id, created, 0 /* Created */); - onWatchEventType(id, deleted, 2 /* Deleted */); - onWatchEventType(id, updated, 1 /* Changed */); - } - function onWatchEventType(id, paths, eventKind) { - if (!(paths == null ? void 0 : paths.length)) return; - forEachCallback(watchedFiles, id, paths, (callback, eventPath) => callback(eventPath, eventKind)); - forEachCallback(watchedDirectories, id, paths, (callback, eventPath) => callback(eventPath)); - forEachCallback(watchedDirectoriesRecursive, id, paths, (callback, eventPath) => callback(eventPath)); - } - function forEachCallback(hostWatcherMap, id, eventPaths, cb) { - var _a; - (_a = hostWatcherMap.idToCallbacks.get(id)) == null ? void 0 : _a.forEach((callback) => { - eventPaths.forEach((eventPath) => cb(callback, normalizeSlashes(eventPath))); - }); - } -} -var _ProjectService = class _ProjectService { - constructor(opts) { - /** - * Container of all known scripts - * - * @internal - */ - this.filenameToScriptInfo = /* @__PURE__ */ new Map(); - this.nodeModulesWatchers = /* @__PURE__ */ new Map(); - /** - * Contains all the deleted script info's version information so that - * it does not reset when creating script info again - * (and could have potentially collided with version where contents mismatch) - */ - this.filenameToScriptInfoVersion = /* @__PURE__ */ new Map(); - // Set of all '.js' files ever opened. - this.allJsFilesForOpenFileTelemetry = /* @__PURE__ */ new Map(); - /** - * maps external project file name to list of config files that were the part of this project - */ - this.externalProjectToConfiguredProjectMap = /* @__PURE__ */ new Map(); - /** - * external projects (configuration and list of root files is not controlled by tsserver) - */ - this.externalProjects = []; - /** - * projects built from openFileRoots - */ - this.inferredProjects = []; - /** - * projects specified by a tsconfig.json file - */ - this.configuredProjects = /* @__PURE__ */ new Map(); - /** @internal */ - this.newInferredProjectName = createProjectNameFactoryWithCounter(makeInferredProjectName); - /** @internal */ - this.newAutoImportProviderProjectName = createProjectNameFactoryWithCounter(makeAutoImportProviderProjectName); - /** @internal */ - this.newAuxiliaryProjectName = createProjectNameFactoryWithCounter(makeAuxiliaryProjectName); - /** - * Open files: with value being project root path, and key being Path of the file that is open - */ - this.openFiles = /* @__PURE__ */ new Map(); - /** Config files looked up and cached config files for open script info */ - this.configFileForOpenFiles = /* @__PURE__ */ new Map(); - /** Set of open script infos that are root of inferred project */ - this.rootOfInferredProjects = /* @__PURE__ */ new Set(); - /** - * Map of open files that are opened without complete path but have projectRoot as current directory - */ - this.openFilesWithNonRootedDiskPath = /* @__PURE__ */ new Map(); - this.compilerOptionsForInferredProjectsPerProjectRoot = /* @__PURE__ */ new Map(); - this.watchOptionsForInferredProjectsPerProjectRoot = /* @__PURE__ */ new Map(); - this.typeAcquisitionForInferredProjectsPerProjectRoot = /* @__PURE__ */ new Map(); - /** - * Project size for configured or external projects - */ - this.projectToSizeMap = /* @__PURE__ */ new Map(); - /** - * This is a map of config file paths existence that doesnt need query to disk - * - The entry can be present because there is inferred project that needs to watch addition of config file to directory - * In this case the exists could be true/false based on config file is present or not - * - Or it is present if we have configured project open with config file at that location - * In this case the exists property is always true - * - * @internal - */ - this.configFileExistenceInfoCache = /* @__PURE__ */ new Map(); - this.safelist = defaultTypeSafeList; - this.legacySafelist = /* @__PURE__ */ new Map(); - this.pendingProjectUpdates = /* @__PURE__ */ new Map(); - /** @internal */ - this.pendingEnsureProjectForOpenFiles = false; - /** Tracks projects that we have already sent telemetry for. */ - this.seenProjects = /* @__PURE__ */ new Map(); - this.sharedExtendedConfigFileWatchers = /* @__PURE__ */ new Map(); - this.extendedConfigCache = /* @__PURE__ */ new Map(); - /** @internal */ - this.baseline = noop; - /** @internal */ - this.verifyDocumentRegistry = noop; - /** @internal */ - this.verifyProgram = noop; - /** @internal */ - this.onProjectCreation = noop; - var _a; - this.host = opts.host; - this.logger = opts.logger; - this.cancellationToken = opts.cancellationToken; - this.useSingleInferredProject = opts.useSingleInferredProject; - this.useInferredProjectPerProjectRoot = opts.useInferredProjectPerProjectRoot; - this.typingsInstaller = opts.typingsInstaller || nullTypingsInstaller; - this.throttleWaitMilliseconds = opts.throttleWaitMilliseconds; - this.eventHandler = opts.eventHandler; - this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents; - this.globalPlugins = opts.globalPlugins || emptyArray2; - this.pluginProbeLocations = opts.pluginProbeLocations || emptyArray2; - this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; - this.typesMapLocation = opts.typesMapLocation === void 0 ? combinePaths(getDirectoryPath(this.getExecutingFilePath()), "typesMap.json") : opts.typesMapLocation; - this.session = opts.session; - this.jsDocParsingMode = opts.jsDocParsingMode; - if (opts.serverMode !== void 0) { - this.serverMode = opts.serverMode; - } else { - this.serverMode = 0 /* Semantic */; - } - if (this.host.realpath) { - this.realpathToScriptInfos = createMultiMap(); - } - this.currentDirectory = toNormalizedPath(this.host.getCurrentDirectory()); - 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); - if (this.typesMapLocation) { - this.loadTypesMap(); - } else { - this.logger.info("No types map provided; using the default"); - } - this.typingsInstaller.attach(this); - this.hostConfiguration = { - formatCodeOptions: getDefaultFormatCodeSettings(this.host.newLine), - preferences: emptyOptions, - hostInfo: "Unknown host", - extraFileExtensions: [] - }; - 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); - this.watchFactory = this.serverMode !== 0 /* Semantic */ ? { - watchFile: returnNoopFileWatcher, - watchDirectory: returnNoopFileWatcher - } : getWatchFactory( - createWatchFactoryHostUsingWatchEvents(this, opts.canUseWatchEvents) || this.host, - watchLogLevel, - log, - getDetailWatchInfo - ); - this.canUseWatchEvents = getCanUseWatchEvents(this, opts.canUseWatchEvents); - (_a = opts.incrementalVerifier) == null ? void 0 : _a.call(opts, this); - } - toPath(fileName) { - return toPath(fileName, this.currentDirectory, this.toCanonicalFileName); - } - /** @internal */ - getExecutingFilePath() { - return this.getNormalizedAbsolutePath(this.host.getExecutingFilePath()); - } - /** @internal */ - getNormalizedAbsolutePath(fileName) { - return getNormalizedAbsolutePath(fileName, this.host.getCurrentDirectory()); - } - /** @internal */ - setDocument(key, path, sourceFile) { - const info = Debug.checkDefined(this.getScriptInfoForPath(path)); - info.cacheSourceFile = { key, sourceFile }; - } - /** @internal */ - getDocument(key, path) { - const info = this.getScriptInfoForPath(path); - return info && info.cacheSourceFile && info.cacheSourceFile.key === key ? info.cacheSourceFile.sourceFile : void 0; - } - /** @internal */ - ensureInferredProjectsUpToDate_TestOnly() { - this.ensureProjectStructuresUptoDate(); - } - /** @internal */ - getCompilerOptionsForInferredProjects() { - return this.compilerOptionsForInferredProjects; - } - /** @internal */ - onUpdateLanguageServiceStateForProject(project, languageServiceEnabled) { - if (!this.eventHandler) { - return; - } - const event = { - eventName: ProjectLanguageServiceStateEvent, - data: { project, languageServiceEnabled } - }; - this.eventHandler(event); - } - loadTypesMap() { - try { - const fileContent = this.host.readFile(this.typesMapLocation); - if (fileContent === void 0) { - this.logger.info(`Provided types map file "${this.typesMapLocation}" doesn't exist`); - return; - } - const raw = JSON.parse(fileContent); - for (const k of Object.keys(raw.typesMap)) { - raw.typesMap[k].match = new RegExp(raw.typesMap[k].match, "i"); - } - this.safelist = raw.typesMap; - for (const key in raw.simpleMap) { - if (hasProperty(raw.simpleMap, key)) { - this.legacySafelist.set(key, raw.simpleMap[key].toLowerCase()); - } - } - } catch (e) { - this.logger.info(`Error loading types map: ${e}`); - this.safelist = defaultTypeSafeList; - this.legacySafelist.clear(); - } - } - // eslint-disable-line @typescript-eslint/unified-signatures - updateTypingsForProject(response) { - const project = this.findProject(response.projectName); - if (!project) { - return; - } - switch (response.kind) { - case ActionSet: - project.updateTypingFiles( - response.compilerOptions, - response.typeAcquisition, - response.unresolvedImports, - response.typings - ); - return; - case ActionInvalidate: - project.enqueueInstallTypingsForProject( - /*forceRefresh*/ - true - ); - return; - } - } - /** @internal */ - watchTypingLocations(response) { - var _a; - (_a = this.findProject(response.projectName)) == null ? void 0 : _a.watchTypingLocations(response.files); - } - /** @internal */ - delayEnsureProjectForOpenFiles() { - if (!this.openFiles.size) return; - this.pendingEnsureProjectForOpenFiles = true; - this.throttledOperations.schedule( - ensureProjectForOpenFileSchedule, - /*delay*/ - 2500, - () => { - if (this.pendingProjectUpdates.size !== 0) { - this.delayEnsureProjectForOpenFiles(); - } else { - if (this.pendingEnsureProjectForOpenFiles) { - this.ensureProjectForOpenFiles(); - this.sendProjectsUpdatedInBackgroundEvent(); - } - } - } - ); - } - delayUpdateProjectGraph(project) { - if (isProjectDeferredClose(project)) return; - project.markAsDirty(); - if (isBackgroundProject(project)) return; - const projectName = project.getProjectName(); - this.pendingProjectUpdates.set(projectName, project); - this.throttledOperations.schedule( - projectName, - /*delay*/ - 250, - () => { - if (this.pendingProjectUpdates.delete(projectName)) { - updateProjectIfDirty(project); - } - } - ); - } - /** @internal */ - hasPendingProjectUpdate(project) { - return this.pendingProjectUpdates.has(project.getProjectName()); - } - /** @internal */ - sendProjectsUpdatedInBackgroundEvent() { - if (!this.eventHandler) { - return; - } - const event = { - eventName: ProjectsUpdatedInBackgroundEvent, - data: { - openFiles: arrayFrom(this.openFiles.keys(), (path) => this.getScriptInfoForPath(path).fileName) - } - }; - this.eventHandler(event); - } - /** @internal */ - sendLargeFileReferencedEvent(file, fileSize) { - if (!this.eventHandler) { - return; - } - const event = { - eventName: LargeFileReferencedEvent, - data: { file, fileSize, maxFileSize } - }; - this.eventHandler(event); - } - /** @internal */ - sendProjectLoadingStartEvent(project, reason) { - if (!this.eventHandler) { - return; - } - project.sendLoadingProjectFinish = true; - const event = { - eventName: ProjectLoadingStartEvent, - data: { project, reason } - }; - this.eventHandler(event); - } - /** @internal */ - sendProjectLoadingFinishEvent(project) { - if (!this.eventHandler || !project.sendLoadingProjectFinish) { - return; - } - project.sendLoadingProjectFinish = false; - const event = { - eventName: ProjectLoadingFinishEvent, - data: { project } - }; - this.eventHandler(event); - } - /** @internal */ - sendPerformanceEvent(kind, durationMs) { - if (this.performanceEventHandler) { - this.performanceEventHandler({ kind, durationMs }); - } - } - /** @internal */ - delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project) { - this.delayUpdateProjectGraph(project); - this.delayEnsureProjectForOpenFiles(); - } - delayUpdateProjectGraphs(projects, clearSourceMapperCache) { - if (projects.length) { - for (const project of projects) { - if (clearSourceMapperCache) project.clearSourceMapperCache(); - this.delayUpdateProjectGraph(project); - } - this.delayEnsureProjectForOpenFiles(); - } - } - setCompilerOptionsForInferredProjects(projectCompilerOptions, projectRootPath) { - Debug.assert(projectRootPath === void 0 || this.useInferredProjectPerProjectRoot, "Setting compiler options per project root path is only supported when useInferredProjectPerProjectRoot is enabled"); - const compilerOptions = convertCompilerOptions(projectCompilerOptions); - const watchOptions = convertWatchOptions(projectCompilerOptions, projectRootPath); - const typeAcquisition = convertTypeAcquisition(projectCompilerOptions); - compilerOptions.allowNonTsExtensions = true; - const canonicalProjectRootPath = projectRootPath && this.toCanonicalFileName(projectRootPath); - if (canonicalProjectRootPath) { - this.compilerOptionsForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, compilerOptions); - this.watchOptionsForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, watchOptions || false); - this.typeAcquisitionForInferredProjectsPerProjectRoot.set(canonicalProjectRootPath, typeAcquisition); - } else { - this.compilerOptionsForInferredProjects = compilerOptions; - this.watchOptionsForInferredProjects = watchOptions; - this.typeAcquisitionForInferredProjects = typeAcquisition; - } - for (const project of this.inferredProjects) { - if (canonicalProjectRootPath ? project.projectRootPath === canonicalProjectRootPath : !project.projectRootPath || !this.compilerOptionsForInferredProjectsPerProjectRoot.has(project.projectRootPath)) { - project.setCompilerOptions(compilerOptions); - project.setTypeAcquisition(typeAcquisition); - project.setWatchOptions(watchOptions == null ? void 0 : watchOptions.watchOptions); - project.setProjectErrors(watchOptions == null ? void 0 : watchOptions.errors); - project.compileOnSaveEnabled = compilerOptions.compileOnSave; - project.markAsDirty(); - this.delayUpdateProjectGraph(project); - } - } - this.delayEnsureProjectForOpenFiles(); - } - findProject(projectName) { - if (projectName === void 0) { - return void 0; - } - if (isInferredProjectName(projectName)) { - return findProjectByName(projectName, this.inferredProjects); - } - return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(toNormalizedPath(projectName)); - } - /** @internal */ - forEachProject(cb) { - this.externalProjects.forEach(cb); - this.configuredProjects.forEach(cb); - this.inferredProjects.forEach(cb); - } - /** @internal */ - forEachEnabledProject(cb) { - this.forEachProject((project) => { - if (!project.isOrphan() && project.languageServiceEnabled) { - cb(project); - } - }); - } - getDefaultProjectForFile(fileName, ensureProject) { - return ensureProject ? this.ensureDefaultProjectForFile(fileName) : this.tryGetDefaultProjectForFile(fileName); - } - /** @internal */ - tryGetDefaultProjectForFile(fileNameOrScriptInfo) { - const scriptInfo = isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo; - return scriptInfo && !scriptInfo.isOrphan() ? scriptInfo.getDefaultProject() : void 0; - } - /** - * If there is default project calculation pending for this file, - * then it completes that calculation so that correct default project is used for the project - */ - tryGetDefaultProjectForEnsuringConfiguredProjectForFile(fileNameOrScriptInfo) { - var _a; - const scriptInfo = isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo; - if (!scriptInfo) return void 0; - if ((_a = this.pendingOpenFileProjectUpdates) == null ? void 0 : _a.delete(scriptInfo.path)) { - this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo( - scriptInfo, - 1 /* Create */ - ); - if (scriptInfo.isOrphan()) { - this.assignOrphanScriptInfoToInferredProject(scriptInfo, this.openFiles.get(scriptInfo.path)); - } - } - return this.tryGetDefaultProjectForFile(scriptInfo); - } - /** @internal */ - ensureDefaultProjectForFile(fileNameOrScriptInfo) { - return this.tryGetDefaultProjectForEnsuringConfiguredProjectForFile(fileNameOrScriptInfo) || this.doEnsureDefaultProjectForFile(fileNameOrScriptInfo); - } - doEnsureDefaultProjectForFile(fileNameOrScriptInfo) { - this.ensureProjectStructuresUptoDate(); - const scriptInfo = isString(fileNameOrScriptInfo) ? this.getScriptInfoForNormalizedPath(fileNameOrScriptInfo) : fileNameOrScriptInfo; - return scriptInfo ? scriptInfo.getDefaultProject() : (this.logErrorForScriptInfoNotFound(isString(fileNameOrScriptInfo) ? fileNameOrScriptInfo : fileNameOrScriptInfo.fileName), Errors.ThrowNoProject()); - } - getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName) { - this.ensureProjectStructuresUptoDate(); - return this.getScriptInfo(uncheckedFileName); - } - /** - * Ensures the project structures are upto date - * This means, - * - we go through all the projects and update them if they are dirty - * - if updates reflect some change in structure or there was pending request to ensure projects for open files - * ensure that each open script info has project - */ - ensureProjectStructuresUptoDate() { - let hasChanges = this.pendingEnsureProjectForOpenFiles; - this.pendingProjectUpdates.clear(); - const updateGraph = (project) => { - hasChanges = updateProjectIfDirty(project) || hasChanges; - }; - this.externalProjects.forEach(updateGraph); - this.configuredProjects.forEach(updateGraph); - this.inferredProjects.forEach(updateGraph); - if (hasChanges) { - this.ensureProjectForOpenFiles(); - } - } - getFormatCodeOptions(file) { - const info = this.getScriptInfoForNormalizedPath(file); - return info && info.getFormatCodeSettings() || this.hostConfiguration.formatCodeOptions; - } - getPreferences(file) { - const info = this.getScriptInfoForNormalizedPath(file); - return { ...this.hostConfiguration.preferences, ...info && info.getPreferences() }; - } - getHostFormatCodeOptions() { - return this.hostConfiguration.formatCodeOptions; - } - getHostPreferences() { - return this.hostConfiguration.preferences; - } - onSourceFileChanged(info, eventKind) { - Debug.assert(!info.isScriptOpen()); - if (eventKind === 2 /* Deleted */) { - this.handleDeletedFile( - info, - /*deferredDelete*/ - true - ); - } else { - if (info.deferredDelete) info.deferredDelete = void 0; - info.delayReloadNonMixedContentFile(); - this.delayUpdateProjectGraphs( - info.containingProjects, - /*clearSourceMapperCache*/ - false - ); - this.handleSourceMapProjects(info); - } - } - handleSourceMapProjects(info) { - if (info.sourceMapFilePath) { - if (isString(info.sourceMapFilePath)) { - const sourceMapFileInfo = this.getScriptInfoForPath(info.sourceMapFilePath); - this.delayUpdateSourceInfoProjects(sourceMapFileInfo == null ? void 0 : sourceMapFileInfo.sourceInfos); - } else { - this.delayUpdateSourceInfoProjects(info.sourceMapFilePath.sourceInfos); - } - } - this.delayUpdateSourceInfoProjects(info.sourceInfos); - if (info.declarationInfoPath) { - this.delayUpdateProjectsOfScriptInfoPath(info.declarationInfoPath); - } - } - delayUpdateSourceInfoProjects(sourceInfos) { - if (sourceInfos) { - sourceInfos.forEach((_value, path) => this.delayUpdateProjectsOfScriptInfoPath(path)); - } - } - delayUpdateProjectsOfScriptInfoPath(path) { - const info = this.getScriptInfoForPath(path); - if (info) { - this.delayUpdateProjectGraphs( - info.containingProjects, - /*clearSourceMapperCache*/ - true - ); - } - } - handleDeletedFile(info, deferredDelete) { - Debug.assert(!info.isScriptOpen()); - this.delayUpdateProjectGraphs( - info.containingProjects, - /*clearSourceMapperCache*/ - false - ); - this.handleSourceMapProjects(info); - info.detachAllProjects(); - if (deferredDelete) { - info.delayReloadNonMixedContentFile(); - info.deferredDelete = true; - } else { - this.deleteScriptInfo(info); - } - } - /** - * This is to watch whenever files are added or removed to the wildcard directories - */ - watchWildcardDirectory(directory, flags, configFileName, config) { - let watcher = this.watchFactory.watchDirectory( - directory, - (fileOrDirectory) => this.onWildCardDirectoryWatcherInvoke( - directory, - configFileName, - config, - result, - fileOrDirectory - ), - flags, - this.getWatchOptionsFromProjectWatchOptions(config.parsedCommandLine.watchOptions, getDirectoryPath(configFileName)), - WatchType.WildcardDirectory, - configFileName - ); - const result = { - packageJsonWatches: void 0, - close() { - var _a; - if (watcher) { - watcher.close(); - watcher = void 0; - (_a = result.packageJsonWatches) == null ? void 0 : _a.forEach((watcher2) => { - watcher2.projects.delete(result); - watcher2.close(); - }); - result.packageJsonWatches = void 0; - } - } - }; - return result; - } - onWildCardDirectoryWatcherInvoke(directory, configFileName, config, wildCardWatcher, fileOrDirectory) { - const fileOrDirectoryPath = this.toPath(fileOrDirectory); - const fsResult = config.cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); - if (getBaseFileName(fileOrDirectoryPath) === "package.json" && !isInsideNodeModules(fileOrDirectoryPath) && (fsResult && fsResult.fileExists || !fsResult && this.host.fileExists(fileOrDirectory))) { - const file = this.getNormalizedAbsolutePath(fileOrDirectory); - this.logger.info(`Config: ${configFileName} Detected new package.json: ${file}`); - this.packageJsonCache.addOrUpdate(file, fileOrDirectoryPath); - this.watchPackageJsonFile(file, fileOrDirectoryPath, wildCardWatcher); - } - if (!(fsResult == null ? void 0 : fsResult.fileExists)) { - this.sendSourceFileChange(fileOrDirectoryPath); - } - const configuredProjectForConfig = this.findConfiguredProjectByProjectName(configFileName); - if (isIgnoredFileFromWildCardWatching({ - watchedDirPath: this.toPath(directory), - fileOrDirectory, - fileOrDirectoryPath, - configFileName, - extraFileExtensions: this.hostConfiguration.extraFileExtensions, - currentDirectory: this.currentDirectory, - options: config.parsedCommandLine.options, - program: (configuredProjectForConfig == null ? void 0 : configuredProjectForConfig.getCurrentProgram()) || config.parsedCommandLine.fileNames, - useCaseSensitiveFileNames: this.host.useCaseSensitiveFileNames, - writeLog: (s) => this.logger.info(s), - toPath: (s) => this.toPath(s), - getScriptKind: configuredProjectForConfig ? (fileName) => configuredProjectForConfig.getScriptKind(fileName) : void 0 - })) return; - if (config.updateLevel !== 2 /* Full */) config.updateLevel = 1 /* RootNamesAndUpdate */; - config.projects.forEach((watchWildcardDirectories, projectCanonicalPath) => { - var _a; - if (!watchWildcardDirectories) return; - const project = this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath); - if (!project) return; - if (configuredProjectForConfig !== project && this.getHostPreferences().includeCompletionsForModuleExports) { - const path = this.toPath(configFileName); - if (find((_a = project.getCurrentProgram()) == null ? void 0 : _a.getResolvedProjectReferences(), (ref) => (ref == null ? void 0 : ref.sourceFile.path) === path)) { - project.markAutoImportProviderAsDirty(); - } - } - const updateLevel = configuredProjectForConfig === project ? 1 /* RootNamesAndUpdate */ : 0 /* Update */; - if (project.pendingUpdateLevel > updateLevel) return; - if (this.openFiles.has(fileOrDirectoryPath)) { - const info = Debug.checkDefined(this.getScriptInfoForPath(fileOrDirectoryPath)); - if (info.isAttached(project)) { - const loadLevelToSet = Math.max(updateLevel, project.openFileWatchTriggered.get(fileOrDirectoryPath) || 0 /* Update */); - project.openFileWatchTriggered.set(fileOrDirectoryPath, loadLevelToSet); - } else { - project.pendingUpdateLevel = updateLevel; - this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); - } - } else { - project.pendingUpdateLevel = updateLevel; - this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); - } - }); - } - delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalConfigFilePath, loadReason) { - const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); - if (!(configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config)) return false; - let scheduledAnyProjectUpdate = false; - configFileExistenceInfo.config.updateLevel = 2 /* Full */; - configFileExistenceInfo.config.projects.forEach((_watchWildcardDirectories, projectCanonicalPath) => { - var _a; - const project = this.getConfiguredProjectByCanonicalConfigFilePath(projectCanonicalPath); - if (!project) return; - scheduledAnyProjectUpdate = true; - if (projectCanonicalPath === canonicalConfigFilePath) { - if (project.isInitialLoadPending()) return; - project.pendingUpdateLevel = 2 /* Full */; - project.pendingUpdateReason = loadReason; - this.delayUpdateProjectGraph(project); - project.markAutoImportProviderAsDirty(); - } else { - 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)) { - project.markAutoImportProviderAsDirty(); - } - } - }); - return scheduledAnyProjectUpdate; - } - onConfigFileChanged(configFileName, canonicalConfigFilePath, eventKind) { - const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); - const project = this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath); - const wasDefferedClose = project == null ? void 0 : project.deferredClose; - if (eventKind === 2 /* Deleted */) { - configFileExistenceInfo.exists = false; - if (project) project.deferredClose = true; - } else { - configFileExistenceInfo.exists = true; - if (wasDefferedClose) { - project.deferredClose = void 0; - project.markAsDirty(); - } - } - this.delayUpdateProjectsFromParsedConfigOnConfigFileChange( - 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); - if (!((_a = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.has(path))) return; - this.configFileForOpenFiles.delete(path); - const info = this.getScriptInfoForPath(path); - const newConfigFileNameForInfo = this.getConfigFileNameForFile( - info, - /*findFromCacheOnly*/ - 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(); - } - removeProject(project) { - this.logger.info("`remove Project::"); - project.print( - /*writeProjectFileNames*/ - true, - /*writeFileExplaination*/ - true, - /*writeFileVersionAndText*/ - false - ); - project.close(); - if (Debug.shouldAssert(1 /* Normal */)) { - this.filenameToScriptInfo.forEach( - (info) => Debug.assert( - !info.isAttached(project), - "Found script Info still attached to project", - () => `${project.projectName}: ScriptInfos still attached: ${JSON.stringify( - arrayFrom( - mapDefinedIterator( - this.filenameToScriptInfo.values(), - (info2) => info2.isAttached(project) ? { - fileName: info2.fileName, - projects: info2.containingProjects.map((p) => p.projectName), - hasMixedContent: info2.hasMixedContent - } : void 0 - ) - ), - /*replacer*/ - void 0, - " " - )}` - ) - ); - } - this.pendingProjectUpdates.delete(project.getProjectName()); - switch (project.projectKind) { - case 2 /* External */: - unorderedRemoveItem(this.externalProjects, project); - this.projectToSizeMap.delete(project.getProjectName()); - break; - case 1 /* Configured */: - this.configuredProjects.delete(project.canonicalConfigFilePath); - this.projectToSizeMap.delete(project.canonicalConfigFilePath); - break; - case 0 /* Inferred */: - unorderedRemoveItem(this.inferredProjects, project); - break; - } - } - /** @internal */ - assignOrphanScriptInfoToInferredProject(info, projectRootPath) { - Debug.assert(info.isOrphan()); - const project = this.getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) || this.getOrCreateSingleInferredProjectIfEnabled() || this.getOrCreateSingleInferredWithoutProjectRoot( - info.isDynamic ? projectRootPath || this.currentDirectory : getDirectoryPath( - isRootedDiskPath(info.fileName) ? info.fileName : getNormalizedAbsolutePath( - info.fileName, - projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory - ) - ) - ); - project.addRoot(info); - if (info.containingProjects[0] !== project) { - orderedRemoveItem(info.containingProjects, project); - info.containingProjects.unshift(project); - } - project.updateGraph(); - if (!this.useSingleInferredProject && !project.projectRootPath) { - for (const inferredProject of this.inferredProjects) { - if (inferredProject === project || inferredProject.isOrphan()) { - continue; - } - const roots = inferredProject.getRootScriptInfos(); - Debug.assert(roots.length === 1 || !!inferredProject.projectRootPath); - if (roots.length === 1 && forEach(roots[0].containingProjects, (p) => p !== roots[0].containingProjects[0] && !p.isOrphan())) { - inferredProject.removeFile( - roots[0], - /*fileExists*/ - true, - /*detachFromProject*/ - true - ); - } - } - } - return project; - } - assignOrphanScriptInfosToInferredProject() { - this.openFiles.forEach((projectRootPath, path) => { - const info = this.getScriptInfoForPath(path); - if (info.isOrphan()) { - this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); - } - }); - } - /** - * Remove this file from the set of open, non-configured files. - * @param info The file that has been closed or newly configured - */ - closeOpenFile(info, skipAssignOrphanScriptInfosToInferredProject) { - var _a; - const fileExists = info.isDynamic ? false : this.host.fileExists(info.fileName); - info.close(fileExists); - this.stopWatchingConfigFilesForScriptInfo(info); - const canonicalFileName = this.toCanonicalFileName(info.fileName); - if (this.openFilesWithNonRootedDiskPath.get(canonicalFileName) === info) { - this.openFilesWithNonRootedDiskPath.delete(canonicalFileName); - } - let ensureProjectsForOpenFiles = false; - for (const p of info.containingProjects) { - if (isConfiguredProject(p)) { - if (info.hasMixedContent) { - info.registerFileUpdate(); - } - const updateLevel = p.openFileWatchTriggered.get(info.path); - if (updateLevel !== void 0) { - p.openFileWatchTriggered.delete(info.path); - if (p.pendingUpdateLevel < updateLevel) { - p.pendingUpdateLevel = updateLevel; - p.markFileAsDirty(info.path); - } - } - } else if (isInferredProject(p) && p.isRoot(info)) { - if (p.isProjectWithSingleRoot()) { - ensureProjectsForOpenFiles = true; - } - p.removeFile( - info, - fileExists, - /*detachFromProject*/ - true - ); - } - if (!p.languageServiceEnabled) { - p.markAsDirty(); - } - } - this.openFiles.delete(info.path); - this.configFileForOpenFiles.delete(info.path); - (_a = this.pendingOpenFileProjectUpdates) == null ? void 0 : _a.delete(info.path); - Debug.assert(!this.rootOfInferredProjects.has(info)); - if (!skipAssignOrphanScriptInfosToInferredProject && ensureProjectsForOpenFiles) { - this.assignOrphanScriptInfosToInferredProject(); - } - if (fileExists) { - this.watchClosedScriptInfo(info); - } else { - this.handleDeletedFile( - info, - /*deferredDelete*/ - false - ); - } - return ensureProjectsForOpenFiles; - } - deleteScriptInfo(info) { - Debug.assert(!info.isScriptOpen()); - this.filenameToScriptInfo.delete(info.path); - this.filenameToScriptInfoVersion.set(info.path, info.textStorage.version); - this.stopWatchingScriptInfo(info); - const realpath = info.getRealpathIfDifferent(); - if (realpath) { - this.realpathToScriptInfos.remove(realpath, info); - } - info.closeSourceMapFileWatcher(); - } - configFileExists(configFileName, canonicalConfigFilePath, info) { - const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); - let openFilesImpactedByConfigFile; - if (this.openFiles.has(info.path) && !isAncestorConfigFileInfo(info)) { - if (configFileExistenceInfo) (configFileExistenceInfo.openFilesImpactedByConfigFile ?? (configFileExistenceInfo.openFilesImpactedByConfigFile = /* @__PURE__ */ new Set())).add(info.path); - else (openFilesImpactedByConfigFile = /* @__PURE__ */ new Set()).add(info.path); - } - if (configFileExistenceInfo) return configFileExistenceInfo.exists; - const exists = this.host.fileExists(configFileName); - this.configFileExistenceInfoCache.set(canonicalConfigFilePath, { exists, openFilesImpactedByConfigFile }); - return exists; - } - createConfigFileWatcherForParsedConfig(configFileName, canonicalConfigFilePath, forProject) { - var _a, _b; - const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); - if (!configFileExistenceInfo.watcher || configFileExistenceInfo.watcher === noopConfigFileWatcher) { - configFileExistenceInfo.watcher = this.watchFactory.watchFile( - configFileName, - (_fileName, eventKind) => this.onConfigFileChanged(configFileName, canonicalConfigFilePath, eventKind), - 2e3 /* High */, - this.getWatchOptionsFromProjectWatchOptions((_b = (_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.config) == null ? void 0 : _a.parsedCommandLine) == null ? void 0 : _b.watchOptions, getDirectoryPath(configFileName)), - WatchType.ConfigFile, - forProject - ); - } - const projects = configFileExistenceInfo.config.projects; - projects.set(forProject.canonicalConfigFilePath, projects.get(forProject.canonicalConfigFilePath) || false); - } - /** @internal */ - releaseParsedConfig(canonicalConfigFilePath, forProject) { - var _a, _b, _c; - const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); - if (!((_a = configFileExistenceInfo.config) == null ? void 0 : _a.projects.delete(forProject.canonicalConfigFilePath))) return; - if ((_b = configFileExistenceInfo.config) == null ? void 0 : _b.projects.size) return; - configFileExistenceInfo.config = void 0; - clearSharedExtendedConfigFileWatcher(canonicalConfigFilePath, this.sharedExtendedConfigFileWatchers); - Debug.checkDefined(configFileExistenceInfo.watcher); - if ((_c = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _c.size) { - if (configFileExistenceInfo.inferredProjectRoots) { - if (!canWatchDirectoryOrFile(getPathComponents(getDirectoryPath(canonicalConfigFilePath)))) { - configFileExistenceInfo.watcher.close(); - configFileExistenceInfo.watcher = noopConfigFileWatcher; - } - } else { - configFileExistenceInfo.watcher.close(); - configFileExistenceInfo.watcher = void 0; - } - } else { - configFileExistenceInfo.watcher.close(); - this.configFileExistenceInfoCache.delete(canonicalConfigFilePath); - } - } - /** - * This is called on file close or when its removed from inferred project as root, - * so that we handle the watches and inferred project root data - * @internal - */ - stopWatchingConfigFilesForScriptInfo(info) { - if (this.serverMode !== 0 /* Semantic */) return; - const isRootOfInferredProject = this.rootOfInferredProjects.delete(info); - const isOpen = info.isScriptOpen(); - if (isOpen && !isRootOfInferredProject) return; - this.forEachConfigFileLocation(info, (canonicalConfigFilePath) => { - var _a, _b, _c; - const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); - if (!configFileExistenceInfo) return; - if (isOpen) { - if (!((_a = configFileExistenceInfo == null ? void 0 : configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _a.has(info.path))) return; - } else { - if (!((_b = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _b.delete(info.path))) return; - } - if (isRootOfInferredProject) { - configFileExistenceInfo.inferredProjectRoots--; - if (configFileExistenceInfo.watcher && !configFileExistenceInfo.config && !configFileExistenceInfo.inferredProjectRoots) { - configFileExistenceInfo.watcher.close(); - configFileExistenceInfo.watcher = void 0; - } - } - if (!((_c = configFileExistenceInfo.openFilesImpactedByConfigFile) == null ? void 0 : _c.size) && !configFileExistenceInfo.config) { - Debug.assert(!configFileExistenceInfo.watcher); - this.configFileExistenceInfoCache.delete(canonicalConfigFilePath); - } - }); - } - /** - * This is called by inferred project whenever script info is added as a root - * - * @internal - */ - startWatchingConfigFilesForInferredProjectRoot(info) { - if (this.serverMode !== 0 /* Semantic */) return; - Debug.assert(info.isScriptOpen()); - this.rootOfInferredProjects.add(info); - this.forEachConfigFileLocation(info, (canonicalConfigFilePath, configFileName) => { - let configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); - if (!configFileExistenceInfo) { - configFileExistenceInfo = { exists: this.host.fileExists(configFileName), inferredProjectRoots: 1 }; - this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo); - } else { - 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( - configFileName, - (_filename, eventKind) => this.onConfigFileChanged(configFileName, canonicalConfigFilePath, eventKind), - 2e3 /* High */, - this.hostConfiguration.watchOptions, - WatchType.ConfigFileForInferredRoot - ) : noopConfigFileWatcher); - }); - } - /** - * This function tries to search for a tsconfig.json for the given file. - * This is different from the method the compiler uses because - * the compiler can assume it will always start searching in the - * current directory (the directory in which tsc was invoked). - * The server must start searching from the directory containing - * the newly opened file. - */ - forEachConfigFileLocation(info, action) { - if (this.serverMode !== 0 /* Semantic */) { - return void 0; - } - Debug.assert(!isOpenScriptInfo(info) || this.openFiles.has(info.path)); - const projectRootPath = this.openFiles.get(info.path); - const scriptInfo = Debug.checkDefined(this.getScriptInfo(info.path)); - if (scriptInfo.isDynamic) return void 0; - let searchPath = asNormalizedPath(getDirectoryPath(info.fileName)); - const isSearchPathInProjectRoot = () => containsPath(projectRootPath, searchPath, this.currentDirectory, !this.host.useCaseSensitiveFileNames); - const anySearchPathOk = !projectRootPath || !isSearchPathInProjectRoot(); - let searchInDirectory = !isAncestorConfigFileInfo(info); - do { - if (searchInDirectory) { - const canonicalSearchPath = normalizedPathToPath(searchPath, this.currentDirectory, this.toCanonicalFileName); - const tsconfigFileName = asNormalizedPath(combinePaths(searchPath, "tsconfig.json")); - let result = action(combinePaths(canonicalSearchPath, "tsconfig.json"), tsconfigFileName); - if (result) return tsconfigFileName; - const jsconfigFileName = asNormalizedPath(combinePaths(searchPath, "jsconfig.json")); - result = action(combinePaths(canonicalSearchPath, "jsconfig.json"), jsconfigFileName); - if (result) return jsconfigFileName; - if (isNodeModulesDirectory(canonicalSearchPath)) { - break; - } - } - const parentPath = asNormalizedPath(getDirectoryPath(searchPath)); - if (parentPath === searchPath) break; - searchPath = parentPath; - searchInDirectory = true; - } while (anySearchPathOk || isSearchPathInProjectRoot()); - return void 0; - } - /** @internal */ - findDefaultConfiguredProject(info) { - var _a; - return info.isScriptOpen() ? (_a = this.tryFindDefaultConfiguredProjectForOpenScriptInfo( - info, - 0 /* Find */ - )) == null ? void 0 : _a.defaultProject : void 0; - } - /** Get cached configFileName for scriptInfo or ancestor of open script info */ - getConfigFileNameForFileFromCache(info, lookInPendingFilesForValue) { - if (lookInPendingFilesForValue) { - const result = getConfigFileNameFromCache(info, this.pendingOpenFileProjectUpdates); - if (result !== void 0) return result; - } - return getConfigFileNameFromCache(info, this.configFileForOpenFiles); - } - /** 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); - } - /** - * This function tries to search for a tsconfig.json for the given file. - * This is different from the method the compiler uses because - * the compiler can assume it will always start searching in the - * current directory (the directory in which tsc was invoked). - * The server must start searching from the directory containing - * the newly opened file. - * If script info is passed in, it is asserted to be open script info - * otherwise just file name - * when findFromCacheOnly is true only looked up in cache instead of hitting disk to figure things out - * @internal - */ - getConfigFileNameForFile(info, findFromCacheOnly) { - const fromCache = this.getConfigFileNameForFileFromCache(info, findFromCacheOnly); - if (fromCache !== void 0) return fromCache || void 0; - if (findFromCacheOnly) return void 0; - const configFileName = this.forEachConfigFileLocation(info, (canonicalConfigFilePath, configFileName2) => this.configFileExists(configFileName2, canonicalConfigFilePath, info)); - this.logger.info(`getConfigFileNameForFile:: File: ${info.fileName} ProjectRootPath: ${this.openFiles.get(info.path)}:: Result: ${configFileName}`); - this.setConfigFileNameForFileInCache(info, configFileName); - return configFileName; - } - printProjects() { - if (!this.logger.hasLevel(1 /* normal */)) { - return; - } - this.logger.startGroup(); - this.externalProjects.forEach(printProjectWithoutFileNames); - this.configuredProjects.forEach(printProjectWithoutFileNames); - this.inferredProjects.forEach(printProjectWithoutFileNames); - this.logger.info("Open files: "); - this.openFiles.forEach((projectRootPath, path) => { - const info = this.getScriptInfoForPath(path); - this.logger.info(` FileName: ${info.fileName} ProjectRootPath: ${projectRootPath}`); - this.logger.info(` Projects: ${info.containingProjects.map((p) => p.getProjectName())}`); - }); - this.logger.endGroup(); - } - /** @internal */ - findConfiguredProjectByProjectName(configFileName, allowDeferredClosed) { - const canonicalConfigFilePath = asNormalizedPath(this.toCanonicalFileName(configFileName)); - const result = this.getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath); - return allowDeferredClosed ? result : !(result == null ? void 0 : result.deferredClose) ? result : void 0; - } - getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath) { - return this.configuredProjects.get(canonicalConfigFilePath); - } - findExternalProjectByProjectName(projectFileName) { - return findProjectByName(projectFileName, this.externalProjects); - } - /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ - getFilenameForExceededTotalSizeLimitForNonTsFiles(name, options, fileNames, propertyReader) { - if (options && options.disableSizeLimit || !this.host.getFileSize) { - return; - } - let availableSpace = maxProgramSizeForNonTsFiles; - this.projectToSizeMap.set(name, 0); - this.projectToSizeMap.forEach((val) => availableSpace -= val || 0); - let totalNonTsFileSize = 0; - for (const f of fileNames) { - const fileName = propertyReader.getFileName(f); - if (hasTSFileExtension(fileName)) { - continue; - } - totalNonTsFileSize += this.host.getFileSize(fileName); - if (totalNonTsFileSize > maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - const top5LargestFiles = fileNames.map((f2) => propertyReader.getFileName(f2)).filter((name2) => !hasTSFileExtension(name2)).map((name2) => ({ name: name2, size: this.host.getFileSize(name2) })).sort((a, b) => b.size - a.size).slice(0, 5); - this.logger.info(`Non TS file size exceeded limit (${totalNonTsFileSize}). Largest files: ${top5LargestFiles.map((file) => `${file.name}:${file.size}`).join(", ")}`); - return fileName; - } - } - this.projectToSizeMap.set(name, totalNonTsFileSize); - } - createExternalProject(projectFileName, files, options, typeAcquisition, excludedFiles) { - const compilerOptions = convertCompilerOptions(options); - const watchOptionsAndErrors = convertWatchOptions(options, getDirectoryPath(normalizeSlashes(projectFileName))); - const project = new ExternalProject( - projectFileName, - this, - this.documentRegistry, - compilerOptions, - /*lastFileExceededProgramSize*/ - this.getFilenameForExceededTotalSizeLimitForNonTsFiles(projectFileName, compilerOptions, files, externalFilePropertyReader), - options.compileOnSave === void 0 ? true : options.compileOnSave, - /*projectFilePath*/ - void 0, - watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions - ); - project.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors); - project.excludedFiles = excludedFiles; - this.addFilesToNonInferredProject(project, files, externalFilePropertyReader, typeAcquisition); - this.externalProjects.push(project); - return project; - } - /** @internal */ - sendProjectTelemetry(project) { - if (this.seenProjects.has(project.projectName)) { - setProjectOptionsUsed(project); - return; - } - this.seenProjects.set(project.projectName, true); - if (!this.eventHandler || !this.host.createSHA256Hash) { - setProjectOptionsUsed(project); - return; - } - const projectOptions = isConfiguredProject(project) ? project.projectOptions : void 0; - setProjectOptionsUsed(project); - const data = { - projectId: this.host.createSHA256Hash(project.projectName), - fileStats: countEachFileTypes( - project.getScriptInfos(), - /*includeSizes*/ - true - ), - compilerOptions: convertCompilerOptionsForTelemetry(project.getCompilationSettings()), - typeAcquisition: convertTypeAcquisition2(project.getTypeAcquisition()), - extends: projectOptions && projectOptions.configHasExtendsProperty, - files: projectOptions && projectOptions.configHasFilesProperty, - include: projectOptions && projectOptions.configHasIncludeProperty, - exclude: projectOptions && projectOptions.configHasExcludeProperty, - compileOnSave: project.compileOnSaveEnabled, - configFileName: configFileName(), - projectType: project instanceof ExternalProject ? "external" : "configured", - languageServiceEnabled: project.languageServiceEnabled, - version - }; - this.eventHandler({ eventName: ProjectInfoTelemetryEvent, data }); - function configFileName() { - if (!isConfiguredProject(project)) { - return "other"; - } - return getBaseConfigFileName(project.getConfigFilePath()) || "other"; - } - function convertTypeAcquisition2({ enable: enable2, include, exclude }) { - return { - enable: enable2, - include: include !== void 0 && include.length !== 0, - exclude: exclude !== void 0 && exclude.length !== 0 - }; - } - } - addFilesToNonInferredProject(project, files, propertyReader, typeAcquisition) { - this.updateNonInferredProjectFiles(project, files, propertyReader); - project.setTypeAcquisition(typeAcquisition); - project.markAsDirty(); - } - /** @internal */ - 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) { - this.configFileExistenceInfoCache.set(canonicalConfigFilePath, configFileExistenceInfo = { exists: true }); - } else { - configFileExistenceInfo.exists = true; - } - if (!configFileExistenceInfo.config) { - configFileExistenceInfo.config = { - cachedDirectoryStructureHost: createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames), - projects: /* @__PURE__ */ new Map(), - updateLevel: 2 /* Full */ - }; - } - const project = new ConfiguredProject2( - configFileName, - canonicalConfigFilePath, - this, - this.documentRegistry, - configFileExistenceInfo.config.cachedDirectoryStructureHost, - reason - ); - Debug.assert(!this.configuredProjects.has(canonicalConfigFilePath)); - this.configuredProjects.set(canonicalConfigFilePath, project); - this.createConfigFileWatcherForParsedConfig(configFileName, canonicalConfigFilePath, project); - return project; - } - /** - * Read the config file of the project, and update the project root file names. - */ - loadConfiguredProject(project, reason) { - 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 configFileExistenceInfo = this.ensureParsedConfigUptoDate( - configFilename, - project.canonicalConfigFilePath, - this.configFileExistenceInfoCache.get(project.canonicalConfigFilePath), - project - ); - const parsedCommandLine = configFileExistenceInfo.config.parsedCommandLine; - Debug.assert(!!parsedCommandLine.fileNames); - const compilerOptions = parsedCommandLine.options; - if (!project.projectOptions) { - project.projectOptions = { - configHasExtendsProperty: parsedCommandLine.raw.extends !== void 0, - configHasFilesProperty: parsedCommandLine.raw.files !== void 0, - configHasIncludeProperty: parsedCommandLine.raw.include !== void 0, - configHasExcludeProperty: parsedCommandLine.raw.exclude !== void 0 - }; - } - project.canConfigFileJsonReportNoInputFiles = canJsonReportNoInputFiles(parsedCommandLine.raw); - project.setProjectErrors(parsedCommandLine.options.configFile.parseDiagnostics); - project.updateReferences(parsedCommandLine.projectReferences); - const lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(project.canonicalConfigFilePath, compilerOptions, parsedCommandLine.fileNames, fileNamePropertyReader); - if (lastFileExceededProgramSize) { - project.disableLanguageService(lastFileExceededProgramSize); - this.configFileExistenceInfoCache.forEach((_configFileExistenceInfo, canonicalConfigFilePath) => this.stopWatchingWildCards(canonicalConfigFilePath, project)); - } else { - project.setCompilerOptions(compilerOptions); - project.setWatchOptions(parsedCommandLine.watchOptions); - project.enableLanguageService(); - this.watchWildcards(configFilename, configFileExistenceInfo, project); - } - project.enablePluginsWithOptions(compilerOptions); - const filesToAdd = parsedCommandLine.fileNames.concat(project.getExternalFiles(2 /* Full */)); - this.updateRootAndOptionsOfNonInferredProject(project, filesToAdd, fileNamePropertyReader, compilerOptions, parsedCommandLine.typeAcquisition, parsedCommandLine.compileOnSave, parsedCommandLine.watchOptions); - (_b = tracing) == null ? void 0 : _b.pop(); - } - /** @internal */ - 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); - 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 : ""); - const configFileErrors = configFile.parseDiagnostics; - if (!isString(configFileContent)) configFileErrors.push(configFileContent); - const configDir = getDirectoryPath(configFilename); - const parsedCommandLine = parseJsonSourceFileConfigFileContent( - configFile, - cachedDirectoryStructureHost, - configDir, - /*existingOptions*/ - void 0, - configFilename, - /*resolutionStack*/ - void 0, - this.hostConfiguration.extraFileExtensions, - this.extendedConfigCache - ); - if (parsedCommandLine.errors.length) { - configFileErrors.push(...parsedCommandLine.errors); - } - this.logger.info(`Config: ${configFilename} : ${JSON.stringify( - { - rootNames: parsedCommandLine.fileNames, - options: parsedCommandLine.options, - watchOptions: parsedCommandLine.watchOptions, - projectReferences: parsedCommandLine.projectReferences - }, - /*replacer*/ - void 0, - " " - )}`); - const oldCommandLine = (_b = configFileExistenceInfo.config) == null ? void 0 : _b.parsedCommandLine; - if (!configFileExistenceInfo.config) { - configFileExistenceInfo.config = { parsedCommandLine, cachedDirectoryStructureHost, projects: /* @__PURE__ */ new Map() }; - } else { - configFileExistenceInfo.config.parsedCommandLine = parsedCommandLine; - configFileExistenceInfo.config.watchedDirectoriesStale = true; - configFileExistenceInfo.config.updateLevel = void 0; - } - if (!oldCommandLine && !isJsonEqual( - // Old options - this.getWatchOptionsFromProjectWatchOptions( - /*projectOptions*/ - void 0, - configDir - ), - // New options - this.getWatchOptionsFromProjectWatchOptions(parsedCommandLine.watchOptions, configDir) - )) { - (_c = configFileExistenceInfo.watcher) == null ? void 0 : _c.close(); - configFileExistenceInfo.watcher = void 0; - } - this.createConfigFileWatcherForParsedConfig(configFilename, canonicalConfigFilePath, forProject); - updateSharedExtendedConfigFileWatcher( - canonicalConfigFilePath, - parsedCommandLine.options, - this.sharedExtendedConfigFileWatchers, - (extendedConfigFileName, extendedConfigFilePath) => this.watchFactory.watchFile( - extendedConfigFileName, - () => { - var _a2; - cleanExtendedConfigCache(this.extendedConfigCache, extendedConfigFilePath, (fileName) => this.toPath(fileName)); - let ensureProjectsForOpenFiles = false; - (_a2 = this.sharedExtendedConfigFileWatchers.get(extendedConfigFilePath)) == null ? void 0 : _a2.projects.forEach((canonicalPath) => { - ensureProjectsForOpenFiles = this.delayUpdateProjectsFromParsedConfigOnConfigFileChange(canonicalPath, `Change in extended config file ${extendedConfigFileName} detected`) || ensureProjectsForOpenFiles; - }); - if (ensureProjectsForOpenFiles) this.delayEnsureProjectForOpenFiles(); - }, - 2e3 /* High */, - this.hostConfiguration.watchOptions, - WatchType.ExtendedConfigFile, - configFilename - ), - (fileName) => this.toPath(fileName) - ); - return configFileExistenceInfo; - } - /** @internal */ - watchWildcards(configFileName, { exists, config }, forProject) { - config.projects.set(forProject.canonicalConfigFilePath, true); - if (exists) { - if (config.watchedDirectories && !config.watchedDirectoriesStale) return; - config.watchedDirectoriesStale = false; - updateWatchingWildcardDirectories( - config.watchedDirectories || (config.watchedDirectories = /* @__PURE__ */ new Map()), - config.parsedCommandLine.wildcardDirectories, - // Create new directory watcher - (directory, flags) => this.watchWildcardDirectory(directory, flags, configFileName, config) - ); - } else { - config.watchedDirectoriesStale = false; - if (!config.watchedDirectories) return; - clearMap(config.watchedDirectories, closeFileWatcherOf); - config.watchedDirectories = void 0; - } - } - /** @internal */ - stopWatchingWildCards(canonicalConfigFilePath, forProject) { - const configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); - if (!configFileExistenceInfo.config || !configFileExistenceInfo.config.projects.get(forProject.canonicalConfigFilePath)) { - return; - } - configFileExistenceInfo.config.projects.set(forProject.canonicalConfigFilePath, false); - if (forEachEntry(configFileExistenceInfo.config.projects, identity)) return; - if (configFileExistenceInfo.config.watchedDirectories) { - clearMap(configFileExistenceInfo.config.watchedDirectories, closeFileWatcherOf); - configFileExistenceInfo.config.watchedDirectories = void 0; - } - configFileExistenceInfo.config.watchedDirectoriesStale = void 0; - } - updateNonInferredProjectFiles(project, files, propertyReader) { - var _a; - const projectRootFilesMap = project.getRootFilesMap(); - const newRootScriptInfoMap = /* @__PURE__ */ new Map(); - for (const f of files) { - const newRootFile = propertyReader.getFileName(f); - const fileName = toNormalizedPath(newRootFile); - const isDynamic = isDynamicFileName(fileName); - let path; - if (!isDynamic && !project.fileExists(newRootFile)) { - path = normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName); - const existingValue = projectRootFilesMap.get(path); - if (existingValue) { - if (((_a = existingValue.info) == null ? void 0 : _a.path) === path) { - project.removeFile( - existingValue.info, - /*fileExists*/ - false, - /*detachFromProject*/ - true - ); - existingValue.info = void 0; - } - existingValue.fileName = fileName; - } else { - projectRootFilesMap.set(path, { fileName }); - } - } else { - const scriptKind = propertyReader.getScriptKind(f, this.hostConfiguration.extraFileExtensions); - const hasMixedContent = propertyReader.hasMixedContent(f, this.hostConfiguration.extraFileExtensions); - const scriptInfo = Debug.checkDefined(this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath( - fileName, - project.currentDirectory, - scriptKind, - hasMixedContent, - project.directoryStructureHost, - /*deferredDeleteOk*/ - false - )); - path = scriptInfo.path; - const existingValue = projectRootFilesMap.get(path); - if (!existingValue || existingValue.info !== scriptInfo) { - project.addRoot(scriptInfo, fileName); - if (scriptInfo.isScriptOpen()) { - this.removeRootOfInferredProjectIfNowPartOfOtherProject(scriptInfo); - } - } else { - existingValue.fileName = fileName; - } - } - newRootScriptInfoMap.set(path, true); - } - if (projectRootFilesMap.size > newRootScriptInfoMap.size) { - projectRootFilesMap.forEach((value, path) => { - if (!newRootScriptInfoMap.has(path)) { - if (value.info) { - project.removeFile( - value.info, - project.fileExists(value.info.fileName), - /*detachFromProject*/ - true - ); - } else { - projectRootFilesMap.delete(path); - } - } - }); - } - } - updateRootAndOptionsOfNonInferredProject(project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave, watchOptions) { - project.setCompilerOptions(newOptions); - project.setWatchOptions(watchOptions); - if (compileOnSave !== void 0) { - project.compileOnSaveEnabled = compileOnSave; - } - this.addFilesToNonInferredProject(project, newUncheckedFiles, propertyReader, newTypeAcquisition); - } - /** - * Reload the file names from config file specs and update the project graph - * - * @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); - project.markAsDirty(); - return project.updateGraph(); - } - reloadFileNamesOfParsedConfig(configFileName, config) { - if (config.updateLevel === void 0) return config.parsedCommandLine.fileNames; - Debug.assert(config.updateLevel === 1 /* RootNamesAndUpdate */); - const configFileSpecs = config.parsedCommandLine.options.configFile.configFileSpecs; - const fileNames = getFileNamesFromConfigSpecs( - configFileSpecs, - getDirectoryPath(configFileName), - config.parsedCommandLine.options, - config.cachedDirectoryStructureHost, - this.hostConfiguration.extraFileExtensions - ); - config.parsedCommandLine = { ...config.parsedCommandLine, fileNames }; - return fileNames; - } - /** @internal */ - setFileNamesOfAutpImportProviderOrAuxillaryProject(project, fileNames) { - this.updateNonInferredProjectFiles(project, fileNames, fileNamePropertyReader); - } - /** @internal */ - reloadConfiguredProjectClearingSemanticCache(project, reason, reloadedProjects) { - if (!tryAddToSet(reloadedProjects, project)) return false; - this.clearSemanticCache(project); - this.reloadConfiguredProject(project, reloadReason(reason)); - return true; - } - /** - * 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(); - this.loadConfiguredProject(project, reason); - updateWithTriggerFile( - project, - project.triggerFileForConfigFileDiag ?? project.getConfigFilePath(), - /*isReload*/ - true - ); - } - clearSemanticCache(project) { - project.originalConfiguredProjects = void 0; - project.resolutionCache.clear(); - project.getLanguageService( - /*ensureSynchronized*/ - false - ).cleanupSemanticCache(); - project.cleanupProgram(); - project.markAsDirty(); - } - /** @internal */ - sendConfigFileDiagEvent(project, triggerFile, force) { - if (!this.eventHandler || this.suppressDiagnosticEvents) return false; - const diagnostics = project.getLanguageService().getCompilerOptionsDiagnostics(); - diagnostics.push(...project.getAllProjectErrors()); - if (!force && diagnostics.length === (project.configDiagDiagnosticsReported ?? 0)) return false; - project.configDiagDiagnosticsReported = diagnostics.length; - this.eventHandler( - { - eventName: ConfigFileDiagEvent, - data: { configFileName: project.getConfigFilePath(), diagnostics, triggerFile: triggerFile ?? project.getConfigFilePath() } - } - ); - return true; - } - getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath) { - if (!this.useInferredProjectPerProjectRoot || // Its a dynamic info opened without project root - info.isDynamic && projectRootPath === void 0) { - return void 0; - } - if (projectRootPath) { - const canonicalProjectRootPath = this.toCanonicalFileName(projectRootPath); - for (const project of this.inferredProjects) { - if (project.projectRootPath === canonicalProjectRootPath) { - return project; - } - } - return this.createInferredProject( - projectRootPath, - /*isSingleInferredProject*/ - false, - projectRootPath - ); - } - let bestMatch; - for (const project of this.inferredProjects) { - if (!project.projectRootPath) continue; - if (!containsPath(project.projectRootPath, info.path, this.host.getCurrentDirectory(), !this.host.useCaseSensitiveFileNames)) continue; - if (bestMatch && bestMatch.projectRootPath.length > project.projectRootPath.length) continue; - bestMatch = project; - } - return bestMatch; - } - getOrCreateSingleInferredProjectIfEnabled() { - if (!this.useSingleInferredProject) { - return void 0; - } - if (this.inferredProjects.length > 0 && this.inferredProjects[0].projectRootPath === void 0) { - return this.inferredProjects[0]; - } - return this.createInferredProject( - "", - /*isSingleInferredProject*/ - true - ); - } - getOrCreateSingleInferredWithoutProjectRoot(currentDirectory) { - Debug.assert(!this.useSingleInferredProject); - const expectedCurrentDirectory = this.toCanonicalFileName(this.getNormalizedAbsolutePath(currentDirectory)); - for (const inferredProject of this.inferredProjects) { - if (!inferredProject.projectRootPath && inferredProject.isOrphan() && inferredProject.canonicalCurrentDirectory === expectedCurrentDirectory) { - return inferredProject; - } - } - return this.createInferredProject(currentDirectory); - } - createInferredProject(currentDirectory, isSingleInferredProject, projectRootPath) { - const compilerOptions = projectRootPath && this.compilerOptionsForInferredProjectsPerProjectRoot.get(projectRootPath) || this.compilerOptionsForInferredProjects; - let watchOptionsAndErrors; - let typeAcquisition; - if (projectRootPath) { - watchOptionsAndErrors = this.watchOptionsForInferredProjectsPerProjectRoot.get(projectRootPath); - typeAcquisition = this.typeAcquisitionForInferredProjectsPerProjectRoot.get(projectRootPath); - } - if (watchOptionsAndErrors === void 0) { - watchOptionsAndErrors = this.watchOptionsForInferredProjects; - } - if (typeAcquisition === void 0) { - typeAcquisition = this.typeAcquisitionForInferredProjects; - } - watchOptionsAndErrors = watchOptionsAndErrors || void 0; - const project = new InferredProject2(this, this.documentRegistry, compilerOptions, watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions, projectRootPath, currentDirectory, typeAcquisition); - project.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors); - if (isSingleInferredProject) { - this.inferredProjects.unshift(project); - } else { - this.inferredProjects.push(project); - } - return project; - } - /** @internal */ - getOrCreateScriptInfoNotOpenedByClient(uncheckedFileName, currentDirectory, hostToQueryFileExistsOn, deferredDeleteOk) { - return this.getOrCreateScriptInfoNotOpenedByClientForNormalizedPath( - toNormalizedPath(uncheckedFileName), - currentDirectory, - /*scriptKind*/ - void 0, - /*hasMixedContent*/ - void 0, - hostToQueryFileExistsOn, - deferredDeleteOk - ); - } - getScriptInfo(uncheckedFileName) { - return this.getScriptInfoForNormalizedPath(toNormalizedPath(uncheckedFileName)); - } - /** @internal */ - getScriptInfoOrConfig(uncheckedFileName) { - const path = toNormalizedPath(uncheckedFileName); - const info = this.getScriptInfoForNormalizedPath(path); - if (info) return info; - const configProject = this.configuredProjects.get(this.toPath(uncheckedFileName)); - return configProject && configProject.getCompilerOptions().configFile; - } - /** @internal */ - logErrorForScriptInfoNotFound(fileName) { - const names = arrayFrom( - mapDefinedIterator( - this.filenameToScriptInfo.entries(), - (entry) => entry[1].deferredDelete ? void 0 : entry - ), - ([path, scriptInfo]) => ({ path, fileName: scriptInfo.fileName }) - ); - this.logger.msg(`Could not find file ${JSON.stringify(fileName)}. -All files are: ${JSON.stringify(names)}`, "Err" /* Err */); - } - /** - * Returns the projects that contain script info through SymLink - * Note that this does not return projects in info.containingProjects - * - * @internal - */ - getSymlinkedProjects(info) { - let projects; - if (this.realpathToScriptInfos) { - const realpath = info.getRealpathIfDifferent(); - if (realpath) { - forEach(this.realpathToScriptInfos.get(realpath), combineProjects); - } - forEach(this.realpathToScriptInfos.get(info.path), combineProjects); - } - return projects; - function combineProjects(toAddInfo) { - if (toAddInfo !== info) { - for (const project of toAddInfo.containingProjects) { - if (project.languageServiceEnabled && !project.isOrphan() && !project.getCompilerOptions().preserveSymlinks && !info.isAttached(project)) { - if (!projects) { - projects = createMultiMap(); - projects.add(toAddInfo.path, project); - } else if (!forEachEntry(projects, (projs, path) => path === toAddInfo.path ? false : contains(projs, project))) { - projects.add(toAddInfo.path, project); - } - } - } - } - } - } - watchClosedScriptInfo(info) { - Debug.assert(!info.fileWatcher); - if (!info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || !startsWith(info.path, this.globalCacheLocationDirectoryPath))) { - const indexOfNodeModules = info.fileName.indexOf("/node_modules/"); - if (!this.host.getModifiedTime || indexOfNodeModules === -1) { - info.fileWatcher = this.watchFactory.watchFile( - info.fileName, - (_fileName, eventKind) => this.onSourceFileChanged(info, eventKind), - 500 /* Medium */, - this.hostConfiguration.watchOptions, - WatchType.ClosedScriptInfo - ); - } else { - info.mTime = this.getModifiedTime(info); - info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.fileName.substring(0, indexOfNodeModules)); - } - } - } - createNodeModulesWatcher(dir, dirPath) { - let watcher = this.watchFactory.watchDirectory( - dir, - (fileOrDirectory) => { - var _a; - const fileOrDirectoryPath = removeIgnoredPath(this.toPath(fileOrDirectory)); - if (!fileOrDirectoryPath) return; - const basename = getBaseFileName(fileOrDirectoryPath); - if (((_a = result.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a.size) && (basename === "package.json" || basename === "node_modules")) { - result.affectedModuleSpecifierCacheProjects.forEach((project) => { - var _a2; - (_a2 = project.getModuleSpecifierCache()) == null ? void 0 : _a2.clear(); - }); - } - if (result.refreshScriptInfoRefCount) { - if (dirPath === fileOrDirectoryPath) { - this.refreshScriptInfosInDirectory(dirPath); - } else { - const info = this.filenameToScriptInfo.get(fileOrDirectoryPath); - if (info) { - if (isScriptInfoWatchedFromNodeModules(info)) { - this.refreshScriptInfo(info); - } - } else if (!hasExtension(fileOrDirectoryPath)) { - this.refreshScriptInfosInDirectory(fileOrDirectoryPath); - } - } - } - }, - 1 /* Recursive */, - this.hostConfiguration.watchOptions, - WatchType.NodeModules - ); - const result = { - refreshScriptInfoRefCount: 0, - affectedModuleSpecifierCacheProjects: void 0, - close: () => { - var _a; - if (watcher && !result.refreshScriptInfoRefCount && !((_a = result.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a.size)) { - watcher.close(); - watcher = void 0; - this.nodeModulesWatchers.delete(dirPath); - } - } - }; - this.nodeModulesWatchers.set(dirPath, result); - return result; - } - /** @internal */ - watchPackageJsonsInNodeModules(dir, project) { - var _a; - const dirPath = this.toPath(dir); - const watcher = this.nodeModulesWatchers.get(dirPath) || this.createNodeModulesWatcher(dir, dirPath); - Debug.assert(!((_a = watcher.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a.has(project))); - (watcher.affectedModuleSpecifierCacheProjects || (watcher.affectedModuleSpecifierCacheProjects = /* @__PURE__ */ new Set())).add(project); - return { - close: () => { - var _a2; - (_a2 = watcher.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a2.delete(project); - watcher.close(); - } - }; - } - watchClosedScriptInfoInNodeModules(dir) { - const watchDir = dir + "/node_modules"; - const watchDirPath = this.toPath(watchDir); - const watcher = this.nodeModulesWatchers.get(watchDirPath) || this.createNodeModulesWatcher(watchDir, watchDirPath); - watcher.refreshScriptInfoRefCount++; - return { - close: () => { - watcher.refreshScriptInfoRefCount--; - watcher.close(); - } - }; - } - getModifiedTime(info) { - return (this.host.getModifiedTime(info.fileName) || missingFileModifiedTime).getTime(); - } - refreshScriptInfo(info) { - const mTime = this.getModifiedTime(info); - if (mTime !== info.mTime) { - const eventKind = getFileWatcherEventKind(info.mTime, mTime); - info.mTime = mTime; - this.onSourceFileChanged(info, eventKind); - } - } - refreshScriptInfosInDirectory(dir) { - dir = dir + directorySeparator; - this.filenameToScriptInfo.forEach((info) => { - if (isScriptInfoWatchedFromNodeModules(info) && startsWith(info.path, dir)) { - this.refreshScriptInfo(info); - } - }); - } - stopWatchingScriptInfo(info) { - if (info.fileWatcher) { - info.fileWatcher.close(); - info.fileWatcher = void 0; - } - } - getOrCreateScriptInfoNotOpenedByClientForNormalizedPath(fileName, currentDirectory, scriptKind, hasMixedContent, hostToQueryFileExistsOn, deferredDeleteOk) { - if (isRootedDiskPath(fileName) || isDynamicFileName(fileName)) { - return this.getOrCreateScriptInfoWorker( - fileName, - currentDirectory, - /*openedByClient*/ - false, - /*fileContent*/ - void 0, - scriptKind, - !!hasMixedContent, - hostToQueryFileExistsOn, - deferredDeleteOk - ); - } - const info = this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)); - if (info) { - return info; - } - return void 0; - } - getOrCreateScriptInfoForNormalizedPath(fileName, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { - return this.getOrCreateScriptInfoWorker( - fileName, - this.currentDirectory, - openedByClient, - fileContent, - scriptKind, - !!hasMixedContent, - hostToQueryFileExistsOn, - /*deferredDeleteOk*/ - false - ); - } - getOrCreateScriptInfoWorker(fileName, currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn, deferredDeleteOk) { - Debug.assert(fileContent === void 0 || openedByClient, "ScriptInfo needs to be opened by client to be able to set its user defined content"); - const path = normalizedPathToPath(fileName, currentDirectory, this.toCanonicalFileName); - let info = this.filenameToScriptInfo.get(path); - if (!info) { - const isDynamic = isDynamicFileName(fileName); - Debug.assert(isRootedDiskPath(fileName) || isDynamic || openedByClient, "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })} -Script info with non-dynamic relative file name can only be open script info or in context of host currentDirectory`); - Debug.assert(!isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })} -Open script files with non rooted disk path opened with current directory context cannot have same canonical names`); - Debug.assert(!isDynamic || this.currentDirectory === currentDirectory || this.useInferredProjectPerProjectRoot, "", () => `${JSON.stringify({ fileName, currentDirectory, hostCurrentDirectory: this.currentDirectory, openKeys: arrayFrom(this.openFilesWithNonRootedDiskPath.keys()) })} -Dynamic files must always be opened with service's current directory or service should support inferred project per projectRootPath.`); - if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { - return; - } - info = new ScriptInfo(this.host, fileName, scriptKind, hasMixedContent, path, this.filenameToScriptInfoVersion.get(path)); - this.filenameToScriptInfo.set(info.path, info); - this.filenameToScriptInfoVersion.delete(info.path); - if (!openedByClient) { - this.watchClosedScriptInfo(info); - } else if (!isRootedDiskPath(fileName) && (!isDynamic || this.currentDirectory !== currentDirectory)) { - this.openFilesWithNonRootedDiskPath.set(this.toCanonicalFileName(fileName), info); - } - } else if (info.deferredDelete) { - Debug.assert(!info.isDynamic); - if (!openedByClient && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { - return deferredDeleteOk ? info : void 0; - } - info.deferredDelete = void 0; - } - if (openedByClient) { - this.stopWatchingScriptInfo(info); - info.open(fileContent); - if (hasMixedContent) { - info.registerFileUpdate(); - } - } - return info; - } - /** - * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred - */ - getScriptInfoForNormalizedPath(fileName) { - return !isRootedDiskPath(fileName) && this.openFilesWithNonRootedDiskPath.get(this.toCanonicalFileName(fileName)) || this.getScriptInfoForPath(normalizedPathToPath(fileName, this.currentDirectory, this.toCanonicalFileName)); - } - getScriptInfoForPath(fileName) { - const info = this.filenameToScriptInfo.get(fileName); - return !info || !info.deferredDelete ? info : void 0; - } - /** @internal */ - getDocumentPositionMapper(project, generatedFileName, sourceFileName) { - const declarationInfo = this.getOrCreateScriptInfoNotOpenedByClient( - generatedFileName, - project.currentDirectory, - this.host, - /*deferredDeleteOk*/ - false - ); - if (!declarationInfo) { - if (sourceFileName) { - project.addGeneratedFileWatch(generatedFileName, sourceFileName); - } - return void 0; - } - declarationInfo.getSnapshot(); - if (isString(declarationInfo.sourceMapFilePath)) { - const sourceMapFileInfo2 = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath); - if (sourceMapFileInfo2) { - sourceMapFileInfo2.getSnapshot(); - if (sourceMapFileInfo2.documentPositionMapper !== void 0) { - sourceMapFileInfo2.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo2.sourceInfos); - return sourceMapFileInfo2.documentPositionMapper ? sourceMapFileInfo2.documentPositionMapper : void 0; - } - } - declarationInfo.sourceMapFilePath = void 0; - } else if (declarationInfo.sourceMapFilePath) { - declarationInfo.sourceMapFilePath.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, declarationInfo.sourceMapFilePath.sourceInfos); - return void 0; - } else if (declarationInfo.sourceMapFilePath !== void 0) { - return void 0; - } - let sourceMapFileInfo; - let readMapFile = (mapFileName, mapFileNameFromDts) => { - const mapInfo = this.getOrCreateScriptInfoNotOpenedByClient( - mapFileName, - project.currentDirectory, - this.host, - /*deferredDeleteOk*/ - true - ); - sourceMapFileInfo = mapInfo || mapFileNameFromDts; - if (!mapInfo || mapInfo.deferredDelete) return void 0; - const snap = mapInfo.getSnapshot(); - if (mapInfo.documentPositionMapper !== void 0) return mapInfo.documentPositionMapper; - return getSnapshotText(snap); - }; - const projectName = project.projectName; - const documentPositionMapper = getDocumentPositionMapper( - { getCanonicalFileName: this.toCanonicalFileName, log: (s) => this.logger.info(s), getSourceFileLike: (f) => this.getSourceFileLike(f, projectName, declarationInfo) }, - declarationInfo.fileName, - declarationInfo.textStorage.getLineInfo(), - readMapFile - ); - readMapFile = void 0; - if (sourceMapFileInfo) { - if (!isString(sourceMapFileInfo)) { - declarationInfo.sourceMapFilePath = sourceMapFileInfo.path; - sourceMapFileInfo.declarationInfoPath = declarationInfo.path; - if (!sourceMapFileInfo.deferredDelete) sourceMapFileInfo.documentPositionMapper = documentPositionMapper || false; - sourceMapFileInfo.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo.sourceInfos); - } else { - declarationInfo.sourceMapFilePath = { - watcher: this.addMissingSourceMapFile( - project.currentDirectory === this.currentDirectory ? sourceMapFileInfo : getNormalizedAbsolutePath(sourceMapFileInfo, project.currentDirectory), - declarationInfo.path - ), - sourceInfos: this.addSourceInfoToSourceMap(sourceFileName, project) - }; - } - } else { - declarationInfo.sourceMapFilePath = false; - } - return documentPositionMapper; - } - addSourceInfoToSourceMap(sourceFileName, project, sourceInfos) { - if (sourceFileName) { - const sourceInfo = this.getOrCreateScriptInfoNotOpenedByClient( - sourceFileName, - project.currentDirectory, - project.directoryStructureHost, - /*deferredDeleteOk*/ - false - ); - (sourceInfos || (sourceInfos = /* @__PURE__ */ new Set())).add(sourceInfo.path); - } - return sourceInfos; - } - addMissingSourceMapFile(mapFileName, declarationInfoPath) { - const fileWatcher = this.watchFactory.watchFile( - mapFileName, - () => { - const declarationInfo = this.getScriptInfoForPath(declarationInfoPath); - if (declarationInfo && declarationInfo.sourceMapFilePath && !isString(declarationInfo.sourceMapFilePath)) { - this.delayUpdateProjectGraphs( - declarationInfo.containingProjects, - /*clearSourceMapperCache*/ - true - ); - this.delayUpdateSourceInfoProjects(declarationInfo.sourceMapFilePath.sourceInfos); - declarationInfo.closeSourceMapFileWatcher(); - } - }, - 2e3 /* High */, - this.hostConfiguration.watchOptions, - WatchType.MissingSourceMapFile - ); - return fileWatcher; - } - /** @internal */ - getSourceFileLike(fileName, projectNameOrProject, declarationInfo) { - const project = projectNameOrProject.projectName ? projectNameOrProject : this.findProject(projectNameOrProject); - if (project) { - const path = project.toPath(fileName); - const sourceFile = project.getSourceFile(path); - if (sourceFile && sourceFile.resolvedPath === path) return sourceFile; - } - const info = this.getOrCreateScriptInfoNotOpenedByClient( - fileName, - (project || this).currentDirectory, - project ? project.directoryStructureHost : this.host, - /*deferredDeleteOk*/ - false - ); - if (!info) return void 0; - if (declarationInfo && isString(declarationInfo.sourceMapFilePath) && info !== declarationInfo) { - const sourceMapInfo = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath); - if (sourceMapInfo) { - (sourceMapInfo.sourceInfos ?? (sourceMapInfo.sourceInfos = /* @__PURE__ */ new Set())).add(info.path); - } - } - if (info.cacheSourceFile) return info.cacheSourceFile.sourceFile; - if (!info.sourceFileLike) { - info.sourceFileLike = { - get text() { - Debug.fail("shouldnt need text"); - return ""; - }, - getLineAndCharacterOfPosition: (pos) => { - const lineOffset = info.positionToLineOffset(pos); - return { line: lineOffset.line - 1, character: lineOffset.offset - 1 }; - }, - getPositionOfLineAndCharacter: (line, character, allowEdits) => info.lineOffsetToPosition(line + 1, character + 1, allowEdits) - }; - } - return info.sourceFileLike; - } - /** @internal */ - setPerformanceEventHandler(performanceEventHandler) { - this.performanceEventHandler = performanceEventHandler; - } - setHostConfiguration(args) { - var _a; - if (args.file) { - const info = this.getScriptInfoForNormalizedPath(toNormalizedPath(args.file)); - if (info) { - info.setOptions(convertFormatOptions(args.formatOptions), args.preferences); - this.logger.info(`Host configuration update for file ${args.file}`); - } - } else { - if (args.hostInfo !== void 0) { - this.hostConfiguration.hostInfo = args.hostInfo; - this.logger.info(`Host information ${args.hostInfo}`); - } - if (args.formatOptions) { - this.hostConfiguration.formatCodeOptions = { ...this.hostConfiguration.formatCodeOptions, ...convertFormatOptions(args.formatOptions) }; - this.logger.info("Format host information updated"); - } - if (args.preferences) { - const { - lazyConfiguredProjectsFromExternalProject, - includePackageJsonAutoImports, - includeCompletionsForModuleExports - } = this.hostConfiguration.preferences; - this.hostConfiguration.preferences = { ...this.hostConfiguration.preferences, ...args.preferences }; - if (lazyConfiguredProjectsFromExternalProject && !this.hostConfiguration.preferences.lazyConfiguredProjectsFromExternalProject) { - this.externalProjectToConfiguredProjectMap.forEach( - (projects) => projects.forEach((project) => { - if (!project.deferredClose && !project.isClosed() && project.pendingUpdateLevel === 2 /* Full */ && !this.hasPendingProjectUpdate(project)) { - project.updateGraph(); - } - }) - ); - } - if (includePackageJsonAutoImports !== args.preferences.includePackageJsonAutoImports || !!includeCompletionsForModuleExports !== !!args.preferences.includeCompletionsForModuleExports) { - this.forEachProject((project) => { - project.onAutoImportProviderSettingsChanged(); - }); - } - } - if (args.extraFileExtensions) { - this.hostConfiguration.extraFileExtensions = args.extraFileExtensions; - this.reloadProjects(); - this.logger.info("Host file extension mappings updated"); - } - if (args.watchOptions) { - const watchOptions = (_a = convertWatchOptions(args.watchOptions)) == null ? void 0 : _a.watchOptions; - const substitution = handleWatchOptionsConfigDirTemplateSubstitution(watchOptions, this.currentDirectory); - this.hostConfiguration.watchOptions = substitution; - this.hostConfiguration.beforeSubstitution = substitution === watchOptions ? void 0 : watchOptions; - this.logger.info(`Host watch options changed to ${JSON.stringify(this.hostConfiguration.watchOptions)}, it will be take effect for next watches.`); - } - } - } - /** @internal */ - getWatchOptions(project) { - return this.getWatchOptionsFromProjectWatchOptions(project.getWatchOptions(), project.getCurrentDirectory()); - } - getWatchOptionsFromProjectWatchOptions(projectOptions, basePath) { - const hostWatchOptions = !this.hostConfiguration.beforeSubstitution ? this.hostConfiguration.watchOptions : handleWatchOptionsConfigDirTemplateSubstitution( - this.hostConfiguration.beforeSubstitution, - basePath - ); - return projectOptions && hostWatchOptions ? { ...hostWatchOptions, ...projectOptions } : projectOptions || hostWatchOptions; - } - closeLog() { - this.logger.close(); - } - sendSourceFileChange(inPath) { - this.filenameToScriptInfo.forEach((info) => { - if (this.openFiles.has(info.path)) return; - if (!info.fileWatcher) return; - const eventKind = memoize( - () => this.host.fileExists(info.fileName) ? info.deferredDelete ? 0 /* Created */ : 1 /* Changed */ : 2 /* Deleted */ - ); - if (inPath) { - if (isScriptInfoWatchedFromNodeModules(info) || !info.path.startsWith(inPath)) return; - if (eventKind() === 2 /* Deleted */ && info.deferredDelete) return; - this.logger.info(`Invoking sourceFileChange on ${info.fileName}:: ${eventKind()}`); - } - this.onSourceFileChanged( - info, - eventKind() - ); - }); - } - /** - * This function rebuilds the project for every file opened by the client - * This does not reload contents of open files from disk. But we could do that if needed - */ - reloadProjects() { - this.logger.info("reload projects."); - this.sendSourceFileChange( - /*inPath*/ - void 0 - ); - this.pendingProjectUpdates.forEach((_project, projectName) => { - this.throttledOperations.cancel(projectName); - this.pendingProjectUpdates.delete(projectName); - }); - this.throttledOperations.cancel(ensureProjectForOpenFileSchedule); - this.pendingOpenFileProjectUpdates = void 0; - this.pendingEnsureProjectForOpenFiles = false; - this.configFileExistenceInfoCache.forEach((info) => { - if (info.config) info.config.updateLevel = 2 /* Full */; - }); - this.configFileForOpenFiles.clear(); - this.externalProjects.forEach((project) => { - this.clearSemanticCache(project); - project.updateGraph(); - }); - const reloadedConfiguredProjects = /* @__PURE__ */ new Set(); - 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); - } else { - this.reloadConfiguredProjectClearingSemanticCache( - project, - reason, - reloadedConfiguredProjects - ); - } - }); - }); - this.openFiles.forEach((_projectRootPath, path) => { - const info = this.getScriptInfoForPath(path); - if (find(info.containingProjects, isExternalProject)) return; - this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo( - info, - 2 /* Reload */, - reloadedConfiguredProjects, - delayReloadedConfiguredProjects - ); - }); - delayReloadedConfiguredProjects.forEach((p) => reloadedConfiguredProjects.add(p)); - this.inferredProjects.forEach((project) => this.clearSemanticCache(project)); - this.ensureProjectForOpenFiles(); - this.cleanupProjectsAndScriptInfos( - reloadedConfiguredProjects, - new Set(this.openFiles.keys()), - new Set(this.externalProjectToConfiguredProjectMap.keys()) - ); - this.logger.info("After reloading projects.."); - this.printProjects(); - } - /** - * Remove the root of inferred project if script info is part of another project - */ - removeRootOfInferredProjectIfNowPartOfOtherProject(info) { - Debug.assert(info.containingProjects.length > 0); - const firstProject = info.containingProjects[0]; - if (!firstProject.isOrphan() && isInferredProject(firstProject) && firstProject.isRoot(info) && forEach(info.containingProjects, (p) => p !== firstProject && !p.isOrphan())) { - firstProject.removeFile( - info, - /*fileExists*/ - true, - /*detachFromProject*/ - true - ); - } - } - /** - * This function is to update the project structure for every inferred project. - * It is called on the premise that all the configured projects are - * up to date. - * This will go through open files and assign them to inferred project if open file is not part of any other project - * After that all the inferred project graphs are updated - */ - ensureProjectForOpenFiles() { - this.logger.info("Before ensureProjectForOpenFiles:"); - this.printProjects(); - const pendingOpenFileProjectUpdates = this.pendingOpenFileProjectUpdates; - this.pendingOpenFileProjectUpdates = void 0; - pendingOpenFileProjectUpdates == null ? void 0 : pendingOpenFileProjectUpdates.forEach( - (_config, path) => this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo( - this.getScriptInfoForPath(path), - 1 /* Create */ - ) - ); - this.openFiles.forEach((projectRootPath, path) => { - const info = this.getScriptInfoForPath(path); - if (info.isOrphan()) { - this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); - } else { - this.removeRootOfInferredProjectIfNowPartOfOtherProject(info); - } - }); - this.pendingEnsureProjectForOpenFiles = false; - this.inferredProjects.forEach(updateProjectIfDirty); - this.logger.info("After ensureProjectForOpenFiles:"); - this.printProjects(); - } - /** - * Open file whose contents is managed by the client - * @param filename is absolute pathname - * @param fileContent is a known version of the file content that is more up to date than the one on disk - */ - openClientFile(fileName, fileContent, scriptKind, projectRootPath) { - return this.openClientFileWithNormalizedPath( - toNormalizedPath(fileName), - fileContent, - scriptKind, - /*hasMixedContent*/ - false, - projectRootPath ? toNormalizedPath(projectRootPath) : void 0 - ); - } - /** @internal */ - getOriginalLocationEnsuringConfiguredProject(project, location) { - const isSourceOfProjectReferenceRedirect = project.isSourceOfProjectReferenceRedirect(location.fileName); - const originalLocation = isSourceOfProjectReferenceRedirect ? location : project.getSourceMapper().tryGetSourcePosition(location); - if (!originalLocation) return void 0; - const { fileName } = originalLocation; - const scriptInfo = this.getScriptInfo(fileName); - if (!scriptInfo && !this.host.fileExists(fileName)) return void 0; - const originalFileInfo = { fileName: toNormalizedPath(fileName), path: this.toPath(fileName) }; - const configFileName = this.getConfigFileNameForFile( - originalFileInfo, - /*findFromCacheOnly*/ - false - ); - if (!configFileName) return void 0; - let configuredProject = this.findConfiguredProjectByProjectName(configFileName); - if (!configuredProject) { - if (project.getCompilerOptions().disableReferencedProjectLoad) { - if (isSourceOfProjectReferenceRedirect) { - return location; - } - return (scriptInfo == null ? void 0 : scriptInfo.containingProjects.length) ? originalLocation : location; - } - 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( - 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); - const originalScriptInfo = this.getScriptInfo(fileName); - if (!originalScriptInfo || !originalScriptInfo.containingProjects.length) return void 0; - originalScriptInfo.containingProjects.forEach((project2) => { - if (isConfiguredProject(project2)) { - addOriginalConfiguredProject(project2); - } - }); - return originalLocation; - function addOriginalConfiguredProject(originalProject) { - (project.originalConfiguredProjects ?? (project.originalConfiguredProjects = /* @__PURE__ */ new Set())).add(originalProject.canonicalConfigFilePath); - } - } - /** @internal */ - fileExists(fileName) { - return !!this.getScriptInfoForNormalizedPath(fileName) || this.host.fileExists(fileName); - } - findExternalProjectContainingOpenScriptInfo(info) { - return find(this.externalProjects, (proj) => { - updateProjectIfDirty(proj); - return proj.containsScriptInfo(info); - }); - } - getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { - const info = this.getOrCreateScriptInfoWorker( - fileName, - projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, - /*openedByClient*/ - true, - fileContent, - scriptKind, - !!hasMixedContent, - /*hostToQueryFileExistsOn*/ - void 0, - /*deferredDeleteOk*/ - true - ); - this.openFiles.set(info.path, projectRootPath); - return info; - } - assignProjectToOpenedScriptInfo(info) { - let configFileName; - let configFileErrors; - const project = this.findExternalProjectContainingOpenScriptInfo(info); - let retainProjects; - let sentConfigDiag; - if (!project && this.serverMode === 0 /* Semantic */) { - const result = this.tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo( - info, - 1 /* Create */ - ); - if (result) { - retainProjects = result.seenProjects; - sentConfigDiag = result.sentConfigDiag; - if (result.defaultProject) { - configFileName = result.defaultProject.getConfigFilePath(); - configFileErrors = result.defaultProject.getAllProjectErrors(); - } - } - } - info.containingProjects.forEach(updateProjectIfDirty); - if (info.isOrphan()) { - retainProjects == null ? void 0 : retainProjects.forEach((project2) => { - if (!sentConfigDiag.has(project2)) this.sendConfigFileDiagEvent( - project2, - info.fileName, - /*force*/ - true - ); - }); - Debug.assert(this.openFiles.has(info.path)); - this.assignOrphanScriptInfoToInferredProject(info, this.openFiles.get(info.path)); - } - Debug.assert(!info.isOrphan()); - return { configFileName, configFileErrors, retainProjects }; - } - /** - * Depending on kind - * - Find the configuedProject and return it - if allowDeferredClosed is set it will find the deferredClosed project as well - * - Create - if the project doesnt exist, it creates one as well. If not delayLoad, the project is updated (with triggerFile if passed) - * - 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); - let sentConfigFileDiag = false; - switch (kind) { - case 0 /* Find */: - if (!project) return; - break; - case 1 /* Create */: - project ?? (project = this.createConfiguredProject(configFileName, reason)); - sentConfigFileDiag = !delayLoad && updateConfiguredProject(project, triggerFile); - break; - case 2 /* 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); - delayReloadedConfiguredProjects.add(project); - } - break; - default: - Debug.assertNever(kind); - } - return { project, sentConfigFileDiag }; - } - /** - * Finds the default configured project for given info - * For any tsconfig found, it looks into that project, if not then all its references, - * The search happens for all tsconfigs till projectRootPath - */ - tryFindDefaultConfiguredProjectForOpenScriptInfo(info, kind, allowDeferredClosed, reloadedProjects) { - const configFileName = this.getConfigFileNameForFile(info, kind === 0 /* Find */); - if (!configFileName) return; - const result = this.findCreateOrReloadConfiguredProject( - configFileName, - kind, - fileOpenReason(info), - allowDeferredClosed, - info.fileName, - reloadedProjects - ); - if (!result) return; - const seenProjects = /* @__PURE__ */ new Set(); - const sentConfigDiag = new Set(result.sentConfigFileDiag ? [result.project] : void 0); - let defaultProject; - let possiblyDefault; - tryFindDefaultConfiguredProject(result.project); - return { - defaultProject: defaultProject ?? possiblyDefault, - sentConfigDiag, - seenProjects - }; - 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 tryFindDefaultConfiguredProjectFromReferences(project) { - return forEachResolvedProjectReferenceProject( - 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`, - allowDeferredClosed, - info.fileName, - reloadedProjects - ); - } - } - tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo(info, kind, reloadedProjects, delayReloadedConfiguredProjects) { - const allowDeferredClosed = kind === 0 /* Find */; - const result = this.tryFindDefaultConfiguredProjectForOpenScriptInfo( - info, - kind, - allowDeferredClosed, - reloadedProjects - ); - if (!result) return; - const { defaultProject, seenProjects } = result; - if (defaultProject) { - forEachAncestorProject( - info, - defaultProject, - (ancestor) => { - seenProjects.add(ancestor); - }, - kind, - `Creating project possibly referencing default composite project ${defaultProject.getProjectName()} of open file ${info.fileName}`, - allowDeferredClosed, - reloadedProjects, - delayReloadedConfiguredProjects - ); - } - return result; - } - /** @internal */ - loadAncestorProjectTree(forProjects) { - forProjects ?? (forProjects = new Set( - mapDefinedIterator(this.configuredProjects.entries(), ([key, project]) => !project.isInitialLoadPending() ? key : void 0) - )); - const seenProjects = /* @__PURE__ */ new Set(); - const currentConfiguredProjects = arrayFrom(this.configuredProjects.values()); - for (const project of currentConfiguredProjects) { - if (forEachPotentialProjectReference(project, (potentialRefPath) => forProjects.has(potentialRefPath))) { - updateProjectIfDirty(project); - } - this.ensureProjectChildren(project, forProjects, seenProjects); - } - } - ensureProjectChildren(project, forProjects, seenProjects) { - var _a; - if (!tryAddToSet(seenProjects, project.canonicalConfigFilePath)) return; - if (project.getCompilerOptions().disableReferencedProjectLoad) return; - const children = (_a = project.getCurrentProgram()) == null ? void 0 : _a.getResolvedProjectReferences(); - if (!children) return; - for (const child of children) { - if (!child) continue; - const referencedProject = forEachResolvedProjectReference(child.references, (ref) => forProjects.has(ref.sourceFile.path) ? ref : void 0); - if (!referencedProject) continue; - const configFileName = toNormalizedPath(child.sourceFile.fileName); - const childProject = this.findConfiguredProjectByProjectName(configFileName) ?? this.createConfiguredProject( - configFileName, - `Creating project referenced by : ${project.projectName} as it references project ${referencedProject.sourceFile.fileName}` - ); - updateProjectIfDirty(childProject); - this.ensureProjectChildren(childProject, forProjects, seenProjects); - } - } - cleanupConfiguredProjects(toRetainConfiguredProjects, externalProjectsRetainingConfiguredProjects, openFilesWithRetainedConfiguredProject) { - this.getOrphanConfiguredProjects( - toRetainConfiguredProjects, - openFilesWithRetainedConfiguredProject, - externalProjectsRetainingConfiguredProjects - ).forEach((project) => this.removeProject(project)); - } - cleanupProjectsAndScriptInfos(toRetainConfiguredProjects, openFilesWithRetainedConfiguredProject, externalProjectsRetainingConfiguredProjects) { - this.cleanupConfiguredProjects( - toRetainConfiguredProjects, - externalProjectsRetainingConfiguredProjects, - openFilesWithRetainedConfiguredProject - ); - for (const inferredProject of this.inferredProjects.slice()) { - if (inferredProject.isOrphan()) { - this.removeProject(inferredProject); - } - } - this.removeOrphanScriptInfos(); - } - tryInvokeWildCardDirectories(info) { - this.configFileExistenceInfoCache.forEach((configFileExistenceInfo, config) => { - var _a, _b; - if (!((_a = configFileExistenceInfo.config) == null ? void 0 : _a.parsedCommandLine) || contains( - configFileExistenceInfo.config.parsedCommandLine.fileNames, - info.fileName, - !this.host.useCaseSensitiveFileNames ? equateStringsCaseInsensitive : equateStringsCaseSensitive - )) { - return; - } - (_b = configFileExistenceInfo.config.watchedDirectories) == null ? void 0 : _b.forEach((watcher, directory) => { - if (containsPath(directory, info.fileName, !this.host.useCaseSensitiveFileNames)) { - this.logger.info(`Invoking ${config}:: wildcard for open scriptInfo:: ${info.fileName}`); - this.onWildCardDirectoryWatcherInvoke( - directory, - config, - configFileExistenceInfo.config, - watcher.watcher, - info.fileName - ); - } - }); - }); - } - openClientFileWithNormalizedPath(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { - const existing = this.getScriptInfoForPath(normalizedPathToPath( - fileName, - projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, - this.toCanonicalFileName - )); - const info = this.getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath); - if (!existing && info && !info.isDynamic) this.tryInvokeWildCardDirectories(info); - const { retainProjects, ...result } = this.assignProjectToOpenedScriptInfo(info); - this.cleanupProjectsAndScriptInfos( - retainProjects, - /* @__PURE__ */ new Set([info.path]), - /*externalProjectsRetainingConfiguredProjects*/ - void 0 - ); - this.telemetryOnOpenFile(info); - this.printProjects(); - return result; - } - /** @internal */ - getOrphanConfiguredProjects(toRetainConfiguredProjects, openFilesWithRetainedConfiguredProject, externalProjectsRetainingConfiguredProjects) { - const toRemoveConfiguredProjects = new Set(this.configuredProjects.values()); - const markOriginalProjectsAsUsed = (project) => { - if (project.originalConfiguredProjects && (isConfiguredProject(project) || !project.isOrphan())) { - project.originalConfiguredProjects.forEach( - (_value, configuredProjectPath) => { - const project2 = this.getConfiguredProjectByCanonicalConfigFilePath(configuredProjectPath); - return project2 && retainConfiguredProject(project2); - } - ); - } - }; - toRetainConfiguredProjects == null ? void 0 : toRetainConfiguredProjects.forEach(retainConfiguredProject); - this.inferredProjects.forEach(markOriginalProjectsAsUsed); - this.externalProjects.forEach(markOriginalProjectsAsUsed); - this.externalProjectToConfiguredProjectMap.forEach((projects, externalProjectName) => { - if (!(externalProjectsRetainingConfiguredProjects == null ? void 0 : externalProjectsRetainingConfiguredProjects.has(externalProjectName))) { - projects.forEach(retainConfiguredProject); - } - }); - this.openFiles.forEach((_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 */ - ); - if (result == null ? void 0 : result.defaultProject) { - result == null ? void 0 : result.seenProjects.forEach(retainConfiguredProject); - } - }); - this.configuredProjects.forEach((project) => { - if (toRemoveConfiguredProjects.has(project)) { - if (isPendingUpdate(project) || forEachReferencedProject(project, isRetained)) { - retainConfiguredProject(project); - } - } - }); - return toRemoveConfiguredProjects; - function isRetained(project) { - return !toRemoveConfiguredProjects.has(project) || isPendingUpdate(project); - } - function isPendingUpdate(project) { - var _a, _b; - return (project.deferredClose || project.projectService.hasPendingProjectUpdate(project)) && !!((_b = (_a = project.projectService.configFileExistenceInfoCache.get(project.canonicalConfigFilePath)) == null ? void 0 : _a.openFilesImpactedByConfigFile) == null ? void 0 : _b.size); - } - function retainConfiguredProject(project) { - if (!toRemoveConfiguredProjects.delete(project)) return; - markOriginalProjectsAsUsed(project); - forEachReferencedProject(project, retainConfiguredProject); - } - } - removeOrphanScriptInfos() { - const toRemoveScriptInfos = new Map(this.filenameToScriptInfo); - this.filenameToScriptInfo.forEach((info) => { - if (info.deferredDelete) return; - if (!info.isScriptOpen() && info.isOrphan() && !info.isContainedByBackgroundProject()) { - if (!info.sourceMapFilePath) return; - let sourceInfos; - if (isString(info.sourceMapFilePath)) { - const sourceMapInfo = this.filenameToScriptInfo.get(info.sourceMapFilePath); - sourceInfos = sourceMapInfo == null ? void 0 : sourceMapInfo.sourceInfos; - } else { - sourceInfos = info.sourceMapFilePath.sourceInfos; - } - if (!sourceInfos) return; - if (!forEachKey(sourceInfos, (path) => { - const info2 = this.getScriptInfoForPath(path); - return !!info2 && (info2.isScriptOpen() || !info2.isOrphan()); - })) { - return; - } - } - toRemoveScriptInfos.delete(info.path); - if (info.sourceMapFilePath) { - let sourceInfos; - if (isString(info.sourceMapFilePath)) { - const sourceMapInfo = this.filenameToScriptInfo.get(info.sourceMapFilePath); - if (sourceMapInfo == null ? void 0 : sourceMapInfo.deferredDelete) { - info.sourceMapFilePath = { - watcher: this.addMissingSourceMapFile(sourceMapInfo.fileName, info.path), - sourceInfos: sourceMapInfo.sourceInfos - }; - } else { - toRemoveScriptInfos.delete(info.sourceMapFilePath); - } - sourceInfos = sourceMapInfo == null ? void 0 : sourceMapInfo.sourceInfos; - } else { - sourceInfos = info.sourceMapFilePath.sourceInfos; - } - if (sourceInfos) { - sourceInfos.forEach((_value, path) => toRemoveScriptInfos.delete(path)); - } - } - }); - toRemoveScriptInfos.forEach((info) => this.deleteScriptInfo(info)); - } - telemetryOnOpenFile(scriptInfo) { - if (this.serverMode !== 0 /* Semantic */ || !this.eventHandler || !scriptInfo.isJavaScript() || !addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) { - return; - } - const project = this.ensureDefaultProjectForFile(scriptInfo); - if (!project.languageServiceEnabled) { - return; - } - const sourceFile = project.getSourceFile(scriptInfo.path); - const checkJs = !!sourceFile && !!sourceFile.checkJsDirective; - this.eventHandler({ eventName: OpenFileInfoTelemetryEvent, data: { info: { checkJs } } }); - } - closeClientFile(uncheckedFileName, skipAssignOrphanScriptInfosToInferredProject) { - const info = this.getScriptInfoForNormalizedPath(toNormalizedPath(uncheckedFileName)); - const result = info ? this.closeOpenFile(info, skipAssignOrphanScriptInfosToInferredProject) : false; - if (!skipAssignOrphanScriptInfosToInferredProject) { - this.printProjects(); - } - return result; - } - collectChanges(lastKnownProjectVersions, currentProjects, includeProjectReferenceRedirectInfo, result) { - for (const proj of currentProjects) { - const knownProject = find(lastKnownProjectVersions, (p) => p.projectName === proj.getProjectName()); - result.push(proj.getChangesSinceVersion(knownProject && knownProject.version, includeProjectReferenceRedirectInfo)); - } - } - /** @internal */ - synchronizeProjectList(knownProjects, includeProjectReferenceRedirectInfo) { - const files = []; - this.collectChanges(knownProjects, this.externalProjects, includeProjectReferenceRedirectInfo, files); - this.collectChanges(knownProjects, mapDefinedIterator(this.configuredProjects.values(), (p) => p.deferredClose ? void 0 : p), includeProjectReferenceRedirectInfo, files); - this.collectChanges(knownProjects, this.inferredProjects, includeProjectReferenceRedirectInfo, files); - return files; - } - /** @internal */ - applyChangesInOpenFiles(openFiles, changedFiles, closedFiles) { - let existingOpenScriptInfos; - let openScriptInfos; - let assignOrphanScriptInfosToInferredProject = false; - if (openFiles) { - for (const file of openFiles) { - (existingOpenScriptInfos ?? (existingOpenScriptInfos = [])).push(this.getScriptInfoForPath(normalizedPathToPath( - toNormalizedPath(file.fileName), - file.projectRootPath ? this.getNormalizedAbsolutePath(file.projectRootPath) : this.currentDirectory, - this.toCanonicalFileName - ))); - const info = this.getOrCreateOpenScriptInfo( - toNormalizedPath(file.fileName), - file.content, - tryConvertScriptKindName(file.scriptKind), - file.hasMixedContent, - file.projectRootPath ? toNormalizedPath(file.projectRootPath) : void 0 - ); - (openScriptInfos || (openScriptInfos = [])).push(info); - } - } - if (changedFiles) { - for (const file of changedFiles) { - const scriptInfo = this.getScriptInfo(file.fileName); - Debug.assert(!!scriptInfo); - this.applyChangesToFile(scriptInfo, file.changes); - } - } - if (closedFiles) { - for (const file of closedFiles) { - assignOrphanScriptInfosToInferredProject = this.closeClientFile( - file, - /*skipAssignOrphanScriptInfosToInferredProject*/ - true - ) || assignOrphanScriptInfosToInferredProject; - } - } - let retainProjects; - forEach( - 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)); - }); - if (assignOrphanScriptInfosToInferredProject) { - this.assignOrphanScriptInfosToInferredProject(); - } - if (openScriptInfos) { - this.cleanupProjectsAndScriptInfos( - retainProjects, - new Set(openScriptInfos.map((info) => info.path)), - /*externalProjectsRetainingConfiguredProjects*/ - void 0 - ); - openScriptInfos.forEach((info) => this.telemetryOnOpenFile(info)); - this.printProjects(); - } else if (length(closedFiles)) { - this.printProjects(); - } - } - /** @internal */ - applyChangesToFile(scriptInfo, changes) { - for (const change of changes) { - scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); - } - } - // eslint-disable-line @typescript-eslint/unified-signatures - closeExternalProject(uncheckedFileName, cleanupAfter) { - const fileName = toNormalizedPath(uncheckedFileName); - const projects = this.externalProjectToConfiguredProjectMap.get(fileName); - if (projects) { - this.externalProjectToConfiguredProjectMap.delete(fileName); - } else { - const externalProject = this.findExternalProjectByProjectName(uncheckedFileName); - if (externalProject) { - this.removeProject(externalProject); - } - } - if (cleanupAfter) { - this.cleanupConfiguredProjects(); - this.printProjects(); - } - } - openExternalProjects(projects) { - const projectsToClose = new Set(this.externalProjects.map((p) => p.getProjectName())); - this.externalProjectToConfiguredProjectMap.forEach((_, externalProjectName) => projectsToClose.add(externalProjectName)); - for (const externalProject of projects) { - this.openExternalProject( - externalProject, - /*cleanupAfter*/ - false - ); - projectsToClose.delete(externalProject.projectFileName); - } - projectsToClose.forEach((externalProjectName) => this.closeExternalProject( - externalProjectName, - /*cleanupAfter*/ - false - )); - this.cleanupConfiguredProjects(); - this.printProjects(); - } - static escapeFilenameForRegex(filename) { - return filename.replace(this.filenameEscapeRegexp, "\\$&"); - } - resetSafeList() { - this.safelist = defaultTypeSafeList; - } - applySafeList(proj) { - const typeAcquisition = proj.typeAcquisition; - Debug.assert(!!typeAcquisition, "proj.typeAcquisition should be set by now"); - const result = this.applySafeListWorker(proj, proj.rootFiles, typeAcquisition); - return (result == null ? void 0 : result.excludedFiles) ?? []; - } - applySafeListWorker(proj, rootFiles, typeAcquisition) { - if (typeAcquisition.enable === false || typeAcquisition.disableFilenameBasedTypeAcquisition) { - return void 0; - } - const typeAcqInclude = typeAcquisition.include || (typeAcquisition.include = []); - const excludeRules = []; - const normalizedNames = rootFiles.map((f) => normalizeSlashes(f.fileName)); - for (const name of Object.keys(this.safelist)) { - const rule2 = this.safelist[name]; - for (const root of normalizedNames) { - if (rule2.match.test(root)) { - this.logger.info(`Excluding files based on rule ${name} matching file '${root}'`); - if (rule2.types) { - for (const type of rule2.types) { - if (!typeAcqInclude.includes(type)) { - typeAcqInclude.push(type); - } - } - } - if (rule2.exclude) { - for (const exclude of rule2.exclude) { - const processedRule = root.replace(rule2.match, (...groups) => { - return exclude.map((groupNumberOrString) => { - if (typeof groupNumberOrString === "number") { - if (!isString(groups[groupNumberOrString])) { - this.logger.info(`Incorrect RegExp specification in safelist rule ${name} - not enough groups`); - return "\\*"; - } - return _ProjectService.escapeFilenameForRegex(groups[groupNumberOrString]); - } - return groupNumberOrString; - }).join(""); - }); - if (!excludeRules.includes(processedRule)) { - excludeRules.push(processedRule); - } - } - } else { - const escaped = _ProjectService.escapeFilenameForRegex(root); - if (!excludeRules.includes(escaped)) { - excludeRules.push(escaped); - } - } - } - } - } - const excludeRegexes = excludeRules.map((e) => new RegExp(e, "i")); - let filesToKeep; - let excludedFiles; - for (let i = 0; i < rootFiles.length; i++) { - if (excludeRegexes.some((re) => re.test(normalizedNames[i]))) { - addExcludedFile(i); - } else { - if (typeAcquisition.enable) { - const baseName = getBaseFileName(toFileNameLowerCase(normalizedNames[i])); - if (fileExtensionIs(baseName, "js")) { - const inferredTypingName = removeFileExtension(baseName); - const cleanedTypingName = removeMinAndVersionNumbers(inferredTypingName); - const typeName = this.legacySafelist.get(cleanedTypingName); - if (typeName !== void 0) { - this.logger.info(`Excluded '${normalizedNames[i]}' because it matched ${cleanedTypingName} from the legacy safelist`); - addExcludedFile(i); - if (!typeAcqInclude.includes(typeName)) { - typeAcqInclude.push(typeName); - } - continue; - } - } - } - if (/^.+[.-]min\.js$/.test(normalizedNames[i])) { - addExcludedFile(i); - } else { - filesToKeep == null ? void 0 : filesToKeep.push(rootFiles[i]); - } - } - } - return excludedFiles ? { - rootFiles: filesToKeep, - excludedFiles - } : void 0; - function addExcludedFile(index) { - if (!excludedFiles) { - Debug.assert(!filesToKeep); - filesToKeep = rootFiles.slice(0, index); - excludedFiles = []; - } - excludedFiles.push(normalizedNames[index]); - } - } - // eslint-disable-line @typescript-eslint/unified-signatures - openExternalProject(proj, cleanupAfter) { - const existingExternalProject = this.findExternalProjectByProjectName(proj.projectFileName); - let configuredProjects; - let rootFiles = []; - for (const file of proj.rootFiles) { - const normalized = toNormalizedPath(file.fileName); - if (getBaseConfigFileName(normalized)) { - if (this.serverMode === 0 /* Semantic */ && this.host.fileExists(normalized)) { - let project = this.findConfiguredProjectByProjectName(normalized); - if (!project) { - project = this.createConfiguredProject(normalized, `Creating configured project in external project: ${proj.projectFileName}`); - if (!this.getHostPreferences().lazyConfiguredProjectsFromExternalProject) project.updateGraph(); - } - (configuredProjects ?? (configuredProjects = /* @__PURE__ */ new Set())).add(project); - Debug.assert(!project.isClosed()); - } - } else { - rootFiles.push(file); - } - } - if (configuredProjects) { - this.externalProjectToConfiguredProjectMap.set(proj.projectFileName, configuredProjects); - if (existingExternalProject) this.removeProject(existingExternalProject); - } else { - this.externalProjectToConfiguredProjectMap.delete(proj.projectFileName); - const typeAcquisition = proj.typeAcquisition || {}; - typeAcquisition.include = typeAcquisition.include || []; - typeAcquisition.exclude = typeAcquisition.exclude || []; - if (typeAcquisition.enable === void 0) { - typeAcquisition.enable = hasNoTypeScriptSource(rootFiles.map((f) => f.fileName)); - } - const excludeResult = this.applySafeListWorker(proj, rootFiles, typeAcquisition); - const excludedFiles = (excludeResult == null ? void 0 : excludeResult.excludedFiles) ?? []; - rootFiles = (excludeResult == null ? void 0 : excludeResult.rootFiles) ?? rootFiles; - if (existingExternalProject) { - existingExternalProject.excludedFiles = excludedFiles; - const compilerOptions = convertCompilerOptions(proj.options); - const watchOptionsAndErrors = convertWatchOptions(proj.options, existingExternalProject.getCurrentDirectory()); - const lastFileExceededProgramSize = this.getFilenameForExceededTotalSizeLimitForNonTsFiles(proj.projectFileName, compilerOptions, rootFiles, externalFilePropertyReader); - if (lastFileExceededProgramSize) { - existingExternalProject.disableLanguageService(lastFileExceededProgramSize); - } else { - existingExternalProject.enableLanguageService(); - } - existingExternalProject.setProjectErrors(watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.errors); - this.updateRootAndOptionsOfNonInferredProject(existingExternalProject, rootFiles, externalFilePropertyReader, compilerOptions, typeAcquisition, proj.options.compileOnSave, watchOptionsAndErrors == null ? void 0 : watchOptionsAndErrors.watchOptions); - existingExternalProject.updateGraph(); - } else { - const project = this.createExternalProject(proj.projectFileName, rootFiles, proj.options, typeAcquisition, excludedFiles); - project.updateGraph(); - } - } - if (cleanupAfter) { - this.cleanupConfiguredProjects( - configuredProjects, - new Set(proj.projectFileName) - ); - this.printProjects(); - } - } - hasDeferredExtension() { - for (const extension of this.hostConfiguration.extraFileExtensions) { - if (extension.scriptKind === 7 /* Deferred */) { - return true; - } - } - return false; - } - /** - * Performs the initial steps of enabling a plugin by finding and instantiating the module for a plugin either asynchronously or synchronously - * @internal - */ - requestEnablePlugin(project, pluginConfigEntry, searchPaths) { - if (!this.host.importPlugin && !this.host.require) { - this.logger.info("Plugins were requested but not running in environment that supports 'require'. Nothing will be loaded"); - return; - } - this.logger.info(`Enabling plugin ${pluginConfigEntry.name} from candidate paths: ${searchPaths.join(",")}`); - if (!pluginConfigEntry.name || isExternalModuleNameRelative(pluginConfigEntry.name) || /[\\/]\.\.?(?:$|[\\/])/.test(pluginConfigEntry.name)) { - this.logger.info(`Skipped loading plugin ${pluginConfigEntry.name || JSON.stringify(pluginConfigEntry)} because only package name is allowed plugin name`); - return; - } - if (this.host.importPlugin) { - const importPromise = Project2.importServicePluginAsync( - pluginConfigEntry, - searchPaths, - this.host, - (s) => this.logger.info(s) - ); - this.pendingPluginEnablements ?? (this.pendingPluginEnablements = /* @__PURE__ */ new Map()); - let promises = this.pendingPluginEnablements.get(project); - if (!promises) this.pendingPluginEnablements.set(project, promises = []); - promises.push(importPromise); - return; - } - this.endEnablePlugin( - project, - Project2.importServicePluginSync( - pluginConfigEntry, - searchPaths, - this.host, - (s) => this.logger.info(s) - ) - ); - } - /** - * Performs the remaining steps of enabling a plugin after its module has been instantiated. - */ - endEnablePlugin(project, { pluginConfigEntry, resolvedModule, errorLogs }) { - var _a; - if (resolvedModule) { - const configurationOverride = (_a = this.currentPluginConfigOverrides) == null ? void 0 : _a.get(pluginConfigEntry.name); - if (configurationOverride) { - const pluginName = pluginConfigEntry.name; - pluginConfigEntry = configurationOverride; - pluginConfigEntry.name = pluginName; - } - project.enableProxy(resolvedModule, pluginConfigEntry); - } else { - forEach(errorLogs, (message) => this.logger.info(message)); - this.logger.info(`Couldn't find ${pluginConfigEntry.name}`); - } - } - /** @internal */ - hasNewPluginEnablementRequests() { - return !!this.pendingPluginEnablements; - } - /** @internal */ - hasPendingPluginEnablements() { - return !!this.currentPluginEnablementPromise; - } - /** - * Waits for any ongoing plugin enablement requests to complete. - * - * @internal - */ - async waitForPendingPlugins() { - while (this.currentPluginEnablementPromise) { - await this.currentPluginEnablementPromise; - } - } - /** - * Starts enabling any requested plugins without waiting for the result. - * - * @internal - */ - enableRequestedPlugins() { - if (this.pendingPluginEnablements) { - void this.enableRequestedPluginsAsync(); - } - } - async enableRequestedPluginsAsync() { - if (this.currentPluginEnablementPromise) { - await this.waitForPendingPlugins(); - } - if (!this.pendingPluginEnablements) { - return; - } - const entries = arrayFrom(this.pendingPluginEnablements.entries()); - this.pendingPluginEnablements = void 0; - this.currentPluginEnablementPromise = this.enableRequestedPluginsWorker(entries); - await this.currentPluginEnablementPromise; - } - async enableRequestedPluginsWorker(pendingPlugins) { - Debug.assert(this.currentPluginEnablementPromise === void 0); - let sendProjectsUpdatedInBackgroundEvent = false; - await Promise.all(map(pendingPlugins, async ([project, promises]) => { - const results = await Promise.all(promises); - if (project.isClosed() || isProjectDeferredClose(project)) { - this.logger.info(`Cancelling plugin enabling for ${project.getProjectName()} as it is ${project.isClosed() ? "closed" : "deferred close"}`); - return; - } - sendProjectsUpdatedInBackgroundEvent = true; - for (const result of results) { - this.endEnablePlugin(project, result); - } - this.delayUpdateProjectGraph(project); - })); - this.currentPluginEnablementPromise = void 0; - if (sendProjectsUpdatedInBackgroundEvent) this.sendProjectsUpdatedInBackgroundEvent(); - } - configurePlugin(args) { - this.forEachEnabledProject((project) => project.onPluginConfigurationChanged(args.pluginName, args.configuration)); - this.currentPluginConfigOverrides = this.currentPluginConfigOverrides || /* @__PURE__ */ new Map(); - this.currentPluginConfigOverrides.set(args.pluginName, args.configuration); - } - /** @internal */ - getPackageJsonsVisibleToFile(fileName, project, rootDir) { - const packageJsonCache = this.packageJsonCache; - const rootPath = rootDir && this.toPath(rootDir); - const result = []; - const processDirectory = (directory) => { - switch (packageJsonCache.directoryHasPackageJson(directory)) { - case 3 /* Maybe */: - packageJsonCache.searchDirectoryAndAncestors(directory); - return processDirectory(directory); - case -1 /* True */: - const packageJsonFileName = combinePaths(directory, "package.json"); - this.watchPackageJsonFile(packageJsonFileName, this.toPath(packageJsonFileName), project); - const info = packageJsonCache.getInDirectory(directory); - if (info) result.push(info); - } - if (rootPath && rootPath === directory) { - return true; - } - }; - forEachAncestorDirectory(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; - } - }); - } - watchPackageJsonFile(file, path, project) { - Debug.assert(project !== void 0); - let result = (this.packageJsonFilesMap ?? (this.packageJsonFilesMap = /* @__PURE__ */ new Map())).get(path); - if (!result) { - let watcher = this.watchFactory.watchFile( - file, - (fileName, eventKind) => { - switch (eventKind) { - case 0 /* Created */: - case 1 /* Changed */: - this.packageJsonCache.addOrUpdate(fileName, path); - this.onPackageJsonChange(result); - break; - case 2 /* Deleted */: - this.packageJsonCache.delete(path); - this.onPackageJsonChange(result); - result.projects.clear(); - result.close(); - } - }, - 250 /* Low */, - this.hostConfiguration.watchOptions, - WatchType.PackageJson - ); - result = { - projects: /* @__PURE__ */ new Set(), - close: () => { - var _a; - if (result.projects.size || !watcher) return; - watcher.close(); - watcher = void 0; - (_a = this.packageJsonFilesMap) == null ? void 0 : _a.delete(path); - this.packageJsonCache.invalidate(path); - } - }; - this.packageJsonFilesMap.set(path, result); - } - result.projects.add(project); - (project.packageJsonWatches ?? (project.packageJsonWatches = /* @__PURE__ */ new Set())).add(result); - } - onPackageJsonChange(result) { - result.projects.forEach((project) => { - var _a; - return (_a = project.onPackageJsonChange) == null ? void 0 : _a.call(project); - }); - } - /** @internal */ - includePackageJsonAutoImports() { - switch (this.hostConfiguration.preferences.includePackageJsonAutoImports) { - case "on": - return 1 /* On */; - case "off": - return 0 /* Off */; - default: - return 2 /* Auto */; - } - } - /** @internal */ - getIncompleteCompletionsCache() { - return this.incompleteCompletionsCache || (this.incompleteCompletionsCache = createIncompleteCompletionsCache()); - } -}; -/** Makes a filename safe to insert in a RegExp */ -_ProjectService.filenameEscapeRegexp = /[-/\\^$*+?.()|[\]{}]/g; -var ProjectService2 = _ProjectService; -function createIncompleteCompletionsCache() { - let info; - return { - get() { - return info; - }, - set(newInfo) { - info = newInfo; - }, - clear() { - info = void 0; - } - }; -} -function isConfigFile(config) { - return config.kind !== void 0; -} -function printProjectWithoutFileNames(project) { - project.print( - /*writeProjectFileNames*/ - false, - /*writeFileExplaination*/ - false, - /*writeFileVersionAndText*/ - false - ); -} - -// src/server/moduleSpecifierCache.ts -function createModuleSpecifierCache(host) { - let containedNodeModulesWatchers; - let cache; - let currentKey; - const result = { - get(fromFileName, toFileName2, preferences, options) { - if (!cache || currentKey !== key(fromFileName, preferences, options)) return void 0; - return cache.get(toFileName2); - }, - set(fromFileName, toFileName2, preferences, options, kind, modulePaths, moduleSpecifiers) { - ensureCache(fromFileName, preferences, options).set(toFileName2, createInfo( - kind, - modulePaths, - moduleSpecifiers, - /*packageName*/ - void 0, - /*isBlockedByPackageJsonDependencies*/ - false - )); - if (moduleSpecifiers) { - for (const p of modulePaths) { - if (p.isInNodeModules) { - const nodeModulesPath = p.path.substring(0, p.path.indexOf(nodeModulesPathPart) + nodeModulesPathPart.length - 1); - const key2 = host.toPath(nodeModulesPath); - if (!(containedNodeModulesWatchers == null ? void 0 : containedNodeModulesWatchers.has(key2))) { - (containedNodeModulesWatchers || (containedNodeModulesWatchers = /* @__PURE__ */ new Map())).set( - key2, - host.watchNodeModulesForPackageJsonChanges(nodeModulesPath) - ); - } - } - } - } - }, - setModulePaths(fromFileName, toFileName2, preferences, options, modulePaths) { - const cache2 = ensureCache(fromFileName, preferences, options); - const info = cache2.get(toFileName2); - if (info) { - info.modulePaths = modulePaths; - } else { - cache2.set(toFileName2, createInfo( - /*kind*/ - void 0, - modulePaths, - /*moduleSpecifiers*/ - void 0, - /*packageName*/ - void 0, - /*isBlockedByPackageJsonDependencies*/ - void 0 - )); - } - }, - setBlockedByPackageJsonDependencies(fromFileName, toFileName2, preferences, options, packageName, isBlockedByPackageJsonDependencies) { - const cache2 = ensureCache(fromFileName, preferences, options); - const info = cache2.get(toFileName2); - if (info) { - info.isBlockedByPackageJsonDependencies = isBlockedByPackageJsonDependencies; - info.packageName = packageName; - } else { - cache2.set(toFileName2, createInfo( - /*kind*/ - void 0, - /*modulePaths*/ - void 0, - /*moduleSpecifiers*/ - void 0, - packageName, - isBlockedByPackageJsonDependencies - )); - } - }, - clear() { - containedNodeModulesWatchers == null ? void 0 : containedNodeModulesWatchers.forEach(closeFileWatcher); - cache == null ? void 0 : cache.clear(); - containedNodeModulesWatchers == null ? void 0 : containedNodeModulesWatchers.clear(); - currentKey = void 0; - }, - count() { - return cache ? cache.size : 0; - } - }; - if (Debug.isDebugging) { - Object.defineProperty(result, "__cache", { get: () => cache }); - } - return result; - function ensureCache(fromFileName, preferences, options) { - const newKey = key(fromFileName, preferences, options); - if (cache && currentKey !== newKey) { - result.clear(); - } - currentKey = newKey; - return cache || (cache = /* @__PURE__ */ new Map()); - } - function key(fromFileName, preferences, options) { - return `${fromFileName},${preferences.importModuleSpecifierEnding},${preferences.importModuleSpecifierPreference},${options.overrideImportMode}`; - } - function createInfo(kind, modulePaths, moduleSpecifiers, packageName, isBlockedByPackageJsonDependencies) { - return { kind, modulePaths, moduleSpecifiers, packageName, isBlockedByPackageJsonDependencies }; - } -} - -// src/server/packageJsonCache.ts -function createPackageJsonCache(host) { - const packageJsons = /* @__PURE__ */ new Map(); - const directoriesWithoutPackageJson = /* @__PURE__ */ new Map(); - return { - addOrUpdate, - invalidate, - delete: (fileName) => { - packageJsons.delete(fileName); - directoriesWithoutPackageJson.set(getDirectoryPath(fileName), true); - }, - getInDirectory: (directory) => { - 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); - } - }); - } - }; - function addOrUpdate(fileName, path) { - const packageJsonInfo = Debug.checkDefined(createPackageJsonInfo(fileName, host.host)); - packageJsons.set(path, packageJsonInfo); - directoriesWithoutPackageJson.delete(getDirectoryPath(path)); - } - function invalidate(path) { - packageJsons.delete(path); - directoriesWithoutPackageJson.delete(getDirectoryPath(path)); - } - function directoryHasPackageJson(directory) { - return packageJsons.has(combinePaths(directory, "package.json")) ? -1 /* True */ : directoriesWithoutPackageJson.has(directory) ? 0 /* False */ : 3 /* Maybe */; - } -} - -// src/server/session.ts -var nullCancellationToken = { - isCancellationRequested: () => false, - setRequest: () => void 0, - resetRequest: () => void 0 -}; -function hrTimeToMilliseconds(time) { - const seconds = time[0]; - const nanoseconds = time[1]; - return (1e9 * seconds + nanoseconds) / 1e6; -} -function isDeclarationFileInJSOnlyNonConfiguredProject(project, file) { - if ((isInferredProject(project) || isExternalProject(project)) && project.isJsOnlyProject()) { - const scriptInfo = project.getScriptInfoForNormalizedPath(file); - return scriptInfo && !scriptInfo.isJavaScript(); - } - return false; -} -function dtsChangeCanAffectEmit(compilationSettings) { - return getEmitDeclarations(compilationSettings) || !!compilationSettings.emitDecoratorMetadata; -} -function formatDiag(fileName, project, diag2) { - const scriptInfo = project.getScriptInfoForNormalizedPath(fileName); - return { - start: scriptInfo.positionToLineOffset(diag2.start), - end: scriptInfo.positionToLineOffset(diag2.start + diag2.length), - // TODO: GH#18217 - text: flattenDiagnosticMessageText(diag2.messageText, "\n"), - code: diag2.code, - category: diagnosticCategoryName(diag2), - reportsUnnecessary: diag2.reportsUnnecessary, - reportsDeprecated: diag2.reportsDeprecated, - source: diag2.source, - relatedInformation: map(diag2.relatedInformation, formatRelatedInformation) - }; -} -function formatRelatedInformation(info) { - if (!info.file) { - return { - message: flattenDiagnosticMessageText(info.messageText, "\n"), - category: diagnosticCategoryName(info), - code: info.code - }; - } - return { - span: { - start: convertToLocation(getLineAndCharacterOfPosition(info.file, info.start)), - end: convertToLocation(getLineAndCharacterOfPosition(info.file, info.start + info.length)), - // TODO: GH#18217 - file: info.file.fileName - }, - message: flattenDiagnosticMessageText(info.messageText, "\n"), - category: diagnosticCategoryName(info), - code: info.code - }; -} -function convertToLocation(lineAndCharacter) { - return { line: lineAndCharacter.line + 1, offset: lineAndCharacter.character + 1 }; -} -function formatDiagnosticToProtocol(diag2, includeFileName) { - const start = diag2.file && convertToLocation(getLineAndCharacterOfPosition(diag2.file, diag2.start)); - const end = diag2.file && convertToLocation(getLineAndCharacterOfPosition(diag2.file, diag2.start + diag2.length)); - const text = flattenDiagnosticMessageText(diag2.messageText, "\n"); - const { code, source } = diag2; - const category = diagnosticCategoryName(diag2); - const common = { - start, - end, - text, - code, - category, - reportsUnnecessary: diag2.reportsUnnecessary, - reportsDeprecated: diag2.reportsDeprecated, - source, - relatedInformation: map(diag2.relatedInformation, formatRelatedInformation) - }; - return includeFileName ? { ...common, fileName: diag2.file && diag2.file.fileName } : common; -} -function allEditsBeforePos(edits, pos) { - return edits.every((edit) => textSpanEnd(edit.span) < pos); -} -var CommandNames = CommandTypes; -function formatMessage2(msg, logger, byteLength, newLine) { - const verboseLogging = logger.hasLevel(3 /* verbose */); - const json = JSON.stringify(msg); - if (verboseLogging) { - logger.info(`${msg.type}:${stringifyIndented(msg)}`); - } - const len = byteLength(json, "utf8"); - return `Content-Length: ${1 + len}\r -\r -${json}${newLine}`; -} -var MultistepOperation = class { - constructor(operationHost) { - this.operationHost = operationHost; - } - startNew(action) { - this.complete(); - this.requestId = this.operationHost.getCurrentRequestId(); - this.executeAction(action); - } - complete() { - if (this.requestId !== void 0) { - this.operationHost.sendRequestCompletedEvent(this.requestId, this.performanceData); - this.requestId = void 0; - } - this.setTimerHandle(void 0); - this.setImmediateId(void 0); - this.performanceData = void 0; - } - immediate(actionType, action) { - const requestId = this.requestId; - Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "immediate: incorrect request id"); - this.setImmediateId( - this.operationHost.getServerHost().setImmediate(() => { - this.immediateId = void 0; - this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action), this.performanceData); - }, actionType) - ); - } - delay(actionType, ms, action) { - const requestId = this.requestId; - Debug.assert(requestId === this.operationHost.getCurrentRequestId(), "delay: incorrect request id"); - this.setTimerHandle( - this.operationHost.getServerHost().setTimeout( - () => { - this.timerHandle = void 0; - this.operationHost.executeWithRequestId(requestId, () => this.executeAction(action), this.performanceData); - }, - ms, - actionType - ) - ); - } - executeAction(action) { - var _a, _b, _c, _d, _e, _f; - let stop = false; - try { - if (this.operationHost.isCancellationRequested()) { - stop = true; - (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "stepCanceled", { seq: this.requestId, early: true }); - } else { - (_b = tracing) == null ? void 0 : _b.push(tracing.Phase.Session, "stepAction", { seq: this.requestId }); - action(this); - (_c = tracing) == null ? void 0 : _c.pop(); - } - } catch (e) { - (_d = tracing) == null ? void 0 : _d.popAll(); - stop = true; - if (e instanceof OperationCanceledException) { - (_e = tracing) == null ? void 0 : _e.instant(tracing.Phase.Session, "stepCanceled", { seq: this.requestId }); - } else { - (_f = tracing) == null ? void 0 : _f.instant(tracing.Phase.Session, "stepError", { seq: this.requestId, message: e.message }); - this.operationHost.logError(e, `delayed processing of request ${this.requestId}`); - } - } - this.performanceData = this.operationHost.getPerformanceData(); - if (stop || !this.hasPendingWork()) { - this.complete(); - } - } - setTimerHandle(timerHandle) { - if (this.timerHandle !== void 0) { - this.operationHost.getServerHost().clearTimeout(this.timerHandle); - } - this.timerHandle = timerHandle; - } - setImmediateId(immediateId) { - if (this.immediateId !== void 0) { - this.operationHost.getServerHost().clearImmediate(this.immediateId); - } - this.immediateId = immediateId; - } - hasPendingWork() { - return !!this.timerHandle || !!this.immediateId; - } -}; -function toEvent(eventName, body) { - return { - seq: 0, - type: "event", - event: eventName, - body - }; -} -function combineProjectOutput(defaultValue, getValue, projects, action) { - const outputs = flatMapToMutable(isArray(projects) ? projects : projects.projects, (project) => action(project, defaultValue)); - if (!isArray(projects) && projects.symLinkedProjects) { - projects.symLinkedProjects.forEach((projects2, path) => { - const value = getValue(path); - outputs.push(...flatMap(projects2, (project) => action(project, value))); - }); - } - return deduplicate(outputs, equateValues); -} -function createDocumentSpanSet(useCaseSensitiveFileNames2) { - return createSet(({ textSpan }) => textSpan.start + 100003 * textSpan.length, getDocumentSpansEqualityComparer(useCaseSensitiveFileNames2)); -} -function getRenameLocationsWorker(projects, defaultProject, initialLocation, findInStrings, findInComments, preferences, useCaseSensitiveFileNames2) { - const perProjectResults = getPerProjectReferences( - projects, - defaultProject, - initialLocation, - /*isForRename*/ - true, - (project, position) => project.getLanguageService().findRenameLocations(position.fileName, position.pos, findInStrings, findInComments, preferences), - (renameLocation, cb) => cb(documentSpanLocation(renameLocation)) - ); - if (isArray(perProjectResults)) { - return perProjectResults; - } - const results = []; - const seen = createDocumentSpanSet(useCaseSensitiveFileNames2); - perProjectResults.forEach((projectResults, project) => { - for (const result of projectResults) { - if (!seen.has(result) && !getMappedLocationForProject(documentSpanLocation(result), project)) { - results.push(result); - seen.add(result); - } - } - }); - return results; -} -function getDefinitionLocation(defaultProject, initialLocation, isForRename) { - const infos = defaultProject.getLanguageService().getDefinitionAtPosition( - initialLocation.fileName, - initialLocation.pos, - /*searchOtherFilesOnly*/ - false, - /*stopAtAlias*/ - isForRename - ); - const info = infos && firstOrUndefined(infos); - return info && !info.isLocal ? { fileName: info.fileName, pos: info.textSpan.start } : void 0; -} -function getReferencesWorker(projects, defaultProject, initialLocation, useCaseSensitiveFileNames2, logger) { - var _a, _b; - const perProjectResults = getPerProjectReferences( - projects, - defaultProject, - initialLocation, - /*isForRename*/ - false, - (project, position) => { - logger.info(`Finding references to ${position.fileName} position ${position.pos} in project ${project.getProjectName()}`); - return project.getLanguageService().findReferences(position.fileName, position.pos); - }, - (referencedSymbol, cb) => { - cb(documentSpanLocation(referencedSymbol.definition)); - for (const ref of referencedSymbol.references) { - cb(documentSpanLocation(ref)); - } - } - ); - if (isArray(perProjectResults)) { - return perProjectResults; - } - const defaultProjectResults = perProjectResults.get(defaultProject); - if (((_b = (_a = defaultProjectResults == null ? void 0 : defaultProjectResults[0]) == null ? void 0 : _a.references[0]) == null ? void 0 : _b.isDefinition) === void 0) { - perProjectResults.forEach((projectResults) => { - for (const referencedSymbol of projectResults) { - for (const ref of referencedSymbol.references) { - delete ref.isDefinition; - } - } - }); - } else { - const knownSymbolSpans = createDocumentSpanSet(useCaseSensitiveFileNames2); - for (const referencedSymbol of defaultProjectResults) { - for (const ref of referencedSymbol.references) { - if (ref.isDefinition) { - knownSymbolSpans.add(ref); - break; - } - } - } - const updatedProjects = /* @__PURE__ */ new Set(); - while (true) { - let progress = false; - perProjectResults.forEach((referencedSymbols, project) => { - if (updatedProjects.has(project)) return; - const updated = project.getLanguageService().updateIsDefinitionOfReferencedSymbols(referencedSymbols, knownSymbolSpans); - if (updated) { - updatedProjects.add(project); - progress = true; - } - }); - if (!progress) break; - } - perProjectResults.forEach((referencedSymbols, project) => { - if (updatedProjects.has(project)) return; - for (const referencedSymbol of referencedSymbols) { - for (const ref of referencedSymbol.references) { - ref.isDefinition = false; - } - } - }); - } - const results = []; - const seenRefs = createDocumentSpanSet(useCaseSensitiveFileNames2); - perProjectResults.forEach((projectResults, project) => { - for (const referencedSymbol of projectResults) { - const mappedDefinitionFile = getMappedLocationForProject(documentSpanLocation(referencedSymbol.definition), project); - const definition = mappedDefinitionFile === void 0 ? referencedSymbol.definition : { - ...referencedSymbol.definition, - textSpan: createTextSpan(mappedDefinitionFile.pos, referencedSymbol.definition.textSpan.length), - // Why would the length be the same in the original? - fileName: mappedDefinitionFile.fileName, - contextSpan: getMappedContextSpanForProject(referencedSymbol.definition, project) - }; - let symbolToAddTo = find(results, (o) => documentSpansEqual(o.definition, definition, useCaseSensitiveFileNames2)); - if (!symbolToAddTo) { - symbolToAddTo = { definition, references: [] }; - results.push(symbolToAddTo); - } - for (const ref of referencedSymbol.references) { - if (!seenRefs.has(ref) && !getMappedLocationForProject(documentSpanLocation(ref), project)) { - seenRefs.add(ref); - symbolToAddTo.references.push(ref); - } - } - } - }); - return results.filter((o) => o.references.length !== 0); -} -function forEachProjectInProjects(projects, path, cb) { - for (const project of isArray(projects) ? projects : projects.projects) { - cb(project, path); - } - if (!isArray(projects) && projects.symLinkedProjects) { - projects.symLinkedProjects.forEach((symlinkedProjects, symlinkedPath) => { - for (const project of symlinkedProjects) { - cb(project, symlinkedPath); - } - }); - } -} -function getPerProjectReferences(projects, defaultProject, initialLocation, isForRename, getResultsForPosition, forPositionInResult) { - const resultsMap = /* @__PURE__ */ new Map(); - const queue = createQueue(); - queue.enqueue({ project: defaultProject, location: initialLocation }); - forEachProjectInProjects(projects, initialLocation.fileName, (project, path) => { - const location = { fileName: path, pos: initialLocation.pos }; - queue.enqueue({ project, location }); - }); - 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) - ); - const getSourceDefinition = memoize( - () => defaultProject.isSourceOfProjectReferenceRedirect(defaultDefinition.fileName) ? defaultDefinition : defaultProject.getLanguageService().getSourceMapper().tryGetSourcePosition(defaultDefinition) - ); - const searchedProjectKeys = /* @__PURE__ */ new Set(); - onCancellation: - while (!queue.isEmpty()) { - while (!queue.isEmpty()) { - if (cancellationToken.isCancellationRequested()) break onCancellation; - const { project, location } = queue.dequeue(); - if (resultsMap.has(project)) continue; - if (isLocationProjectReferenceRedirect(project, location)) continue; - updateProjectIfDirty(project); - if (!project.containsFile(toNormalizedPath(location.fileName))) { - continue; - } - const projectResults = searchPosition(project, location); - resultsMap.set(project, projectResults ?? emptyArray2); - searchedProjectKeys.add(getProjectKey(project)); - } - if (defaultDefinition) { - projectService.loadAncestorProjectTree(searchedProjectKeys); - projectService.forEachEnabledProject((project) => { - if (cancellationToken.isCancellationRequested()) return; - if (resultsMap.has(project)) return; - const location = mapDefinitionInProject(defaultDefinition, project, getGeneratedDefinition, getSourceDefinition); - if (location) { - queue.enqueue({ project, location }); - } - }); - } - } - if (resultsMap.size === 1) { - return firstIterator(resultsMap.values()); - } - return resultsMap; - function searchPosition(project, location) { - const projectResults = getResultsForPosition(project, location); - if (!projectResults) return void 0; - for (const result of projectResults) { - forPositionInResult(result, (position) => { - const originalLocation = projectService.getOriginalLocationEnsuringConfiguredProject(project, position); - if (!originalLocation) return; - const originalScriptInfo = projectService.getScriptInfo(originalLocation.fileName); - for (const project2 of originalScriptInfo.containingProjects) { - if (!project2.isOrphan() && !resultsMap.has(project2)) { - queue.enqueue({ project: project2, location: originalLocation }); - } - } - const symlinkedProjectsMap = projectService.getSymlinkedProjects(originalScriptInfo); - if (symlinkedProjectsMap) { - symlinkedProjectsMap.forEach((symlinkedProjects, symlinkedPath) => { - for (const symlinkedProject of symlinkedProjects) { - if (!symlinkedProject.isOrphan() && !resultsMap.has(symlinkedProject)) { - queue.enqueue({ project: symlinkedProject, location: { fileName: symlinkedPath, pos: originalLocation.pos } }); - } - } - }); - } - }); - } - return projectResults; - } -} -function mapDefinitionInProject(definition, project, getGeneratedDefinition, getSourceDefinition) { - if (project.containsFile(toNormalizedPath(definition.fileName)) && !isLocationProjectReferenceRedirect(project, definition)) { - return definition; - } - const generatedDefinition = getGeneratedDefinition(); - if (generatedDefinition && project.containsFile(toNormalizedPath(generatedDefinition.fileName))) return generatedDefinition; - const sourceDefinition = getSourceDefinition(); - return sourceDefinition && project.containsFile(toNormalizedPath(sourceDefinition.fileName)) ? sourceDefinition : void 0; -} -function isLocationProjectReferenceRedirect(project, location) { - if (!location) return false; - const program = project.getLanguageService().getProgram(); - if (!program) return false; - const sourceFile = program.getSourceFile(location.fileName); - return !!sourceFile && sourceFile.resolvedPath !== sourceFile.path && sourceFile.resolvedPath !== project.toPath(location.fileName); -} -function getProjectKey(project) { - return isConfiguredProject(project) ? project.canonicalConfigFilePath : project.getProjectName(); -} -function documentSpanLocation({ fileName, textSpan }) { - return { fileName, pos: textSpan.start }; -} -function getMappedLocationForProject(location, project) { - return getMappedLocation(location, project.getSourceMapper(), (p) => project.projectService.fileExists(p)); -} -function getMappedDocumentSpanForProject(documentSpan, project) { - return getMappedDocumentSpan(documentSpan, project.getSourceMapper(), (p) => project.projectService.fileExists(p)); -} -function getMappedContextSpanForProject(documentSpan, project) { - return getMappedContextSpan(documentSpan, project.getSourceMapper(), (p) => project.projectService.fileExists(p)); -} -var invalidPartialSemanticModeCommands = [ - "openExternalProject" /* OpenExternalProject */, - "openExternalProjects" /* OpenExternalProjects */, - "closeExternalProject" /* CloseExternalProject */, - "synchronizeProjectList" /* SynchronizeProjectList */, - "emit-output" /* EmitOutput */, - "compileOnSaveAffectedFileList" /* CompileOnSaveAffectedFileList */, - "compileOnSaveEmitFile" /* CompileOnSaveEmitFile */, - "compilerOptionsDiagnostics-full" /* CompilerOptionsDiagnosticsFull */, - "encodedSemanticClassifications-full" /* EncodedSemanticClassificationsFull */, - "semanticDiagnosticsSync" /* SemanticDiagnosticsSync */, - "suggestionDiagnosticsSync" /* SuggestionDiagnosticsSync */, - "geterrForProject" /* GeterrForProject */, - "reload" /* Reload */, - "reloadProjects" /* ReloadProjects */, - "getCodeFixes" /* GetCodeFixes */, - "getCodeFixes-full" /* GetCodeFixesFull */, - "getCombinedCodeFix" /* GetCombinedCodeFix */, - "getCombinedCodeFix-full" /* GetCombinedCodeFixFull */, - "applyCodeActionCommand" /* ApplyCodeActionCommand */, - "getSupportedCodeFixes" /* GetSupportedCodeFixes */, - "getApplicableRefactors" /* GetApplicableRefactors */, - "getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */, - "getEditsForRefactor" /* GetEditsForRefactor */, - "getEditsForRefactor-full" /* GetEditsForRefactorFull */, - "organizeImports" /* OrganizeImports */, - "organizeImports-full" /* OrganizeImportsFull */, - "getEditsForFileRename" /* GetEditsForFileRename */, - "getEditsForFileRename-full" /* GetEditsForFileRenameFull */, - "prepareCallHierarchy" /* PrepareCallHierarchy */, - "provideCallHierarchyIncomingCalls" /* ProvideCallHierarchyIncomingCalls */, - "provideCallHierarchyOutgoingCalls" /* ProvideCallHierarchyOutgoingCalls */, - "getPasteEdits" /* GetPasteEdits */ -]; -var invalidSyntacticModeCommands = [ - ...invalidPartialSemanticModeCommands, - "definition" /* Definition */, - "definition-full" /* DefinitionFull */, - "definitionAndBoundSpan" /* DefinitionAndBoundSpan */, - "definitionAndBoundSpan-full" /* DefinitionAndBoundSpanFull */, - "typeDefinition" /* TypeDefinition */, - "implementation" /* Implementation */, - "implementation-full" /* ImplementationFull */, - "references" /* References */, - "references-full" /* ReferencesFull */, - "rename" /* Rename */, - "renameLocations-full" /* RenameLocationsFull */, - "rename-full" /* RenameInfoFull */, - "quickinfo" /* Quickinfo */, - "quickinfo-full" /* QuickinfoFull */, - "completionInfo" /* CompletionInfo */, - "completions" /* Completions */, - "completions-full" /* CompletionsFull */, - "completionEntryDetails" /* CompletionDetails */, - "completionEntryDetails-full" /* CompletionDetailsFull */, - "signatureHelp" /* SignatureHelp */, - "signatureHelp-full" /* SignatureHelpFull */, - "navto" /* Navto */, - "navto-full" /* NavtoFull */, - "documentHighlights" /* DocumentHighlights */, - "documentHighlights-full" /* DocumentHighlightsFull */ -]; -var Session3 = class _Session { - constructor(opts) { - this.changeSeq = 0; - // Minimum number of lines for attempting to use region diagnostics for a file. - /** @internal */ - this.regionDiagLineCountThreshold = 500; - this.handlers = new Map(Object.entries({ - // TODO(jakebailey): correctly type the handlers - ["status" /* Status */]: () => { - const response = { version }; - return this.requiredResponse(response); - }, - ["openExternalProject" /* OpenExternalProject */]: (request) => { - this.projectService.openExternalProject( - request.arguments, - /*cleanupAfter*/ - true - ); - return this.requiredResponse( - /*response*/ - true - ); - }, - ["openExternalProjects" /* OpenExternalProjects */]: (request) => { - this.projectService.openExternalProjects(request.arguments.projects); - return this.requiredResponse( - /*response*/ - true - ); - }, - ["closeExternalProject" /* CloseExternalProject */]: (request) => { - this.projectService.closeExternalProject( - request.arguments.projectFileName, - /*cleanupAfter*/ - true - ); - return this.requiredResponse( - /*response*/ - true - ); - }, - ["synchronizeProjectList" /* SynchronizeProjectList */]: (request) => { - const result = this.projectService.synchronizeProjectList(request.arguments.knownProjects, request.arguments.includeProjectReferenceRedirectInfo); - if (!result.some((p) => p.projectErrors && p.projectErrors.length !== 0)) { - return this.requiredResponse(result); - } - const converted = map(result, (p) => { - if (!p.projectErrors || p.projectErrors.length === 0) { - return p; - } - return { - info: p.info, - changes: p.changes, - files: p.files, - projectErrors: this.convertToDiagnosticsWithLinePosition( - p.projectErrors, - /*scriptInfo*/ - void 0 - ) - }; - }); - return this.requiredResponse(converted); - }, - ["updateOpen" /* UpdateOpen */]: (request) => { - this.changeSeq++; - this.projectService.applyChangesInOpenFiles( - request.arguments.openFiles && mapIterator(request.arguments.openFiles, (file) => ({ - fileName: file.file, - content: file.fileContent, - scriptKind: file.scriptKindName, - projectRootPath: file.projectRootPath - })), - request.arguments.changedFiles && mapIterator(request.arguments.changedFiles, (file) => ({ - fileName: file.fileName, - changes: mapDefinedIterator(arrayReverseIterator(file.textChanges), (change) => { - const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(file.fileName)); - const start = scriptInfo.lineOffsetToPosition(change.start.line, change.start.offset); - const end = scriptInfo.lineOffsetToPosition(change.end.line, change.end.offset); - return start >= 0 ? { span: { start, length: end - start }, newText: change.newText } : void 0; - }) - })), - request.arguments.closedFiles - ); - return this.requiredResponse( - /*response*/ - true - ); - }, - ["applyChangedToOpenFiles" /* ApplyChangedToOpenFiles */]: (request) => { - this.changeSeq++; - this.projectService.applyChangesInOpenFiles( - request.arguments.openFiles, - request.arguments.changedFiles && mapIterator(request.arguments.changedFiles, (file) => ({ - fileName: file.fileName, - // apply changes in reverse order - changes: arrayReverseIterator(file.changes) - })), - request.arguments.closedFiles - ); - return this.requiredResponse( - /*response*/ - true - ); - }, - ["exit" /* Exit */]: () => { - this.exit(); - return this.notRequired( - /*request*/ - void 0 - ); - }, - ["definition" /* Definition */]: (request) => { - return this.requiredResponse(this.getDefinition( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["definition-full" /* DefinitionFull */]: (request) => { - return this.requiredResponse(this.getDefinition( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["definitionAndBoundSpan" /* DefinitionAndBoundSpan */]: (request) => { - return this.requiredResponse(this.getDefinitionAndBoundSpan( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["definitionAndBoundSpan-full" /* DefinitionAndBoundSpanFull */]: (request) => { - return this.requiredResponse(this.getDefinitionAndBoundSpan( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["findSourceDefinition" /* FindSourceDefinition */]: (request) => { - return this.requiredResponse(this.findSourceDefinition(request.arguments)); - }, - ["emit-output" /* EmitOutput */]: (request) => { - return this.requiredResponse(this.getEmitOutput(request.arguments)); - }, - ["typeDefinition" /* TypeDefinition */]: (request) => { - return this.requiredResponse(this.getTypeDefinition(request.arguments)); - }, - ["implementation" /* Implementation */]: (request) => { - return this.requiredResponse(this.getImplementation( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["implementation-full" /* ImplementationFull */]: (request) => { - return this.requiredResponse(this.getImplementation( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["references" /* References */]: (request) => { - return this.requiredResponse(this.getReferences( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["references-full" /* ReferencesFull */]: (request) => { - return this.requiredResponse(this.getReferences( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["rename" /* Rename */]: (request) => { - return this.requiredResponse(this.getRenameLocations( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["renameLocations-full" /* RenameLocationsFull */]: (request) => { - return this.requiredResponse(this.getRenameLocations( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["rename-full" /* RenameInfoFull */]: (request) => { - return this.requiredResponse(this.getRenameInfo(request.arguments)); - }, - ["open" /* Open */]: (request) => { - this.openClientFile( - toNormalizedPath(request.arguments.file), - request.arguments.fileContent, - convertScriptKindName(request.arguments.scriptKindName), - // TODO: GH#18217 - request.arguments.projectRootPath ? toNormalizedPath(request.arguments.projectRootPath) : void 0 - ); - return this.notRequired(request); - }, - ["quickinfo" /* Quickinfo */]: (request) => { - return this.requiredResponse(this.getQuickInfoWorker( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["quickinfo-full" /* QuickinfoFull */]: (request) => { - return this.requiredResponse(this.getQuickInfoWorker( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["getOutliningSpans" /* GetOutliningSpans */]: (request) => { - return this.requiredResponse(this.getOutliningSpans( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["outliningSpans" /* GetOutliningSpansFull */]: (request) => { - return this.requiredResponse(this.getOutliningSpans( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["todoComments" /* TodoComments */]: (request) => { - return this.requiredResponse(this.getTodoComments(request.arguments)); - }, - ["indentation" /* Indentation */]: (request) => { - return this.requiredResponse(this.getIndentation(request.arguments)); - }, - ["nameOrDottedNameSpan" /* NameOrDottedNameSpan */]: (request) => { - return this.requiredResponse(this.getNameOrDottedNameSpan(request.arguments)); - }, - ["breakpointStatement" /* BreakpointStatement */]: (request) => { - return this.requiredResponse(this.getBreakpointStatement(request.arguments)); - }, - ["braceCompletion" /* BraceCompletion */]: (request) => { - return this.requiredResponse(this.isValidBraceCompletion(request.arguments)); - }, - ["docCommentTemplate" /* DocCommentTemplate */]: (request) => { - return this.requiredResponse(this.getDocCommentTemplate(request.arguments)); - }, - ["getSpanOfEnclosingComment" /* GetSpanOfEnclosingComment */]: (request) => { - return this.requiredResponse(this.getSpanOfEnclosingComment(request.arguments)); - }, - ["fileReferences" /* FileReferences */]: (request) => { - return this.requiredResponse(this.getFileReferences( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["fileReferences-full" /* FileReferencesFull */]: (request) => { - return this.requiredResponse(this.getFileReferences( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["format" /* Format */]: (request) => { - return this.requiredResponse(this.getFormattingEditsForRange(request.arguments)); - }, - ["formatonkey" /* Formatonkey */]: (request) => { - return this.requiredResponse(this.getFormattingEditsAfterKeystroke(request.arguments)); - }, - ["format-full" /* FormatFull */]: (request) => { - return this.requiredResponse(this.getFormattingEditsForDocumentFull(request.arguments)); - }, - ["formatonkey-full" /* FormatonkeyFull */]: (request) => { - return this.requiredResponse(this.getFormattingEditsAfterKeystrokeFull(request.arguments)); - }, - ["formatRange-full" /* FormatRangeFull */]: (request) => { - return this.requiredResponse(this.getFormattingEditsForRangeFull(request.arguments)); - }, - ["completionInfo" /* CompletionInfo */]: (request) => { - return this.requiredResponse(this.getCompletions(request.arguments, "completionInfo" /* CompletionInfo */)); - }, - ["completions" /* Completions */]: (request) => { - return this.requiredResponse(this.getCompletions(request.arguments, "completions" /* Completions */)); - }, - ["completions-full" /* CompletionsFull */]: (request) => { - return this.requiredResponse(this.getCompletions(request.arguments, "completions-full" /* CompletionsFull */)); - }, - ["completionEntryDetails" /* CompletionDetails */]: (request) => { - return this.requiredResponse(this.getCompletionEntryDetails( - request.arguments, - /*fullResult*/ - false - )); - }, - ["completionEntryDetails-full" /* CompletionDetailsFull */]: (request) => { - return this.requiredResponse(this.getCompletionEntryDetails( - request.arguments, - /*fullResult*/ - true - )); - }, - ["compileOnSaveAffectedFileList" /* CompileOnSaveAffectedFileList */]: (request) => { - return this.requiredResponse(this.getCompileOnSaveAffectedFileList(request.arguments)); - }, - ["compileOnSaveEmitFile" /* CompileOnSaveEmitFile */]: (request) => { - return this.requiredResponse(this.emitFile(request.arguments)); - }, - ["signatureHelp" /* SignatureHelp */]: (request) => { - return this.requiredResponse(this.getSignatureHelpItems( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["signatureHelp-full" /* SignatureHelpFull */]: (request) => { - return this.requiredResponse(this.getSignatureHelpItems( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["compilerOptionsDiagnostics-full" /* CompilerOptionsDiagnosticsFull */]: (request) => { - return this.requiredResponse(this.getCompilerOptionsDiagnostics(request.arguments)); - }, - ["encodedSyntacticClassifications-full" /* EncodedSyntacticClassificationsFull */]: (request) => { - return this.requiredResponse(this.getEncodedSyntacticClassifications(request.arguments)); - }, - ["encodedSemanticClassifications-full" /* EncodedSemanticClassificationsFull */]: (request) => { - return this.requiredResponse(this.getEncodedSemanticClassifications(request.arguments)); - }, - ["cleanup" /* Cleanup */]: () => { - this.cleanup(); - return this.requiredResponse( - /*response*/ - true - ); - }, - ["semanticDiagnosticsSync" /* SemanticDiagnosticsSync */]: (request) => { - return this.requiredResponse(this.getSemanticDiagnosticsSync(request.arguments)); - }, - ["syntacticDiagnosticsSync" /* SyntacticDiagnosticsSync */]: (request) => { - return this.requiredResponse(this.getSyntacticDiagnosticsSync(request.arguments)); - }, - ["suggestionDiagnosticsSync" /* SuggestionDiagnosticsSync */]: (request) => { - return this.requiredResponse(this.getSuggestionDiagnosticsSync(request.arguments)); - }, - ["geterr" /* Geterr */]: (request) => { - this.errorCheck.startNew((next) => this.getDiagnostics(next, request.arguments.delay, request.arguments.files)); - return this.notRequired( - /*request*/ - void 0 - ); - }, - ["geterrForProject" /* GeterrForProject */]: (request) => { - this.errorCheck.startNew((next) => this.getDiagnosticsForProject(next, request.arguments.delay, request.arguments.file)); - return this.notRequired( - /*request*/ - void 0 - ); - }, - ["change" /* Change */]: (request) => { - this.change(request.arguments); - return this.notRequired(request); - }, - ["configure" /* Configure */]: (request) => { - this.projectService.setHostConfiguration(request.arguments); - return this.notRequired(request); - }, - ["reload" /* Reload */]: (request) => { - this.reload(request.arguments); - return this.requiredResponse({ reloadFinished: true }); - }, - ["saveto" /* Saveto */]: (request) => { - const savetoArgs = request.arguments; - this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); - return this.notRequired(request); - }, - ["close" /* Close */]: (request) => { - const closeArgs = request.arguments; - this.closeClientFile(closeArgs.file); - return this.notRequired(request); - }, - ["navto" /* Navto */]: (request) => { - return this.requiredResponse(this.getNavigateToItems( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["navto-full" /* NavtoFull */]: (request) => { - return this.requiredResponse(this.getNavigateToItems( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["brace" /* Brace */]: (request) => { - return this.requiredResponse(this.getBraceMatching( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["brace-full" /* BraceFull */]: (request) => { - return this.requiredResponse(this.getBraceMatching( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["navbar" /* NavBar */]: (request) => { - return this.requiredResponse(this.getNavigationBarItems( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["navbar-full" /* NavBarFull */]: (request) => { - return this.requiredResponse(this.getNavigationBarItems( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["navtree" /* NavTree */]: (request) => { - return this.requiredResponse(this.getNavigationTree( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["navtree-full" /* NavTreeFull */]: (request) => { - return this.requiredResponse(this.getNavigationTree( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["documentHighlights" /* DocumentHighlights */]: (request) => { - return this.requiredResponse(this.getDocumentHighlights( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["documentHighlights-full" /* DocumentHighlightsFull */]: (request) => { - return this.requiredResponse(this.getDocumentHighlights( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["compilerOptionsForInferredProjects" /* CompilerOptionsForInferredProjects */]: (request) => { - this.setCompilerOptionsForInferredProjects(request.arguments); - return this.requiredResponse( - /*response*/ - true - ); - }, - ["projectInfo" /* ProjectInfo */]: (request) => { - return this.requiredResponse(this.getProjectInfo(request.arguments)); - }, - ["reloadProjects" /* ReloadProjects */]: (request) => { - this.projectService.reloadProjects(); - return this.notRequired(request); - }, - ["jsxClosingTag" /* JsxClosingTag */]: (request) => { - return this.requiredResponse(this.getJsxClosingTag(request.arguments)); - }, - ["linkedEditingRange" /* LinkedEditingRange */]: (request) => { - return this.requiredResponse(this.getLinkedEditingRange(request.arguments)); - }, - ["getCodeFixes" /* GetCodeFixes */]: (request) => { - return this.requiredResponse(this.getCodeFixes( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["getCodeFixes-full" /* GetCodeFixesFull */]: (request) => { - return this.requiredResponse(this.getCodeFixes( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["getCombinedCodeFix" /* GetCombinedCodeFix */]: (request) => { - return this.requiredResponse(this.getCombinedCodeFix( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["getCombinedCodeFix-full" /* GetCombinedCodeFixFull */]: (request) => { - return this.requiredResponse(this.getCombinedCodeFix( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["applyCodeActionCommand" /* ApplyCodeActionCommand */]: (request) => { - return this.requiredResponse(this.applyCodeActionCommand(request.arguments)); - }, - ["getSupportedCodeFixes" /* GetSupportedCodeFixes */]: (request) => { - return this.requiredResponse(this.getSupportedCodeFixes(request.arguments)); - }, - ["getApplicableRefactors" /* GetApplicableRefactors */]: (request) => { - return this.requiredResponse(this.getApplicableRefactors(request.arguments)); - }, - ["getEditsForRefactor" /* GetEditsForRefactor */]: (request) => { - return this.requiredResponse(this.getEditsForRefactor( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["getMoveToRefactoringFileSuggestions" /* GetMoveToRefactoringFileSuggestions */]: (request) => { - return this.requiredResponse(this.getMoveToRefactoringFileSuggestions(request.arguments)); - }, - ["getPasteEdits" /* GetPasteEdits */]: (request) => { - return this.requiredResponse(this.getPasteEdits(request.arguments)); - }, - ["getEditsForRefactor-full" /* GetEditsForRefactorFull */]: (request) => { - return this.requiredResponse(this.getEditsForRefactor( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["organizeImports" /* OrganizeImports */]: (request) => { - return this.requiredResponse(this.organizeImports( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["organizeImports-full" /* OrganizeImportsFull */]: (request) => { - return this.requiredResponse(this.organizeImports( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["getEditsForFileRename" /* GetEditsForFileRename */]: (request) => { - return this.requiredResponse(this.getEditsForFileRename( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["getEditsForFileRename-full" /* GetEditsForFileRenameFull */]: (request) => { - return this.requiredResponse(this.getEditsForFileRename( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["configurePlugin" /* ConfigurePlugin */]: (request) => { - this.configurePlugin(request.arguments); - return this.notRequired(request); - }, - ["selectionRange" /* SelectionRange */]: (request) => { - return this.requiredResponse(this.getSmartSelectionRange( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["selectionRange-full" /* SelectionRangeFull */]: (request) => { - return this.requiredResponse(this.getSmartSelectionRange( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["prepareCallHierarchy" /* PrepareCallHierarchy */]: (request) => { - return this.requiredResponse(this.prepareCallHierarchy(request.arguments)); - }, - ["provideCallHierarchyIncomingCalls" /* ProvideCallHierarchyIncomingCalls */]: (request) => { - return this.requiredResponse(this.provideCallHierarchyIncomingCalls(request.arguments)); - }, - ["provideCallHierarchyOutgoingCalls" /* ProvideCallHierarchyOutgoingCalls */]: (request) => { - return this.requiredResponse(this.provideCallHierarchyOutgoingCalls(request.arguments)); - }, - ["toggleLineComment" /* ToggleLineComment */]: (request) => { - return this.requiredResponse(this.toggleLineComment( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["toggleLineComment-full" /* ToggleLineCommentFull */]: (request) => { - return this.requiredResponse(this.toggleLineComment( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["toggleMultilineComment" /* ToggleMultilineComment */]: (request) => { - return this.requiredResponse(this.toggleMultilineComment( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["toggleMultilineComment-full" /* ToggleMultilineCommentFull */]: (request) => { - return this.requiredResponse(this.toggleMultilineComment( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["commentSelection" /* CommentSelection */]: (request) => { - return this.requiredResponse(this.commentSelection( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["commentSelection-full" /* CommentSelectionFull */]: (request) => { - return this.requiredResponse(this.commentSelection( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["uncommentSelection" /* UncommentSelection */]: (request) => { - return this.requiredResponse(this.uncommentSelection( - request.arguments, - /*simplifiedResult*/ - true - )); - }, - ["uncommentSelection-full" /* UncommentSelectionFull */]: (request) => { - return this.requiredResponse(this.uncommentSelection( - request.arguments, - /*simplifiedResult*/ - false - )); - }, - ["provideInlayHints" /* ProvideInlayHints */]: (request) => { - return this.requiredResponse(this.provideInlayHints(request.arguments)); - }, - ["mapCode" /* MapCode */]: (request) => { - return this.requiredResponse(this.mapCode(request.arguments)); - } - })); - this.host = opts.host; - this.cancellationToken = opts.cancellationToken; - this.typingsInstaller = opts.typingsInstaller || nullTypingsInstaller; - this.byteLength = opts.byteLength; - this.hrtime = opts.hrtime; - this.logger = opts.logger; - this.canUseEvents = opts.canUseEvents; - this.suppressDiagnosticEvents = opts.suppressDiagnosticEvents; - this.noGetErrOnBackgroundUpdate = opts.noGetErrOnBackgroundUpdate; - const { throttleWaitMilliseconds } = opts; - this.eventHandler = this.canUseEvents ? opts.eventHandler || ((event) => this.defaultEventHandler(event)) : void 0; - const multistepOperationHost = { - executeWithRequestId: (requestId, action, performanceData) => this.executeWithRequestId(requestId, action, performanceData), - getCurrentRequestId: () => this.currentRequestId, - getPerformanceData: () => this.performanceData, - getServerHost: () => this.host, - logError: (err, cmd) => this.logError(err, cmd), - sendRequestCompletedEvent: (requestId, performanceData) => this.sendRequestCompletedEvent(requestId, performanceData), - isCancellationRequested: () => this.cancellationToken.isCancellationRequested() - }; - this.errorCheck = new MultistepOperation(multistepOperationHost); - const settings = { - host: this.host, - logger: this.logger, - cancellationToken: this.cancellationToken, - useSingleInferredProject: opts.useSingleInferredProject, - useInferredProjectPerProjectRoot: opts.useInferredProjectPerProjectRoot, - typingsInstaller: this.typingsInstaller, - throttleWaitMilliseconds, - eventHandler: this.eventHandler, - suppressDiagnosticEvents: this.suppressDiagnosticEvents, - globalPlugins: opts.globalPlugins, - pluginProbeLocations: opts.pluginProbeLocations, - allowLocalPluginLoads: opts.allowLocalPluginLoads, - typesMapLocation: opts.typesMapLocation, - serverMode: opts.serverMode, - session: this, - canUseWatchEvents: opts.canUseWatchEvents, - incrementalVerifier: opts.incrementalVerifier - }; - this.projectService = new ProjectService2(settings); - this.projectService.setPerformanceEventHandler(this.performanceEventHandler.bind(this)); - this.gcTimer = new GcTimer( - this.host, - /*delay*/ - 7e3, - this.logger - ); - switch (this.projectService.serverMode) { - case 0 /* Semantic */: - break; - case 1 /* PartialSemantic */: - invalidPartialSemanticModeCommands.forEach( - (commandName) => this.handlers.set(commandName, (request) => { - throw new Error(`Request: ${request.command} not allowed in LanguageServiceMode.PartialSemantic`); - }) - ); - break; - case 2 /* Syntactic */: - invalidSyntacticModeCommands.forEach( - (commandName) => this.handlers.set(commandName, (request) => { - throw new Error(`Request: ${request.command} not allowed in LanguageServiceMode.Syntactic`); - }) - ); - break; - default: - Debug.assertNever(this.projectService.serverMode); - } - } - sendRequestCompletedEvent(requestId, performanceData) { - this.event( - { - request_seq: requestId, - performanceData: performanceData && toProtocolPerformanceData(performanceData) - }, - "requestCompleted" - ); - } - addPerformanceData(key, value) { - if (!this.performanceData) { - this.performanceData = {}; - } - this.performanceData[key] = (this.performanceData[key] ?? 0) + value; - } - addDiagnosticsPerformanceData(file, kind, duration) { - var _a, _b; - if (!this.performanceData) { - this.performanceData = {}; - } - let fileDiagnosticDuration = (_a = this.performanceData.diagnosticsDuration) == null ? void 0 : _a.get(file); - if (!fileDiagnosticDuration) ((_b = this.performanceData).diagnosticsDuration ?? (_b.diagnosticsDuration = /* @__PURE__ */ new Map())).set(file, fileDiagnosticDuration = {}); - fileDiagnosticDuration[kind] = duration; - } - performanceEventHandler(event) { - switch (event.kind) { - case "UpdateGraph": - this.addPerformanceData("updateGraphDurationMs", event.durationMs); - break; - case "CreatePackageJsonAutoImportProvider": - this.addPerformanceData("createAutoImportProviderProgramDurationMs", event.durationMs); - break; - } - } - defaultEventHandler(event) { - switch (event.eventName) { - case ProjectsUpdatedInBackgroundEvent: - this.projectsUpdatedInBackgroundEvent(event.data.openFiles); - break; - case ProjectLoadingStartEvent: - this.event({ - projectName: event.data.project.getProjectName(), - reason: event.data.reason - }, event.eventName); - break; - case ProjectLoadingFinishEvent: - this.event({ - projectName: event.data.project.getProjectName() - }, event.eventName); - break; - case LargeFileReferencedEvent: - case CreateFileWatcherEvent: - case CreateDirectoryWatcherEvent: - case CloseFileWatcherEvent: - this.event(event.data, event.eventName); - break; - case ConfigFileDiagEvent: - this.event({ - triggerFile: event.data.triggerFile, - configFile: event.data.configFileName, - diagnostics: map(event.data.diagnostics, (diagnostic) => formatDiagnosticToProtocol( - diagnostic, - /*includeFileName*/ - true - )) - }, event.eventName); - break; - case ProjectLanguageServiceStateEvent: { - this.event({ - projectName: event.data.project.getProjectName(), - languageServiceEnabled: event.data.languageServiceEnabled - }, event.eventName); - break; - } - case ProjectInfoTelemetryEvent: { - const eventName = "telemetry"; - this.event({ - telemetryEventName: event.eventName, - payload: event.data - }, eventName); - break; - } - } - } - projectsUpdatedInBackgroundEvent(openFiles) { - this.projectService.logger.info(`got projects updated in background ${openFiles}`); - if (openFiles.length) { - if (!this.suppressDiagnosticEvents && !this.noGetErrOnBackgroundUpdate) { - this.projectService.logger.info(`Queueing diagnostics update for ${openFiles}`); - this.errorCheck.startNew((next) => this.updateErrorCheck( - next, - openFiles, - 100, - /*requireOpen*/ - true - )); - } - this.event({ - openFiles - }, ProjectsUpdatedInBackgroundEvent); - } - } - logError(err, cmd) { - this.logErrorWorker(err, cmd); - } - logErrorWorker(err, cmd, fileRequest) { - let msg = "Exception on executing command " + cmd; - if (err.message) { - msg += ":\n" + indent2(err.message); - if (err.stack) { - msg += "\n" + indent2(err.stack); - } - } - if (this.logger.hasLevel(3 /* verbose */)) { - if (fileRequest) { - try { - const { file, project } = this.getFileAndProject(fileRequest); - const scriptInfo = project.getScriptInfoForNormalizedPath(file); - if (scriptInfo) { - const text = getSnapshotText(scriptInfo.getSnapshot()); - msg += ` - -File text of ${fileRequest.file}:${indent2(text)} -`; - } - } catch { - } - } - if (err.ProgramFiles) { - msg += ` - -Program files: ${JSON.stringify(err.ProgramFiles)} -`; - msg += ` - -Projects:: -`; - let counter = 0; - const addProjectInfo = (project) => { - msg += ` -Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter} -`; - msg += project.filesToString( - /*writeProjectFileNames*/ - true - ); - msg += "\n-----------------------------------------------\n"; - counter++; - }; - this.projectService.externalProjects.forEach(addProjectInfo); - this.projectService.configuredProjects.forEach(addProjectInfo); - this.projectService.inferredProjects.forEach(addProjectInfo); - } - } - this.logger.msg(msg, "Err" /* Err */); - } - send(msg) { - if (msg.type === "event" && !this.canUseEvents) { - if (this.logger.hasLevel(3 /* verbose */)) { - this.logger.info(`Session does not support events: ignored event: ${stringifyIndented(msg)}`); - } - return; - } - this.writeMessage(msg); - } - writeMessage(msg) { - const msgText = formatMessage2(msg, this.logger, this.byteLength, this.host.newLine); - this.host.write(msgText); - } - event(body, eventName) { - this.send(toEvent(eventName, body)); - } - /** @internal */ - doOutput(info, cmdName, reqSeq, success, performanceData, message) { - const res = { - seq: 0, - type: "response", - command: cmdName, - request_seq: reqSeq, - success, - performanceData: performanceData && toProtocolPerformanceData(performanceData) - }; - if (success) { - let metadata; - if (isArray(info)) { - res.body = info; - metadata = info.metadata; - delete info.metadata; - } else if (typeof info === "object") { - if (info.metadata) { - const { metadata: infoMetadata, ...body } = info; - res.body = body; - metadata = infoMetadata; - } else { - res.body = info; - } - } else { - res.body = info; - } - if (metadata) res.metadata = metadata; - } else { - Debug.assert(info === void 0); - } - if (message) { - res.message = message; - } - this.send(res); - } - semanticCheck(file, project) { - var _a, _b; - const diagnosticsStartTime = timestamp(); - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "semanticCheck", { file, configFilePath: project.canonicalConfigFilePath }); - const diags = isDeclarationFileInJSOnlyNonConfiguredProject(project, file) ? emptyArray2 : project.getLanguageService().getSemanticDiagnostics(file).filter((d) => !!d.file); - this.sendDiagnosticsEvent(file, project, diags, "semanticDiag", diagnosticsStartTime); - (_b = tracing) == null ? void 0 : _b.pop(); - } - syntacticCheck(file, project) { - var _a, _b; - const diagnosticsStartTime = timestamp(); - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "syntacticCheck", { file, configFilePath: project.canonicalConfigFilePath }); - this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSyntacticDiagnostics(file), "syntaxDiag", diagnosticsStartTime); - (_b = tracing) == null ? void 0 : _b.pop(); - } - suggestionCheck(file, project) { - var _a, _b; - const diagnosticsStartTime = timestamp(); - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "suggestionCheck", { file, configFilePath: project.canonicalConfigFilePath }); - this.sendDiagnosticsEvent(file, project, project.getLanguageService().getSuggestionDiagnostics(file), "suggestionDiag", diagnosticsStartTime); - (_b = tracing) == null ? void 0 : _b.pop(); - } - regionSemanticCheck(file, project, ranges) { - var _a, _b, _c; - const diagnosticsStartTime = timestamp(); - (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Session, "regionSemanticCheck", { file, configFilePath: project.canonicalConfigFilePath }); - let diagnosticsResult; - if (!this.shouldDoRegionCheck(file) || !(diagnosticsResult = project.getLanguageService().getRegionSemanticDiagnostics(file, ranges))) { - (_b = tracing) == null ? void 0 : _b.pop(); - return; - } - this.sendDiagnosticsEvent(file, project, diagnosticsResult.diagnostics, "regionSemanticDiag", diagnosticsStartTime, diagnosticsResult.spans); - (_c = tracing) == null ? void 0 : _c.pop(); - return; - } - // We should only do the region-based semantic check if we think it would be - // considerably faster than a whole-file semantic check. - /** @internal */ - shouldDoRegionCheck(file) { - var _a; - const lineCount = (_a = this.projectService.getScriptInfoForNormalizedPath(file)) == null ? void 0 : _a.textStorage.getLineInfo().getLineCount(); - return !!(lineCount && lineCount >= this.regionDiagLineCountThreshold); - } - sendDiagnosticsEvent(file, project, diagnostics, kind, diagnosticsStartTime, spans) { - try { - const scriptInfo = Debug.checkDefined(project.getScriptInfo(file)); - const duration = timestamp() - diagnosticsStartTime; - const body = { - file, - diagnostics: diagnostics.map((diag2) => formatDiag(file, project, diag2)), - spans: spans == null ? void 0 : spans.map((span) => toProtocolTextSpan(span, scriptInfo)) - }; - this.event( - body, - kind - ); - this.addDiagnosticsPerformanceData(file, kind, duration); - } catch (err) { - this.logError(err, kind); - } - } - /** It is the caller's responsibility to verify that `!this.suppressDiagnosticEvents`. */ - updateErrorCheck(next, checkList, ms, requireOpen = true) { - if (checkList.length === 0) { - return; - } - Debug.assert(!this.suppressDiagnosticEvents); - const seq = this.changeSeq; - const followMs = Math.min(ms, 200); - let index = 0; - const goNext = () => { - index++; - if (checkList.length > index) { - return next.delay("checkOne", followMs, checkOne); - } - }; - const doSemanticCheck = (fileName, project) => { - this.semanticCheck(fileName, project); - if (this.changeSeq !== seq) { - return; - } - if (this.getPreferences(fileName).disableSuggestions) { - return goNext(); - } - next.immediate("suggestionCheck", () => { - this.suggestionCheck(fileName, project); - goNext(); - }); - }; - const checkOne = () => { - if (this.changeSeq !== seq) { - return; - } - let ranges; - let item = checkList[index]; - if (isString(item)) { - item = this.toPendingErrorCheck(item); - } else if ("ranges" in item) { - ranges = item.ranges; - item = this.toPendingErrorCheck(item.file); - } - if (!item) { - return goNext(); - } - const { fileName, project } = item; - updateProjectIfDirty(project); - if (!project.containsFile(fileName, requireOpen)) { - return; - } - this.syntacticCheck(fileName, project); - if (this.changeSeq !== seq) { - return; - } - if (project.projectService.serverMode !== 0 /* Semantic */) { - return goNext(); - } - if (ranges) { - return next.immediate("regionSemanticCheck", () => { - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(fileName); - if (scriptInfo) { - this.regionSemanticCheck(fileName, project, ranges.map((range) => this.getRange({ file: fileName, ...range }, scriptInfo))); - } - if (this.changeSeq !== seq) { - return; - } - next.immediate("semanticCheck", () => doSemanticCheck(fileName, project)); - }); - } - next.immediate("semanticCheck", () => doSemanticCheck(fileName, project)); - }; - if (checkList.length > index && this.changeSeq === seq) { - next.delay("checkOne", ms, checkOne); - } - } - cleanProjects(caption, projects) { - if (!projects) { - return; - } - this.logger.info(`cleaning ${caption}`); - for (const p of projects) { - p.getLanguageService( - /*ensureSynchronized*/ - false - ).cleanupSemanticCache(); - p.cleanupProgram(); - } - } - cleanup() { - this.cleanProjects("inferred projects", this.projectService.inferredProjects); - this.cleanProjects("configured projects", arrayFrom(this.projectService.configuredProjects.values())); - this.cleanProjects("external projects", this.projectService.externalProjects); - if (this.host.gc) { - this.logger.info(`host.gc()`); - this.host.gc(); - } - } - getEncodedSyntacticClassifications(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - return languageService.getEncodedSyntacticClassifications(file, args); - } - getEncodedSemanticClassifications(args) { - const { file, project } = this.getFileAndProject(args); - const format = args.format === "2020" ? "2020" /* TwentyTwenty */ : "original" /* Original */; - return project.getLanguageService().getEncodedSemanticClassifications(file, args, format); - } - getProject(projectFileName) { - return projectFileName === void 0 ? void 0 : this.projectService.findProject(projectFileName); - } - getConfigFileAndProject(args) { - const project = this.getProject(args.projectFileName); - const file = toNormalizedPath(args.file); - return { - configFile: project && project.hasConfigFile(file) ? file : void 0, - project - }; - } - getConfigFileDiagnostics(configFile, project, includeLinePosition) { - const projectErrors = project.getAllProjectErrors(); - const optionsErrors = project.getLanguageService().getCompilerOptionsDiagnostics(); - const diagnosticsForConfigFile = filter( - concatenate(projectErrors, optionsErrors), - (diagnostic) => !!diagnostic.file && diagnostic.file.fileName === configFile - ); - return includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnosticsForConfigFile) : map( - diagnosticsForConfigFile, - (diagnostic) => formatDiagnosticToProtocol( - diagnostic, - /*includeFileName*/ - false - ) - ); - } - convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics) { - return diagnostics.map((d) => ({ - message: flattenDiagnosticMessageText(d.messageText, this.host.newLine), - start: d.start, - // TODO: GH#18217 - length: d.length, - // TODO: GH#18217 - category: diagnosticCategoryName(d), - code: d.code, - source: d.source, - startLocation: d.file && convertToLocation(getLineAndCharacterOfPosition(d.file, d.start)), - // TODO: GH#18217 - endLocation: d.file && convertToLocation(getLineAndCharacterOfPosition(d.file, d.start + d.length)), - // TODO: GH#18217 - reportsUnnecessary: d.reportsUnnecessary, - reportsDeprecated: d.reportsDeprecated, - relatedInformation: map(d.relatedInformation, formatRelatedInformation) - })); - } - getCompilerOptionsDiagnostics(args) { - const project = this.getProject(args.projectFileName); - return this.convertToDiagnosticsWithLinePosition( - filter( - project.getLanguageService().getCompilerOptionsDiagnostics(), - (diagnostic) => !diagnostic.file - ), - /*scriptInfo*/ - void 0 - ); - } - convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) { - return diagnostics.map( - (d) => ({ - message: flattenDiagnosticMessageText(d.messageText, this.host.newLine), - start: d.start, - length: d.length, - category: diagnosticCategoryName(d), - code: d.code, - source: d.source, - startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start), - // TODO: GH#18217 - endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length), - reportsUnnecessary: d.reportsUnnecessary, - reportsDeprecated: d.reportsDeprecated, - relatedInformation: map(d.relatedInformation, formatRelatedInformation) - }) - ); - } - getDiagnosticsWorker(args, isSemantic, selector, includeLinePosition) { - const { project, file } = this.getFileAndProject(args); - if (isSemantic && isDeclarationFileInJSOnlyNonConfiguredProject(project, file)) { - return emptyArray2; - } - const scriptInfo = project.getScriptInfoForNormalizedPath(file); - const diagnostics = selector(project, file); - return includeLinePosition ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) : diagnostics.map((d) => formatDiag(file, project, d)); - } - getDefinition(args, simplifiedResult) { - const { file, project } = this.getFileAndProject(args); - const position = this.getPositionInFile(args, file); - const definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getDefinitionAtPosition(file, position) || emptyArray2, project); - return simplifiedResult ? this.mapDefinitionInfo(definitions, project) : definitions.map(_Session.mapToOriginalLocation); - } - mapDefinitionInfoLocations(definitions, project) { - return definitions.map((info) => { - const newDocumentSpan = getMappedDocumentSpanForProject(info, project); - return !newDocumentSpan ? info : { - ...newDocumentSpan, - containerKind: info.containerKind, - containerName: info.containerName, - kind: info.kind, - name: info.name, - failedAliasResolution: info.failedAliasResolution, - ...info.unverified && { unverified: info.unverified } - }; - }); - } - getDefinitionAndBoundSpan(args, simplifiedResult) { - const { file, project } = this.getFileAndProject(args); - const position = this.getPositionInFile(args, file); - const scriptInfo = Debug.checkDefined(project.getScriptInfo(file)); - const unmappedDefinitionAndBoundSpan = project.getLanguageService().getDefinitionAndBoundSpan(file, position); - if (!unmappedDefinitionAndBoundSpan || !unmappedDefinitionAndBoundSpan.definitions) { - return { - definitions: emptyArray2, - textSpan: void 0 - // TODO: GH#18217 - }; - } - const definitions = this.mapDefinitionInfoLocations(unmappedDefinitionAndBoundSpan.definitions, project); - const { textSpan } = unmappedDefinitionAndBoundSpan; - if (simplifiedResult) { - return { - definitions: this.mapDefinitionInfo(definitions, project), - textSpan: toProtocolTextSpan(textSpan, scriptInfo) - }; - } - return { - definitions: definitions.map(_Session.mapToOriginalLocation), - textSpan - }; - } - findSourceDefinition(args) { - var _a; - const { file, project } = this.getFileAndProject(args); - const position = this.getPositionInFile(args, file); - const unmappedDefinitions = project.getLanguageService().getDefinitionAtPosition(file, position); - let definitions = this.mapDefinitionInfoLocations(unmappedDefinitions || emptyArray2, project).slice(); - const needsJsResolution = this.projectService.serverMode === 0 /* Semantic */ && (!some(definitions, (d) => toNormalizedPath(d.fileName) !== file && !d.isAmbient) || some(definitions, (d) => !!d.failedAliasResolution)); - if (needsJsResolution) { - const definitionSet = createSet( - (d) => d.textSpan.start, - getDocumentSpansEqualityComparer(this.host.useCaseSensitiveFileNames) - ); - definitions == null ? void 0 : definitions.forEach((d) => definitionSet.add(d)); - const noDtsProject = project.getNoDtsResolutionProject(file); - const ls = noDtsProject.getLanguageService(); - const jsDefinitions = (_a = ls.getDefinitionAtPosition( - file, - position, - /*searchOtherFilesOnly*/ - true, - /*stopAtAlias*/ - false - )) == null ? void 0 : _a.filter((d) => toNormalizedPath(d.fileName) !== file); - if (some(jsDefinitions)) { - for (const jsDefinition of jsDefinitions) { - if (jsDefinition.unverified) { - const refined = tryRefineDefinition(jsDefinition, project.getLanguageService().getProgram(), ls.getProgram()); - if (some(refined)) { - for (const def of refined) { - definitionSet.add(def); - } - continue; - } - } - definitionSet.add(jsDefinition); - } - } else { - const ambientCandidates = definitions.filter((d) => toNormalizedPath(d.fileName) !== file && d.isAmbient); - for (const candidate of some(ambientCandidates) ? ambientCandidates : getAmbientCandidatesByClimbingAccessChain()) { - const fileNameToSearch = findImplementationFileFromDtsFileName(candidate.fileName, file, noDtsProject); - if (!fileNameToSearch) continue; - const info = this.projectService.getOrCreateScriptInfoNotOpenedByClient( - fileNameToSearch, - noDtsProject.currentDirectory, - noDtsProject.directoryStructureHost, - /*deferredDeleteOk*/ - false - ); - if (!info) continue; - if (!noDtsProject.containsScriptInfo(info)) { - noDtsProject.addRoot(info); - noDtsProject.updateGraph(); - } - const noDtsProgram = ls.getProgram(); - const fileToSearch = Debug.checkDefined(noDtsProgram.getSourceFile(fileNameToSearch)); - for (const match of searchForDeclaration(candidate.name, fileToSearch, noDtsProgram)) { - definitionSet.add(match); - } - } - } - definitions = arrayFrom(definitionSet.values()); - } - definitions = definitions.filter((d) => !d.isAmbient && !d.failedAliasResolution); - return this.mapDefinitionInfo(definitions, project); - function findImplementationFileFromDtsFileName(fileName, resolveFromFile, auxiliaryProject) { - var _a2, _b, _c; - const nodeModulesPathParts = getNodeModulePathParts(fileName); - if (nodeModulesPathParts && fileName.lastIndexOf(nodeModulesPathPart) === nodeModulesPathParts.topLevelNodeModulesIndex) { - const packageDirectory = fileName.substring(0, nodeModulesPathParts.packageRootIndex); - const packageJsonCache = (_a2 = project.getModuleResolutionCache()) == null ? void 0 : _a2.getPackageJsonInfoCache(); - const compilerOptions = project.getCompilationSettings(); - const packageJson = getPackageScopeForPath(getNormalizedAbsolutePath(packageDirectory, project.getCurrentDirectory()), getTemporaryModuleResolutionState(packageJsonCache, project, compilerOptions)); - if (!packageJson) return void 0; - const entrypoints = getEntrypointsFromPackageJsonInfo( - packageJson, - { moduleResolution: 2 /* Node10 */ }, - project, - project.getModuleResolutionCache() - ); - const packageNamePathPart = fileName.substring( - nodeModulesPathParts.topLevelPackageNameIndex + 1, - nodeModulesPathParts.packageRootIndex - ); - const packageName = getPackageNameFromTypesPackageName(unmangleScopedPackageName(packageNamePathPart)); - const path = project.toPath(fileName); - if (entrypoints && some(entrypoints, (e) => project.toPath(e) === path)) { - return (_b = auxiliaryProject.resolutionCache.resolveSingleModuleNameWithoutWatching(packageName, resolveFromFile).resolvedModule) == null ? void 0 : _b.resolvedFileName; - } else { - const pathToFileInPackage = fileName.substring(nodeModulesPathParts.packageRootIndex + 1); - const specifier = `${packageName}/${removeFileExtension(pathToFileInPackage)}`; - return (_c = auxiliaryProject.resolutionCache.resolveSingleModuleNameWithoutWatching(specifier, resolveFromFile).resolvedModule) == null ? void 0 : _c.resolvedFileName; - } - } - return void 0; - } - function getAmbientCandidatesByClimbingAccessChain() { - const ls = project.getLanguageService(); - const program = ls.getProgram(); - const initialNode = getTouchingPropertyName(program.getSourceFile(file), position); - if ((isStringLiteralLike(initialNode) || isIdentifier(initialNode)) && isAccessExpression(initialNode.parent)) { - return forEachNameInAccessChainWalkingLeft(initialNode, (nameInChain) => { - var _a2; - if (nameInChain === initialNode) return void 0; - const candidates = (_a2 = ls.getDefinitionAtPosition( - file, - nameInChain.getStart(), - /*searchOtherFilesOnly*/ - true, - /*stopAtAlias*/ - false - )) == null ? void 0 : _a2.filter((d) => toNormalizedPath(d.fileName) !== file && d.isAmbient).map((d) => ({ - fileName: d.fileName, - name: getTextOfIdentifierOrLiteral(initialNode) - })); - if (some(candidates)) { - return candidates; - } - }) || emptyArray2; - } - return emptyArray2; - } - function tryRefineDefinition(definition, program, noDtsProgram) { - var _a2; - const fileToSearch = noDtsProgram.getSourceFile(definition.fileName); - if (!fileToSearch) { - return void 0; - } - const initialNode = getTouchingPropertyName(program.getSourceFile(file), position); - const symbol = program.getTypeChecker().getSymbolAtLocation(initialNode); - const importSpecifier = symbol && getDeclarationOfKind(symbol, 276 /* ImportSpecifier */); - if (!importSpecifier) return void 0; - const nameToSearch = ((_a2 = importSpecifier.propertyName) == null ? void 0 : _a2.text) || importSpecifier.name.text; - return searchForDeclaration(nameToSearch, fileToSearch, noDtsProgram); - } - function searchForDeclaration(declarationName, fileToSearch, noDtsProgram) { - const matches = ts_FindAllReferences_exports.Core.getTopMostDeclarationNamesInFile(declarationName, fileToSearch); - return mapDefined(matches, (match) => { - const symbol = noDtsProgram.getTypeChecker().getSymbolAtLocation(match); - const decl = getDeclarationFromName(match); - if (symbol && decl) { - return ts_GoToDefinition_exports.createDefinitionInfo( - decl, - noDtsProgram.getTypeChecker(), - symbol, - decl, - /*unverified*/ - true - ); - } - }); - } - } - getEmitOutput(args) { - const { file, project } = this.getFileAndProject(args); - if (!project.shouldEmitFile(project.getScriptInfo(file))) { - return { emitSkipped: true, outputFiles: [], diagnostics: [] }; - } - const result = project.getLanguageService().getEmitOutput(file); - return args.richResponse ? { - ...result, - diagnostics: args.includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(result.diagnostics) : result.diagnostics.map((d) => formatDiagnosticToProtocol( - d, - /*includeFileName*/ - true - )) - } : result; - } - mapJSDocTagInfo(tags, project, richResponse) { - return tags ? tags.map((tag) => { - var _a; - return { - ...tag, - text: richResponse ? this.mapDisplayParts(tag.text, project) : (_a = tag.text) == null ? void 0 : _a.map((part) => part.text).join("") - }; - }) : []; - } - mapDisplayParts(parts, project) { - if (!parts) { - return []; - } - return parts.map( - (part) => part.kind !== "linkName" ? part : { - ...part, - target: this.toFileSpan(part.target.fileName, part.target.textSpan, project) - } - ); - } - mapSignatureHelpItems(items, project, richResponse) { - return items.map((item) => ({ - ...item, - documentation: this.mapDisplayParts(item.documentation, project), - parameters: item.parameters.map((p) => ({ ...p, documentation: this.mapDisplayParts(p.documentation, project) })), - tags: this.mapJSDocTagInfo(item.tags, project, richResponse) - })); - } - mapDefinitionInfo(definitions, project) { - return definitions.map((def) => ({ ...this.toFileSpanWithContext(def.fileName, def.textSpan, def.contextSpan, project), ...def.unverified && { unverified: def.unverified } })); - } - /* - * When we map a .d.ts location to .ts, Visual Studio gets confused because there's no associated Roslyn Document in - * the same project which corresponds to the file. VS Code has no problem with this, and luckily we have two protocols. - * This retains the existing behavior for the "simplified" (VS Code) protocol but stores the .d.ts location in a - * set of additional fields, and does the reverse for VS (store the .d.ts location where - * it used to be and stores the .ts location in the additional fields). - */ - static mapToOriginalLocation(def) { - if (def.originalFileName) { - Debug.assert(def.originalTextSpan !== void 0, "originalTextSpan should be present if originalFileName is"); - return { - ...def, - fileName: def.originalFileName, - textSpan: def.originalTextSpan, - targetFileName: def.fileName, - targetTextSpan: def.textSpan, - contextSpan: def.originalContextSpan, - targetContextSpan: def.contextSpan - }; - } - return def; - } - toFileSpan(fileName, textSpan, project) { - const ls = project.getLanguageService(); - const start = ls.toLineColumnOffset(fileName, textSpan.start); - const end = ls.toLineColumnOffset(fileName, textSpanEnd(textSpan)); - return { - file: fileName, - start: { line: start.line + 1, offset: start.character + 1 }, - end: { line: end.line + 1, offset: end.character + 1 } - }; - } - toFileSpanWithContext(fileName, textSpan, contextSpan, project) { - const fileSpan = this.toFileSpan(fileName, textSpan, project); - const context = contextSpan && this.toFileSpan(fileName, contextSpan, project); - return context ? { ...fileSpan, contextStart: context.start, contextEnd: context.end } : fileSpan; - } - getTypeDefinition(args) { - const { file, project } = this.getFileAndProject(args); - const position = this.getPositionInFile(args, file); - const definitions = this.mapDefinitionInfoLocations(project.getLanguageService().getTypeDefinitionAtPosition(file, position) || emptyArray2, project); - return this.mapDefinitionInfo(definitions, project); - } - mapImplementationLocations(implementations, project) { - return implementations.map((info) => { - const newDocumentSpan = getMappedDocumentSpanForProject(info, project); - return !newDocumentSpan ? info : { - ...newDocumentSpan, - kind: info.kind, - displayParts: info.displayParts - }; - }); - } - getImplementation(args, simplifiedResult) { - const { file, project } = this.getFileAndProject(args); - const position = this.getPositionInFile(args, file); - const implementations = this.mapImplementationLocations(project.getLanguageService().getImplementationAtPosition(file, position) || emptyArray2, project); - return simplifiedResult ? implementations.map(({ fileName, textSpan, contextSpan }) => this.toFileSpanWithContext(fileName, textSpan, contextSpan, project)) : implementations.map(_Session.mapToOriginalLocation); - } - getSyntacticDiagnosticsSync(args) { - const { configFile } = this.getConfigFileAndProject(args); - if (configFile) { - return emptyArray2; - } - return this.getDiagnosticsWorker( - args, - /*isSemantic*/ - false, - (project, file) => project.getLanguageService().getSyntacticDiagnostics(file), - !!args.includeLinePosition - ); - } - getSemanticDiagnosticsSync(args) { - const { configFile, project } = this.getConfigFileAndProject(args); - if (configFile) { - return this.getConfigFileDiagnostics(configFile, project, !!args.includeLinePosition); - } - return this.getDiagnosticsWorker( - args, - /*isSemantic*/ - true, - (project2, file) => project2.getLanguageService().getSemanticDiagnostics(file).filter((d) => !!d.file), - !!args.includeLinePosition - ); - } - getSuggestionDiagnosticsSync(args) { - const { configFile } = this.getConfigFileAndProject(args); - if (configFile) { - return emptyArray2; - } - return this.getDiagnosticsWorker( - args, - /*isSemantic*/ - true, - (project, file) => project.getLanguageService().getSuggestionDiagnostics(file), - !!args.includeLinePosition - ); - } - getJsxClosingTag(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const position = this.getPositionInFile(args, file); - const tag = languageService.getJsxClosingTagAtPosition(file, position); - return tag === void 0 ? void 0 : { newText: tag.newText, caretOffset: 0 }; - } - getLinkedEditingRange(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const position = this.getPositionInFile(args, file); - const linkedEditInfo = languageService.getLinkedEditingRangeAtPosition(file, position); - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - if (scriptInfo === void 0 || linkedEditInfo === void 0) return void 0; - return convertLinkedEditInfoToRanges(linkedEditInfo, scriptInfo); - } - getDocumentHighlights(args, simplifiedResult) { - const { file, project } = this.getFileAndProject(args); - const position = this.getPositionInFile(args, file); - const documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); - if (!documentHighlights) return emptyArray2; - if (!simplifiedResult) return documentHighlights; - return documentHighlights.map(({ fileName, highlightSpans }) => { - const scriptInfo = project.getScriptInfo(fileName); - return { - file: fileName, - highlightSpans: highlightSpans.map(({ textSpan, kind, contextSpan }) => ({ - ...toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo), - kind - })) - }; - }); - } - provideInlayHints(args) { - const { file, project } = this.getFileAndProject(args); - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - const hints = project.getLanguageService().provideInlayHints(file, args, this.getPreferences(file)); - return hints.map((hint) => { - const { position, displayParts } = hint; - return { - ...hint, - position: scriptInfo.positionToLineOffset(position), - displayParts: displayParts == null ? void 0 : displayParts.map(({ text, span, file: file2 }) => { - if (span) { - Debug.assertIsDefined(file2, "Target file should be defined together with its span."); - const scriptInfo2 = this.projectService.getScriptInfo(file2); - return { - text, - span: { - start: scriptInfo2.positionToLineOffset(span.start), - end: scriptInfo2.positionToLineOffset(span.start + span.length), - file: file2 - } - }; - } else { - return { text }; - } - }) - }; - }); - } - mapCode(args) { - var _a; - const formatOptions = this.getHostFormatOptions(); - const preferences = this.getHostPreferences(); - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - const focusLocations = (_a = args.mapping.focusLocations) == null ? void 0 : _a.map((spans) => { - return spans.map((loc) => { - const start = scriptInfo.lineOffsetToPosition(loc.start.line, loc.start.offset); - const end = scriptInfo.lineOffsetToPosition(loc.end.line, loc.end.offset); - return { - start, - length: end - start - }; - }); - }); - const changes = languageService.mapCode(file, args.mapping.contents, focusLocations, formatOptions, preferences); - return this.mapTextChangesToCodeEdits(changes); - } - setCompilerOptionsForInferredProjects(args) { - this.projectService.setCompilerOptionsForInferredProjects(args.options, args.projectRootPath); - } - getProjectInfo(args) { - return this.getProjectInfoWorker( - args.file, - args.projectFileName, - args.needFileNameList, - /*excludeConfigFiles*/ - false - ); - } - getProjectInfoWorker(uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles) { - const { project } = this.getFileAndProjectWorker(uncheckedFileName, projectFileName); - updateProjectIfDirty(project); - const projectInfo = { - configFileName: project.getProjectName(), - languageServiceDisabled: !project.languageServiceEnabled, - fileNames: needFileNameList ? project.getFileNames( - /*excludeFilesFromExternalLibraries*/ - false, - excludeConfigFiles - ) : void 0 - }; - return projectInfo; - } - getRenameInfo(args) { - const { file, project } = this.getFileAndProject(args); - const position = this.getPositionInFile(args, file); - const preferences = this.getPreferences(file); - return project.getLanguageService().getRenameInfo(file, position, preferences); - } - getProjects(args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) { - let projects; - let symLinkedProjects; - if (args.projectFileName) { - const project = this.getProject(args.projectFileName); - if (project) { - projects = [project]; - } - } else { - const scriptInfo = getScriptInfoEnsuringProjectsUptoDate ? this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file) : this.projectService.getScriptInfo(args.file); - if (!scriptInfo) { - if (ignoreNoProjectError) return emptyArray2; - this.projectService.logErrorForScriptInfoNotFound(args.file); - return Errors.ThrowNoProject(); - } else if (!getScriptInfoEnsuringProjectsUptoDate) { - this.projectService.ensureDefaultProjectForFile(scriptInfo); - } - projects = scriptInfo.containingProjects; - symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo); - } - projects = filter(projects, (p) => p.languageServiceEnabled && !p.isOrphan()); - if (!ignoreNoProjectError && (!projects || !projects.length) && !symLinkedProjects) { - this.projectService.logErrorForScriptInfoNotFound(args.file ?? args.projectFileName); - return Errors.ThrowNoProject(); - } - return symLinkedProjects ? { projects, symLinkedProjects } : projects; - } - getDefaultProject(args) { - if (args.projectFileName) { - const project = this.getProject(args.projectFileName); - if (project) { - return project; - } - if (!args.file) { - return Errors.ThrowNoProject(); - } - } - const info = this.projectService.getScriptInfo(args.file); - return info.getDefaultProject(); - } - getRenameLocations(args, simplifiedResult) { - const file = toNormalizedPath(args.file); - const position = this.getPositionInFile(args, file); - const projects = this.getProjects(args); - const defaultProject = this.getDefaultProject(args); - const preferences = this.getPreferences(file); - const renameInfo = this.mapRenameInfo( - defaultProject.getLanguageService().getRenameInfo(file, position, preferences), - Debug.checkDefined(this.projectService.getScriptInfo(file)) - ); - if (!renameInfo.canRename) return simplifiedResult ? { info: renameInfo, locs: [] } : []; - const locations = getRenameLocationsWorker( - projects, - defaultProject, - { fileName: args.file, pos: position }, - !!args.findInStrings, - !!args.findInComments, - preferences, - this.host.useCaseSensitiveFileNames - ); - if (!simplifiedResult) return locations; - return { info: renameInfo, locs: this.toSpanGroups(locations) }; - } - mapRenameInfo(info, scriptInfo) { - if (info.canRename) { - const { canRename, fileToRename, displayName, fullDisplayName, kind, kindModifiers, triggerSpan } = info; - return identity( - { canRename, fileToRename, displayName, fullDisplayName, kind, kindModifiers, triggerSpan: toProtocolTextSpan(triggerSpan, scriptInfo) } - ); - } else { - return info; - } - } - toSpanGroups(locations) { - const map2 = /* @__PURE__ */ new Map(); - for (const { fileName, textSpan, contextSpan, originalContextSpan: _2, originalTextSpan: _, originalFileName: _1, ...prefixSuffixText } of locations) { - let group2 = map2.get(fileName); - if (!group2) map2.set(fileName, group2 = { file: fileName, locs: [] }); - const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(fileName)); - group2.locs.push({ ...toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo), ...prefixSuffixText }); - } - return arrayFrom(map2.values()); - } - getReferences(args, simplifiedResult) { - const file = toNormalizedPath(args.file); - const projects = this.getProjects(args); - const position = this.getPositionInFile(args, file); - const references = getReferencesWorker( - projects, - this.getDefaultProject(args), - { fileName: args.file, pos: position }, - this.host.useCaseSensitiveFileNames, - this.logger - ); - if (!simplifiedResult) return references; - const preferences = this.getPreferences(file); - const defaultProject = this.getDefaultProject(args); - const scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); - const nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); - const symbolDisplayString = nameInfo ? displayPartsToString(nameInfo.displayParts) : ""; - const nameSpan = nameInfo && nameInfo.textSpan; - const symbolStartOffset = nameSpan ? scriptInfo.positionToLineOffset(nameSpan.start).offset : 0; - const symbolName2 = nameSpan ? scriptInfo.getSnapshot().getText(nameSpan.start, textSpanEnd(nameSpan)) : ""; - const refs = flatMap(references, (referencedSymbol) => { - return referencedSymbol.references.map((entry) => referenceEntryToReferencesResponseItem(this.projectService, entry, preferences)); - }); - return { refs, symbolName: symbolName2, symbolStartOffset, symbolDisplayString }; - } - 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( - projects, - /*path*/ - void 0, - (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); - } - } - } - } - ); - if (!simplifiedResult) return references; - const refs = references.map((entry) => referenceEntryToReferencesResponseItem(this.projectService, entry, preferences)); - return { - refs, - symbolName: `"${args.file}"` - }; - } - /** - * @param fileName is the name of the file to be opened - * @param fileContent is a version of the file content that is known to be more up to date than the one on disk - */ - openClientFile(fileName, fileContent, scriptKind, projectRootPath) { - this.projectService.openClientFileWithNormalizedPath( - fileName, - fileContent, - scriptKind, - /*hasMixedContent*/ - false, - projectRootPath - ); - } - getPosition(args, scriptInfo) { - return args.position !== void 0 ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); - } - getPositionInFile(args, file) { - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - return this.getPosition(args, scriptInfo); - } - getFileAndProject(args) { - return this.getFileAndProjectWorker(args.file, args.projectFileName); - } - getFileAndLanguageServiceForSyntacticOperation(args) { - const { file, project } = this.getFileAndProject(args); - return { - file, - languageService: project.getLanguageService( - /*ensureSynchronized*/ - false - ) - }; - } - getFileAndProjectWorker(uncheckedFileName, projectFileName) { - const file = toNormalizedPath(uncheckedFileName); - const project = this.getProject(projectFileName) || this.projectService.ensureDefaultProjectForFile(file); - return { file, project }; - } - getOutliningSpans(args, simplifiedResult) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const spans = languageService.getOutliningSpans(file); - if (simplifiedResult) { - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - return spans.map((s) => ({ - textSpan: toProtocolTextSpan(s.textSpan, scriptInfo), - hintSpan: toProtocolTextSpan(s.hintSpan, scriptInfo), - bannerText: s.bannerText, - autoCollapse: s.autoCollapse, - kind: s.kind - })); - } else { - return spans; - } - } - getTodoComments(args) { - const { file, project } = this.getFileAndProject(args); - return project.getLanguageService().getTodoComments(file, args.descriptors); - } - getDocCommentTemplate(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const position = this.getPositionInFile(args, file); - return languageService.getDocCommentTemplateAtPosition(file, position, this.getPreferences(file), this.getFormatOptions(file)); - } - getSpanOfEnclosingComment(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const onlyMultiLine = args.onlyMultiLine; - const position = this.getPositionInFile(args, file); - return languageService.getSpanOfEnclosingComment(file, position, onlyMultiLine); - } - getIndentation(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const position = this.getPositionInFile(args, file); - const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file); - const indentation = languageService.getIndentationAtPosition(file, position, options); - return { position, indentation }; - } - getBreakpointStatement(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const position = this.getPositionInFile(args, file); - return languageService.getBreakpointStatementAtPosition(file, position); - } - getNameOrDottedNameSpan(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const position = this.getPositionInFile(args, file); - return languageService.getNameOrDottedNameSpan(file, position, position); - } - isValidBraceCompletion(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const position = this.getPositionInFile(args, file); - return languageService.isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); - } - getQuickInfoWorker(args, simplifiedResult) { - const { file, project } = this.getFileAndProject(args); - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - const quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo)); - if (!quickInfo) { - return void 0; - } - const useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc; - if (simplifiedResult) { - const displayString = displayPartsToString(quickInfo.displayParts); - return { - kind: quickInfo.kind, - kindModifiers: quickInfo.kindModifiers, - start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start), - end: scriptInfo.positionToLineOffset(textSpanEnd(quickInfo.textSpan)), - displayString, - documentation: useDisplayParts ? this.mapDisplayParts(quickInfo.documentation, project) : displayPartsToString(quickInfo.documentation), - tags: this.mapJSDocTagInfo(quickInfo.tags, project, useDisplayParts) - }; - } else { - return useDisplayParts ? quickInfo : { - ...quickInfo, - tags: this.mapJSDocTagInfo( - quickInfo.tags, - project, - /*richResponse*/ - false - ) - }; - } - } - getFormattingEditsForRange(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - const startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); - const endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); - const edits = languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.getFormatOptions(file)); - if (!edits) { - return void 0; - } - return edits.map((edit) => this.convertTextChangeToCodeEdit(edit, scriptInfo)); - } - getFormattingEditsForRangeFull(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file); - return languageService.getFormattingEditsForRange(file, args.position, args.endPosition, options); - } - getFormattingEditsForDocumentFull(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file); - return languageService.getFormattingEditsForDocument(file, options); - } - getFormattingEditsAfterKeystrokeFull(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const options = args.options ? convertFormatOptions(args.options) : this.getFormatOptions(file); - return languageService.getFormattingEditsAfterKeystroke(file, args.position, args.key, options); - } - getFormattingEditsAfterKeystroke(args) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - const position = scriptInfo.lineOffsetToPosition(args.line, args.offset); - const formatOptions = this.getFormatOptions(file); - const edits = languageService.getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); - if (args.key === "\n" && (!edits || edits.length === 0 || allEditsBeforePos(edits, position))) { - const { lineText, absolutePosition } = scriptInfo.textStorage.getAbsolutePositionAndLineText(args.line); - if (lineText && lineText.search("\\S") < 0) { - const preferredIndent = languageService.getIndentationAtPosition(file, position, formatOptions); - let hasIndent = 0; - let i, len; - for (i = 0, len = lineText.length; i < len; i++) { - if (lineText.charAt(i) === " ") { - hasIndent++; - } else if (lineText.charAt(i) === " ") { - hasIndent += formatOptions.tabSize; - } else { - break; - } - } - if (preferredIndent !== hasIndent) { - const firstNoWhiteSpacePosition = absolutePosition + i; - edits.push({ - span: createTextSpanFromBounds(absolutePosition, firstNoWhiteSpacePosition), - newText: ts_formatting_exports.getIndentationString(preferredIndent, formatOptions) - }); - } - } - } - if (!edits) { - return void 0; - } - return edits.map((edit) => { - return { - start: scriptInfo.positionToLineOffset(edit.span.start), - end: scriptInfo.positionToLineOffset(textSpanEnd(edit.span)), - newText: edit.newText ? edit.newText : "" - }; - }); - } - getCompletions(args, kind) { - const { file, project } = this.getFileAndProject(args); - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - const position = this.getPosition(args, scriptInfo); - const completions = project.getLanguageService().getCompletionsAtPosition( - file, - position, - { - ...convertUserPreferences(this.getPreferences(file)), - triggerCharacter: args.triggerCharacter, - triggerKind: args.triggerKind, - includeExternalModuleExports: args.includeExternalModuleExports, - includeInsertTextCompletions: args.includeInsertTextCompletions - }, - project.projectService.getFormatCodeOptions(file) - ); - if (completions === void 0) return void 0; - if (kind === "completions-full" /* CompletionsFull */) return completions; - const prefix = args.prefix || ""; - const entries = mapDefined(completions.entries, (entry) => { - if (completions.isMemberCompletion || startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { - const convertedSpan = entry.replacementSpan ? toProtocolTextSpan(entry.replacementSpan, scriptInfo) : void 0; - return { - ...entry, - replacementSpan: convertedSpan, - hasAction: entry.hasAction || void 0, - symbol: void 0 - }; - } - }); - if (kind === "completions" /* Completions */) { - if (completions.metadata) entries.metadata = completions.metadata; - return entries; - } - const res = { - ...completions, - optionalReplacementSpan: completions.optionalReplacementSpan && toProtocolTextSpan(completions.optionalReplacementSpan, scriptInfo), - entries - }; - return res; - } - getCompletionEntryDetails(args, fullResult) { - const { file, project } = this.getFileAndProject(args); - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - const position = this.getPosition(args, scriptInfo); - const formattingOptions = project.projectService.getFormatCodeOptions(file); - const useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc; - const result = mapDefined(args.entryNames, (entryName) => { - const { name, source, data } = typeof entryName === "string" ? { name: entryName, source: void 0, data: void 0 } : entryName; - return project.getLanguageService().getCompletionEntryDetails(file, position, name, formattingOptions, source, this.getPreferences(file), data ? cast(data, isCompletionEntryData) : void 0); - }); - return fullResult ? useDisplayParts ? result : result.map((details) => ({ ...details, tags: this.mapJSDocTagInfo( - details.tags, - project, - /*richResponse*/ - false - ) })) : result.map((details) => ({ - ...details, - codeActions: map(details.codeActions, (action) => this.mapCodeAction(action)), - documentation: this.mapDisplayParts(details.documentation, project), - tags: this.mapJSDocTagInfo(details.tags, project, useDisplayParts) - })); - } - getCompileOnSaveAffectedFileList(args) { - const projects = this.getProjects( - args, - /*getScriptInfoEnsuringProjectsUptoDate*/ - true, - /*ignoreNoProjectError*/ - true - ); - const info = this.projectService.getScriptInfo(args.file); - if (!info) { - return emptyArray2; - } - return combineProjectOutput( - info, - (path) => this.projectService.getScriptInfoForPath(path), - projects, - (project, info2) => { - if (!project.compileOnSaveEnabled || !project.languageServiceEnabled || project.isOrphan()) { - return void 0; - } - const compilationSettings = project.getCompilationSettings(); - if (!!compilationSettings.noEmit || isDeclarationFileName(info2.fileName) && !dtsChangeCanAffectEmit(compilationSettings)) { - return void 0; - } - return { - projectFileName: project.getProjectName(), - fileNames: project.getCompileOnSaveAffectedFileList(info2), - projectUsesOutFile: !!compilationSettings.outFile - }; - } - ); - } - emitFile(args) { - const { file, project } = this.getFileAndProject(args); - if (!project) { - Errors.ThrowNoProject(); - } - if (!project.languageServiceEnabled) { - return args.richResponse ? { emitSkipped: true, diagnostics: [] } : false; - } - const scriptInfo = project.getScriptInfo(file); - const { emitSkipped, diagnostics } = project.emitFile(scriptInfo, (path, data, writeByteOrderMark) => this.host.writeFile(path, data, writeByteOrderMark)); - return args.richResponse ? { - emitSkipped, - diagnostics: args.includeLinePosition ? this.convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics) : diagnostics.map((d) => formatDiagnosticToProtocol( - d, - /*includeFileName*/ - true - )) - } : !emitSkipped; - } - getSignatureHelpItems(args, simplifiedResult) { - const { file, project } = this.getFileAndProject(args); - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - const position = this.getPosition(args, scriptInfo); - const helpItems = project.getLanguageService().getSignatureHelpItems(file, position, args); - const useDisplayParts = !!this.getPreferences(file).displayPartsForJSDoc; - if (helpItems && simplifiedResult) { - const span = helpItems.applicableSpan; - return { - ...helpItems, - applicableSpan: { - start: scriptInfo.positionToLineOffset(span.start), - end: scriptInfo.positionToLineOffset(span.start + span.length) - }, - items: this.mapSignatureHelpItems(helpItems.items, project, useDisplayParts) - }; - } else if (useDisplayParts || !helpItems) { - return helpItems; - } else { - return { - ...helpItems, - items: helpItems.items.map((item) => ({ ...item, tags: this.mapJSDocTagInfo( - item.tags, - project, - /*richResponse*/ - false - ) })) - }; - } - } - toPendingErrorCheck(uncheckedFileName) { - const fileName = toNormalizedPath(uncheckedFileName); - const project = this.projectService.tryGetDefaultProjectForFile(fileName); - return project && { fileName, project }; - } - getDiagnostics(next, delay, fileArgs) { - if (this.suppressDiagnosticEvents) { - return; - } - if (fileArgs.length > 0) { - this.updateErrorCheck(next, fileArgs, delay); - } - } - change(args) { - const scriptInfo = this.projectService.getScriptInfo(args.file); - Debug.assert(!!scriptInfo); - scriptInfo.textStorage.switchToScriptVersionCache(); - const start = scriptInfo.lineOffsetToPosition(args.line, args.offset); - const end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); - if (start >= 0) { - this.changeSeq++; - this.projectService.applyChangesToFile( - scriptInfo, - singleIterator({ - span: { start, length: end - start }, - newText: args.insertString - // TODO: GH#18217 - }) - ); - } - } - reload(args) { - const file = toNormalizedPath(args.file); - const tempFileName = args.tmpfile === void 0 ? void 0 : toNormalizedPath(args.tmpfile); - const info = this.projectService.getScriptInfoForNormalizedPath(file); - if (info) { - this.changeSeq++; - info.reloadFromFile(tempFileName); - } - } - saveToTmp(fileName, tempFileName) { - const scriptInfo = this.projectService.getScriptInfo(fileName); - if (scriptInfo) { - scriptInfo.saveTo(tempFileName); - } - } - closeClientFile(fileName) { - if (!fileName) { - return; - } - const file = normalizePath(fileName); - this.projectService.closeClientFile(file); - } - mapLocationNavigationBarItems(items, scriptInfo) { - return map(items, (item) => ({ - text: item.text, - kind: item.kind, - kindModifiers: item.kindModifiers, - spans: item.spans.map((span) => toProtocolTextSpan(span, scriptInfo)), - childItems: this.mapLocationNavigationBarItems(item.childItems, scriptInfo), - indent: item.indent - })); - } - getNavigationBarItems(args, simplifiedResult) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const items = languageService.getNavigationBarItems(file); - return !items ? void 0 : simplifiedResult ? this.mapLocationNavigationBarItems(items, this.projectService.getScriptInfoForNormalizedPath(file)) : items; - } - toLocationNavigationTree(tree, scriptInfo) { - return { - text: tree.text, - kind: tree.kind, - kindModifiers: tree.kindModifiers, - spans: tree.spans.map((span) => toProtocolTextSpan(span, scriptInfo)), - nameSpan: tree.nameSpan && toProtocolTextSpan(tree.nameSpan, scriptInfo), - childItems: map(tree.childItems, (item) => this.toLocationNavigationTree(item, scriptInfo)) - }; - } - getNavigationTree(args, simplifiedResult) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const tree = languageService.getNavigationTree(file); - return !tree ? void 0 : simplifiedResult ? this.toLocationNavigationTree(tree, this.projectService.getScriptInfoForNormalizedPath(file)) : tree; - } - getNavigateToItems(args, simplifiedResult) { - const full = this.getFullNavigateToItems(args); - return !simplifiedResult ? flatMap(full, ({ navigateToItems }) => navigateToItems) : flatMap( - full, - ({ project, navigateToItems }) => navigateToItems.map((navItem) => { - const scriptInfo = project.getScriptInfo(navItem.fileName); - const bakedItem = { - name: navItem.name, - kind: navItem.kind, - kindModifiers: navItem.kindModifiers, - isCaseSensitive: navItem.isCaseSensitive, - matchKind: navItem.matchKind, - file: navItem.fileName, - start: scriptInfo.positionToLineOffset(navItem.textSpan.start), - end: scriptInfo.positionToLineOffset(textSpanEnd(navItem.textSpan)) - }; - if (navItem.kindModifiers && navItem.kindModifiers !== "") { - bakedItem.kindModifiers = navItem.kindModifiers; - } - if (navItem.containerName && navItem.containerName.length > 0) { - bakedItem.containerName = navItem.containerName; - } - if (navItem.containerKind && navItem.containerKind.length > 0) { - bakedItem.containerKind = navItem.containerKind; - } - return bakedItem; - }) - ); - } - getFullNavigateToItems(args) { - const { currentFileOnly, searchValue, maxResultCount, projectFileName } = args; - if (currentFileOnly) { - Debug.assertIsDefined(args.file); - const { file, project } = this.getFileAndProject(args); - return [{ project, navigateToItems: project.getLanguageService().getNavigateToItems(searchValue, maxResultCount, file) }]; - } - const preferences = this.getHostPreferences(); - const outputs = []; - const seenItems = /* @__PURE__ */ new Map(); - if (!args.file && !projectFileName) { - this.projectService.loadAncestorProjectTree(); - this.projectService.forEachEnabledProject((project) => addItemsForProject(project)); - } else { - const projects = this.getProjects(args); - forEachProjectInProjects( - projects, - /*path*/ - void 0, - (project) => addItemsForProject(project) - ); - } - return outputs; - function addItemsForProject(project) { - const projectItems = project.getLanguageService().getNavigateToItems( - searchValue, - maxResultCount, - /*fileName*/ - void 0, - /*excludeDts*/ - project.isNonTsProject(), - /*excludeLibFiles*/ - preferences.excludeLibrarySymbolsInNavTo - ); - const unseenItems = filter(projectItems, (item) => tryAddSeenItem(item) && !getMappedLocationForProject(documentSpanLocation(item), project)); - if (unseenItems.length) { - outputs.push({ project, navigateToItems: unseenItems }); - } - } - function tryAddSeenItem(item) { - const name = item.name; - if (!seenItems.has(name)) { - seenItems.set(name, [item]); - return true; - } - const seen = seenItems.get(name); - for (const seenItem of seen) { - if (navigateToItemIsEqualTo(seenItem, item)) { - return false; - } - } - seen.push(item); - return true; - } - function navigateToItemIsEqualTo(a, b) { - if (a === b) { - return true; - } - if (!a || !b) { - return false; - } - return a.containerKind === b.containerKind && a.containerName === b.containerName && a.fileName === b.fileName && a.isCaseSensitive === b.isCaseSensitive && a.kind === b.kind && a.kindModifiers === b.kindModifiers && a.matchKind === b.matchKind && a.name === b.name && a.textSpan.start === b.textSpan.start && a.textSpan.length === b.textSpan.length; - } - } - getSupportedCodeFixes(args) { - if (!args) return getSupportedCodeFixes(); - if (args.file) { - const { file, project: project2 } = this.getFileAndProject(args); - return project2.getLanguageService().getSupportedCodeFixes(file); - } - const project = this.getProject(args.projectFileName); - if (!project) Errors.ThrowNoProject(); - return project.getLanguageService().getSupportedCodeFixes(); - } - isLocation(locationOrSpan) { - return locationOrSpan.line !== void 0; - } - extractPositionOrRange(args, scriptInfo) { - let position; - let textRange; - if (this.isLocation(args)) { - position = getPosition(args); - } else { - textRange = this.getRange(args, scriptInfo); - } - return Debug.checkDefined(position === void 0 ? textRange : position); - function getPosition(loc) { - return loc.position !== void 0 ? loc.position : scriptInfo.lineOffsetToPosition(loc.line, loc.offset); - } - } - getRange(args, scriptInfo) { - const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo); - return { pos: startPosition, end: endPosition }; - } - getApplicableRefactors(args) { - const { file, project } = this.getFileAndProject(args); - const scriptInfo = project.getScriptInfoForNormalizedPath(file); - const result = project.getLanguageService().getApplicableRefactors(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file), args.triggerReason, args.kind, args.includeInteractiveActions); - return result.map((result2) => ({ ...result2, actions: result2.actions.map((action) => ({ ...action, range: action.range ? { start: convertToLocation({ line: action.range.start.line, character: action.range.start.offset }), end: convertToLocation({ line: action.range.end.line, character: action.range.end.offset }) } : void 0 })) })); - } - getEditsForRefactor(args, simplifiedResult) { - const { file, project } = this.getFileAndProject(args); - const scriptInfo = project.getScriptInfoForNormalizedPath(file); - const result = project.getLanguageService().getEditsForRefactor( - file, - this.getFormatOptions(file), - this.extractPositionOrRange(args, scriptInfo), - args.refactor, - args.action, - this.getPreferences(file), - args.interactiveRefactorArguments - ); - if (result === void 0) { - return { - edits: [] - }; - } - if (simplifiedResult) { - const { renameFilename, renameLocation, edits } = result; - let mappedRenameLocation; - if (renameFilename !== void 0 && renameLocation !== void 0) { - const renameScriptInfo = project.getScriptInfoForNormalizedPath(toNormalizedPath(renameFilename)); - mappedRenameLocation = getLocationInNewDocument(getSnapshotText(renameScriptInfo.getSnapshot()), renameFilename, renameLocation, edits); - } - return { - renameLocation: mappedRenameLocation, - renameFilename, - edits: this.mapTextChangesToCodeEdits(edits), - notApplicableReason: result.notApplicableReason - }; - } - return result; - } - getMoveToRefactoringFileSuggestions(args) { - const { file, project } = this.getFileAndProject(args); - const scriptInfo = project.getScriptInfoForNormalizedPath(file); - return project.getLanguageService().getMoveToRefactoringFileSuggestions(file, this.extractPositionOrRange(args, scriptInfo), this.getPreferences(file)); - } - getPasteEdits(args) { - const { file, project } = this.getFileAndProject(args); - 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( - { - targetFile: file, - pastedText: args.pastedText, - pasteLocations: args.pasteLocations.map((paste) => this.getRange({ file, startLine: paste.start.line, startOffset: paste.start.offset, endLine: paste.end.line, endOffset: paste.end.offset }, project.getScriptInfoForNormalizedPath(file))), - copiedFrom, - preferences: this.getPreferences(file) - }, - this.getFormatOptions(file) - ); - return result && this.mapPasteEditsAction(result); - } - organizeImports(args, simplifiedResult) { - Debug.assert(args.scope.type === "file"); - const { file, project } = this.getFileAndProject(args.scope.args); - const changes = project.getLanguageService().organizeImports( - { - fileName: file, - mode: args.mode ?? (args.skipDestructiveCodeActions ? "SortAndCombine" /* SortAndCombine */ : void 0), - type: "file" - }, - this.getFormatOptions(file), - this.getPreferences(file) - ); - if (simplifiedResult) { - return this.mapTextChangesToCodeEdits(changes); - } else { - return changes; - } - } - getEditsForFileRename(args, simplifiedResult) { - const oldPath = toNormalizedPath(args.oldFilePath); - const newPath = toNormalizedPath(args.newFilePath); - const formatOptions = this.getHostFormatOptions(); - const preferences = this.getHostPreferences(); - const seenFiles = /* @__PURE__ */ new Set(); - const textChanges2 = []; - this.projectService.loadAncestorProjectTree(); - this.projectService.forEachEnabledProject((project) => { - const projectTextChanges = project.getLanguageService().getEditsForFileRename(oldPath, newPath, formatOptions, preferences); - const projectFiles = []; - for (const textChange of projectTextChanges) { - if (!seenFiles.has(textChange.fileName)) { - textChanges2.push(textChange); - projectFiles.push(textChange.fileName); - } - } - for (const file of projectFiles) { - seenFiles.add(file); - } - }); - return simplifiedResult ? textChanges2.map((c) => this.mapTextChangeToCodeEdit(c)) : textChanges2; - } - getCodeFixes(args, simplifiedResult) { - const { file, project } = this.getFileAndProject(args); - const scriptInfo = project.getScriptInfoForNormalizedPath(file); - const { startPosition, endPosition } = this.getStartAndEndPosition(args, scriptInfo); - let codeActions; - try { - codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes, this.getFormatOptions(file), this.getPreferences(file)); - } catch (e) { - const ls = project.getLanguageService(); - const existingDiagCodes = [ - ...ls.getSyntacticDiagnostics(file), - ...ls.getSemanticDiagnostics(file), - ...ls.getSuggestionDiagnostics(file) - ].map( - (d) => decodedTextSpanIntersectsWith(startPosition, endPosition - startPosition, d.start, d.length) && d.code - ); - const badCode = args.errorCodes.find((c) => !existingDiagCodes.includes(c)); - if (badCode !== void 0) { - e.message = `BADCLIENT: Bad error code, ${badCode} not found in range ${startPosition}..${endPosition} (found: ${existingDiagCodes.join(", ")}); could have caused this error: -${e.message}`; - } - throw e; - } - return simplifiedResult ? codeActions.map((codeAction) => this.mapCodeFixAction(codeAction)) : codeActions; - } - getCombinedCodeFix({ scope, fixId: fixId55 }, 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)); - if (simplifiedResult) { - return { changes: this.mapTextChangesToCodeEdits(res.changes), commands: res.commands }; - } else { - return res; - } - } - applyCodeActionCommand(args) { - const commands = args.command; - for (const command of toArray(commands)) { - const { file, project } = this.getFileAndProject(command); - project.getLanguageService().applyCodeActionCommand(command, this.getFormatOptions(file)).then( - (_result) => { - }, - (_error) => { - } - ); - } - return {}; - } - getStartAndEndPosition(args, scriptInfo) { - let startPosition, endPosition; - if (args.startPosition !== void 0) { - startPosition = args.startPosition; - } else { - startPosition = scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); - args.startPosition = startPosition; - } - if (args.endPosition !== void 0) { - endPosition = args.endPosition; - } else { - endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); - args.endPosition = endPosition; - } - return { startPosition, endPosition }; - } - 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 }; - } - mapPasteEditsAction({ edits, fixId: fixId55 }) { - return { edits: this.mapTextChangesToCodeEdits(edits), fixId: fixId55 }; - } - mapTextChangesToCodeEdits(textChanges2) { - return textChanges2.map((change) => this.mapTextChangeToCodeEdit(change)); - } - mapTextChangeToCodeEdit(textChanges2) { - const scriptInfo = this.projectService.getScriptInfoOrConfig(textChanges2.fileName); - if (!!textChanges2.isNewFile === !!scriptInfo) { - if (!scriptInfo) { - this.projectService.logErrorForScriptInfoNotFound(textChanges2.fileName); - } - Debug.fail("Expected isNewFile for (only) new files. " + JSON.stringify({ isNewFile: !!textChanges2.isNewFile, hasScriptInfo: !!scriptInfo })); - } - return scriptInfo ? { fileName: textChanges2.fileName, textChanges: textChanges2.textChanges.map((textChange) => convertTextChangeToCodeEdit(textChange, scriptInfo)) } : convertNewFileTextChangeToCodeEdit(textChanges2); - } - convertTextChangeToCodeEdit(change, scriptInfo) { - return { - start: scriptInfo.positionToLineOffset(change.span.start), - end: scriptInfo.positionToLineOffset(change.span.start + change.span.length), - newText: change.newText ? change.newText : "" - }; - } - getBraceMatching(args, simplifiedResult) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - const position = this.getPosition(args, scriptInfo); - const spans = languageService.getBraceMatchingAtPosition(file, position); - return !spans ? void 0 : simplifiedResult ? spans.map((span) => toProtocolTextSpan(span, scriptInfo)) : spans; - } - getDiagnosticsForProject(next, delay, fileName) { - if (this.suppressDiagnosticEvents) { - return; - } - const { fileNames, languageServiceDisabled } = this.getProjectInfoWorker( - fileName, - /*projectFileName*/ - void 0, - /*needFileNameList*/ - true, - /*excludeConfigFiles*/ - true - ); - if (languageServiceDisabled) { - return; - } - const fileNamesInProject = fileNames.filter((value) => !value.includes("lib.d.ts")); - if (fileNamesInProject.length === 0) { - return; - } - const highPriorityFiles = []; - const mediumPriorityFiles = []; - const lowPriorityFiles = []; - const veryLowPriorityFiles = []; - const normalizedFileName = toNormalizedPath(fileName); - const project = this.projectService.ensureDefaultProjectForFile(normalizedFileName); - for (const fileNameInProject of fileNamesInProject) { - if (this.getCanonicalFileName(fileNameInProject) === this.getCanonicalFileName(fileName)) { - highPriorityFiles.push(fileNameInProject); - } else { - const info = this.projectService.getScriptInfo(fileNameInProject); - if (!info.isScriptOpen()) { - if (isDeclarationFileName(fileNameInProject)) { - veryLowPriorityFiles.push(fileNameInProject); - } else { - lowPriorityFiles.push(fileNameInProject); - } - } else { - mediumPriorityFiles.push(fileNameInProject); - } - } - } - const sortedFiles = [...highPriorityFiles, ...mediumPriorityFiles, ...lowPriorityFiles, ...veryLowPriorityFiles]; - const checkList = sortedFiles.map((fileName2) => ({ fileName: fileName2, project })); - this.updateErrorCheck( - next, - checkList, - delay, - /*requireOpen*/ - false - ); - } - configurePlugin(args) { - this.projectService.configurePlugin(args); - } - getSmartSelectionRange(args, simplifiedResult) { - const { locations } = args; - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const scriptInfo = Debug.checkDefined(this.projectService.getScriptInfo(file)); - return map(locations, (location) => { - const pos = this.getPosition(location, scriptInfo); - const selectionRange = languageService.getSmartSelectionRange(file, pos); - return simplifiedResult ? this.mapSelectionRange(selectionRange, scriptInfo) : selectionRange; - }); - } - toggleLineComment(args, simplifiedResult) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const scriptInfo = this.projectService.getScriptInfo(file); - const textRange = this.getRange(args, scriptInfo); - const textChanges2 = languageService.toggleLineComment(file, textRange); - if (simplifiedResult) { - const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file); - return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2)); - } - return textChanges2; - } - toggleMultilineComment(args, simplifiedResult) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - const textRange = this.getRange(args, scriptInfo); - const textChanges2 = languageService.toggleMultilineComment(file, textRange); - if (simplifiedResult) { - const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file); - return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2)); - } - return textChanges2; - } - commentSelection(args, simplifiedResult) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - const textRange = this.getRange(args, scriptInfo); - const textChanges2 = languageService.commentSelection(file, textRange); - if (simplifiedResult) { - const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file); - return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2)); - } - return textChanges2; - } - uncommentSelection(args, simplifiedResult) { - const { file, languageService } = this.getFileAndLanguageServiceForSyntacticOperation(args); - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - const textRange = this.getRange(args, scriptInfo); - const textChanges2 = languageService.uncommentSelection(file, textRange); - if (simplifiedResult) { - const scriptInfo2 = this.projectService.getScriptInfoForNormalizedPath(file); - return textChanges2.map((textChange) => this.convertTextChangeToCodeEdit(textChange, scriptInfo2)); - } - return textChanges2; - } - mapSelectionRange(selectionRange, scriptInfo) { - const result = { - textSpan: toProtocolTextSpan(selectionRange.textSpan, scriptInfo) - }; - if (selectionRange.parent) { - result.parent = this.mapSelectionRange(selectionRange.parent, scriptInfo); - } - return result; - } - getScriptInfoFromProjectService(file) { - const normalizedFile = toNormalizedPath(file); - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(normalizedFile); - if (!scriptInfo) { - this.projectService.logErrorForScriptInfoNotFound(normalizedFile); - return Errors.ThrowNoProject(); - } - return scriptInfo; - } - toProtocolCallHierarchyItem(item) { - const scriptInfo = this.getScriptInfoFromProjectService(item.file); - return { - name: item.name, - kind: item.kind, - kindModifiers: item.kindModifiers, - file: item.file, - containerName: item.containerName, - span: toProtocolTextSpan(item.span, scriptInfo), - selectionSpan: toProtocolTextSpan(item.selectionSpan, scriptInfo) - }; - } - toProtocolCallHierarchyIncomingCall(incomingCall) { - const scriptInfo = this.getScriptInfoFromProjectService(incomingCall.from.file); - return { - from: this.toProtocolCallHierarchyItem(incomingCall.from), - fromSpans: incomingCall.fromSpans.map((fromSpan) => toProtocolTextSpan(fromSpan, scriptInfo)) - }; - } - toProtocolCallHierarchyOutgoingCall(outgoingCall, scriptInfo) { - return { - to: this.toProtocolCallHierarchyItem(outgoingCall.to), - fromSpans: outgoingCall.fromSpans.map((fromSpan) => toProtocolTextSpan(fromSpan, scriptInfo)) - }; - } - prepareCallHierarchy(args) { - const { file, project } = this.getFileAndProject(args); - const scriptInfo = this.projectService.getScriptInfoForNormalizedPath(file); - if (scriptInfo) { - const position = this.getPosition(args, scriptInfo); - const result = project.getLanguageService().prepareCallHierarchy(file, position); - return result && mapOneOrMany(result, (item) => this.toProtocolCallHierarchyItem(item)); - } - return void 0; - } - provideCallHierarchyIncomingCalls(args) { - const { file, project } = this.getFileAndProject(args); - const scriptInfo = this.getScriptInfoFromProjectService(file); - const incomingCalls = project.getLanguageService().provideCallHierarchyIncomingCalls(file, this.getPosition(args, scriptInfo)); - return incomingCalls.map((call) => this.toProtocolCallHierarchyIncomingCall(call)); - } - provideCallHierarchyOutgoingCalls(args) { - const { file, project } = this.getFileAndProject(args); - const scriptInfo = this.getScriptInfoFromProjectService(file); - const outgoingCalls = project.getLanguageService().provideCallHierarchyOutgoingCalls(file, this.getPosition(args, scriptInfo)); - return outgoingCalls.map((call) => this.toProtocolCallHierarchyOutgoingCall(call, scriptInfo)); - } - getCanonicalFileName(fileName) { - const name = this.host.useCaseSensitiveFileNames ? fileName : toFileNameLowerCase(fileName); - return normalizePath(name); - } - exit() { - } - notRequired(request) { - if (request) this.doOutput( - /*info*/ - void 0, - request.command, - request.seq, - /*success*/ - true, - this.performanceData - ); - return { responseRequired: false, performanceData: this.performanceData }; - } - requiredResponse(response) { - return { response, responseRequired: true, performanceData: this.performanceData }; - } - addProtocolHandler(command, handler) { - if (this.handlers.has(command)) { - throw new Error(`Protocol handler already exists for command "${command}"`); - } - this.handlers.set(command, handler); - } - setCurrentRequest(requestId) { - Debug.assert(this.currentRequestId === void 0); - this.currentRequestId = requestId; - this.cancellationToken.setRequest(requestId); - } - resetCurrentRequest(requestId) { - Debug.assert(this.currentRequestId === requestId); - this.currentRequestId = void 0; - this.cancellationToken.resetRequest(requestId); - } - // eslint-disable-line @typescript-eslint/unified-signatures - executeWithRequestId(requestId, f, perfomanceData) { - const currentPerformanceData = this.performanceData; - try { - this.performanceData = perfomanceData; - this.setCurrentRequest(requestId); - return f(); - } finally { - this.resetCurrentRequest(requestId); - this.performanceData = currentPerformanceData; - } - } - executeCommand(request) { - const handler = this.handlers.get(request.command); - if (handler) { - const response = this.executeWithRequestId( - request.seq, - () => handler(request), - /*perfomanceData*/ - void 0 - ); - this.projectService.enableRequestedPlugins(); - return response; - } else { - this.logger.msg(`Unrecognized JSON command:${stringifyIndented(request)}`, "Err" /* Err */); - this.doOutput( - /*info*/ - void 0, - "unknown" /* Unknown */, - request.seq, - /*success*/ - false, - /*performanceData*/ - void 0, - `Unrecognized JSON command: ${request.command}` - ); - return { responseRequired: false }; - } - } - onMessage(message) { - var _a, _b, _c, _d, _e, _f, _g; - this.gcTimer.scheduleCollect(); - let start; - const currentPerformanceData = this.performanceData; - if (this.logger.hasLevel(2 /* requestTime */)) { - start = this.hrtime(); - if (this.logger.hasLevel(3 /* verbose */)) { - this.logger.info(`request:${indent2(this.toStringMessage(message))}`); - } - } - let request; - let relevantFile; - try { - request = this.parseMessage(message); - relevantFile = request.arguments && request.arguments.file ? request.arguments : void 0; - (_a = tracing) == null ? void 0 : _a.instant(tracing.Phase.Session, "request", { seq: request.seq, command: request.command }); - (_b = tracing) == null ? void 0 : _b.push( - tracing.Phase.Session, - "executeCommand", - { seq: request.seq, command: request.command }, - /*separateBeginAndEnd*/ - true - ); - const { response, responseRequired, performanceData } = this.executeCommand(request); - (_c = tracing) == null ? void 0 : _c.pop(); - if (this.logger.hasLevel(2 /* requestTime */)) { - const elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); - if (responseRequired) { - this.logger.perftrc(`${request.seq}::${request.command}: elapsed time (in milliseconds) ${elapsedTime}`); - } else { - this.logger.perftrc(`${request.seq}::${request.command}: async elapsed time (in milliseconds) ${elapsedTime}`); - } - } - (_d = tracing) == null ? void 0 : _d.instant(tracing.Phase.Session, "response", { seq: request.seq, command: request.command, success: !!response }); - if (response) { - this.doOutput( - response, - request.command, - request.seq, - /*success*/ - true, - performanceData - ); - } else if (responseRequired) { - this.doOutput( - /*info*/ - void 0, - request.command, - request.seq, - /*success*/ - false, - performanceData, - "No content available." - ); - } - } catch (err) { - (_e = tracing) == null ? void 0 : _e.popAll(); - if (err instanceof OperationCanceledException) { - (_f = tracing) == null ? void 0 : _f.instant(tracing.Phase.Session, "commandCanceled", { seq: request == null ? void 0 : request.seq, command: request == null ? void 0 : request.command }); - this.doOutput( - { canceled: true }, - request.command, - request.seq, - /*success*/ - true, - this.performanceData - ); - return; - } - this.logErrorWorker(err, this.toStringMessage(message), relevantFile); - (_g = tracing) == null ? void 0 : _g.instant(tracing.Phase.Session, "commandError", { seq: request == null ? void 0 : request.seq, command: request == null ? void 0 : request.command, message: err.message }); - this.doOutput( - /*info*/ - void 0, - request ? request.command : "unknown" /* Unknown */, - request ? request.seq : 0, - /*success*/ - false, - this.performanceData, - "Error processing request. " + err.message + "\n" + err.stack - ); - } finally { - this.performanceData = currentPerformanceData; - } - } - parseMessage(message) { - return JSON.parse(message); - } - toStringMessage(message) { - return message; - } - getFormatOptions(file) { - return this.projectService.getFormatCodeOptions(file); - } - getPreferences(file) { - return this.projectService.getPreferences(file); - } - getHostFormatOptions() { - return this.projectService.getHostFormatCodeOptions(); - } - getHostPreferences() { - return this.projectService.getHostPreferences(); - } -}; -function toProtocolPerformanceData(performanceData) { - const diagnosticsDuration = performanceData.diagnosticsDuration && arrayFrom(performanceData.diagnosticsDuration, ([file, data]) => ({ ...data, file })); - return { ...performanceData, diagnosticsDuration }; -} -function toProtocolTextSpan(textSpan, scriptInfo) { - return { - start: scriptInfo.positionToLineOffset(textSpan.start), - end: scriptInfo.positionToLineOffset(textSpanEnd(textSpan)) - }; -} -function toProtocolTextSpanWithContext(span, contextSpan, scriptInfo) { - const textSpan = toProtocolTextSpan(span, scriptInfo); - const contextTextSpan = contextSpan && toProtocolTextSpan(contextSpan, scriptInfo); - return contextTextSpan ? { ...textSpan, contextStart: contextTextSpan.start, contextEnd: contextTextSpan.end } : textSpan; -} -function convertTextChangeToCodeEdit(change, scriptInfo) { - return { start: positionToLineOffset(scriptInfo, change.span.start), end: positionToLineOffset(scriptInfo, textSpanEnd(change.span)), newText: change.newText }; -} -function positionToLineOffset(info, position) { - return isConfigFile(info) ? locationFromLineAndCharacter(info.getLineAndCharacterOfPosition(position)) : info.positionToLineOffset(position); -} -function convertLinkedEditInfoToRanges(linkedEdit, scriptInfo) { - const ranges = linkedEdit.ranges.map( - (r) => { - return { - start: scriptInfo.positionToLineOffset(r.start), - end: scriptInfo.positionToLineOffset(r.start + r.length) - }; - } - ); - if (!linkedEdit.wordPattern) return { ranges }; - return { ranges, wordPattern: linkedEdit.wordPattern }; -} -function locationFromLineAndCharacter(lc) { - return { line: lc.line + 1, offset: lc.character + 1 }; -} -function convertNewFileTextChangeToCodeEdit(textChanges2) { - Debug.assert(textChanges2.textChanges.length === 1); - const change = first(textChanges2.textChanges); - Debug.assert(change.span.start === 0 && change.span.length === 0); - return { fileName: textChanges2.fileName, textChanges: [{ start: { line: 0, offset: 0 }, end: { line: 0, offset: 0 }, newText: change.newText }] }; -} -function getLocationInNewDocument(oldText, renameFilename, renameLocation, edits) { - const newText = applyEdits(oldText, renameFilename, edits); - const { line, character } = computeLineAndCharacterOfPosition(computeLineStarts(newText), renameLocation); - return { line: line + 1, offset: character + 1 }; -} -function applyEdits(text, textFilename, edits) { - for (const { fileName, textChanges: textChanges2 } of edits) { - if (fileName !== textFilename) { - continue; - } - for (let i = textChanges2.length - 1; i >= 0; i--) { - const { newText, span: { start, length: length2 } } = textChanges2[i]; - text = text.slice(0, start) + newText + text.slice(start + length2); - } - } - return text; -} -function referenceEntryToReferencesResponseItem(projectService, { fileName, textSpan, contextSpan, isWriteAccess: isWriteAccess2, isDefinition }, { disableLineTextInReferences }) { - const scriptInfo = Debug.checkDefined(projectService.getScriptInfo(fileName)); - const span = toProtocolTextSpanWithContext(textSpan, contextSpan, scriptInfo); - const lineText = disableLineTextInReferences ? void 0 : getLineText(scriptInfo, span); +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 { - file: fileName, - ...span, - lineText, - isWriteAccess: isWriteAccess2, - isDefinition + pos: isIdentifier(startToken) && pos <= startToken.getStart(sourceFile) ? startToken.getFullStart() : pos, + end: isIdentifier(endToken) && end === endToken.getEnd() ? ts_textChanges_exports.getAdjustedEndPosition(sourceFile, endToken, {}) : end }; } -function getLineText(scriptInfo, span) { - const lineSpan = scriptInfo.lineToTextSpan(span.start.line - 1); - return scriptInfo.getSnapshot().getText(lineSpan.start, textSpanEnd(lineSpan)).replace(/\r|\n/g, ""); -} -function isCompletionEntryData(data) { - return data === void 0 || data && typeof data === "object" && typeof data.exportName === "string" && (data.fileName === void 0 || typeof data.fileName === "string") && (data.ambientModuleName === void 0 || typeof data.ambientModuleName === "string" && (data.isPackageJsonImport === void 0 || typeof data.isPackageJsonImport === "boolean")); -} - -// src/server/scriptVersionCache.ts -var lineCollectionCapacity = 4; -var CharRangeSection = /* @__PURE__ */ ((CharRangeSection2) => { - CharRangeSection2[CharRangeSection2["PreStart"] = 0] = "PreStart"; - CharRangeSection2[CharRangeSection2["Start"] = 1] = "Start"; - CharRangeSection2[CharRangeSection2["Entire"] = 2] = "Entire"; - CharRangeSection2[CharRangeSection2["Mid"] = 3] = "Mid"; - CharRangeSection2[CharRangeSection2["End"] = 4] = "End"; - CharRangeSection2[CharRangeSection2["PostEnd"] = 5] = "PostEnd"; - return CharRangeSection2; -})(CharRangeSection || {}); -var EditWalker = class { - constructor() { - this.goSubtree = true; - this.lineIndex = new LineIndex(); - this.endBranch = []; - this.state = 2 /* Entire */; - this.initialText = ""; - this.trailingText = ""; - this.lineIndex.root = new LineNode(); - this.startPath = [this.lineIndex.root]; - this.stack = [this.lineIndex.root]; - } - get done() { - return false; - } - insertLines(insertedText, suppressTrailingText) { - if (suppressTrailingText) { - this.trailingText = ""; - } - if (insertedText) { - insertedText = this.initialText + insertedText + this.trailingText; - } else { - insertedText = this.initialText + this.trailingText; - } - const lm = LineIndex.linesFromText(insertedText); - const lines = lm.lines; - if (lines.length > 1 && lines[lines.length - 1] === "") { - lines.pop(); - } - let branchParent; - let lastZeroCount; - for (let k = this.endBranch.length - 1; k >= 0; k--) { - this.endBranch[k].updateCounts(); - if (this.endBranch[k].charCount() === 0) { - lastZeroCount = this.endBranch[k]; - if (k > 0) { - branchParent = this.endBranch[k - 1]; - } else { - branchParent = this.branchNode; - } - } - } - if (lastZeroCount) { - branchParent.remove(lastZeroCount); - } - const leafNode = this.startPath[this.startPath.length - 1]; - if (lines.length > 0) { - leafNode.text = lines[0]; - if (lines.length > 1) { - let insertedNodes = new Array(lines.length - 1); - let startNode2 = leafNode; - for (let i = 1; i < lines.length; i++) { - insertedNodes[i - 1] = new LineLeaf(lines[i]); - } - let pathIndex = this.startPath.length - 2; - while (pathIndex >= 0) { - const insertionNode = this.startPath[pathIndex]; - insertedNodes = insertionNode.insertAt(startNode2, insertedNodes); - pathIndex--; - startNode2 = insertionNode; - } - let insertedNodesLen = insertedNodes.length; - while (insertedNodesLen > 0) { - const newRoot = new LineNode(); - newRoot.add(this.lineIndex.root); - insertedNodes = newRoot.insertAt(this.lineIndex.root, insertedNodes); - insertedNodesLen = insertedNodes.length; - this.lineIndex.root = newRoot; - } - this.lineIndex.root.updateCounts(); - } else { - for (let j = this.startPath.length - 2; j >= 0; j--) { - this.startPath[j].updateCounts(); - } - } - } else { - const insertionNode = this.startPath[this.startPath.length - 2]; - insertionNode.remove(leafNode); - for (let j = this.startPath.length - 2; j >= 0; j--) { - this.startPath[j].updateCounts(); - } - } - return this.lineIndex; - } - post(_relativeStart, _relativeLength, lineCollection) { - if (lineCollection === this.lineCollectionAtBranch) { - this.state = 4 /* End */; - } - this.stack.pop(); - } - pre(_relativeStart, _relativeLength, lineCollection, _parent, nodeType) { - const currentNode = this.stack[this.stack.length - 1]; - if (this.state === 2 /* Entire */ && nodeType === 1 /* Start */) { - this.state = 1 /* Start */; - this.branchNode = currentNode; - this.lineCollectionAtBranch = lineCollection; - } - let child; - function fresh(node) { - if (node.isLeaf()) { - return new LineLeaf(""); - } else return new LineNode(); - } - switch (nodeType) { - case 0 /* PreStart */: - this.goSubtree = false; - if (this.state !== 4 /* End */) { - currentNode.add(lineCollection); - } - break; - case 1 /* Start */: - if (this.state === 4 /* End */) { - this.goSubtree = false; - } else { - child = fresh(lineCollection); - currentNode.add(child); - this.startPath.push(child); - } - break; - case 2 /* Entire */: - if (this.state !== 4 /* End */) { - child = fresh(lineCollection); - currentNode.add(child); - this.startPath.push(child); - } else { - if (!lineCollection.isLeaf()) { - child = fresh(lineCollection); - currentNode.add(child); - this.endBranch.push(child); - } - } - break; - case 3 /* Mid */: - this.goSubtree = false; - break; - case 4 /* End */: - if (this.state !== 4 /* End */) { - this.goSubtree = false; - } else { - if (!lineCollection.isLeaf()) { - child = fresh(lineCollection); - currentNode.add(child); - this.endBranch.push(child); - } - } - break; - case 5 /* PostEnd */: - this.goSubtree = false; - if (this.state !== 1 /* Start */) { - currentNode.add(lineCollection); - } - break; - } - if (this.goSubtree) { - this.stack.push(child); - } - } - // just gather text from the leaves - leaf(relativeStart, relativeLength, ll) { - if (this.state === 1 /* Start */) { - this.initialText = ll.text.substring(0, relativeStart); - } else if (this.state === 2 /* Entire */) { - this.initialText = ll.text.substring(0, relativeStart); - this.trailingText = ll.text.substring(relativeStart + relativeLength); - } else { - this.trailingText = ll.text.substring(relativeStart + relativeLength); - } - } -}; -var TextChange9 = class { - constructor(pos, deleteLen, insertedText) { - this.pos = pos; - this.deleteLen = deleteLen; - this.insertedText = insertedText; - } - getTextChangeRange() { - return createTextChangeRange(createTextSpan(this.pos, this.deleteLen), this.insertedText ? this.insertedText.length : 0); - } -}; -var _ScriptVersionCache = class _ScriptVersionCache { - constructor() { - this.changes = []; - this.versions = new Array(_ScriptVersionCache.maxVersions); - this.minVersion = 0; - // no versions earlier than min version will maintain change history - this.currentVersion = 0; - } - versionToIndex(version2) { - if (version2 < this.minVersion || version2 > this.currentVersion) { - return void 0; - } - return version2 % _ScriptVersionCache.maxVersions; - } - currentVersionToIndex() { - return this.currentVersion % _ScriptVersionCache.maxVersions; - } - // REVIEW: can optimize by coalescing simple edits - edit(pos, deleteLen, insertedText) { - this.changes.push(new TextChange9(pos, deleteLen, insertedText)); - if (this.changes.length > _ScriptVersionCache.changeNumberThreshold || deleteLen > _ScriptVersionCache.changeLengthThreshold || insertedText && insertedText.length > _ScriptVersionCache.changeLengthThreshold) { - this.getSnapshot(); - } - } - getSnapshot() { - return this._getSnapshot(); - } - _getSnapshot() { - let snap = this.versions[this.currentVersionToIndex()]; - if (this.changes.length > 0) { - let snapIndex = snap.index; - for (const change of this.changes) { - snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText); - } - snap = new LineIndexSnapshot(this.currentVersion + 1, this, snapIndex, this.changes); - this.currentVersion = snap.version; - this.versions[this.currentVersionToIndex()] = snap; - this.changes = []; - if (this.currentVersion - this.minVersion >= _ScriptVersionCache.maxVersions) { - this.minVersion = this.currentVersion - _ScriptVersionCache.maxVersions + 1; - } - } - return snap; - } - getSnapshotVersion() { - return this._getSnapshot().version; - } - getAbsolutePositionAndLineText(oneBasedLine) { - return this._getSnapshot().index.lineNumberToInfo(oneBasedLine); - } - lineOffsetToPosition(line, column) { - return this._getSnapshot().index.absolutePositionOfStartOfLine(line) + (column - 1); - } - positionToLineOffset(position) { - return this._getSnapshot().index.positionToLineOffset(position); - } - lineToTextSpan(line) { - const index = this._getSnapshot().index; - const { lineText, absolutePosition } = index.lineNumberToInfo(line + 1); - const len = lineText !== void 0 ? lineText.length : index.absolutePositionOfStartOfLine(line + 2) - absolutePosition; - return createTextSpan(absolutePosition, len); - } - getTextChangesBetweenVersions(oldVersion, newVersion) { - if (oldVersion < newVersion) { - if (oldVersion >= this.minVersion) { - const textChangeRanges = []; - for (let i = oldVersion + 1; i <= newVersion; i++) { - const snap = this.versions[this.versionToIndex(i)]; - for (const textChange of snap.changesSincePreviousVersion) { - textChangeRanges.push(textChange.getTextChangeRange()); - } - } - return collapseTextChangeRangesAcrossMultipleVersions(textChangeRanges); - } else { - return void 0; - } - } else { - return unchangedTextChangeRange; - } - } - getLineCount() { - return this._getSnapshot().index.getLineCount(); - } - static fromString(script) { - const svc = new _ScriptVersionCache(); - const snap = new LineIndexSnapshot(0, svc, new LineIndex()); - svc.versions[svc.currentVersion] = snap; - const lm = LineIndex.linesFromText(script); - snap.index.load(lm.lines); - return svc; - } -}; -_ScriptVersionCache.changeNumberThreshold = 8; -_ScriptVersionCache.changeLengthThreshold = 256; -_ScriptVersionCache.maxVersions = 8; -var ScriptVersionCache = _ScriptVersionCache; -var LineIndexSnapshot = class _LineIndexSnapshot { - constructor(version2, cache, index, changesSincePreviousVersion = emptyArray2) { - this.version = version2; - this.cache = cache; - this.index = index; - this.changesSincePreviousVersion = changesSincePreviousVersion; - } - getText(rangeStart, rangeEnd) { - return this.index.getText(rangeStart, rangeEnd - rangeStart); - } - getLength() { - return this.index.getLength(); - } - getChangeRange(oldSnapshot) { - if (oldSnapshot instanceof _LineIndexSnapshot && this.cache === oldSnapshot.cache) { - if (this.version <= oldSnapshot.version) { - return unchangedTextChangeRange; - } else { - return this.cache.getTextChangesBetweenVersions(oldSnapshot.version, this.version); - } - } - } -}; -var LineIndex = class _LineIndex { - constructor() { - // set this to true to check each edit for accuracy - this.checkEdits = false; - } - absolutePositionOfStartOfLine(oneBasedLine) { - return this.lineNumberToInfo(oneBasedLine).absolutePosition; - } - positionToLineOffset(position) { - const { oneBasedLine, zeroBasedColumn } = this.root.charOffsetToLineInfo(1, position); - return { line: oneBasedLine, offset: zeroBasedColumn + 1 }; - } - positionToColumnAndLineText(position) { - return this.root.charOffsetToLineInfo(1, position); - } - getLineCount() { - return this.root.lineCount(); - } - lineNumberToInfo(oneBasedLine) { - const lineCount = this.getLineCount(); - if (oneBasedLine <= lineCount) { - const { position, leaf } = this.root.lineNumberToInfo(oneBasedLine, 0); - return { absolutePosition: position, lineText: leaf && leaf.text }; - } else { - return { absolutePosition: this.root.charCount(), lineText: void 0 }; - } - } - load(lines) { - if (lines.length > 0) { - const leaves = []; - for (let i = 0; i < lines.length; i++) { - leaves[i] = new LineLeaf(lines[i]); - } - this.root = _LineIndex.buildTreeFromBottom(leaves); - } else { - this.root = new LineNode(); - } - } - walk(rangeStart, rangeLength, walkFns) { - this.root.walk(rangeStart, rangeLength, walkFns); - } - getText(rangeStart, rangeLength) { - let accum = ""; - if (rangeLength > 0 && rangeStart < this.root.charCount()) { - this.walk(rangeStart, rangeLength, { - goSubtree: true, - done: false, - leaf: (relativeStart, relativeLength, ll) => { - accum = accum.concat(ll.text.substring(relativeStart, relativeStart + relativeLength)); - } - }); - } - return accum; - } - getLength() { - return this.root.charCount(); - } - every(f, rangeStart, rangeEnd) { - if (!rangeEnd) { - rangeEnd = this.root.charCount(); - } - const walkFns = { - goSubtree: true, - done: false, - leaf(relativeStart, relativeLength, ll) { - if (!f(ll, relativeStart, relativeLength)) { - this.done = true; - } - } - }; - this.walk(rangeStart, rangeEnd - rangeStart, walkFns); - return !walkFns.done; - } - edit(pos, deleteLength, newText) { - if (this.root.charCount() === 0) { - Debug.assert(deleteLength === 0); - if (newText !== void 0) { - this.load(_LineIndex.linesFromText(newText).lines); - return this; - } - return void 0; - } else { - let checkText; - if (this.checkEdits) { - const source = this.getText(0, this.root.charCount()); - checkText = source.slice(0, pos) + newText + source.slice(pos + deleteLength); - } - const walker = new EditWalker(); - let suppressTrailingText = false; - if (pos >= this.root.charCount()) { - pos = this.root.charCount() - 1; - const endString = this.getText(pos, 1); - if (newText) { - newText = endString + newText; - } else { - newText = endString; - } - deleteLength = 0; - suppressTrailingText = true; - } else if (deleteLength > 0) { - const e = pos + deleteLength; - const { zeroBasedColumn, lineText } = this.positionToColumnAndLineText(e); - if (zeroBasedColumn === 0) { - deleteLength += lineText.length; - newText = newText ? newText + lineText : lineText; - } - } - this.root.walk(pos, deleteLength, walker); - walker.insertLines(newText, suppressTrailingText); - if (this.checkEdits) { - const updatedText = walker.lineIndex.getText(0, walker.lineIndex.getLength()); - Debug.assert(checkText === updatedText, "buffer edit mismatch"); - } - return walker.lineIndex; - } - } - static buildTreeFromBottom(nodes) { - if (nodes.length < lineCollectionCapacity) { - return new LineNode(nodes); - } - const interiorNodes = new Array(Math.ceil(nodes.length / lineCollectionCapacity)); - let nodeIndex = 0; - for (let i = 0; i < interiorNodes.length; i++) { - const end = Math.min(nodeIndex + lineCollectionCapacity, nodes.length); - interiorNodes[i] = new LineNode(nodes.slice(nodeIndex, end)); - nodeIndex = end; - } - return this.buildTreeFromBottom(interiorNodes); - } - static linesFromText(text) { - const lineMap = computeLineStarts(text); - if (lineMap.length === 0) { - return { lines: [], lineMap }; - } - const lines = new Array(lineMap.length); - const lc = lineMap.length - 1; - for (let lmi = 0; lmi < lc; lmi++) { - lines[lmi] = text.substring(lineMap[lmi], lineMap[lmi + 1]); - } - const endText = text.substring(lineMap[lc]); - if (endText.length > 0) { - lines[lc] = endText; - } else { - lines.pop(); - } - return { lines, lineMap }; - } -}; -var LineNode = class _LineNode { - constructor(children = []) { - this.children = children; - this.totalChars = 0; - this.totalLines = 0; - if (children.length) this.updateCounts(); - } - isLeaf() { - return false; - } - updateCounts() { - this.totalChars = 0; - this.totalLines = 0; - for (const child of this.children) { - this.totalChars += child.charCount(); - this.totalLines += child.lineCount(); - } - } - execWalk(rangeStart, rangeLength, walkFns, childIndex, nodeType) { - if (walkFns.pre) { - walkFns.pre(rangeStart, rangeLength, this.children[childIndex], this, nodeType); - } - if (walkFns.goSubtree) { - this.children[childIndex].walk(rangeStart, rangeLength, walkFns); - if (walkFns.post) { - walkFns.post(rangeStart, rangeLength, this.children[childIndex], this, nodeType); - } - } else { - walkFns.goSubtree = true; - } - return walkFns.done; - } - skipChild(relativeStart, relativeLength, childIndex, walkFns, nodeType) { - if (walkFns.pre && !walkFns.done) { - walkFns.pre(relativeStart, relativeLength, this.children[childIndex], this, nodeType); - walkFns.goSubtree = true; - } - } - walk(rangeStart, rangeLength, walkFns) { - let childIndex = 0; - let childCharCount = this.children[childIndex].charCount(); - let adjustedStart = rangeStart; - while (adjustedStart >= childCharCount) { - this.skipChild(adjustedStart, rangeLength, childIndex, walkFns, 0 /* PreStart */); - adjustedStart -= childCharCount; - childIndex++; - childCharCount = this.children[childIndex].charCount(); - } - if (adjustedStart + rangeLength <= childCharCount) { - if (this.execWalk(adjustedStart, rangeLength, walkFns, childIndex, 2 /* Entire */)) { - return; - } - } else { - if (this.execWalk(adjustedStart, childCharCount - adjustedStart, walkFns, childIndex, 1 /* Start */)) { - return; - } - let adjustedLength = rangeLength - (childCharCount - adjustedStart); - childIndex++; - const child = this.children[childIndex]; - childCharCount = child.charCount(); - while (adjustedLength > childCharCount) { - if (this.execWalk(0, childCharCount, walkFns, childIndex, 3 /* Mid */)) { - return; - } - adjustedLength -= childCharCount; - childIndex++; - childCharCount = this.children[childIndex].charCount(); - } - if (adjustedLength > 0) { - if (this.execWalk(0, adjustedLength, walkFns, childIndex, 4 /* End */)) { - return; - } - } - } - if (walkFns.pre) { - const clen = this.children.length; - if (childIndex < clen - 1) { - for (let ej = childIndex + 1; ej < clen; ej++) { - this.skipChild(0, 0, ej, walkFns, 5 /* PostEnd */); - } - } - } - } - // Input position is relative to the start of this node. - // Output line number is absolute. - charOffsetToLineInfo(lineNumberAccumulator, relativePosition) { - if (this.children.length === 0) { - return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: void 0 }; - } - for (const child of this.children) { - if (child.charCount() > relativePosition) { - if (child.isLeaf()) { - return { oneBasedLine: lineNumberAccumulator, zeroBasedColumn: relativePosition, lineText: child.text }; - } else { - return child.charOffsetToLineInfo(lineNumberAccumulator, relativePosition); - } - } else { - relativePosition -= child.charCount(); - lineNumberAccumulator += child.lineCount(); - } - } - const lineCount = this.lineCount(); - if (lineCount === 0) { - return { oneBasedLine: 1, zeroBasedColumn: 0, lineText: void 0 }; - } - const leaf = Debug.checkDefined(this.lineNumberToInfo(lineCount, 0).leaf); - return { oneBasedLine: lineCount, zeroBasedColumn: leaf.charCount(), lineText: void 0 }; - } - /** - * Input line number is relative to the start of this node. - * Output line number is relative to the child. - * positionAccumulator will be an absolute position once relativeLineNumber reaches 0. - */ - lineNumberToInfo(relativeOneBasedLine, positionAccumulator) { - for (const child of this.children) { - const childLineCount = child.lineCount(); - if (childLineCount >= relativeOneBasedLine) { - return child.isLeaf() ? { position: positionAccumulator, leaf: child } : child.lineNumberToInfo(relativeOneBasedLine, positionAccumulator); - } else { - relativeOneBasedLine -= childLineCount; - positionAccumulator += child.charCount(); - } - } - return { position: positionAccumulator, leaf: void 0 }; - } - splitAfter(childIndex) { - let splitNode; - const clen = this.children.length; - childIndex++; - const endLength = childIndex; - if (childIndex < clen) { - splitNode = new _LineNode(); - while (childIndex < clen) { - splitNode.add(this.children[childIndex]); - childIndex++; - } - splitNode.updateCounts(); - } - this.children.length = endLength; - return splitNode; - } - remove(child) { - const childIndex = this.findChildIndex(child); - const clen = this.children.length; - if (childIndex < clen - 1) { - for (let i = childIndex; i < clen - 1; i++) { - this.children[i] = this.children[i + 1]; - } - } - this.children.pop(); - } - findChildIndex(child) { - const childIndex = this.children.indexOf(child); - Debug.assert(childIndex !== -1); - return childIndex; - } - insertAt(child, nodes) { - let childIndex = this.findChildIndex(child); - const clen = this.children.length; - const nodeCount = nodes.length; - if (clen < lineCollectionCapacity && childIndex === clen - 1 && nodeCount === 1) { - this.add(nodes[0]); - this.updateCounts(); - return []; - } else { - const shiftNode = this.splitAfter(childIndex); - let nodeIndex = 0; - childIndex++; - while (childIndex < lineCollectionCapacity && nodeIndex < nodeCount) { - this.children[childIndex] = nodes[nodeIndex]; - childIndex++; - nodeIndex++; - } - let splitNodes = []; - let splitNodeCount = 0; - if (nodeIndex < nodeCount) { - splitNodeCount = Math.ceil((nodeCount - nodeIndex) / lineCollectionCapacity); - splitNodes = new Array(splitNodeCount); - let splitNodeIndex = 0; - for (let i = 0; i < splitNodeCount; i++) { - splitNodes[i] = new _LineNode(); - } - let splitNode = splitNodes[0]; - while (nodeIndex < nodeCount) { - splitNode.add(nodes[nodeIndex]); - nodeIndex++; - if (splitNode.children.length === lineCollectionCapacity) { - splitNodeIndex++; - splitNode = splitNodes[splitNodeIndex]; - } - } - for (let i = splitNodes.length - 1; i >= 0; i--) { - if (splitNodes[i].children.length === 0) { - splitNodes.pop(); - } - } - } - if (shiftNode) { - splitNodes.push(shiftNode); - } - this.updateCounts(); - for (let i = 0; i < splitNodeCount; i++) { - splitNodes[i].updateCounts(); - } - return splitNodes; - } - } - // assume there is room for the item; return true if more room - add(collection) { - this.children.push(collection); - Debug.assert(this.children.length <= lineCollectionCapacity); - } - charCount() { - return this.totalChars; - } - lineCount() { - return this.totalLines; - } -}; -var LineLeaf = class { - constructor(text) { - this.text = text; - } - isLeaf() { - return true; - } - walk(rangeStart, rangeLength, walkFns) { - walkFns.leaf(rangeStart, rangeLength, this); - } - charCount() { - return this.text.length; - } - lineCount() { - return 1; - } -}; - -// src/server/typingInstallerAdapter.ts -var _TypingsInstallerAdapter = class _TypingsInstallerAdapter { - constructor(telemetryEnabled, logger, host, globalTypingsCacheLocation, event, maxActiveRequestCount) { - this.telemetryEnabled = telemetryEnabled; - this.logger = logger; - this.host = host; - this.globalTypingsCacheLocation = globalTypingsCacheLocation; - this.event = event; - this.maxActiveRequestCount = maxActiveRequestCount; - this.activeRequestCount = 0; - this.requestQueue = createQueue(); - this.requestMap = /* @__PURE__ */ new Map(); - // Maps project name to newest requestQueue entry for that project - /** We will lazily request the types registry on the first call to `isKnownTypesPackageName` and store it in `typesRegistryCache`. */ - this.requestedRegistry = false; - this.packageInstallId = 0; - } - isKnownTypesPackageName(name) { - var _a; - const validationResult = ts_JsTyping_exports.validatePackageName(name); - if (validationResult !== ts_JsTyping_exports.NameValidationResult.Ok) { - return false; - } - if (!this.requestedRegistry) { - this.requestedRegistry = true; - this.installer.send({ kind: "typesRegistry" }); - } - return !!((_a = this.typesRegistryCache) == null ? void 0 : _a.has(name)); - } - installPackage(options) { - this.packageInstallId++; - const request = { kind: "installPackage", ...options, id: this.packageInstallId }; - const promise = new Promise((resolve, reject) => { - (this.packageInstalledPromise ?? (this.packageInstalledPromise = /* @__PURE__ */ new Map())).set(this.packageInstallId, { resolve, reject }); - }); - this.installer.send(request); - return promise; - } - attach(projectService) { - this.projectService = projectService; - this.installer = this.createInstallerProcess(); - } - onProjectClosed(p) { - this.installer.send({ projectName: p.getProjectName(), kind: "closeProject" }); - } - enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports) { - const request = createInstallTypingsRequest(project, typeAcquisition, unresolvedImports); - if (this.logger.hasLevel(3 /* verbose */)) { - this.logger.info(`TIAdapter:: Scheduling throttled operation:${stringifyIndented(request)}`); - } - if (this.activeRequestCount < this.maxActiveRequestCount) { - this.scheduleRequest(request); - } else { - if (this.logger.hasLevel(3 /* verbose */)) { - this.logger.info(`TIAdapter:: Deferring request for: ${request.projectName}`); - } - this.requestQueue.enqueue(request); - this.requestMap.set(request.projectName, request); - } - } - handleMessage(response) { - var _a, _b; - if (this.logger.hasLevel(3 /* verbose */)) { - this.logger.info(`TIAdapter:: Received response:${stringifyIndented(response)}`); - } - switch (response.kind) { - case EventTypesRegistry: - this.typesRegistryCache = new Map(Object.entries(response.typesRegistry)); - break; - case ActionPackageInstalled: { - const promise = (_a = this.packageInstalledPromise) == null ? void 0 : _a.get(response.id); - Debug.assertIsDefined(promise, "Should find the promise for package install"); - (_b = this.packageInstalledPromise) == null ? void 0 : _b.delete(response.id); - if (response.success) { - promise.resolve({ successMessage: response.message }); - } else { - promise.reject(response.message); - } - this.projectService.updateTypingsForProject(response); - this.event(response, "setTypings"); - break; - } - case EventInitializationFailed: { - const body = { - message: response.message - }; - const eventName = "typesInstallerInitializationFailed"; - this.event(body, eventName); - break; - } - case EventBeginInstallTypes: { - const body = { - eventId: response.eventId, - packages: response.packagesToInstall - }; - const eventName = "beginInstallTypes"; - this.event(body, eventName); - break; - } - case EventEndInstallTypes: { - if (this.telemetryEnabled) { - const body2 = { - telemetryEventName: "typingsInstalled", - payload: { - installedPackages: response.packagesToInstall.join(","), - installSuccess: response.installSuccess, - typingsInstallerVersion: response.typingsInstallerVersion - } - }; - const eventName2 = "telemetry"; - this.event(body2, eventName2); - } - const body = { - eventId: response.eventId, - packages: response.packagesToInstall, - success: response.installSuccess - }; - const eventName = "endInstallTypes"; - this.event(body, eventName); - break; - } - case ActionInvalidate: { - this.projectService.updateTypingsForProject(response); - break; - } - case ActionSet: { - if (this.activeRequestCount > 0) { - this.activeRequestCount--; - } else { - Debug.fail("TIAdapter:: Received too many responses"); - } - while (!this.requestQueue.isEmpty()) { - const queuedRequest = this.requestQueue.dequeue(); - if (this.requestMap.get(queuedRequest.projectName) === queuedRequest) { - this.requestMap.delete(queuedRequest.projectName); - this.scheduleRequest(queuedRequest); - break; - } - if (this.logger.hasLevel(3 /* verbose */)) { - this.logger.info(`TIAdapter:: Skipping defunct request for: ${queuedRequest.projectName}`); - } - } - this.projectService.updateTypingsForProject(response); - this.event(response, "setTypings"); - break; - } - case ActionWatchTypingLocations: - this.projectService.watchTypingLocations(response); - break; - default: - assertType(response); - } - } - scheduleRequest(request) { - if (this.logger.hasLevel(3 /* verbose */)) { - this.logger.info(`TIAdapter:: Scheduling request for: ${request.projectName}`); - } - this.activeRequestCount++; - this.host.setTimeout( - () => { - if (this.logger.hasLevel(3 /* verbose */)) { - this.logger.info(`TIAdapter:: Sending request:${stringifyIndented(request)}`); - } - this.installer.send(request); - }, - _TypingsInstallerAdapter.requestDelayMillis, - `${request.projectName}::${request.kind}` - ); - } -}; -// This number is essentially arbitrary. Processing more than one typings request -// at a time makes sense, but having too many in the pipe results in a hang -// (see https://github.com/nodejs/node/issues/7657). -// It would be preferable to base our limit on the amount of space left in the -// buffer, but we have yet to find a way to retrieve that value. -_TypingsInstallerAdapter.requestDelayMillis = 100; -var TypingsInstallerAdapter = _TypingsInstallerAdapter; - -// src/typescript/_namespaces/ts.server.ts -var ts_server_exports4 = {}; -__export(ts_server_exports4, { - ActionInvalidate: () => ActionInvalidate, - ActionPackageInstalled: () => ActionPackageInstalled, - ActionSet: () => ActionSet, - ActionWatchTypingLocations: () => ActionWatchTypingLocations, - Arguments: () => Arguments, - AutoImportProviderProject: () => AutoImportProviderProject, - AuxiliaryProject: () => AuxiliaryProject, - CharRangeSection: () => CharRangeSection, - CloseFileWatcherEvent: () => CloseFileWatcherEvent, - CommandNames: () => CommandNames, - ConfigFileDiagEvent: () => ConfigFileDiagEvent, - ConfiguredProject: () => ConfiguredProject2, - ConfiguredProjectLoadKind: () => ConfiguredProjectLoadKind, - CreateDirectoryWatcherEvent: () => CreateDirectoryWatcherEvent, - CreateFileWatcherEvent: () => CreateFileWatcherEvent, - Errors: () => Errors, - EventBeginInstallTypes: () => EventBeginInstallTypes, - EventEndInstallTypes: () => EventEndInstallTypes, - EventInitializationFailed: () => EventInitializationFailed, - EventTypesRegistry: () => EventTypesRegistry, - ExternalProject: () => ExternalProject, - GcTimer: () => GcTimer, - InferredProject: () => InferredProject2, - LargeFileReferencedEvent: () => LargeFileReferencedEvent, - LineIndex: () => LineIndex, - LineLeaf: () => LineLeaf, - LineNode: () => LineNode, - LogLevel: () => LogLevel2, - Msg: () => Msg, - OpenFileInfoTelemetryEvent: () => OpenFileInfoTelemetryEvent, - Project: () => Project2, - ProjectInfoTelemetryEvent: () => ProjectInfoTelemetryEvent, - ProjectKind: () => ProjectKind, - ProjectLanguageServiceStateEvent: () => ProjectLanguageServiceStateEvent, - ProjectLoadingFinishEvent: () => ProjectLoadingFinishEvent, - ProjectLoadingStartEvent: () => ProjectLoadingStartEvent, - ProjectService: () => ProjectService2, - ProjectsUpdatedInBackgroundEvent: () => ProjectsUpdatedInBackgroundEvent, - ScriptInfo: () => ScriptInfo, - ScriptVersionCache: () => ScriptVersionCache, - Session: () => Session3, - TextStorage: () => TextStorage, - ThrottledOperations: () => ThrottledOperations, - TypingsInstallerAdapter: () => TypingsInstallerAdapter, - allFilesAreJsOrDts: () => allFilesAreJsOrDts, - allRootFilesAreJsOrDts: () => allRootFilesAreJsOrDts, - asNormalizedPath: () => asNormalizedPath, - convertCompilerOptions: () => convertCompilerOptions, - convertFormatOptions: () => convertFormatOptions, - convertScriptKindName: () => convertScriptKindName, - convertTypeAcquisition: () => convertTypeAcquisition, - convertUserPreferences: () => convertUserPreferences, - convertWatchOptions: () => convertWatchOptions, - countEachFileTypes: () => countEachFileTypes, - createInstallTypingsRequest: () => createInstallTypingsRequest, - createModuleSpecifierCache: () => createModuleSpecifierCache, - createNormalizedPathMap: () => createNormalizedPathMap, - createPackageJsonCache: () => createPackageJsonCache, - createSortedArray: () => createSortedArray2, - emptyArray: () => emptyArray2, - findArgument: () => findArgument, - formatDiagnosticToProtocol: () => formatDiagnosticToProtocol, - formatMessage: () => formatMessage2, - getBaseConfigFileName: () => getBaseConfigFileName, - getLocationInNewDocument: () => getLocationInNewDocument, - hasArgument: () => hasArgument, - hasNoTypeScriptSource: () => hasNoTypeScriptSource, - indent: () => indent2, - isBackgroundProject: () => isBackgroundProject, - isConfigFile: () => isConfigFile, - isConfiguredProject: () => isConfiguredProject, - isDynamicFileName: () => isDynamicFileName, - isExternalProject: () => isExternalProject, - isInferredProject: () => isInferredProject, - isInferredProjectName: () => isInferredProjectName, - isProjectDeferredClose: () => isProjectDeferredClose, - makeAutoImportProviderProjectName: () => makeAutoImportProviderProjectName, - makeAuxiliaryProjectName: () => makeAuxiliaryProjectName, - makeInferredProjectName: () => makeInferredProjectName, - maxFileSize: () => maxFileSize, - maxProgramSizeForNonTsFiles: () => maxProgramSizeForNonTsFiles, - normalizedPathToPath: () => normalizedPathToPath, - nowString: () => nowString, - nullCancellationToken: () => nullCancellationToken, - nullTypingsInstaller: () => nullTypingsInstaller, - protocol: () => ts_server_protocol_exports, - stringifyIndented: () => stringifyIndented, - toEvent: () => toEvent, - toNormalizedPath: () => toNormalizedPath, - tryConvertScriptKindName: () => tryConvertScriptKindName, - typingsInstaller: () => ts_server_typingsInstaller_exports, - updateProjectIfDirty: () => updateProjectIfDirty -}); // src/typescript/typescript.ts if (typeof console !== "undefined") { @@ -194210,6 +182075,7 @@ if (typeof console !== "undefined") { PollingWatchKind, PragmaKindFlags, PredicateSemantics, + PreparePasteEdits, PrivateIdentifierKind, ProcessLevel, ProgramUpdateLevel, @@ -194302,10 +182168,8 @@ if (typeof console !== "undefined") { breakIntoWordSpans, buildLinkParts, buildOpts, - buildOverload, bundlerModuleNameResolver, canBeConvertedToAsync, - canEmitTsBuildInfo, canHaveDecorators, canHaveExportModifier, canHaveFlowNode, @@ -194325,6 +182189,7 @@ if (typeof console !== "undefined") { canWatchAffectingLocation, canWatchAtTypes, canWatchDirectoryOrFile, + canWatchDirectoryOrFilePath, cartesianProduct, cast, chainBundle, @@ -194490,7 +182355,6 @@ if (typeof console !== "undefined") { createNodeConverters, createNodeFactory, createOptionNameMap, - createOverload, createPackageJsonImportFilter, createPackageJsonInfo, createParenthesizerRules, @@ -194596,6 +182460,7 @@ if (typeof console !== "undefined") { escapeTemplateSubstitution, evaluatorResult, every, + exclusivelyPrefixedNodeCoreModules, executeCommandLine, expandPreOrPostfixIncrementOrDecrementExpression, explainFiles, @@ -194608,7 +182473,6 @@ if (typeof console !== "undefined") { extensionsNotSupportingExtensionlessResolution, externalHelpersModuleNameText, factory, - fileContainsPackageImport, fileExtensionIs, fileExtensionIsOneOf, fileIncludeReasonToDiagnostics, @@ -194658,8 +182522,10 @@ if (typeof console !== "undefined") { forEach, forEachAncestor, forEachAncestorDirectory, + forEachAncestorDirectoryStoppingAtGlobalCache, forEachChild, forEachChildRecursively, + forEachDynamicImportOrRequireCall, forEachEmittedFile, forEachEnclosingBlockScopeContainer, forEachEntry, @@ -194700,6 +182566,7 @@ if (typeof console !== "undefined") { getAllKeys, getAllProjectOutputs, getAllSuperTypeNodes, + getAllowImportingTsExtensions, getAllowJSCompilerOption, getAllowSyntheticDefaultImports, getAncestor, @@ -195008,6 +182875,7 @@ if (typeof console !== "undefined") { getPositionOfLineAndCharacter, getPossibleGenericSignatures, getPossibleOriginalInputExtensionForExtension, + getPossibleOriginalInputPathWithoutChangingExt, getPossibleTypeArgumentsInfo, getPreEmitDiagnostics, getPrecedingNonSpaceCharacterPosition, @@ -195271,7 +183139,7 @@ if (typeof console !== "undefined") { isBooleanLiteral, isBreakOrContinueStatement, isBreakStatement, - isBuild, + isBuildCommand, isBuildInfoFile, isBuilderProgram, isBundle, @@ -195458,7 +183326,7 @@ if (typeof console !== "undefined") { isImportSpecifier, isImportTypeAssertionContainer, isImportTypeNode, - isImportableFile, + isImportable, isInComment, isInCompoundLikeAssignment, isInExpressionContext, @@ -195557,6 +183425,7 @@ if (typeof console !== "undefined") { isJsxAttributeLike, isJsxAttributeName, isJsxAttributes, + isJsxCallLike, isJsxChild, isJsxClosingElement, isJsxClosingFragment, @@ -195639,6 +183508,7 @@ if (typeof console !== "undefined") { isNamespaceReexportDeclaration, isNewExpression, isNewExpressionTarget, + isNewScopeNode, isNoSubstitutionTemplateLiteral, isNodeArray, isNodeArrayMultiLine, @@ -195687,6 +183557,7 @@ if (typeof console !== "undefined") { isParseTreeNode, isPartOfParameterDeclaration, isPartOfTypeNode, + isPartOfTypeOnlyImportOrExportDeclaration, isPartOfTypeQuery, isPartiallyEmittedExpression, isPatternMatch, @@ -195755,6 +183626,7 @@ if (typeof console !== "undefined") { isSimpleInlineableExpression, isSimpleParameterList, isSingleOrDoubleQuote, + isSolutionConfig, isSourceElement, isSourceFile, isSourceFileFromLibrary, @@ -195863,7 +183735,6 @@ if (typeof console !== "undefined") { isVariableDeclarationInitializedToRequire, isVariableDeclarationList, isVariableLike, - isVariableLikeOrAccessor, isVariableStatement, isVoidExpression, isWatchSet, @@ -195900,6 +183771,7 @@ if (typeof console !== "undefined") { matchPatternOrExact, matchedText, matchesExclude, + matchesExcludeWorker, maxBy, maybeBind, maybeSetLocalizedDiagnosticMessages, @@ -195939,6 +183811,7 @@ if (typeof console !== "undefined") { noTransformers, noTruncationMaximumTruncationLength, nodeCanBeDecorated, + nodeCoreModules, nodeHasName, nodeIsDecorated, nodeIsMissing, @@ -196083,6 +183956,7 @@ if (typeof console !== "undefined") { returnTrue, returnUndefined, returnsPromise, + rewriteModuleSpecifier, sameFlatMap, sameMap, sameMapping, @@ -196128,6 +184002,7 @@ if (typeof console !== "undefined") { setValueDeclaration, shouldAllowImportingTsExtension, shouldPreserveConstEnums, + shouldRewriteModuleSpecifier, shouldUseUriStyleNodeCoreModules, showModuleSpecifier, signatureHasRestParameter, @@ -196185,6 +184060,7 @@ if (typeof console !== "undefined") { tagNamesAreEquivalent, takeWhile, targetOptionDeclaration, + targetToLibMap, testFormatSettings, textChangeRangeIsUnchanged, textChangeRangeNewSpan, @@ -196278,6 +184154,7 @@ if (typeof console !== "undefined") { tryRemoveExtension, tryRemovePrefix, tryRemoveSuffix, + tscBuildOption, typeAcquisitionDeclarations, typeAliasNamePart, typeDirectiveIsEqualTo, @@ -196289,6 +184166,7 @@ if (typeof console !== "undefined") { unescapeLeadingUnderscores, unmangleScopedPackageName, unorderedRemoveItem, + unprefixedNodeCoreModules, unreachableCodeIsError, unsetNodeChildren, unusedLabelIsError, diff --git a/cli/tsc/97_ts_host.js b/cli/tsc/97_ts_host.js index ba82a12b7c00f5..9bafe82dbbd522 100644 --- a/cli/tsc/97_ts_host.js +++ b/cli/tsc/97_ts_host.js @@ -234,7 +234,14 @@ function fromRelatedInformation({ } if (start !== undefined && length !== undefined && file) { let startPos = file.getLineAndCharacterOfPosition(start); - let sourceLine = file.getFullText().split("\n")[startPos.line]; + let endPos = file.getLineAndCharacterOfPosition(start + length); + // ok to get because it's cached via file.getLineAndCharacterOfPosition + const lineStarts = file.getLineStarts(); + /** @type {string | undefined} */ + let sourceLine = file.getFullText().slice( + lineStarts[startPos.line], + lineStarts[startPos.line + 1], + ).trimEnd(); const originalFileName = file.fileName; const fileName = ops.op_remap_specifier ? (ops.op_remap_specifier(file.fileName) ?? file.fileName) @@ -244,12 +251,12 @@ function fromRelatedInformation({ if ( fileName.endsWith(".wasm") && originalFileName.endsWith(".wasm.d.mts") ) { - startPos = { line: 0, character: 0 }; + startPos = endPos = { line: 0, character: 0 }; sourceLine = undefined; } return { start: startPos, - end: file.getLineAndCharacterOfPosition(start + length), + end: endPos, fileName, messageChain, messageText, @@ -296,6 +303,9 @@ const IGNORED_DIAGNOSTICS = [ // TS1479: 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'. 1479, + // TS1543: Importing a JSON file into an ECMAScript module requires a 'type: \"json\"' import + // attribute when 'module' is set to 'NodeNext'. + 1543, // TS2306: File '.../index.d.ts' is not a module. // We get this for `x-typescript-types` declaration files which don't export // anything. We prefer to treat these as modules with no exports. @@ -408,10 +418,6 @@ export const host = { return projectVersion; }, // @ts-ignore Undocumented method. - getModuleSpecifierCache() { - return moduleSpecifierCache; - }, - // @ts-ignore Undocumented method. getCachedExportInfoMap() { return exportMapCache; }, @@ -421,7 +427,7 @@ export const host = { // @ts-ignore Undocumented method. toPath(fileName) { // @ts-ignore Undocumented function. - ts.toPath( + return ts.toPath( fileName, this.getCurrentDirectory(), this.getCanonicalFileName.bind(this), @@ -716,9 +722,6 @@ export const host = { }, }; -// @ts-ignore Undocumented function. -const moduleSpecifierCache = ts.server.createModuleSpecifierCache(host); - // @ts-ignore Undocumented function. const exportMapCache = ts.createCacheableExportInfoMap(host); @@ -747,35 +750,6 @@ export function filterMapDiagnostic(diagnostic) { return false; } - // ignore diagnostics resulting from the `ImportMeta` declaration in deno merging with - // the one in @types/node. the types of the filename and dirname properties are different, - // which causes tsc to error. - const importMetaFilenameDirnameModifiersRe = - /^All declarations of '(filename|dirname)'/; - const importMetaFilenameDirnameTypesRe = - /^Subsequent property declarations must have the same type.\s+Property '(filename|dirname)'/; - // Declarations of X must have identical modifiers. - if (diagnostic.code === 2687) { - if ( - typeof diagnostic.messageText === "string" && - (importMetaFilenameDirnameModifiersRe.test(diagnostic.messageText)) && - (diagnostic.file?.fileName.startsWith("asset:///") || - diagnostic.file?.fileName?.includes("@types/node")) - ) { - return false; - } - } - // Subsequent property declarations must have the same type. - if (diagnostic.code === 2717) { - if ( - typeof diagnostic.messageText === "string" && - (importMetaFilenameDirnameTypesRe.test(diagnostic.messageText)) && - (diagnostic.file?.fileName.startsWith("asset:///") || - diagnostic.file?.fileName?.includes("@types/node")) - ) { - return false; - } - } // make the diagnostic for using an `export =` in an es module a warning if (diagnostic.code === 1203) { diagnostic.category = ts.DiagnosticCategory.Warning; @@ -789,33 +763,98 @@ export function filterMapDiagnostic(diagnostic) { } } } + return true; } // list of globals that should be kept in Node's globalThis -ts.deno.setNodeOnlyGlobalNames([ - "__dirname", - "__filename", - "Buffer", - "BufferConstructor", - "BufferEncoding", - "clearImmediate", - "clearInterval", - "clearTimeout", - "console", - "Console", - "ErrorConstructor", - "gc", - "Global", - "localStorage", - "queueMicrotask", - "RequestInit", - "ResponseInit", - "sessionStorage", - "setImmediate", - "setInterval", - "setTimeout", +ts.deno.setNodeOnlyGlobalNames( + new Set([ + "__dirname", + "__filename", + '"buffer"', + "Buffer", + "BufferConstructor", + "BufferEncoding", + "clearImmediate", + "clearInterval", + "clearTimeout", + "console", + "Console", + "crypto", + "ErrorConstructor", + "gc", + "Global", + "localStorage", + "queueMicrotask", + "RequestInit", + "ResponseInit", + "sessionStorage", + "setImmediate", + "setInterval", + "setTimeout", + ]), +); +// List of globals in @types/node that collide with Deno's types. +// When the `@types/node` package attempts to assign to these types +// if the type is already in the global symbol table, then assignment +// will be a no-op, but if the global type does not exist then the package can +// create the global. +const setTypesNodeIgnorableNames = new Set([ + "AbortController", + "AbortSignal", + "AsyncIteratorObject", + "atob", + "Blob", + "BroadcastChannel", + "btoa", + "ByteLengthQueuingStrategy", + "CompressionStream", + "CountQueuingStrategy", + "DecompressionStream", + "Disposable", + "DOMException", + "Event", + "EventSource", + "EventTarget", + "fetch", + "File", + "Float32Array", + "Float64Array", + "FormData", + "Headers", + "ImportMeta", + "MessageChannel", + "MessageEvent", + "MessagePort", + "performance", + "PerformanceEntry", + "PerformanceMark", + "PerformanceMeasure", + "ReadableByteStreamController", + "ReadableStream", + "ReadableStreamBYOBReader", + "ReadableStreamBYOBRequest", + "ReadableStreamDefaultController", + "ReadableStreamDefaultReader", + "ReadonlyArray", + "Request", + "Response", + "Storage", + "TextDecoder", + "TextDecoderStream", + "TextEncoder", + "TextEncoderStream", + "TransformStream", + "TransformStreamDefaultController", + "URL", + "URLSearchParams", + "WebSocket", + "WritableStream", + "WritableStreamDefaultController", + "WritableStreamDefaultWriter", ]); +ts.deno.setTypesNodeIgnorableNames(setTypesNodeIgnorableNames); export function getAssets() { /** @type {{ specifier: string; text: string; }[]} */ diff --git a/cli/tsc/dts/lib.decorators.d.ts b/cli/tsc/dts/lib.decorators.d.ts index 5ac09b8257186c..5ad7216a1a595e 100644 --- a/cli/tsc/dts/lib.decorators.d.ts +++ b/cli/tsc/dts/lib.decorators.d.ts @@ -110,9 +110,9 @@ interface ClassMethodDecoratorContext< }; /** - * Adds a callback to be invoked either before static initializers are run (when - * decorating a `static` element), or before instance initializers are run (when - * decorating a non-`static` element). + * Adds a callback to be invoked either after static methods are defined but before + * static initializers are run (when decorating a `static` element), or before instance + * initializers are run (when decorating a non-`static` element). * * @example * ```ts @@ -176,9 +176,9 @@ interface ClassGetterDecoratorContext< }; /** - * Adds a callback to be invoked either before static initializers are run (when - * decorating a `static` element), or before instance initializers are run (when - * decorating a non-`static` element). + * Adds a callback to be invoked either after static methods are defined but before + * static initializers are run (when decorating a `static` element), or before instance + * initializers are run (when decorating a non-`static` element). */ addInitializer(initializer: (this: This) => void): void; @@ -223,9 +223,9 @@ interface ClassSetterDecoratorContext< }; /** - * Adds a callback to be invoked either before static initializers are run (when - * decorating a `static` element), or before instance initializers are run (when - * decorating a non-`static` element). + * Adds a callback to be invoked either after static methods are defined but before + * static initializers are run (when decorating a `static` element), or before instance + * initializers are run (when decorating a non-`static` element). */ addInitializer(initializer: (this: This) => void): void; @@ -279,9 +279,8 @@ interface ClassAccessorDecoratorContext< }; /** - * Adds a callback to be invoked either before static initializers are run (when - * decorating a `static` element), or before instance initializers are run (when - * decorating a non-`static` element). + * Adds a callback to be invoked immediately after the auto `accessor` being + * decorated is initialized (regardless if the `accessor` is `static` or not). */ addInitializer(initializer: (this: This) => void): void; @@ -376,9 +375,8 @@ interface ClassFieldDecoratorContext< }; /** - * Adds a callback to be invoked either before static initializers are run (when - * decorating a `static` element), or before instance initializers are run (when - * decorating a non-`static` element). + * Adds a callback to be invoked immediately after the field being decorated + * is initialized (regardless if the field is `static` or not). */ addInitializer(initializer: (this: This) => void): void; diff --git a/cli/tsc/dts/lib.deno.ns.d.ts b/cli/tsc/dts/lib.deno.ns.d.ts index 7bfc3bb97b8ea9..76ca48b1a77f07 100644 --- a/cli/tsc/dts/lib.deno.ns.d.ts +++ b/cli/tsc/dts/lib.deno.ns.d.ts @@ -1786,7 +1786,7 @@ declare namespace Deno { * } * ``` */ - readonly readable: ReadableStream; + readonly readable: ReadableStream>; /** A {@linkcode WritableStream} instance to write the contents of the * file. This makes it easy to interoperate with other web streams based * APIs. @@ -1801,7 +1801,7 @@ declare namespace Deno { * } * ``` */ - readonly writable: WritableStream; + readonly writable: WritableStream>; /** Write the contents of the array buffer (`p`) to the file. * * Resolves to the number of bytes written. @@ -2268,7 +2268,7 @@ declare namespace Deno { */ close(): void; /** A readable stream interface to `stdin`. */ - readonly readable: ReadableStream; + readonly readable: ReadableStream>; /** * Set TTY to be under raw mode or not. In raw mode, characters are read and * returned as is, without being processed. All special processing of @@ -2346,7 +2346,7 @@ declare namespace Deno { */ close(): void; /** A writable stream interface to `stdout`. */ - readonly writable: WritableStream; + readonly writable: WritableStream>; /** * Checks if `stdout` is a TTY (terminal). * @@ -2410,7 +2410,7 @@ declare namespace Deno { */ close(): void; /** A writable stream interface to `stderr`. */ - readonly writable: WritableStream; + readonly writable: WritableStream>; /** * Checks if `stderr` is a TTY (terminal). * @@ -2921,7 +2921,7 @@ declare namespace Deno { export function readFile( path: string | URL, options?: ReadFileOptions, - ): Promise; + ): Promise>; /** Synchronously reads and returns the entire contents of a file as an array * of bytes. `TextDecoder` can be used to transform the bytes to string if @@ -2938,7 +2938,7 @@ declare namespace Deno { * @tags allow-read * @category File System */ - export function readFileSync(path: string | URL): Uint8Array; + export function readFileSync(path: string | URL): Uint8Array; /** Provides information about a file and is returned by * {@linkcode Deno.stat}, {@linkcode Deno.lstat}, {@linkcode Deno.statSync}, @@ -3731,9 +3731,9 @@ declare namespace Deno { * @category Subprocess */ export class ChildProcess implements AsyncDisposable { - get stdin(): WritableStream; - get stdout(): ReadableStream; - get stderr(): ReadableStream; + get stdin(): WritableStream>; + get stdout(): ReadableStream>; + get stderr(): ReadableStream>; readonly pid: number; /** Get the status of the child. */ readonly status: Promise; @@ -3845,9 +3845,9 @@ declare namespace Deno { */ export interface CommandOutput extends CommandStatus { /** The buffered output from the child process' `stdout`. */ - readonly stdout: Uint8Array; + readonly stdout: Uint8Array; /** The buffered output from the child process' `stderr`. */ - readonly stderr: Uint8Array; + readonly stderr: Uint8Array; } /** Option which can be specified when performing {@linkcode Deno.inspect}. diff --git a/cli/tsc/dts/lib.deno.unstable.d.ts b/cli/tsc/dts/lib.deno.unstable.d.ts index bd32845a6acb82..6c901b864c79fb 100644 --- a/cli/tsc/dts/lib.deno.unstable.d.ts +++ b/cli/tsc/dts/lib.deno.unstable.d.ts @@ -77,7 +77,8 @@ declare namespace Deno { * @category Network * @experimental */ - export interface DatagramConn extends AsyncIterable<[Uint8Array, Addr]> { + export interface DatagramConn + extends AsyncIterable<[Uint8Array, Addr]> { /** Joins an IPv4 multicast group. */ joinMulticastV4( address: string, @@ -95,7 +96,7 @@ declare namespace Deno { * Messages are received in the format of a tuple containing the data array * and the address information. */ - receive(p?: Uint8Array): Promise<[Uint8Array, Addr]>; + receive(p?: Uint8Array): Promise<[Uint8Array, Addr]>; /** Sends a message to the target via the connection. The method resolves * with the number of bytes sent. */ send(p: Uint8Array, addr: Addr): Promise; @@ -104,7 +105,9 @@ declare namespace Deno { close(): void; /** Return the address of the instance. */ readonly addr: Addr; - [Symbol.asyncIterator](): AsyncIterableIterator<[Uint8Array, Addr]>; + [Symbol.asyncIterator](): AsyncIterableIterator< + [Uint8Array, Addr] + >; } /** @@ -1402,8 +1405,8 @@ interface WebSocketStreamOptions { * @experimental */ interface WebSocketConnection { - readable: ReadableStream; - writable: WritableStream; + readable: ReadableStream>; + writable: WritableStream>; extensions: string; protocol: string; } @@ -2605,7 +2608,7 @@ declare namespace Temporal { * `Temporal.PlainDateTime` by combining it with a `Temporal.PlainDate` using the * `toPlainDateTime()` method. * - * See https://tc39.es/proposal-temporal/docs/time.html for more details. + * See https://tc39.es/proposal-temporal/docs/plaintime.html for more details. * * @category Temporal * @experimental @@ -3110,7 +3113,7 @@ declare namespace Intl { * @category Platform * @experimental */ -interface Float16Array { +interface Float16Array { /** * The size in bytes of each element in the array. */ @@ -3119,7 +3122,7 @@ interface Float16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBufferLike; + readonly buffer: TArrayBuffer; /** * The length in bytes of the array. @@ -3131,6 +3134,12 @@ interface Float16Array { */ readonly byteOffset: number; + /** + * Returns the item located at the specified index. + * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): number | undefined; + /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target @@ -3151,7 +3160,7 @@ interface Float16Array { * If thisArg is omitted, undefined is used as the this value. */ every( - predicate: (value: number, index: number, array: Float16Array) => unknown, + predicate: (value: number, index: number, array: this) => unknown, thisArg?: any, ): boolean; @@ -3173,9 +3182,9 @@ interface Float16Array { * If thisArg is omitted, undefined is used as the this value. */ filter( - predicate: (value: number, index: number, array: Float16Array) => any, + predicate: (value: number, index: number, array: this) => any, thisArg?: any, - ): Float16Array; + ): Float16Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -3187,7 +3196,7 @@ interface Float16Array { * predicate. If it is not provided, undefined is used instead. */ find( - predicate: (value: number, index: number, obj: Float16Array) => boolean, + predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any, ): number | undefined; @@ -3201,7 +3210,51 @@ interface Float16Array { * predicate. If it is not provided, undefined is used instead. */ findIndex( - predicate: (value: number, index: number, obj: Float16Array) => boolean, + predicate: (value: number, index: number, obj: this) => boolean, + thisArg?: any, + ): number; + + /** + * Returns the value of the last element in the array where predicate is true, and undefined + * otherwise. + * @param predicate findLast calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, findLast + * immediately returns that element value. Otherwise, findLast returns undefined. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLast( + predicate: ( + value: number, + index: number, + array: this, + ) => value is S, + thisArg?: any, + ): S | undefined; + findLast( + predicate: ( + value: number, + index: number, + array: this, + ) => unknown, + thisArg?: any, + ): number | undefined; + + /** + * Returns the index of the last element in the array where predicate is true, and -1 + * otherwise. + * @param predicate findLastIndex calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, + * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1. + * @param thisArg If provided, it will be used as the this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLastIndex( + predicate: ( + value: number, + index: number, + array: this, + ) => unknown, thisArg?: any, ): number; @@ -3213,10 +3266,17 @@ interface Float16Array { * If thisArg is omitted, undefined is used as the this value. */ forEach( - callbackfn: (value: number, index: number, array: Float16Array) => void, + callbackfn: (value: number, index: number, array: this) => void, thisArg?: any, ): void; + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement The element to search for. + * @param fromIndex The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; + /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. @@ -3254,9 +3314,9 @@ interface Float16Array { * If thisArg is omitted, undefined is used as the this value. */ map( - callbackfn: (value: number, index: number, array: Float16Array) => number, + callbackfn: (value: number, index: number, array: this) => number, thisArg?: any, - ): Float16Array; + ): Float16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3273,7 +3333,7 @@ interface Float16Array { previousValue: number, currentValue: number, currentIndex: number, - array: Float16Array, + array: this, ) => number, ): number; reduce( @@ -3281,7 +3341,7 @@ interface Float16Array { previousValue: number, currentValue: number, currentIndex: number, - array: Float16Array, + array: this, ) => number, initialValue: number, ): number; @@ -3301,7 +3361,7 @@ interface Float16Array { previousValue: U, currentValue: number, currentIndex: number, - array: Float16Array, + array: this, ) => U, initialValue: U, ): U; @@ -3321,7 +3381,7 @@ interface Float16Array { previousValue: number, currentValue: number, currentIndex: number, - array: Float16Array, + array: this, ) => number, ): number; reduceRight( @@ -3329,7 +3389,7 @@ interface Float16Array { previousValue: number, currentValue: number, currentIndex: number, - array: Float16Array, + array: this, ) => number, initialValue: number, ): number; @@ -3349,7 +3409,7 @@ interface Float16Array { previousValue: U, currentValue: number, currentIndex: number, - array: Float16Array, + array: this, ) => U, initialValue: U, ): U; @@ -3357,7 +3417,7 @@ interface Float16Array { /** * Reverses the elements in an Array. */ - reverse(): Float16Array; + reverse(): this; /** * Sets a value or an array of values. @@ -3371,7 +3431,7 @@ interface Float16Array { * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. */ - slice(start?: number, end?: number): Float16Array; + slice(start?: number, end?: number): Float16Array; /** * Determines whether the specified callback function returns true for any element of an array. @@ -3382,7 +3442,7 @@ interface Float16Array { * If thisArg is omitted, undefined is used as the this value. */ some( - predicate: (value: number, index: number, array: Float16Array) => unknown, + predicate: (value: number, index: number, array: this) => unknown, thisArg?: any, ): boolean; @@ -3403,12 +3463,34 @@ interface Float16Array { * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ - subarray(begin?: number, end?: number): Float16Array; + subarray(begin?: number, end?: number): Float16Array; /** * Converts a number to a string by using the current locale. */ - toLocaleString(): string; + toLocaleString( + locales?: string | string[], + options?: Intl.NumberFormatOptions, + ): string; + + /** + * Copies the array and returns the copy with the elements in reverse order. + */ + toReversed(): Float16Array; + + /** + * Copies and sorts the array. + * @param compareFn Function used to determine the order of the elements. It is expected to return + * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * const myNums = Float16Array.from([11.25, 2, -22.5, 1]); + * myNums.toSorted((a, b) => a - b) // Float16Array(4) [-22.5, 1, 2, 11.5] + * ``` + */ + toSorted( + compareFn?: (a: number, b: number) => number, + ): Float16Array; /** * Returns a string representation of an array. @@ -3416,9 +3498,37 @@ interface Float16Array { toString(): string; /** Returns the primitive value of the specified object. */ - valueOf(): Float16Array; + valueOf(): this; + + /** + * Copies the array and inserts the given number at the provided index. + * @param index The index of the value to overwrite. If the index is + * negative, then it replaces from the end of the array. + * @param value The value to insert into the copied array. + * @returns A copy of the original array with the inserted value. + */ + with(index: number, value: number): Float16Array; [index: number]: number; + + [Symbol.iterator](): ArrayIterator; + + /** + * Returns an array of key, value pairs for every entry in the array + */ + entries(): ArrayIterator<[number, number]>; + + /** + * Returns an list of keys in the array + */ + keys(): ArrayIterator; + + /** + * Returns an list of values in the array + */ + values(): ArrayIterator; + + readonly [Symbol.toStringTag]: "Float16Array"; } /** @@ -3426,14 +3536,14 @@ interface Float16Array { * @experimental */ interface Float16ArrayConstructor { - readonly prototype: Float16Array; - new (length: number): Float16Array; - new (array: ArrayLike | ArrayBufferLike): Float16Array; - new ( - buffer: ArrayBufferLike, + readonly prototype: Float16Array; + new (length?: number): Float16Array; + new (array: ArrayLike | Iterable): Float16Array; + new ( + buffer: TArrayBuffer, byteOffset?: number, length?: number, - ): Float16Array; + ): Float16Array; /** * The size in bytes of each element in the array. @@ -3444,17 +3554,17 @@ interface Float16ArrayConstructor { * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ - of(...items: number[]): Float16Array; + of(...items: number[]): Float16Array; /** * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. + * @param arrayLike An array-like object to convert to an array. */ - from(arrayLike: ArrayLike): Float16Array; + from(arrayLike: ArrayLike): Float16Array; /** * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. + * @param arrayLike An array-like object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ @@ -3462,181 +3572,61 @@ interface Float16ArrayConstructor { arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any, - ): Float16Array; -} -/** - * @category Platform - * @experimental - */ -declare var Float16Array: Float16ArrayConstructor; + ): Float16Array; -/** - * @category Platform - * @experimental - */ -interface Float16Array { - [Symbol.iterator](): IterableIterator; - /** - * Returns an array of key, value pairs for every entry in the array - */ - entries(): IterableIterator<[number, number]>; - /** - * Returns an list of keys in the array - */ - keys(): IterableIterator; /** - * Returns an list of values in the array + * Creates an array from an array-like or iterable object. + * @param elements An iterable object to convert to an array. */ - values(): IterableIterator; -} - -/** - * @category Platform - * @experimental - */ -interface Float16Constructor { - new (elements: Iterable): Float16Array; + from(elements: Iterable): Float16Array; /** * Creates an array from an array-like or iterable object. - * @param arrayLike An array-like or iterable object to convert to an array. + * @param elements An iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from( - arrayLike: Iterable, - mapfn?: (v: number, k: number) => number, + from( + elements: Iterable, + mapfn?: (v: T, k: number) => number, thisArg?: any, - ): Float16Array; -} - -/** - * @category Platform - * @experimental - */ -interface Float16Array { - readonly [Symbol.toStringTag]: "Float16Array"; -} - -/** - * @category Platform - * @experimental - */ -interface Float16Array { - /** - * Determines whether an array includes a certain element, returning true or false as appropriate. - * @param searchElement The element to search for. - * @param fromIndex The position in this array at which to begin searching for searchElement. - */ - includes(searchElement: number, fromIndex?: number): boolean; -} - -/** - * @category Platform - * @experimental - */ -interface Float16ArrayConstructor { - new (): Float16Array; + ): Float16Array; } /** * @category Platform * @experimental */ -interface Float16Array { - /** - * Returns the item located at the specified index. - * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. - */ - at(index: number): number | undefined; -} +declare var Float16Array: Float16ArrayConstructor; /** * @category Platform * @experimental */ -interface Float16Array { - /** - * Returns the value of the last element in the array where predicate is true, and undefined - * otherwise. - * @param predicate findLast calls predicate once for each element of the array, in descending - * order, until it finds one where predicate returns true. If such an element is found, findLast - * immediately returns that element value. Otherwise, findLast returns undefined. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findLast( - predicate: ( - value: number, - index: number, - array: Float16Array, - ) => value is S, - thisArg?: any, - ): S | undefined; - findLast( - predicate: ( - value: number, - index: number, - array: Float16Array, - ) => unknown, - thisArg?: any, - ): number | undefined; - - /** - * Returns the index of the last element in the array where predicate is true, and -1 - * otherwise. - * @param predicate findLastIndex calls predicate once for each element of the array, in descending - * order, until it finds one where predicate returns true. If such an element is found, - * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1. - * @param thisArg If provided, it will be used as the this value for each invocation of - * predicate. If it is not provided, undefined is used instead. - */ - findLastIndex( - predicate: ( - value: number, - index: number, - array: Float16Array, - ) => unknown, - thisArg?: any, - ): number; - +interface Math { /** - * Copies the array and returns the copy with the elements in reverse order. - */ - toReversed(): Float16Array; - - /** - * Copies and sorts the array. - * @param compareFn Function used to determine the order of the elements. It is expected to return - * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive - * value otherwise. If omitted, the elements are sorted in ascending order. - * ```ts - * const myNums = Float16Array.from([11.25, 2, -22.5, 1]); - * myNums.toSorted((a, b) => a - b) // Float16Array(4) [-22.5, 1, 2, 11.5] - * ``` - */ - toSorted(compareFn?: (a: number, b: number) => number): Float16Array; - - /** - * Copies the array and inserts the given number at the provided index. - * @param index The index of the value to overwrite. If the index is - * negative, then it replaces from the end of the array. - * @param value The value to insert into the copied array. - * @returns A copy of the original array with the inserted value. + * Returns the nearest half precision float representation of a number. + * @param x A numeric expression. + * + * @category Platform + * @experimental */ - with(index: number, value: number): Float16Array; + f16round(x: number): number; } /** * @category Platform * @experimental */ -interface DataView { +interface DataView { /** * Gets the Float16 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. * @param littleEndian If false or undefined, a big-endian value should be read. + * + * @category Platform + * @experimental */ getFloat16(byteOffset: number, littleEndian?: boolean): number; @@ -3645,6 +3635,9 @@ interface DataView { * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written. + * + * @category Platform + * @experimental */ setFloat16(byteOffset: number, value: number, littleEndian?: boolean): void; } diff --git a/cli/tsc/dts/lib.dom.d.ts b/cli/tsc/dts/lib.dom.d.ts index 2684735597a37a..9714699205c7b3 100644 --- a/cli/tsc/dts/lib.dom.d.ts +++ b/cli/tsc/dts/lib.dom.d.ts @@ -27,6 +27,19 @@ interface AddEventListenerOptions extends EventListenerOptions { signal?: AbortSignal; } +interface AddressErrors { + addressLine?: string; + city?: string; + country?: string; + dependentLocality?: string; + organization?: string; + phone?: string; + postalCode?: string; + recipient?: string; + region?: string; + sortingCode?: string; +} + interface AesCbcParams extends Algorithm { iv: BufferSource; } @@ -108,6 +121,59 @@ interface AudioContextOptions { sampleRate?: number; } +interface AudioDataCopyToOptions { + format?: AudioSampleFormat; + frameCount?: number; + frameOffset?: number; + planeIndex: number; +} + +interface AudioDataInit { + data: BufferSource; + format: AudioSampleFormat; + numberOfChannels: number; + numberOfFrames: number; + sampleRate: number; + timestamp: number; + transfer?: ArrayBuffer[]; +} + +interface AudioDecoderConfig { + codec: string; + description?: BufferSource; + numberOfChannels: number; + sampleRate: number; +} + +interface AudioDecoderInit { + error: WebCodecsErrorCallback; + output: AudioDataOutputCallback; +} + +interface AudioDecoderSupport { + config?: AudioDecoderConfig; + supported?: boolean; +} + +interface AudioEncoderConfig { + bitrate?: number; + bitrateMode?: BitrateMode; + codec: string; + numberOfChannels: number; + opus?: OpusEncoderConfig; + sampleRate: number; +} + +interface AudioEncoderInit { + error: WebCodecsErrorCallback; + output: EncodedAudioChunkOutputCallback; +} + +interface AudioEncoderSupport { + config?: AudioEncoderConfig; + supported?: boolean; +} + interface AudioNodeOptions { channelCount?: number; channelCountMode?: ChannelCountMode; @@ -138,12 +204,32 @@ interface AuthenticationExtensionsClientInputs { credProps?: boolean; hmacCreateSecret?: boolean; minPinLength?: boolean; + prf?: AuthenticationExtensionsPRFInputs; +} + +interface AuthenticationExtensionsClientInputsJSON { } interface AuthenticationExtensionsClientOutputs { appid?: boolean; credProps?: CredentialPropertiesOutput; hmacCreateSecret?: boolean; + prf?: AuthenticationExtensionsPRFOutputs; +} + +interface AuthenticationExtensionsPRFInputs { + eval?: AuthenticationExtensionsPRFValues; + evalByCredential?: Record; +} + +interface AuthenticationExtensionsPRFOutputs { + enabled?: boolean; + results?: AuthenticationExtensionsPRFValues; +} + +interface AuthenticationExtensionsPRFValues { + first: BufferSource; + second?: BufferSource; } interface AuthenticatorSelectionCriteria { @@ -209,6 +295,10 @@ interface CanvasRenderingContext2DSettings { willReadFrequently?: boolean; } +interface CaretPositionFromPointOptions { + shadowRoots?: ShadowRoot[]; +} + interface ChannelMergerOptions extends AudioNodeOptions { numberOfInputs?: number; } @@ -469,6 +559,18 @@ interface ElementDefinitionOptions { extends?: string; } +interface EncodedAudioChunkInit { + data: AllowSharedBufferSource; + duration?: number; + timestamp: number; + transfer?: ArrayBuffer[]; + type: EncodedAudioChunkType; +} + +interface EncodedAudioChunkMetadata { + decoderConfig?: AudioDecoderConfig; +} + interface EncodedVideoChunkInit { data: AllowSharedBufferSource; duration?: number; @@ -699,16 +801,6 @@ interface InputEventInit extends UIEventInit { targetRanges?: StaticRange[]; } -interface IntersectionObserverEntryInit { - boundingClientRect: DOMRectInit; - intersectionRatio: number; - intersectionRect: DOMRectInit; - isIntersecting: boolean; - rootBounds: DOMRectInit | null; - target: Element; - time: DOMHighResTimeStamp; -} - interface IntersectionObserverInit { root?: Element | Document | null; rootMargin?: string; @@ -918,6 +1010,7 @@ interface MediaStreamTrackEventInit extends EventInit { interface MediaTrackCapabilities { aspectRatio?: DoubleRange; autoGainControl?: boolean[]; + backgroundBlur?: boolean[]; channelCount?: ULongRange; deviceId?: string; displaySurface?: string; @@ -935,6 +1028,7 @@ interface MediaTrackCapabilities { interface MediaTrackConstraintSet { aspectRatio?: ConstrainDouble; autoGainControl?: ConstrainBoolean; + backgroundBlur?: ConstrainBoolean; channelCount?: ConstrainULong; deviceId?: ConstrainDOMString; displaySurface?: ConstrainDOMString; @@ -956,6 +1050,7 @@ interface MediaTrackConstraints extends MediaTrackConstraintSet { interface MediaTrackSettings { aspectRatio?: number; autoGainControl?: boolean; + backgroundBlur?: boolean; channelCount?: number; deviceId?: string; displaySurface?: string; @@ -973,6 +1068,7 @@ interface MediaTrackSettings { interface MediaTrackSupportedConstraints { aspectRatio?: boolean; autoGainControl?: boolean; + backgroundBlur?: boolean; channelCount?: boolean; deviceId?: boolean; displaySurface?: boolean; @@ -1067,6 +1163,15 @@ interface OptionalEffectTiming { playbackRate?: number; } +interface OpusEncoderConfig { + complexity?: number; + format?: OpusBitstreamFormat; + frameDuration?: number; + packetlossperc?: number; + usedtx?: boolean; + useinbandfec?: boolean; +} + interface OscillatorOptions extends AudioNodeOptions { detune?: number; frequency?: number; @@ -1095,6 +1200,12 @@ interface PannerOptions extends AudioNodeOptions { rolloffFactor?: number; } +interface PayerErrors { + email?: string; + name?: string; + phone?: string; +} + interface PaymentCurrencyAmount { currency: string; value: string; @@ -1103,6 +1214,7 @@ interface PaymentCurrencyAmount { interface PaymentDetailsBase { displayItems?: PaymentItem[]; modifiers?: PaymentDetailsModifier[]; + shippingOptions?: PaymentShippingOption[]; } interface PaymentDetailsInit extends PaymentDetailsBase { @@ -1118,7 +1230,9 @@ interface PaymentDetailsModifier { } interface PaymentDetailsUpdate extends PaymentDetailsBase { + error?: string; paymentMethodErrors?: any; + shippingAddressErrors?: AddressErrors; total?: PaymentItem; } @@ -1138,12 +1252,28 @@ interface PaymentMethodData { supportedMethods: string; } +interface PaymentOptions { + requestPayerEmail?: boolean; + requestPayerName?: boolean; + requestPayerPhone?: boolean; + requestShipping?: boolean; + shippingType?: PaymentShippingType; +} + interface PaymentRequestUpdateEventInit extends EventInit { } +interface PaymentShippingOption { + amount: PaymentCurrencyAmount; + id: string; + label: string; + selected?: boolean; +} + interface PaymentValidationErrors { error?: string; - paymentMethod?: any; + payer?: PayerErrors; + shippingAddress?: AddressErrors; } interface Pbkdf2Params extends Algorithm { @@ -1193,6 +1323,8 @@ interface PlaneLayout { } interface PointerEventInit extends MouseEventInit { + altitudeAngle?: number; + azimuthAngle?: number; coalescedEvents?: PointerEvent[]; height?: number; isPrimary?: boolean; @@ -1258,12 +1390,31 @@ interface PublicKeyCredentialCreationOptions { user: PublicKeyCredentialUserEntity; } +interface PublicKeyCredentialCreationOptionsJSON { + attestation?: string; + authenticatorSelection?: AuthenticatorSelectionCriteria; + challenge: Base64URLString; + excludeCredentials?: PublicKeyCredentialDescriptorJSON[]; + extensions?: AuthenticationExtensionsClientInputsJSON; + hints?: string[]; + pubKeyCredParams: PublicKeyCredentialParameters[]; + rp: PublicKeyCredentialRpEntity; + timeout?: number; + user: PublicKeyCredentialUserEntityJSON; +} + interface PublicKeyCredentialDescriptor { id: BufferSource; transports?: AuthenticatorTransport[]; type: PublicKeyCredentialType; } +interface PublicKeyCredentialDescriptorJSON { + id: Base64URLString; + transports?: string[]; + type: string; +} + interface PublicKeyCredentialEntity { name: string; } @@ -1282,6 +1433,16 @@ interface PublicKeyCredentialRequestOptions { userVerification?: UserVerificationRequirement; } +interface PublicKeyCredentialRequestOptionsJSON { + allowCredentials?: PublicKeyCredentialDescriptorJSON[]; + challenge: Base64URLString; + extensions?: AuthenticationExtensionsClientInputsJSON; + hints?: string[]; + rpId?: string; + timeout?: number; + userVerification?: string; +} + interface PublicKeyCredentialRpEntity extends PublicKeyCredentialEntity { id?: string; } @@ -1291,6 +1452,12 @@ interface PublicKeyCredentialUserEntity extends PublicKeyCredentialEntity { id: BufferSource; } +interface PublicKeyCredentialUserEntityJSON { + displayName: string; + id: Base64URLString; + name: string; +} + interface PushSubscriptionJSON { endpoint?: string; expirationTime?: EpochTimeStamp | null; @@ -2013,6 +2180,7 @@ interface VideoConfiguration { colorGamut?: ColorGamut; contentType: string; framerate: number; + hasAlphaChannel?: boolean; hdrMetadataType?: HdrMetadataType; height: number; scalabilityMode?: string; @@ -2048,6 +2216,7 @@ interface VideoEncoderConfig { bitrate?: number; bitrateMode?: VideoEncoderBitrateMode; codec: string; + contentHint?: string; displayHeight?: number; displayWidth?: number; framerate?: number; @@ -2059,9 +2228,14 @@ interface VideoEncoderConfig { } interface VideoEncoderEncodeOptions { + avc?: VideoEncoderEncodeOptionsForAvc; keyFrame?: boolean; } +interface VideoEncoderEncodeOptionsForAvc { + quantizer?: number | null; +} + interface VideoEncoderInit { error: WebCodecsErrorCallback; output: EncodedVideoChunkOutputCallback; @@ -2099,6 +2273,8 @@ interface VideoFrameCallbackMetadata { } interface VideoFrameCopyToOptions { + colorSpace?: PredefinedColorSpace; + format?: VideoPixelFormat; layout?: PlaneLayout[]; rect?: DOMRectInit; } @@ -2242,6 +2418,8 @@ interface ARIAMixin { ariaColCount: string | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaColIndex) */ ariaColIndex: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaColIndexText) */ + ariaColIndexText: string | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaColSpan) */ ariaColSpan: string | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaCurrent) */ @@ -2289,6 +2467,8 @@ interface ARIAMixin { ariaRowCount: string | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaRowIndex) */ ariaRowIndex: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaRowIndexText) */ + ariaRowIndexText: string | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaRowSpan) */ ariaRowSpan: string | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/ariaSelected) */ @@ -2465,7 +2645,7 @@ interface Animatable { interface AnimationEventMap { "cancel": AnimationPlaybackEvent; "finish": AnimationPlaybackEvent; - "remove": Event; + "remove": AnimationPlaybackEvent; } /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation) */ @@ -2483,7 +2663,7 @@ interface Animation extends EventTarget { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/finish_event) */ onfinish: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/remove_event) */ - onremove: ((this: Animation, ev: Event) => any) | null; + onremove: ((this: Animation, ev: AnimationPlaybackEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/pending) */ readonly pending: boolean; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Animation/playState) */ @@ -2715,6 +2895,74 @@ declare var AudioContext: { new(contextOptions?: AudioContextOptions): AudioContext; }; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData) */ +interface AudioData { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/duration) */ + readonly duration: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/format) */ + readonly format: AudioSampleFormat | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/numberOfChannels) */ + readonly numberOfChannels: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/numberOfFrames) */ + readonly numberOfFrames: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/sampleRate) */ + readonly sampleRate: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/timestamp) */ + readonly timestamp: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/allocationSize) */ + allocationSize(options: AudioDataCopyToOptions): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/clone) */ + clone(): AudioData; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/copyTo) */ + copyTo(destination: AllowSharedBufferSource, options: AudioDataCopyToOptions): void; +} + +declare var AudioData: { + prototype: AudioData; + new(init: AudioDataInit): AudioData; +}; + +interface AudioDecoderEventMap { + "dequeue": Event; +} + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder) + */ +interface AudioDecoder extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/decodeQueueSize) */ + readonly decodeQueueSize: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/dequeue_event) */ + ondequeue: ((this: AudioDecoder, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/state) */ + readonly state: CodecState; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/configure) */ + configure(config: AudioDecoderConfig): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/decode) */ + decode(chunk: EncodedAudioChunk): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/flush) */ + flush(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/reset) */ + reset(): void; + addEventListener(type: K, listener: (this: AudioDecoder, ev: AudioDecoderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioDecoder, ev: AudioDecoderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AudioDecoder: { + prototype: AudioDecoder; + new(init: AudioDecoderInit): AudioDecoder; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/isConfigSupported_static) */ + isConfigSupported(config: AudioDecoderConfig): Promise; +}; + /** * AudioDestinationNode has no output (as it is the output, no more AudioNode can be linked after it in the audio graph) and one input. The number of channels in the input must be between 0 and the maxChannelCount value or an exception is raised. * @@ -2730,6 +2978,45 @@ declare var AudioDestinationNode: { new(): AudioDestinationNode; }; +interface AudioEncoderEventMap { + "dequeue": Event; +} + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder) + */ +interface AudioEncoder extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/encodeQueueSize) */ + readonly encodeQueueSize: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/dequeue_event) */ + ondequeue: ((this: AudioEncoder, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/state) */ + readonly state: CodecState; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/configure) */ + configure(config: AudioEncoderConfig): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/encode) */ + encode(data: AudioData): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/flush) */ + flush(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/reset) */ + reset(): void; + addEventListener(type: K, listener: (this: AudioEncoder, ev: AudioEncoderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioEncoder, ev: AudioEncoderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AudioEncoder: { + prototype: AudioEncoder; + new(init: AudioEncoderInit): AudioEncoder; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/isConfigSupported_static) */ + isConfigSupported(config: AudioEncoderConfig): Promise; +}; + /** * The position and orientation of the unique person listening to the audio scene, and is used in audio spatialization. All PannerNodes spatialize in relation to the AudioListener stored in the BaseAudioContext.listener attribute. * @@ -2925,7 +3212,7 @@ declare var AudioWorklet: { }; interface AudioWorkletNodeEventMap { - "processorerror": Event; + "processorerror": ErrorEvent; } /** @@ -2935,7 +3222,7 @@ interface AudioWorkletNodeEventMap { */ interface AudioWorkletNode extends AudioNode { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioWorkletNode/processorerror_event) */ - onprocessorerror: ((this: AudioWorkletNode, ev: Event) => any) | null; + onprocessorerror: ((this: AudioWorkletNode, ev: ErrorEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioWorkletNode/parameters) */ readonly parameters: AudioParamMap; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioWorkletNode/port) */ @@ -3418,7 +3705,7 @@ interface CSSImportRule extends CSSRule { readonly layerName: string | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSImportRule/media) */ readonly media: MediaList; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSImportRule/stylesheet) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSImportRule/styleSheet) */ readonly styleSheet: CSSStyleSheet | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSImportRule/supportsText) */ readonly supportsText: string | null; @@ -3454,6 +3741,7 @@ declare var CSSKeyframeRule: { interface CSSKeyframesRule extends CSSRule { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSKeyframesRule/cssRules) */ readonly cssRules: CSSRuleList; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSKeyframesRule/length) */ readonly length: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSKeyframesRule/name) */ name: string; @@ -3711,7 +3999,7 @@ declare var CSSPerspective: { interface CSSPropertyRule extends CSSRule { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSPropertyRule/inherits) */ readonly inherits: boolean; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSPropertyRule/initialvalue) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSPropertyRule/initialValue) */ readonly initialValue: string | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSPropertyRule/name) */ readonly name: string; @@ -4102,11 +4390,13 @@ interface CSSStyleDeclaration { clip: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/clip-path) */ clipPath: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/clip-rule) */ clipRule: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/color) */ color: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/color-interpolation) */ colorInterpolation: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/color-interpolation-filters) */ colorInterpolationFilters: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/color-scheme) */ colorScheme: string; @@ -4132,9 +4422,11 @@ interface CSSStyleDeclaration { columns: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/contain) */ contain: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/contain-intrinsic-block-size) */ containIntrinsicBlockSize: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/contain-intrinsic-height) */ containIntrinsicHeight: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/contain-intrinsic-inline-size) */ containIntrinsicInlineSize: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/contain-intrinsic-size) */ containIntrinsicSize: string; @@ -4162,18 +4454,25 @@ interface CSSStyleDeclaration { cssText: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/cursor) */ cursor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/cx) */ cx: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/cy) */ cy: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/d) */ d: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/direction) */ direction: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/display) */ display: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/dominant-baseline) */ dominantBaseline: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/empty-cells) */ emptyCells: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/fill) */ fill: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/fill-opacity) */ fillOpacity: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/fill-rule) */ fillRule: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/filter) */ filter: string; @@ -4360,9 +4659,13 @@ interface CSSStyleDeclaration { marginRight: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/margin-top) */ marginTop: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/marker) */ marker: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/marker-end) */ markerEnd: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/marker-mid) */ markerMid: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/marker-start) */ markerStart: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/mask) */ mask: string; @@ -4512,6 +4815,7 @@ interface CSSStyleDeclaration { printColorAdjust: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/quotes) */ quotes: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/r) */ r: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/resize) */ resize: string; @@ -4521,9 +4825,13 @@ interface CSSStyleDeclaration { rotate: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/row-gap) */ rowGap: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/ruby-align) */ + rubyAlign: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/ruby-position) */ rubyPosition: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/rx) */ rx: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/ry) */ ry: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/scale) */ scale: string; @@ -4591,16 +4899,27 @@ interface CSSStyleDeclaration { shapeMargin: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/shape-outside) */ shapeOutside: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/shape-rendering) */ shapeRendering: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stop-color) */ stopColor: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stop-opacity) */ stopOpacity: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stroke) */ stroke: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stroke-dasharray) */ strokeDasharray: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stroke-dashoffset) */ strokeDashoffset: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stroke-linecap) */ strokeLinecap: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stroke-linejoin) */ strokeLinejoin: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stroke-miterlimit) */ strokeMiterlimit: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stroke-opacity) */ strokeOpacity: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/stroke-width) */ strokeWidth: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/tab-size) */ tabSize: string; @@ -4610,6 +4929,7 @@ interface CSSStyleDeclaration { textAlign: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-align-last) */ textAlignLast: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-anchor) */ textAnchor: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/text-combine-upright) */ textCombineUpright: string; @@ -4685,6 +5005,7 @@ interface CSSStyleDeclaration { unicodeBidi: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/user-select) */ userSelect: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/vector-effect) */ vectorEffect: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/vertical-align) */ verticalAlign: string; @@ -5114,7 +5435,9 @@ interface CSSStyleDeclaration { wordWrap: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/writing-mode) */ writingMode: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/x) */ x: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/y) */ y: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/CSS/z-index) */ zIndex: string; @@ -5652,6 +5975,18 @@ interface CanvasUserInterface { drawFocusIfNeeded(path: Path2D, element: Element): void; } +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CaretPosition) */ +interface CaretPosition { + readonly offset: number; + readonly offsetNode: Node; + getClientRect(): DOMRect | null; +} + +declare var CaretPosition: { + prototype: CaretPosition; + new(): CaretPosition; +}; + /** * The ChannelMergerNode interface, often used in conjunction with its opposite, ChannelSplitterNode, reunites different mono inputs into a single output. Each input is used to fill a channel of the output. This is useful for accessing each channels separately, e.g. for performing channel mixing where gain must be separately controlled on each channel. * @@ -5867,6 +6202,8 @@ declare var CompositionEvent: { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */ interface CompressionStream extends GenericTransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; } declare var CompressionStream: { @@ -6171,27 +6508,49 @@ declare var DOMImplementation: { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix) */ interface DOMMatrix extends DOMMatrixReadOnly { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ a: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ b: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ c: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ d: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ e: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ f: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m11: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m12: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m13: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m14: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m21: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m22: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m23: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m24: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m31: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m32: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m33: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m34: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m41: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m42: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m43: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m44: number; invertSelf(): DOMMatrix; multiplySelf(other?: DOMMatrixInit): DOMMatrix; @@ -6223,29 +6582,51 @@ declare var WebKitCSSMatrix: typeof DOMMatrix; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly) */ interface DOMMatrixReadOnly { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly a: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly b: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly c: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly d: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly e: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly f: number; readonly is2D: boolean; readonly isIdentity: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m11: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m12: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m13: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m14: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m21: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m22: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m23: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m24: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m31: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m32: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m33: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m34: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m41: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m42: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m43: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m44: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/flipX) */ flipX(): DOMMatrix; @@ -6717,6 +7098,8 @@ declare var DataTransferItemList: { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) */ interface DecompressionStream extends GenericTransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; } declare var DecompressionStream: { @@ -6979,6 +7362,8 @@ interface Document extends Node, DocumentOrShadowRoot, FontFaceSource, GlobalEve * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/forms) */ readonly forms: HTMLCollectionOf; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/fragmentDirective) */ + readonly fragmentDirective: FragmentDirective; /** * @deprecated * @@ -7123,6 +7508,8 @@ interface Document extends Node, DocumentOrShadowRoot, FontFaceSource, GlobalEve adoptNode(node: T): T; /** @deprecated */ captureEvents(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/caretPositionFromPoint) */ + caretPositionFromPoint(x: number, y: number, options?: CaretPositionFromPointOptions): CaretPosition | null; /** @deprecated */ caretRangeFromPoint(x: number, y: number): Range | null; /** @@ -7233,8 +7620,6 @@ interface Document extends Node, DocumentOrShadowRoot, FontFaceSource, GlobalEve createEvent(eventInterface: "MessageEvent"): MessageEvent; createEvent(eventInterface: "MouseEvent"): MouseEvent; createEvent(eventInterface: "MouseEvents"): MouseEvent; - createEvent(eventInterface: "MutationEvent"): MutationEvent; - createEvent(eventInterface: "MutationEvents"): MutationEvent; createEvent(eventInterface: "OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent; createEvent(eventInterface: "PageTransitionEvent"): PageTransitionEvent; createEvent(eventInterface: "PaymentMethodChangeEvent"): PaymentMethodChangeEvent; @@ -7441,7 +7826,7 @@ interface Document extends Node, DocumentOrShadowRoot, FontFaceSource, GlobalEve /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/requestStorageAccess) */ requestStorageAccess(): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/startViewTransition) */ - startViewTransition(callbackOptions?: UpdateCallback): ViewTransition; + startViewTransition(callbackOptions?: ViewTransitionUpdateCallback): ViewTransition; /** * Writes one or more HTML expressions to a document in the specified window. * @param content Specifies the text and HTML tags to write. @@ -7710,6 +8095,8 @@ interface Element extends Node, ARIAMixin, Animatable, ChildNode, NonDocumentTyp readonly clientTop: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/clientWidth) */ readonly clientWidth: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Element/currentCSSZoom) */ + readonly currentCSSZoom: number; /** * Returns the value of element's id content attribute. Can be set to change it. * @@ -8041,6 +8428,25 @@ declare var ElementInternals: { new(): ElementInternals; }; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk) */ +interface EncodedAudioChunk { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk/byteLength) */ + readonly byteLength: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk/duration) */ + readonly duration: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk/timestamp) */ + readonly timestamp: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk/type) */ + readonly type: EncodedAudioChunkType; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk/copyTo) */ + copyTo(destination: AllowSharedBufferSource): void; +} + +declare var EncodedAudioChunk: { + prototype: EncodedAudioChunk; + new(init: EncodedAudioChunkInit): EncodedAudioChunk; +}; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedVideoChunk) */ interface EncodedVideoChunk { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedVideoChunk/byteLength) */ @@ -8636,23 +9042,23 @@ interface FontFace { declare var FontFace: { prototype: FontFace; - new(family: string, source: string | BinaryData, descriptors?: FontFaceDescriptors): FontFace; + new(family: string, source: string | BufferSource, descriptors?: FontFaceDescriptors): FontFace; }; interface FontFaceSetEventMap { - "loading": Event; - "loadingdone": Event; - "loadingerror": Event; + "loading": FontFaceSetLoadEvent; + "loadingdone": FontFaceSetLoadEvent; + "loadingerror": FontFaceSetLoadEvent; } /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet) */ interface FontFaceSet extends EventTarget { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet/loading_event) */ - onloading: ((this: FontFaceSet, ev: Event) => any) | null; + onloading: ((this: FontFaceSet, ev: FontFaceSetLoadEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet/loadingdone_event) */ - onloadingdone: ((this: FontFaceSet, ev: Event) => any) | null; + onloadingdone: ((this: FontFaceSet, ev: FontFaceSetLoadEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet/loadingerror_event) */ - onloadingerror: ((this: FontFaceSet, ev: Event) => any) | null; + onloadingerror: ((this: FontFaceSet, ev: FontFaceSetLoadEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet/ready) */ readonly ready: Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet/status) */ @@ -8670,7 +9076,7 @@ interface FontFaceSet extends EventTarget { declare var FontFaceSet: { prototype: FontFaceSet; - new(initialFaces: FontFace[]): FontFaceSet; + new(): FontFaceSet; }; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSetLoadEvent) */ @@ -8734,6 +9140,15 @@ declare var FormDataEvent: { new(type: string, eventInitDict: FormDataEventInit): FormDataEvent; }; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FragmentDirective) */ +interface FragmentDirective { +} + +declare var FragmentDirective: { + prototype: FragmentDirective; + new(): FragmentDirective; +}; + /** * A change in volume. It is an AudioNode audio-processing module that causes a given gain to be applied to the input data before its propagation to the output. A GainNode always has exactly one input and one output, both with the same number of channels. * @@ -8798,7 +9213,7 @@ declare var GamepadButton: { }; /** - * This Gamepad API interface contains references to gamepads connected to the system, which is what the gamepad events globalThis.gamepadconnected and globalThis.gamepaddisconnected are fired in response to. + * This Gamepad API interface contains references to gamepads connected to the system, which is what the gamepad events Window.gamepadconnected and Window.gamepaddisconnected are fired in response to. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/GamepadEvent) */ @@ -8820,6 +9235,7 @@ declare var GamepadEvent: { interface GamepadHapticActuator { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GamepadHapticActuator/playEffect) */ playEffect(type: GamepadHapticEffectType, params?: GamepadEffectParameters): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/GamepadHapticActuator/reset) */ reset(): Promise; } @@ -9668,7 +10084,11 @@ declare var HTMLBRElement: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLBaseElement) */ interface HTMLBaseElement extends HTMLElement { - /** Gets or sets the baseline URL on which relative links are based. */ + /** + * Gets or sets the baseline URL on which relative links are based. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLBaseElement/href) + */ href: string; /** * Sets or retrieves the window or frame at which to target content. @@ -9727,7 +10147,11 @@ declare var HTMLBodyElement: { interface HTMLButtonElement extends HTMLElement, PopoverInvokerElement { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLButtonElement/disabled) */ disabled: boolean; - /** Retrieves a reference to the form that the object is embedded in. */ + /** + * Retrieves a reference to the form that the object is embedded in. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLButtonElement/form) + */ readonly form: HTMLFormElement | null; /** Overrides the action attribute (where the data on a form is sent) on the parent form element. */ formAction: string; @@ -9741,7 +10165,11 @@ interface HTMLButtonElement extends HTMLElement, PopoverInvokerElement { formTarget: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLButtonElement/labels) */ readonly labels: NodeListOf; - /** Sets or retrieves the name of the object. */ + /** + * Sets or retrieves the name of the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLButtonElement/name) + */ name: string; /** * Gets the classification and default behavior of the button. @@ -9749,20 +10177,43 @@ interface HTMLButtonElement extends HTMLElement, PopoverInvokerElement { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLButtonElement/type) */ type: "submit" | "reset" | "button"; - /** Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. */ + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLButtonElement/validationMessage) + */ readonly validationMessage: string; - /** Returns a ValidityState object that represents the validity states of an element. */ + /** + * Returns a ValidityState object that represents the validity states of an element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLButtonElement/validity) + */ readonly validity: ValidityState; - /** Sets or retrieves the default or selected value of the control. */ + /** + * Sets or retrieves the default or selected value of the control. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLButtonElement/value) + */ value: string; - /** Returns whether an element will successfully validate based on forms validation rules and constraints. */ + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLButtonElement/willValidate) + */ readonly willValidate: boolean; - /** Returns whether a form will validate when it is submitted, without having to submit it. */ + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLButtonElement/checkValidity) + */ checkValidity(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLButtonElement/reportValidity) */ reportValidity(): boolean; /** * Sets a custom error message that is displayed when a form is submitted. * @param error Sets a custom error message that is displayed when a form is submitted. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLButtonElement/setCustomValidity) */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLButtonElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -9914,7 +10365,11 @@ declare var HTMLDataElement: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLDataListElement) */ interface HTMLDataListElement extends HTMLElement { - /** Returns an HTMLCollection of the option elements of the datalist element. */ + /** + * Returns an HTMLCollection of the option elements of the datalist element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLDataListElement/options) + */ readonly options: HTMLCollectionOf; addEventListener(type: K, listener: (this: HTMLDataListElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -9929,6 +10384,7 @@ declare var HTMLDataListElement: { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLDetailsElement) */ interface HTMLDetailsElement extends HTMLElement { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLDetailsElement/open) */ name: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLDetailsElement/open) */ open: boolean; @@ -10075,6 +10531,7 @@ interface HTMLElement extends Element, ElementCSSInlineStyle, ElementContentEdit title: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/translate) */ translate: boolean; + writingSuggestions: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/attachInternals) */ attachInternals(): ElementInternals; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLElement/click) */ @@ -10146,26 +10603,59 @@ declare var HTMLEmbedElement: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFieldSetElement) */ interface HTMLFieldSetElement extends HTMLElement { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFieldSetElement/disabled) */ disabled: boolean; - /** Returns an HTMLCollection of the form controls in the element. */ + /** + * Returns an HTMLCollection of the form controls in the element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFieldSetElement/elements) + */ readonly elements: HTMLCollection; - /** Retrieves a reference to the form that the object is embedded in. */ + /** + * Retrieves a reference to the form that the object is embedded in. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFieldSetElement/form) + */ readonly form: HTMLFormElement | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFieldSetElement/name) */ name: string; - /** Returns the string "fieldset". */ + /** + * Returns the string "fieldset". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFieldSetElement/type) + */ readonly type: string; - /** Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. */ + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFieldSetElement/validationMessage) + */ readonly validationMessage: string; - /** Returns a ValidityState object that represents the validity states of an element. */ + /** + * Returns a ValidityState object that represents the validity states of an element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFieldSetElement/validity) + */ readonly validity: ValidityState; - /** Returns whether an element will successfully validate based on forms validation rules and constraints. */ + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFieldSetElement/willValidate) + */ readonly willValidate: boolean; - /** Returns whether a form will validate when it is submitted, without having to submit it. */ + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFieldSetElement/checkValidity) + */ checkValidity(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFieldSetElement/reportValidity) */ reportValidity(): boolean; /** * Sets a custom error message that is displayed when a form is submitted. * @param error Sets a custom error message that is displayed when a form is submitted. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFieldSetElement/setCustomValidity) */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLFieldSetElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -10304,7 +10794,11 @@ interface HTMLFormElement extends HTMLElement { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFormElement/target) */ target: string; - /** Returns whether a form will validate when it is submitted, without having to submit it. */ + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFormElement/checkValidity) + */ checkValidity(): boolean; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLFormElement/reportValidity) */ reportValidity(): boolean; @@ -10867,23 +11361,48 @@ declare var HTMLImageElement: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement) */ interface HTMLInputElement extends HTMLElement, PopoverInvokerElement { - /** Sets or retrieves a comma-separated list of content types. */ + /** + * Sets or retrieves a comma-separated list of content types. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/accept) + */ accept: string; /** * Sets or retrieves how the object is aligned with adjacent text. * @deprecated */ align: string; - /** Sets or retrieves a text alternative to the graphic. */ + /** + * Sets or retrieves a text alternative to the graphic. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/alt) + */ alt: string; - /** Specifies whether autocomplete is applied to an editable text field. */ + /** + * Specifies whether autocomplete is applied to an editable text field. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/autocomplete) + */ autocomplete: AutoFill; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/capture) */ capture: string; - /** Sets or retrieves the state of the check box or radio button. */ + /** + * Sets or retrieves the state of the check box or radio button. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/checked) + */ checked: boolean; - /** Sets or retrieves the state of the check box or radio button. */ + /** + * Sets or retrieves the state of the check box or radio button. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/defaultChecked) + */ defaultChecked: boolean; - /** Sets or retrieves the initial contents of the object. */ + /** + * Sets or retrieves the initial contents of the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/defaultValue) + */ defaultValue: string; dirName: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/disabled) */ @@ -10894,7 +11413,11 @@ interface HTMLInputElement extends HTMLElement, PopoverInvokerElement { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/files) */ files: FileList | null; - /** Retrieves a reference to the form that the object is embedded in. */ + /** + * Retrieves a reference to the form that the object is embedded in. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/form) + */ readonly form: HTMLFormElement | null; /** Overrides the action attribute (where the data on a form is sent) on the parent form element. */ formAction: string; @@ -10906,20 +11429,45 @@ interface HTMLInputElement extends HTMLElement, PopoverInvokerElement { formNoValidate: boolean; /** Overrides the target attribute on a form element. */ formTarget: string; - /** Sets or retrieves the height of the object. */ + /** + * Sets or retrieves the height of the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/height) + */ height: number; - /** When set, overrides the rendering of checkbox controls so that the current value is not visible. */ + /** + * When set, overrides the rendering of checkbox controls so that the current value is not visible. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/indeterminate) + */ indeterminate: boolean; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/labels) */ readonly labels: NodeListOf | null; - /** Specifies the ID of a pre-defined datalist of options for an input element. */ + /** + * Specifies the ID of a pre-defined datalist of options for an input element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/list) + */ readonly list: HTMLDataListElement | null; - /** Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. */ + /** + * Defines the maximum acceptable value for an input element with type="number".When used with the min and step attributes, lets you control the range and increment (such as only even numbers) that the user can enter into an input field. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/max) + */ max: string; - /** Sets or retrieves the maximum number of characters that the user can enter in a text control. */ + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/maxLength) + */ maxLength: number; - /** Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. */ + /** + * Defines the minimum acceptable value for an input element with type="number". When used with the max and step attributes, lets you control the range and increment (such as even numbers only) that the user can enter into an input field. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/min) + */ min: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/minLength) */ minLength: number; /** * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. @@ -10927,14 +11475,31 @@ interface HTMLInputElement extends HTMLElement, PopoverInvokerElement { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/multiple) */ multiple: boolean; - /** Sets or retrieves the name of the object. */ + /** + * Sets or retrieves the name of the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/name) + */ name: string; - /** Gets or sets a string containing a regular expression that the user's input must match. */ + /** + * Gets or sets a string containing a regular expression that the user's input must match. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/pattern) + */ pattern: string; - /** Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. */ + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/placeholder) + */ placeholder: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/readOnly) */ readOnly: boolean; - /** When present, marks an element that can't be submitted without a value. */ + /** + * When present, marks an element that can't be submitted without a value. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/required) + */ required: boolean; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/selectionDirection) */ selectionDirection: "forward" | "backward" | "none" | null; @@ -10950,10 +11515,19 @@ interface HTMLInputElement extends HTMLElement, PopoverInvokerElement { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/selectionStart) */ selectionStart: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/size) */ size: number; - /** The address or URL of the a media resource that is to be considered. */ + /** + * The address or URL of the a media resource that is to be considered. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/src) + */ src: string; - /** Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. */ + /** + * Defines an increment or jump between values that you want to allow the user to enter. When used with the max and min attributes, lets you control the range and increment (for example, allow only even numbers) that the user can enter into an input field. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/step) + */ step: string; /** * Returns the content type of the object. @@ -10966,23 +11540,51 @@ interface HTMLInputElement extends HTMLElement, PopoverInvokerElement { * @deprecated */ useMap: string; - /** Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. */ + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/validationMessage) + */ readonly validationMessage: string; - /** Returns a ValidityState object that represents the validity states of an element. */ + /** + * Returns a ValidityState object that represents the validity states of an element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/validity) + */ readonly validity: ValidityState; - /** Returns the value of the data at the cursor's current position. */ + /** + * Returns the value of the data at the cursor's current position. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/value) + */ value: string; - /** Returns a Date object representing the form control's value, if applicable; otherwise, returns null. Can be set, to change the value. Throws an "InvalidStateError" DOMException if the control isn't date- or time-based. */ + /** + * Returns a Date object representing the form control's value, if applicable; otherwise, returns null. Can be set, to change the value. Throws an "InvalidStateError" DOMException if the control isn't date- or time-based. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/valueAsDate) + */ valueAsDate: Date | null; - /** Returns the input field value as a number. */ + /** + * Returns the input field value as a number. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/valueAsNumber) + */ valueAsNumber: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/webkitEntries) */ readonly webkitEntries: ReadonlyArray; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/webkitdirectory) */ webkitdirectory: boolean; - /** Sets or retrieves the width of the object. */ + /** + * Sets or retrieves the width of the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/width) + */ width: number; - /** Returns whether an element will successfully validate based on forms validation rules and constraints. */ + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLInputElement/willValidate) + */ readonly willValidate: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. @@ -11108,7 +11710,11 @@ declare var HTMLLabelElement: { interface HTMLLegendElement extends HTMLElement { /** @deprecated */ align: string; - /** Retrieves a reference to the form that the object is embedded in. */ + /** + * Retrieves a reference to the form that the object is embedded in. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLLegendElement/form) + */ readonly form: HTMLFormElement | null; addEventListener(type: K, listener: (this: HTMLLegendElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -11140,7 +11746,11 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { disabled: boolean; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLLinkElement/fetchPriority) */ fetchPriority: string; - /** Sets or retrieves a destination URL or an anchor point. */ + /** + * Sets or retrieves a destination URL or an anchor point. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLLinkElement/href) + */ href: string; /** * Sets or retrieves the language code of the object. @@ -11152,7 +11762,11 @@ interface HTMLLinkElement extends HTMLElement, LinkStyle { imageSrcset: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLLinkElement/integrity) */ integrity: string; - /** Sets or retrieves the media type. */ + /** + * Sets or retrieves the media type. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLLinkElement/media) + */ media: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLLinkElement/referrerPolicy) */ referrerPolicy: string; @@ -11198,7 +11812,11 @@ declare var HTMLLinkElement: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMapElement) */ interface HTMLMapElement extends HTMLElement { - /** Retrieves a collection of the area objects defined for the given map object. */ + /** + * Retrieves a collection of the area objects defined for the given map object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMapElement/areas) + */ readonly areas: HTMLCollection; /** * Sets or retrieves the name of the object. @@ -11549,13 +12167,19 @@ declare var HTMLMetaElement: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMeterElement) */ interface HTMLMeterElement extends HTMLElement { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMeterElement/high) */ high: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMeterElement/labels) */ readonly labels: NodeListOf; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMeterElement/low) */ low: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMeterElement/max) */ max: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMeterElement/min) */ min: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMeterElement/optimum) */ optimum: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLMeterElement/value) */ value: number; addEventListener(type: K, listener: (this: HTMLMeterElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -11735,6 +12359,7 @@ interface HTMLObjectElement extends HTMLElement { */ checkValidity(): boolean; getSVGDocument(): Document | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLObjectElement/reportValidity) */ reportValidity(): boolean; /** * Sets a custom error message that is displayed when a form is submitted. @@ -11760,8 +12385,13 @@ declare var HTMLObjectElement: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOptGroupElement) */ interface HTMLOptGroupElement extends HTMLElement { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOptGroupElement/disabled) */ disabled: boolean; - /** Sets or retrieves a value that you can use to implement your own label functionality for the object. */ + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOptGroupElement/label) + */ label: string; addEventListener(type: K, listener: (this: HTMLOptGroupElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -11780,20 +12410,49 @@ declare var HTMLOptGroupElement: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOptionElement) */ interface HTMLOptionElement extends HTMLElement { - /** Sets or retrieves the status of an option. */ + /** + * Sets or retrieves the status of an option. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOptionElement/defaultSelected) + */ defaultSelected: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOptionElement/disabled) */ disabled: boolean; - /** Retrieves a reference to the form that the object is embedded in. */ + /** + * Retrieves a reference to the form that the object is embedded in. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOptionElement/form) + */ readonly form: HTMLFormElement | null; - /** Sets or retrieves the ordinal position of an option in a list box. */ + /** + * Sets or retrieves the ordinal position of an option in a list box. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOptionElement/index) + */ readonly index: number; - /** Sets or retrieves a value that you can use to implement your own label functionality for the object. */ + /** + * Sets or retrieves a value that you can use to implement your own label functionality for the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOptionElement/label) + */ label: string; - /** Sets or retrieves whether the option in the list box is the default item. */ + /** + * Sets or retrieves whether the option in the list box is the default item. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOptionElement/selected) + */ selected: boolean; - /** Sets or retrieves the text string specified by the option tag. */ + /** + * Sets or retrieves the text string specified by the option tag. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOptionElement/text) + */ text: string; - /** Sets or retrieves the value which is returned to the server when the form control is submitted. */ + /** + * Sets or retrieves the value which is returned to the server when the form control is submitted. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOptionElement/value) + */ value: string; addEventListener(type: K, listener: (this: HTMLOptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -11867,24 +12526,38 @@ interface HTMLOrSVGElement { */ interface HTMLOutputElement extends HTMLElement { defaultValue: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOutputElement/form) */ readonly form: HTMLFormElement | null; readonly htmlFor: DOMTokenList; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOutputElement/labels) */ readonly labels: NodeListOf; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOutputElement/name) */ name: string; - /** Returns the string "output". */ + /** + * Returns the string "output". + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOutputElement/type) + */ readonly type: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOutputElement/validationMessage) */ readonly validationMessage: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOutputElement/validity) */ readonly validity: ValidityState; /** * Returns the element's current value. * * Can be set, to change the value. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOutputElement/value) */ value: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOutputElement/willValidate) */ readonly willValidate: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOutputElement/checkValidity) */ checkValidity(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOutputElement/reportValidity) */ reportValidity(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLOutputElement/setCustomValidity) */ setCustomValidity(error: string): void; addEventListener(type: K, listener: (this: HTMLOutputElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; @@ -12140,11 +12813,23 @@ interface HTMLSelectElement extends HTMLElement { readonly form: HTMLFormElement | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLSelectElement/labels) */ readonly labels: NodeListOf; - /** Sets or retrieves the number of objects in a collection. */ + /** + * Sets or retrieves the number of objects in a collection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLSelectElement/length) + */ length: number; - /** Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. */ + /** + * Sets or retrieves the Boolean value indicating whether multiple items can be selected from a list. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLSelectElement/multiple) + */ multiple: boolean; - /** Sets or retrieves the name of the object. */ + /** + * Sets or retrieves the name of the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLSelectElement/name) + */ name: string; /** * Returns an HTMLOptionsCollection of the list of options. @@ -12152,7 +12837,11 @@ interface HTMLSelectElement extends HTMLElement { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLSelectElement/options) */ readonly options: HTMLOptionsCollection; - /** When present, marks an element that can't be submitted without a value. */ + /** + * When present, marks an element that can't be submitted without a value. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLSelectElement/required) + */ required: boolean; /** * Sets or retrieves the index of the selected option in a select object. @@ -12162,7 +12851,11 @@ interface HTMLSelectElement extends HTMLElement { selectedIndex: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLSelectElement/selectedOptions) */ readonly selectedOptions: HTMLCollectionOf; - /** Sets or retrieves the number of rows in the list box. */ + /** + * Sets or retrieves the number of rows in the list box. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLSelectElement/size) + */ size: number; /** * Retrieves the type of select control based on the value of the MULTIPLE attribute. @@ -12170,9 +12863,17 @@ interface HTMLSelectElement extends HTMLElement { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLSelectElement/type) */ readonly type: "select-one" | "select-multiple"; - /** Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. */ + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLSelectElement/validationMessage) + */ readonly validationMessage: string; - /** Returns a ValidityState object that represents the validity states of an element. */ + /** + * Returns a ValidityState object that represents the validity states of an element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLSelectElement/validity) + */ readonly validity: ValidityState; /** * Sets or retrieves the value which is returned to the server when the form control is submitted. @@ -12180,7 +12881,11 @@ interface HTMLSelectElement extends HTMLElement { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLSelectElement/value) */ value: string; - /** Returns whether an element will successfully validate based on forms validation rules and constraints. */ + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLSelectElement/willValidate) + */ readonly willValidate: boolean; /** * Adds an element to the areas, controlRange, or options collection. @@ -12219,6 +12924,7 @@ interface HTMLSelectElement extends HTMLElement { */ remove(): void; remove(index: number): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLSelectElement/reportValidity) */ reportValidity(): boolean; /** * Sets a custom error message that is displayed when a form is submitted. @@ -12353,6 +13059,8 @@ interface HTMLTableCaptionElement extends HTMLElement { /** * Sets or retrieves the alignment of the caption or legend. * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTableCaptionElement/align) */ align: string; addEventListener(type: K, listener: (this: HTMLTableCaptionElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -12715,6 +13423,8 @@ interface HTMLTableRowElement extends HTMLElement { /** * Sets or retrieves how the object is aligned with adjacent text. * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTableRowElement/align) */ align: string; /** @@ -12753,7 +13463,11 @@ interface HTMLTableRowElement extends HTMLElement { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTableRowElement/sectionRowIndex) */ readonly sectionRowIndex: number; - /** @deprecated */ + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTableRowElement/vAlign) + */ vAlign: string; /** * Removes the specified cell from the table row, as well as from the cells collection. @@ -12789,6 +13503,8 @@ interface HTMLTableSectionElement extends HTMLElement { /** * Sets or retrieves a value that indicates the table alignment. * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTableSectionElement/align) */ align: string; /** @@ -12809,7 +13525,11 @@ interface HTMLTableSectionElement extends HTMLElement { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTableSectionElement/rows) */ readonly rows: HTMLCollectionOf; - /** @deprecated */ + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTableSectionElement/vAlign) + */ vAlign: string; /** * Removes the specified row (tr) from the element and from the rows collection. @@ -12873,35 +13593,84 @@ declare var HTMLTemplateElement: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement) */ interface HTMLTextAreaElement extends HTMLElement { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/autocomplete) */ autocomplete: AutoFill; - /** Sets or retrieves the width of the object. */ + /** + * Sets or retrieves the width of the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/cols) + */ cols: number; - /** Sets or retrieves the initial contents of the object. */ + /** + * Sets or retrieves the initial contents of the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/defaultValue) + */ defaultValue: string; dirName: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/disabled) */ disabled: boolean; - /** Retrieves a reference to the form that the object is embedded in. */ + /** + * Retrieves a reference to the form that the object is embedded in. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/form) + */ readonly form: HTMLFormElement | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/labels) */ readonly labels: NodeListOf; - /** Sets or retrieves the maximum number of characters that the user can enter in a text control. */ + /** + * Sets or retrieves the maximum number of characters that the user can enter in a text control. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/maxLength) + */ maxLength: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/minLength) */ minLength: number; - /** Sets or retrieves the name of the object. */ + /** + * Sets or retrieves the name of the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/name) + */ name: string; - /** Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. */ + /** + * Gets or sets a text string that is displayed in an input field as a hint or prompt to users as the format or type of information they need to enter.The text appears in an input field until the user puts focus on the field. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/placeholder) + */ placeholder: string; - /** Sets or retrieves the value indicated whether the content of the object is read-only. */ + /** + * Sets or retrieves the value indicated whether the content of the object is read-only. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/readOnly) + */ readOnly: boolean; - /** When present, marks an element that can't be submitted without a value. */ + /** + * When present, marks an element that can't be submitted without a value. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/required) + */ required: boolean; - /** Sets or retrieves the number of horizontal rows contained in the object. */ + /** + * Sets or retrieves the number of horizontal rows contained in the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/rows) + */ rows: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/selectionDirection) */ selectionDirection: "forward" | "backward" | "none"; - /** Gets or sets the end position or offset of a text selection. */ + /** + * Gets or sets the end position or offset of a text selection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/selectionEnd) + */ selectionEnd: number; - /** Gets or sets the starting position or offset of a text selection. */ + /** + * Gets or sets the starting position or offset of a text selection. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/selectionStart) + */ selectionStart: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/textLength) */ readonly textLength: number; /** * Retrieves the type of control. @@ -12909,26 +13678,58 @@ interface HTMLTextAreaElement extends HTMLElement { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/type) */ readonly type: string; - /** Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. */ + /** + * Returns the error message that would be displayed if the user submits the form, or an empty string if no error message. It also triggers the standard error message, such as "this is a required field". The result is that the user sees validation messages without actually submitting. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/validationMessage) + */ readonly validationMessage: string; - /** Returns a ValidityState object that represents the validity states of an element. */ + /** + * Returns a ValidityState object that represents the validity states of an element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/validity) + */ readonly validity: ValidityState; - /** Retrieves or sets the text in the entry field of the textArea element. */ + /** + * Retrieves or sets the text in the entry field of the textArea element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/value) + */ value: string; - /** Returns whether an element will successfully validate based on forms validation rules and constraints. */ + /** + * Returns whether an element will successfully validate based on forms validation rules and constraints. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/willValidate) + */ readonly willValidate: boolean; - /** Sets or retrieves how to handle wordwrapping in the object. */ + /** + * Sets or retrieves how to handle wordwrapping in the object. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/wrap) + */ wrap: string; - /** Returns whether a form will validate when it is submitted, without having to submit it. */ + /** + * Returns whether a form will validate when it is submitted, without having to submit it. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/checkValidity) + */ checkValidity(): boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/reportValidity) */ reportValidity(): boolean; - /** Highlights the input area of a form element. */ + /** + * Highlights the input area of a form element. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/select) + */ select(): void; /** * Sets a custom error message that is displayed when a form is submitted. * @param error Sets a custom error message that is displayed when a form is submitted. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/setCustomValidity) */ setCustomValidity(error: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/setRangeText) */ setRangeText(replacement: string): void; setRangeText(replacement: string, start: number, end: number, selectionMode?: SelectionMode): void; /** @@ -12936,6 +13737,8 @@ interface HTMLTextAreaElement extends HTMLElement { * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. * @param direction The direction in which the selection is performed. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLTextAreaElement/setSelectionRange) */ setSelectionRange(start: number | null, end: number | null, direction?: "forward" | "backward" | "none"): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; @@ -13064,8 +13867,8 @@ declare var HTMLUnknownElement: { }; interface HTMLVideoElementEventMap extends HTMLMediaElementEventMap { - "enterpictureinpicture": Event; - "leavepictureinpicture": Event; + "enterpictureinpicture": PictureInPictureEvent; + "leavepictureinpicture": PictureInPictureEvent; } /** @@ -13083,9 +13886,9 @@ interface HTMLVideoElement extends HTMLMediaElement { */ height: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement/enterpictureinpicture_event) */ - onenterpictureinpicture: ((this: HTMLVideoElement, ev: Event) => any) | null; + onenterpictureinpicture: ((this: HTMLVideoElement, ev: PictureInPictureEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLVideoElement/leavepictureinpicture_event) */ - onleavepictureinpicture: ((this: HTMLVideoElement, ev: Event) => any) | null; + onleavepictureinpicture: ((this: HTMLVideoElement, ev: PictureInPictureEvent) => any) | null; /** Gets or sets the playsinline of the video element. for example, On iPhone, video elements will now be allowed to play inline, and will not automatically enter fullscreen mode when playback begins. */ playsInline: boolean; /** @@ -13864,7 +14667,7 @@ interface IDBTransaction extends EventTarget { /** * Returns a list of the names of object stores in the transaction's scope. For an upgrade transaction this is all object stores in the database. * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBTransaction/ObjectStoreNames) + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBTransaction/objectStoreNames) */ readonly objectStoreNames: DOMStringList; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBTransaction/abort_event) */ @@ -13972,7 +14775,11 @@ declare var ImageBitmap: { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageBitmapRenderingContext) */ interface ImageBitmapRenderingContext { - /** Returns the canvas element that the context is bound to. */ + /** + * Returns the canvas element that the context is bound to. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ImageBitmapRenderingContext/canvas) + */ readonly canvas: HTMLCanvasElement | OffscreenCanvas; /** * Transfers the underlying bitmap data from imageBitmap to context, and the bitmap becomes the contents of the canvas element to which context is bound. @@ -14111,7 +14918,7 @@ interface IntersectionObserverEntry { declare var IntersectionObserverEntry: { prototype: IntersectionObserverEntry; - new(intersectionObserverEntryInit: IntersectionObserverEntryInit): IntersectionObserverEntry; + new(): IntersectionObserverEntry; }; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/KHR_parallel_shader_compile) */ @@ -14372,7 +15179,7 @@ declare var LockManager: { }; interface MIDIAccessEventMap { - "statechange": Event; + "statechange": MIDIConnectionEvent; } /** @@ -14384,7 +15191,7 @@ interface MIDIAccess extends EventTarget { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/MIDIAccess/inputs) */ readonly inputs: MIDIInputMap; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/MIDIAccess/statechange_event) */ - onstatechange: ((this: MIDIAccess, ev: Event) => any) | null; + onstatechange: ((this: MIDIAccess, ev: MIDIConnectionEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/MIDIAccess/outputs) */ readonly outputs: MIDIOutputMap; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/MIDIAccess/sysexEnabled) */ @@ -14792,6 +15599,7 @@ declare var MediaKeySystemAccess: { interface MediaKeys { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/MediaKeys/createSession) */ createSession(sessionType?: MediaKeySessionType): MediaKeySession; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/MediaKeys/getStatusForPolicy) */ getStatusForPolicy(policy?: MediaKeysPolicy): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/MediaKeys/setServerCertificate) */ setServerCertificate(serverCertificate: BufferSource): Promise; @@ -14894,7 +15702,7 @@ declare var MediaQueryListEvent: { interface MediaRecorderEventMap { "dataavailable": BlobEvent; - "error": Event; + "error": ErrorEvent; "pause": Event; "resume": Event; "start": Event; @@ -14910,7 +15718,7 @@ interface MediaRecorder extends EventTarget { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/MediaRecorder/dataavailable_event) */ ondataavailable: ((this: MediaRecorder, ev: BlobEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/MediaRecorder/error_event) */ - onerror: ((this: MediaRecorder, ev: Event) => any) | null; + onerror: ((this: MediaRecorder, ev: ErrorEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/MediaRecorder/pause_event) */ onpause: ((this: MediaRecorder, ev: Event) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/MediaRecorder/resume_event) */ @@ -15401,63 +16209,6 @@ declare var MouseEvent: { new(type: string, eventInitDict?: MouseEventInit): MouseEvent; }; -/** - * Provides event properties that are specific to modifications to the Document Object Model (DOM) hierarchy and nodes. - * @deprecated DOM4 [DOM] provides a new mechanism using a MutationObserver interface which addresses the use cases that mutation events solve, but in a more performant manner. Thus, this specification describes mutation events for reference and completeness of legacy behavior, but deprecates the use of the MutationEvent interface. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MutationEvent) - */ -interface MutationEvent extends Event { - /** - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MutationEvent/attrChange) - */ - readonly attrChange: number; - /** - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MutationEvent/attrName) - */ - readonly attrName: string; - /** - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MutationEvent/newValue) - */ - readonly newValue: string; - /** - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MutationEvent/prevValue) - */ - readonly prevValue: string; - /** - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MutationEvent/relatedNode) - */ - readonly relatedNode: Node | null; - /** - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MutationEvent/initMutationEvent) - */ - initMutationEvent(typeArg: string, bubblesArg?: boolean, cancelableArg?: boolean, relatedNodeArg?: Node | null, prevValueArg?: string, newValueArg?: string, attrNameArg?: string, attrChangeArg?: number): void; - readonly MODIFICATION: 1; - readonly ADDITION: 2; - readonly REMOVAL: 3; -} - -/** @deprecated */ -declare var MutationEvent: { - prototype: MutationEvent; - new(): MutationEvent; - readonly MODIFICATION: 1; - readonly ADDITION: 2; - readonly REMOVAL: 3; -}; - /** * Provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature which was part of the DOM3 Events specification. * @@ -16267,7 +17018,7 @@ interface OES_vertex_array_object { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/OES_vertex_array_object/bindVertexArrayOES) */ bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/OES_vertex_array_object/createVertexArrayOES) */ - createVertexArrayOES(): WebGLVertexArrayObjectOES | null; + createVertexArrayOES(): WebGLVertexArrayObjectOES; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/OES_vertex_array_object/deleteVertexArrayOES) */ deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/OES_vertex_array_object/isVertexArrayOES) */ @@ -16400,6 +17151,7 @@ declare var OffscreenCanvas: { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/OffscreenCanvasRenderingContext2D) */ interface OffscreenCanvasRenderingContext2D extends CanvasCompositing, CanvasDrawImage, CanvasDrawPath, CanvasFillStrokeStyles, CanvasFilters, CanvasImageData, CanvasImageSmoothing, CanvasPath, CanvasPathDrawingStyles, CanvasRect, CanvasShadowStyles, CanvasState, CanvasText, CanvasTextDrawingStyles, CanvasTransform { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/canvas) */ readonly canvas: OffscreenCanvas; } @@ -16613,6 +17365,37 @@ declare var Path2D: { new(path?: Path2D | string): Path2D; }; +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ContactAddress) */ +interface PaymentAddress { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ContactAddress/addressLine) */ + readonly addressLine: ReadonlyArray; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ContactAddress/city) */ + readonly city: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ContactAddress/country) */ + readonly country: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ContactAddress/dependentLocality) */ + readonly dependentLocality: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ContactAddress/organization) */ + readonly organization: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ContactAddress/phone) */ + readonly phone: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ContactAddress/postalCode) */ + readonly postalCode: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ContactAddress/recipient) */ + readonly recipient: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ContactAddress/region) */ + readonly region: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ContactAddress/sortingCode) */ + readonly sortingCode: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ContactAddress/toJSON) */ + toJSON(): any; +} + +declare var PaymentAddress: { + prototype: PaymentAddress; + new(): PaymentAddress; +}; + /** * Available only in secure contexts. * @@ -16631,7 +17414,9 @@ declare var PaymentMethodChangeEvent: { }; interface PaymentRequestEventMap { - "paymentmethodchange": Event; + "paymentmethodchange": PaymentMethodChangeEvent; + "shippingaddresschange": PaymentRequestUpdateEvent; + "shippingoptionchange": PaymentRequestUpdateEvent; } /** @@ -16644,7 +17429,37 @@ interface PaymentRequest extends EventTarget { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentRequest/id) */ readonly id: string; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentRequest/paymentmethodchange_event) */ - onpaymentmethodchange: ((this: PaymentRequest, ev: Event) => any) | null; + onpaymentmethodchange: ((this: PaymentRequest, ev: PaymentMethodChangeEvent) => any) | null; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentRequest/shippingaddresschange_event) + */ + onshippingaddresschange: ((this: PaymentRequest, ev: PaymentRequestUpdateEvent) => any) | null; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentRequest/shippingoptionchange_event) + */ + onshippingoptionchange: ((this: PaymentRequest, ev: PaymentRequestUpdateEvent) => any) | null; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentRequest/shippingAddress) + */ + readonly shippingAddress: PaymentAddress | null; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentRequest/shippingOption) + */ + readonly shippingOption: string | null; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentRequest/shippingType) + */ + readonly shippingType: PaymentShippingType | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentRequest/abort) */ abort(): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentRequest/canMakePayment) */ @@ -16659,7 +17474,7 @@ interface PaymentRequest extends EventTarget { declare var PaymentRequest: { prototype: PaymentRequest; - new(methodData: PaymentMethodData[], details: PaymentDetailsInit): PaymentRequest; + new(methodData: PaymentMethodData[], details: PaymentDetailsInit, options?: PaymentOptions): PaymentRequest; }; /** @@ -16678,6 +17493,10 @@ declare var PaymentRequestUpdateEvent: { new(type: string, eventInitDict?: PaymentRequestUpdateEventInit): PaymentRequestUpdateEvent; }; +interface PaymentResponseEventMap { + "payerdetailchange": PaymentRequestUpdateEvent; +} + /** * This Payment Request API interface is returned after a user selects a payment method and approves a payment request. * Available only in secure contexts. @@ -16689,14 +17508,30 @@ interface PaymentResponse extends EventTarget { readonly details: any; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentResponse/methodName) */ readonly methodName: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentResponse/payerdetailchange_event) */ + onpayerdetailchange: ((this: PaymentResponse, ev: PaymentRequestUpdateEvent) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentResponse/payerEmail) */ + readonly payerEmail: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentResponse/payerName) */ + readonly payerName: string | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentResponse/payerPhone) */ + readonly payerPhone: string | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentResponse/requestId) */ readonly requestId: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentResponse/shippingAddress) */ + readonly shippingAddress: PaymentAddress | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentResponse/shippingOption) */ + readonly shippingOption: string | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentResponse/complete) */ complete(result?: PaymentComplete): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentResponse/retry) */ retry(errorFields?: PaymentValidationErrors): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PaymentResponse/toJSON) */ toJSON(): any; + addEventListener(type: K, listener: (this: PaymentResponse, ev: PaymentResponseEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: PaymentResponse, ev: PaymentResponseEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } declare var PaymentResponse: { @@ -16988,6 +17823,8 @@ interface PerformanceResourceTiming extends PerformanceEntry { readonly responseEnd: DOMHighResTimeStamp; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/responseStart) */ readonly responseStart: DOMHighResTimeStamp; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/responseStatus) */ + readonly responseStatus: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/secureConnectionStart) */ readonly secureConnectionStart: DOMHighResTimeStamp; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/serverTiming) */ @@ -17323,6 +18160,10 @@ declare var PluginArray: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PointerEvent) */ interface PointerEvent extends MouseEvent { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PointerEvent/altitudeAngle) */ + readonly altitudeAngle: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PointerEvent/azimuthAngle) */ + readonly azimuthAngle: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PointerEvent/height) */ readonly height: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PointerEvent/isPrimary) */ @@ -17448,15 +18289,21 @@ interface PublicKeyCredential extends Credential { readonly response: AuthenticatorResponse; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PublicKeyCredential/getClientExtensionResults) */ getClientExtensionResults(): AuthenticationExtensionsClientOutputs; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PublicKeyCredential/toJSON) */ + toJSON(): PublicKeyCredentialJSON; } declare var PublicKeyCredential: { prototype: PublicKeyCredential; new(): PublicKeyCredential; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PublicKeyCredential/isConditionalMediationAvailable) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PublicKeyCredential/isConditionalMediationAvailable_static) */ isConditionalMediationAvailable(): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PublicKeyCredential/isUserVerifyingPlatformAuthenticatorAvailable_static) */ isUserVerifyingPlatformAuthenticatorAvailable(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PublicKeyCredential/parseCreationOptionsFromJSON_static) */ + parseCreationOptionsFromJSON(options: PublicKeyCredentialCreationOptionsJSON): PublicKeyCredentialCreationOptions; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PublicKeyCredential/parseRequestOptionsFromJSON_static) */ + parseRequestOptionsFromJSON(options: PublicKeyCredentialRequestOptionsJSON): PublicKeyCredentialRequestOptions; }; /** @@ -17581,7 +18428,7 @@ interface RTCDataChannelEventMap { "bufferedamountlow": Event; "close": Event; "closing": Event; - "error": Event; + "error": RTCErrorEvent; "message": MessageEvent; "open": Event; } @@ -17611,7 +18458,7 @@ interface RTCDataChannel extends EventTarget { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCDataChannel/closing_event) */ onclosing: ((this: RTCDataChannel, ev: Event) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCDataChannel/error_event) */ - onerror: ((this: RTCDataChannel, ev: Event) => any) | null; + onerror: ((this: RTCDataChannel, ev: RTCErrorEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCDataChannel/message_event) */ onmessage: ((this: RTCDataChannel, ev: MessageEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCDataChannel/open_event) */ @@ -17652,7 +18499,7 @@ declare var RTCDataChannelEvent: { }; interface RTCDtlsTransportEventMap { - "error": Event; + "error": RTCErrorEvent; "statechange": Event; } @@ -17661,7 +18508,7 @@ interface RTCDtlsTransport extends EventTarget { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCDtlsTransport/iceTransport) */ readonly iceTransport: RTCIceTransport; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCDtlsTransport/error_event) */ - onerror: ((this: RTCDtlsTransport, ev: Event) => any) | null; + onerror: ((this: RTCDtlsTransport, ev: RTCErrorEvent) => any) | null; onstatechange: ((this: RTCDtlsTransport, ev: Event) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCDtlsTransport/state) */ readonly state: RTCDtlsTransportState; @@ -17883,9 +18730,9 @@ interface RTCPeerConnection extends EventTarget { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCPeerConnection/signalingState) */ readonly signalingState: RTCSignalingState; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCPeerConnection/addIceCandidate) */ - addIceCandidate(candidate?: RTCIceCandidateInit): Promise; + addIceCandidate(candidate?: RTCIceCandidateInit | null): Promise; /** @deprecated */ - addIceCandidate(candidate: RTCIceCandidateInit, successCallback: VoidFunction, failureCallback: RTCPeerConnectionErrorCallback): Promise; + addIceCandidate(candidate: RTCIceCandidateInit | null, successCallback: VoidFunction, failureCallback: RTCPeerConnectionErrorCallback): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCPeerConnection/addTrack) */ addTrack(track: MediaStreamTrack, ...streams: MediaStream[]): RTCRtpSender; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCPeerConnection/addTransceiver) */ @@ -18277,7 +19124,7 @@ declare var ReadableStream: { new(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number }): ReadableStream; new(underlyingSource: UnderlyingDefaultSource, strategy?: QueuingStrategy): ReadableStream; new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; - from(asyncIterable: AsyncIterable | Iterable> & object): ReadableStream; + from(asyncIterable: AsyncIterable | Iterable>): ReadableStream; }; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ @@ -18290,7 +19137,7 @@ interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { declare var ReadableStreamBYOBReader: { prototype: ReadableStreamBYOBReader; - new(stream: ReadableStream): ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; }; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ @@ -19872,14 +20719,23 @@ declare var SVGLength: { * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGLengthList) */ interface SVGLengthList { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGLengthList/length) */ readonly length: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGLengthList/numberOfItems) */ readonly numberOfItems: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGLengthList/appendItem) */ appendItem(newItem: SVGLength): SVGLength; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGLengthList/clear) */ clear(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGLengthList/getItem) */ getItem(index: number): SVGLength; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGLengthList/initialize) */ initialize(newItem: SVGLength): SVGLength; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGLengthList/insertItemBefore) */ insertItemBefore(newItem: SVGLength, index: number): SVGLength; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGLengthList/removeItem) */ removeItem(index: number): SVGLength; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGLengthList/replaceItem) */ replaceItem(newItem: SVGLength, index: number): SVGLength; [index: number]: SVGLength; } @@ -21603,7 +22459,7 @@ declare var SubmitEvent: { }; /** - * This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via globalThis.crypto). + * This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto). * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) @@ -21612,7 +22468,7 @@ interface SubtleCrypto { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) */ decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) */ - deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise; + deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length?: number | null): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ deriveKey(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params, extractable: boolean, keyUsages: KeyUsage[]): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) */ @@ -21777,11 +22633,27 @@ declare var TextEncoderStream: { new(): TextEncoderStream; }; +/** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEvent) + */ interface TextEvent extends UIEvent { + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEvent/data) + */ readonly data: string; + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEvent/initTextEvent) + */ initTextEvent(type: string, bubbles?: boolean, cancelable?: boolean, view?: Window | null, data?: string): void; } +/** @deprecated */ declare var TextEvent: { prototype: TextEvent; new(): TextEvent; @@ -22063,7 +22935,7 @@ interface TextTrackList extends EventTarget { onaddtrack: ((this: TextTrackList, ev: TrackEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextTrackList/change_event) */ onchange: ((this: TextTrackList, ev: Event) => any) | null; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextTrackList/removeTrack_event) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextTrackList/removetrack_event) */ onremovetrack: ((this: TextTrackList, ev: TrackEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextTrackList/getTrackById) */ getTrackById(id: string): TextTrack | null; @@ -22448,7 +23320,7 @@ declare var URLSearchParams: { interface UserActivation { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/UserActivation/hasBeenActive) */ readonly hasBeenActive: boolean; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/UserActivation/hasBeenActive) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/UserActivation/isActive) */ readonly isActive: boolean; } @@ -22517,6 +23389,7 @@ declare var VTTRegion: { interface ValidityState { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ValidityState/badInput) */ readonly badInput: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ValidityState/customError) */ readonly customError: boolean; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ValidityState/patternMismatch) */ readonly patternMismatch: boolean; @@ -22532,6 +23405,7 @@ interface ValidityState { readonly tooShort: boolean; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ValidityState/typeMismatch) */ readonly typeMismatch: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ValidityState/valid) */ readonly valid: boolean; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ValidityState/valueMissing) */ readonly valueMissing: boolean; @@ -23595,13 +24469,13 @@ interface WebGL2RenderingContextBase { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/copyTexSubImage3D) */ copyTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/createQuery) */ - createQuery(): WebGLQuery | null; + createQuery(): WebGLQuery; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/createSampler) */ - createSampler(): WebGLSampler | null; + createSampler(): WebGLSampler; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/createTransformFeedback) */ - createTransformFeedback(): WebGLTransformFeedback | null; + createTransformFeedback(): WebGLTransformFeedback; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/createVertexArray) */ - createVertexArray(): WebGLVertexArrayObject | null; + createVertexArray(): WebGLVertexArrayObject; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/deleteQuery) */ deleteQuery(query: WebGLQuery | null): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/deleteSampler) */ @@ -24516,17 +25390,17 @@ interface WebGLRenderingContextBase { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/copyTexSubImage2D) */ copyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/createBuffer) */ - createBuffer(): WebGLBuffer | null; + createBuffer(): WebGLBuffer; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/createFramebuffer) */ - createFramebuffer(): WebGLFramebuffer | null; + createFramebuffer(): WebGLFramebuffer; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/createProgram) */ - createProgram(): WebGLProgram | null; + createProgram(): WebGLProgram; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/createRenderbuffer) */ - createRenderbuffer(): WebGLRenderbuffer | null; + createRenderbuffer(): WebGLRenderbuffer; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/createShader) */ createShader(type: GLenum): WebGLShader | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/createTexture) */ - createTexture(): WebGLTexture | null; + createTexture(): WebGLTexture; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/cullFace) */ cullFace(mode: GLenum): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/deleteBuffer) */ @@ -25784,7 +26658,7 @@ interface WindowOrWorkerGlobalScope { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/createImageBitmap) */ createImageBitmap(image: ImageBitmapSource, options?: ImageBitmapOptions): Promise; createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ fetch(input: RequestInfo | URL, init?: RequestInit): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ queueMicrotask(callback: VoidFunction): void; @@ -26173,7 +27047,11 @@ declare var XPathEvaluator: { interface XPathEvaluatorBase { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createExpression) */ createExpression(expression: string, resolver?: XPathNSResolver | null): XPathExpression; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createNSResolver) */ + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createNSResolver) + */ createNSResolver(nodeResolver: Node): Node; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/evaluate) */ evaluate(expression: string, contextNode: Node, resolver?: XPathNSResolver | null, type?: number, result?: XPathResult | null): XPathResult; @@ -26282,7 +27160,7 @@ interface Console { clear(): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ count(label?: string): void; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countreset_static) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ countReset(label?: string): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ debug(...data: any[]): void; @@ -26294,9 +27172,9 @@ interface Console { error(...data: any[]): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ group(...data: any[]): void; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupcollapsed_static) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ groupCollapsed(...data: any[]): void; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupend_static) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ groupEnd(): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ info(...data: any[]): void; @@ -26306,9 +27184,9 @@ interface Console { table(tabularData?: any, properties?: string[]): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ time(label?: string): void; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeend_static) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ timeEnd(label?: string): void; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timelog_static) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ timeLog(label?: string, ...data: any[]): void; timeStamp(label?: string): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ @@ -26607,6 +27485,10 @@ declare namespace WebAssembly { function validate(bytes: BufferSource): boolean; } +interface AudioDataOutputCallback { + (output: AudioData): void; +} + interface BlobCallback { (blob: Blob | null): void; } @@ -26623,6 +27505,10 @@ interface DecodeSuccessCallback { (decodedData: AudioBuffer): void; } +interface EncodedAudioChunkOutputCallback { + (output: EncodedAudioChunk, metadata?: EncodedAudioChunkMetadata): void; +} + interface EncodedVideoChunkOutputCallback { (chunk: EncodedVideoChunk, metadata?: EncodedVideoChunkMetadata): void; } @@ -26759,10 +27645,6 @@ interface UnderlyingSourceStartCallback { (controller: ReadableStreamController): any; } -interface UpdateCallback { - (): any; -} - interface VideoFrameOutputCallback { (output: VideoFrame): void; } @@ -26771,6 +27653,10 @@ interface VideoFrameRequestCallback { (now: DOMHighResTimeStamp, metadata: VideoFrameCallbackMetadata): void; } +interface ViewTransitionUpdateCallback { + (): any; +} + interface VoidFunction { (): void; } @@ -27820,7 +28706,7 @@ declare function clearTimeout(id: number | undefined): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/createImageBitmap) */ declare function createImageBitmap(image: ImageBitmapSource, options?: ImageBitmapOptions): Promise; declare function createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; -/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ declare function queueMicrotask(callback: VoidFunction): void; @@ -27843,8 +28729,8 @@ type AllowSharedBufferSource = ArrayBuffer | ArrayBufferView; type AutoFill = AutoFillBase | `${OptionalPrefixToken}${OptionalPrefixToken}${AutoFillField}${OptionalPostfixToken}`; type AutoFillField = AutoFillNormalField | `${OptionalPrefixToken}${AutoFillContactField}`; type AutoFillSection = `section-${string}`; +type Base64URLString = string; type BigInteger = Uint8Array; -type BinaryData = ArrayBuffer | ArrayBufferView; type BlobPart = BufferSource | Blob | string; type BodyInit = ReadableStream | XMLHttpRequestBodyInit; type BufferSource = ArrayBufferView | ArrayBuffer; @@ -27896,6 +28782,7 @@ type OnErrorEventHandler = OnErrorEventHandlerNonNull | null; type OptionalPostfixToken = ` ${T}` | ""; type OptionalPrefixToken = `${T} ` | ""; type PerformanceEntryList = PerformanceEntry[]; +type PublicKeyCredentialJSON = any; type RTCRtpTransform = RTCRtpScriptTransform; type ReadableStreamController = ReadableStreamDefaultController | ReadableByteStreamController; type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; @@ -27905,7 +28792,7 @@ type ReportList = Report[]; type RequestInfo = Request | string; type TexImageSource = ImageBitmap | ImageData | HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | OffscreenCanvas | VideoFrame; type TimerHandler = string | Function; -type Transferable = OffscreenCanvas | ImageBitmap | MessagePort | MediaSourceHandle | ReadableStream | WritableStream | TransformStream | VideoFrame | ArrayBuffer; +type Transferable = OffscreenCanvas | ImageBitmap | MessagePort | MediaSourceHandle | ReadableStream | WritableStream | TransformStream | AudioData | VideoFrame | ArrayBuffer; type Uint32List = Uint32Array | GLuint[]; type VibratePattern = number | number[]; type WindowProxy = Window; @@ -27918,6 +28805,7 @@ type AppendMode = "segments" | "sequence"; type AttestationConveyancePreference = "direct" | "enterprise" | "indirect" | "none"; type AudioContextLatencyCategory = "balanced" | "interactive" | "playback"; type AudioContextState = "closed" | "running" | "suspended"; +type AudioSampleFormat = "f32" | "f32-planar" | "s16" | "s16-planar" | "s32" | "s32-planar" | "u8" | "u8-planar"; type AuthenticatorAttachment = "cross-platform" | "platform"; type AuthenticatorTransport = "ble" | "hybrid" | "internal" | "nfc" | "usb"; type AutoFillAddressKind = "billing" | "shipping"; @@ -27931,6 +28819,7 @@ type AutomationRate = "a-rate" | "k-rate"; type AvcBitstreamFormat = "annexb" | "avc"; type BinaryType = "arraybuffer" | "blob"; type BiquadFilterType = "allpass" | "bandpass" | "highpass" | "highshelf" | "lowpass" | "lowshelf" | "notch" | "peaking"; +type BitrateMode = "constant" | "variable"; type CSSMathOperator = "clamp" | "invert" | "max" | "min" | "negate" | "product" | "sum"; type CSSNumericBaseType = "angle" | "flex" | "frequency" | "length" | "percent" | "resolution" | "time"; type CanPlayTypeResult = "" | "maybe" | "probably"; @@ -27960,6 +28849,7 @@ type DisplayCaptureSurfaceType = "browser" | "monitor" | "window"; type DistanceModelType = "exponential" | "inverse" | "linear"; type DocumentReadyState = "complete" | "interactive" | "loading"; type DocumentVisibilityState = "hidden" | "visible"; +type EncodedAudioChunkType = "delta" | "key"; type EncodedVideoChunkType = "delta" | "key"; type EndOfStreamError = "decode" | "network"; type EndingType = "native" | "transparent"; @@ -28008,12 +28898,14 @@ type NavigationTimingType = "back_forward" | "navigate" | "prerender" | "reload" type NotificationDirection = "auto" | "ltr" | "rtl"; type NotificationPermission = "default" | "denied" | "granted"; type OffscreenRenderingContextId = "2d" | "bitmaprenderer" | "webgl" | "webgl2" | "webgpu"; +type OpusBitstreamFormat = "ogg" | "opus"; type OrientationType = "landscape-primary" | "landscape-secondary" | "portrait-primary" | "portrait-secondary"; type OscillatorType = "custom" | "sawtooth" | "sine" | "square" | "triangle"; type OverSampleType = "2x" | "4x" | "none"; type PanningModelType = "HRTF" | "equalpower"; type PaymentComplete = "fail" | "success" | "unknown"; -type PermissionName = "geolocation" | "notifications" | "persistent-storage" | "push" | "screen-wake-lock" | "xr-spatial-tracking"; +type PaymentShippingType = "delivery" | "pickup" | "shipping"; +type PermissionName = "geolocation" | "midi" | "notifications" | "persistent-storage" | "push" | "screen-wake-lock" | "storage-access"; type PermissionState = "denied" | "granted" | "prompt"; type PlaybackDirection = "alternate" | "alternate-reverse" | "normal" | "reverse"; type PositionAlignSetting = "auto" | "center" | "line-left" | "line-right"; diff --git a/cli/tsc/dts/lib.es2015.core.d.ts b/cli/tsc/dts/lib.es2015.core.d.ts index 1b22b29b42a47c..d70f9cdc0a0253 100644 --- a/cli/tsc/dts/lib.es2015.core.d.ts +++ b/cli/tsc/dts/lib.es2015.core.d.ts @@ -560,38 +560,38 @@ interface StringConstructor { raw(template: { raw: readonly string[] | ArrayLike; }, ...substitutions: any[]): string; } -interface Int8Array { +interface Int8Array { toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; } -interface Uint8Array { +interface Uint8Array { toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; } -interface Uint8ClampedArray { +interface Uint8ClampedArray { toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; } -interface Int16Array { +interface Int16Array { toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; } -interface Uint16Array { +interface Uint16Array { toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; } -interface Int32Array { +interface Int32Array { toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; } -interface Uint32Array { +interface Uint32Array { toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; } -interface Float32Array { +interface Float32Array { toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; } -interface Float64Array { +interface Float64Array { toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string; } diff --git a/cli/tsc/dts/lib.es2015.iterable.d.ts b/cli/tsc/dts/lib.es2015.iterable.d.ts index eaff26d9a3d1db..e5cdcd2411c54e 100644 --- a/cli/tsc/dts/lib.es2015.iterable.d.ts +++ b/cli/tsc/dts/lib.es2015.iterable.d.ts @@ -270,7 +270,7 @@ interface String { [Symbol.iterator](): StringIterator; } -interface Int8Array { +interface Int8Array { [Symbol.iterator](): ArrayIterator; /** * Returns an array of key, value pairs for every entry in the array @@ -287,7 +287,7 @@ interface Int8Array { } interface Int8ArrayConstructor { - new (elements: Iterable): Int8Array; + new (elements: Iterable): Int8Array; /** * Creates an array from an array-like or iterable object. @@ -295,10 +295,17 @@ interface Int8ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; + from(arrayLike: Iterable): Int8Array; + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: T, k: number) => number, thisArg?: any): Int8Array; } -interface Uint8Array { +interface Uint8Array { [Symbol.iterator](): ArrayIterator; /** * Returns an array of key, value pairs for every entry in the array @@ -315,7 +322,7 @@ interface Uint8Array { } interface Uint8ArrayConstructor { - new (elements: Iterable): Uint8Array; + new (elements: Iterable): Uint8Array; /** * Creates an array from an array-like or iterable object. @@ -323,10 +330,17 @@ interface Uint8ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; + from(arrayLike: Iterable): Uint8Array; + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: T, k: number) => number, thisArg?: any): Uint8Array; } -interface Uint8ClampedArray { +interface Uint8ClampedArray { [Symbol.iterator](): ArrayIterator; /** * Returns an array of key, value pairs for every entry in the array @@ -345,7 +359,7 @@ interface Uint8ClampedArray { } interface Uint8ClampedArrayConstructor { - new (elements: Iterable): Uint8ClampedArray; + new (elements: Iterable): Uint8ClampedArray; /** * Creates an array from an array-like or iterable object. @@ -353,10 +367,17 @@ interface Uint8ClampedArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; + from(arrayLike: Iterable): Uint8ClampedArray; + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: T, k: number) => number, thisArg?: any): Uint8ClampedArray; } -interface Int16Array { +interface Int16Array { [Symbol.iterator](): ArrayIterator; /** * Returns an array of key, value pairs for every entry in the array @@ -375,7 +396,7 @@ interface Int16Array { } interface Int16ArrayConstructor { - new (elements: Iterable): Int16Array; + new (elements: Iterable): Int16Array; /** * Creates an array from an array-like or iterable object. @@ -383,10 +404,17 @@ interface Int16ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; + from(arrayLike: Iterable): Int16Array; + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: T, k: number) => number, thisArg?: any): Int16Array; } -interface Uint16Array { +interface Uint16Array { [Symbol.iterator](): ArrayIterator; /** * Returns an array of key, value pairs for every entry in the array @@ -403,7 +431,7 @@ interface Uint16Array { } interface Uint16ArrayConstructor { - new (elements: Iterable): Uint16Array; + new (elements: Iterable): Uint16Array; /** * Creates an array from an array-like or iterable object. @@ -411,10 +439,17 @@ interface Uint16ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; + from(arrayLike: Iterable): Uint16Array; + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: T, k: number) => number, thisArg?: any): Uint16Array; } -interface Int32Array { +interface Int32Array { [Symbol.iterator](): ArrayIterator; /** * Returns an array of key, value pairs for every entry in the array @@ -431,7 +466,7 @@ interface Int32Array { } interface Int32ArrayConstructor { - new (elements: Iterable): Int32Array; + new (elements: Iterable): Int32Array; /** * Creates an array from an array-like or iterable object. @@ -439,10 +474,17 @@ interface Int32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; + from(arrayLike: Iterable): Int32Array; + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: T, k: number) => number, thisArg?: any): Int32Array; } -interface Uint32Array { +interface Uint32Array { [Symbol.iterator](): ArrayIterator; /** * Returns an array of key, value pairs for every entry in the array @@ -459,7 +501,7 @@ interface Uint32Array { } interface Uint32ArrayConstructor { - new (elements: Iterable): Uint32Array; + new (elements: Iterable): Uint32Array; /** * Creates an array from an array-like or iterable object. @@ -467,10 +509,17 @@ interface Uint32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; + from(arrayLike: Iterable): Uint32Array; + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: T, k: number) => number, thisArg?: any): Uint32Array; } -interface Float32Array { +interface Float32Array { [Symbol.iterator](): ArrayIterator; /** * Returns an array of key, value pairs for every entry in the array @@ -487,7 +536,7 @@ interface Float32Array { } interface Float32ArrayConstructor { - new (elements: Iterable): Float32Array; + new (elements: Iterable): Float32Array; /** * Creates an array from an array-like or iterable object. @@ -495,10 +544,17 @@ interface Float32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; + from(arrayLike: Iterable): Float32Array; + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: T, k: number) => number, thisArg?: any): Float32Array; } -interface Float64Array { +interface Float64Array { [Symbol.iterator](): ArrayIterator; /** * Returns an array of key, value pairs for every entry in the array @@ -515,7 +571,7 @@ interface Float64Array { } interface Float64ArrayConstructor { - new (elements: Iterable): Float64Array; + new (elements: Iterable): Float64Array; /** * Creates an array from an array-like or iterable object. @@ -523,5 +579,12 @@ interface Float64ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: Iterable, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; + from(arrayLike: Iterable): Float64Array; + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: Iterable, mapfn?: (v: T, k: number) => number, thisArg?: any): Float64Array; } diff --git a/cli/tsc/dts/lib.es2015.symbol.wellknown.d.ts b/cli/tsc/dts/lib.es2015.symbol.wellknown.d.ts index 06bcc35b3d4960..42678a0e455757 100644 --- a/cli/tsc/dts/lib.es2015.symbol.wellknown.d.ts +++ b/cli/tsc/dts/lib.es2015.symbol.wellknown.d.ts @@ -272,43 +272,43 @@ interface ArrayBuffer { readonly [Symbol.toStringTag]: string; } -interface DataView { +interface DataView { readonly [Symbol.toStringTag]: string; } -interface Int8Array { +interface Int8Array { readonly [Symbol.toStringTag]: "Int8Array"; } -interface Uint8Array { +interface Uint8Array { readonly [Symbol.toStringTag]: "Uint8Array"; } -interface Uint8ClampedArray { +interface Uint8ClampedArray { readonly [Symbol.toStringTag]: "Uint8ClampedArray"; } -interface Int16Array { +interface Int16Array { readonly [Symbol.toStringTag]: "Int16Array"; } -interface Uint16Array { +interface Uint16Array { readonly [Symbol.toStringTag]: "Uint16Array"; } -interface Int32Array { +interface Int32Array { readonly [Symbol.toStringTag]: "Int32Array"; } -interface Uint32Array { +interface Uint32Array { readonly [Symbol.toStringTag]: "Uint32Array"; } -interface Float32Array { +interface Float32Array { readonly [Symbol.toStringTag]: "Float32Array"; } -interface Float64Array { +interface Float64Array { readonly [Symbol.toStringTag]: "Float64Array"; } diff --git a/cli/tsc/dts/lib.es2016.array.include.d.ts b/cli/tsc/dts/lib.es2016.array.include.d.ts index 3aa5a044e0b12c..6548c91908dbed 100644 --- a/cli/tsc/dts/lib.es2016.array.include.d.ts +++ b/cli/tsc/dts/lib.es2016.array.include.d.ts @@ -34,7 +34,7 @@ interface ReadonlyArray { includes(searchElement: T, fromIndex?: number): boolean; } -interface Int8Array { +interface Int8Array { /** * Determines whether an array includes a certain element, returning true or false as appropriate. * @param searchElement The element to search for. @@ -43,7 +43,7 @@ interface Int8Array { includes(searchElement: number, fromIndex?: number): boolean; } -interface Uint8Array { +interface Uint8Array { /** * Determines whether an array includes a certain element, returning true or false as appropriate. * @param searchElement The element to search for. @@ -52,7 +52,7 @@ interface Uint8Array { includes(searchElement: number, fromIndex?: number): boolean; } -interface Uint8ClampedArray { +interface Uint8ClampedArray { /** * Determines whether an array includes a certain element, returning true or false as appropriate. * @param searchElement The element to search for. @@ -61,7 +61,7 @@ interface Uint8ClampedArray { includes(searchElement: number, fromIndex?: number): boolean; } -interface Int16Array { +interface Int16Array { /** * Determines whether an array includes a certain element, returning true or false as appropriate. * @param searchElement The element to search for. @@ -70,7 +70,7 @@ interface Int16Array { includes(searchElement: number, fromIndex?: number): boolean; } -interface Uint16Array { +interface Uint16Array { /** * Determines whether an array includes a certain element, returning true or false as appropriate. * @param searchElement The element to search for. @@ -79,7 +79,7 @@ interface Uint16Array { includes(searchElement: number, fromIndex?: number): boolean; } -interface Int32Array { +interface Int32Array { /** * Determines whether an array includes a certain element, returning true or false as appropriate. * @param searchElement The element to search for. @@ -88,7 +88,7 @@ interface Int32Array { includes(searchElement: number, fromIndex?: number): boolean; } -interface Uint32Array { +interface Uint32Array { /** * Determines whether an array includes a certain element, returning true or false as appropriate. * @param searchElement The element to search for. @@ -97,7 +97,7 @@ interface Uint32Array { includes(searchElement: number, fromIndex?: number): boolean; } -interface Float32Array { +interface Float32Array { /** * Determines whether an array includes a certain element, returning true or false as appropriate. * @param searchElement The element to search for. @@ -106,7 +106,7 @@ interface Float32Array { includes(searchElement: number, fromIndex?: number): boolean; } -interface Float64Array { +interface Float64Array { /** * Determines whether an array includes a certain element, returning true or false as appropriate. * @param searchElement The element to search for. diff --git a/cli/tsc/dts/lib.es2016.intl.d.ts b/cli/tsc/dts/lib.es2016.intl.d.ts index 7af6efc2b0993a..83ca380f0b8139 100644 --- a/cli/tsc/dts/lib.es2016.intl.d.ts +++ b/cli/tsc/dts/lib.es2016.intl.d.ts @@ -22,7 +22,7 @@ declare namespace Intl { * the canonical locale names. Duplicates will be omitted and elements * will be validated as structurally valid language tags. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/getCanonicalLocales) + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/getCanonicalLocales) * * @param locale A list of String values for which to get the canonical locale names * @returns An array containing the canonical and validated locale names. diff --git a/cli/tsc/dts/lib.es2017.arraybuffer.d.ts b/cli/tsc/dts/lib.es2017.arraybuffer.d.ts new file mode 100644 index 00000000000000..e2f00b8340a001 --- /dev/null +++ b/cli/tsc/dts/lib.es2017.arraybuffer.d.ts @@ -0,0 +1,21 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +/// + +interface ArrayBufferConstructor { + new (): ArrayBuffer; +} diff --git a/cli/tsc/dts/lib.es2017.d.ts b/cli/tsc/dts/lib.es2017.d.ts index e0bd4eeb721779..234a01f9566389 100644 --- a/cli/tsc/dts/lib.es2017.d.ts +++ b/cli/tsc/dts/lib.es2017.d.ts @@ -17,9 +17,10 @@ and limitations under the License. /// /// +/// +/// +/// /// /// /// -/// /// -/// diff --git a/cli/tsc/dts/lib.es2017.sharedmemory.d.ts b/cli/tsc/dts/lib.es2017.sharedmemory.d.ts index a46c5ccb13d7df..89b703982b7735 100644 --- a/cli/tsc/dts/lib.es2017.sharedmemory.d.ts +++ b/cli/tsc/dts/lib.es2017.sharedmemory.d.ts @@ -28,14 +28,14 @@ interface SharedArrayBuffer { /** * Returns a section of an SharedArrayBuffer. */ - slice(begin: number, end?: number): SharedArrayBuffer; + slice(begin?: number, end?: number): SharedArrayBuffer; readonly [Symbol.species]: SharedArrayBuffer; readonly [Symbol.toStringTag]: "SharedArrayBuffer"; } interface SharedArrayBufferConstructor { readonly prototype: SharedArrayBuffer; - new (byteLength: number): SharedArrayBuffer; + new (byteLength?: number): SharedArrayBuffer; } declare var SharedArrayBuffer: SharedArrayBufferConstructor; @@ -49,28 +49,28 @@ interface Atomics { * Until this atomic operation completes, any other read or write operation against the array * will block. */ - add(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + add(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; /** * Stores the bitwise AND of a value with the value at the given position in the array, * returning the original value. Until this atomic operation completes, any other read or * write operation against the array will block. */ - and(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + and(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; /** * Replaces the value at the given position in the array if the original value equals the given * expected value, returning the original value. Until this atomic operation completes, any * other read or write operation against the array will block. */ - compareExchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, expectedValue: number, replacementValue: number): number; + compareExchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, expectedValue: number, replacementValue: number): number; /** * Replaces the value at the given position in the array, returning the original value. Until * this atomic operation completes, any other read or write operation against the array will * block. */ - exchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + exchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; /** * Returns a value indicating whether high-performance algorithms can use atomic operations @@ -83,27 +83,27 @@ interface Atomics { * Returns the value at the given position in the array. Until this atomic operation completes, * any other read or write operation against the array will block. */ - load(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number): number; + load(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number): number; /** * Stores the bitwise OR of a value with the value at the given position in the array, * returning the original value. Until this atomic operation completes, any other read or write * operation against the array will block. */ - or(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + or(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; /** * Stores a value at the given position in the array, returning the new value. Until this * atomic operation completes, any other read or write operation against the array will block. */ - store(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + store(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; /** * Subtracts a value from the value at the given position in the array, returning the original * value. Until this atomic operation completes, any other read or write operation against the * array will block. */ - sub(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + sub(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; /** * If the value at the given position in the array is equal to the provided value, the current @@ -111,23 +111,23 @@ interface Atomics { * `"timed-out"`) or until the agent is awoken (returning `"ok"`); otherwise, returns * `"not-equal"`. */ - wait(typedArray: Int32Array, index: number, value: number, timeout?: number): "ok" | "not-equal" | "timed-out"; + wait(typedArray: Int32Array, index: number, value: number, timeout?: number): "ok" | "not-equal" | "timed-out"; /** * Wakes up sleeping agents that are waiting on the given index of the array, returning the * number of agents that were awoken. - * @param typedArray A shared Int32Array. + * @param typedArray A shared Int32Array. * @param index The position in the typedArray to wake up on. * @param count The number of sleeping agents to notify. Defaults to +Infinity. */ - notify(typedArray: Int32Array, index: number, count?: number): number; + notify(typedArray: Int32Array, index: number, count?: number): number; /** * Stores the bitwise XOR of a value with the value at the given position in the array, * returning the original value. Until this atomic operation completes, any other read or write * operation against the array will block. */ - xor(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; + xor(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; readonly [Symbol.toStringTag]: "Atomics"; } diff --git a/cli/tsc/dts/lib.es2017.typedarrays.d.ts b/cli/tsc/dts/lib.es2017.typedarrays.d.ts index 2182ec12f8884a..aed22e3ee2a7ea 100644 --- a/cli/tsc/dts/lib.es2017.typedarrays.d.ts +++ b/cli/tsc/dts/lib.es2017.typedarrays.d.ts @@ -17,37 +17,37 @@ and limitations under the License. /// interface Int8ArrayConstructor { - new (): Int8Array; + new (): Int8Array; } interface Uint8ArrayConstructor { - new (): Uint8Array; + new (): Uint8Array; } interface Uint8ClampedArrayConstructor { - new (): Uint8ClampedArray; + new (): Uint8ClampedArray; } interface Int16ArrayConstructor { - new (): Int16Array; + new (): Int16Array; } interface Uint16ArrayConstructor { - new (): Uint16Array; + new (): Uint16Array; } interface Int32ArrayConstructor { - new (): Int32Array; + new (): Int32Array; } interface Uint32ArrayConstructor { - new (): Uint32Array; + new (): Uint32Array; } interface Float32ArrayConstructor { - new (): Float32Array; + new (): Float32Array; } interface Float64ArrayConstructor { - new (): Float64Array; + new (): Float64Array; } diff --git a/cli/tsc/dts/lib.es2020.bigint.d.ts b/cli/tsc/dts/lib.es2020.bigint.d.ts index 9997ac000377b6..2d6204e2d5193f 100644 --- a/cli/tsc/dts/lib.es2020.bigint.d.ts +++ b/cli/tsc/dts/lib.es2020.bigint.d.ts @@ -20,7 +20,7 @@ and limitations under the License. interface BigIntToLocaleStringOptions { /** - * The locale matching algorithm to use.The default is "best fit". For information about this option, see the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation Intl page}. + * The locale matching algorithm to use.The default is "best fit". For information about this option, see the {@link https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation Intl page}. */ localeMatcher?: string; /** @@ -146,12 +146,12 @@ declare var BigInt: BigIntConstructor; * A typed array of 64-bit signed integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated, an exception is raised. */ -interface BigInt64Array { +interface BigInt64Array { /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBufferLike; + readonly buffer: TArrayBuffer; /** The length in bytes of the array. */ readonly byteLength: number; @@ -181,7 +181,7 @@ interface BigInt64Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - every(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean; + every(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean; /** * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array @@ -200,7 +200,7 @@ interface BigInt64Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - filter(predicate: (value: bigint, index: number, array: BigInt64Array) => any, thisArg?: any): BigInt64Array; + filter(predicate: (value: bigint, index: number, array: BigInt64Array) => any, thisArg?: any): BigInt64Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -211,7 +211,7 @@ interface BigInt64Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): bigint | undefined; + find(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): bigint | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -222,7 +222,7 @@ interface BigInt64Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -231,7 +231,7 @@ interface BigInt64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (value: bigint, index: number, array: BigInt64Array) => void, thisArg?: any): void; + forEach(callbackfn: (value: bigint, index: number, array: BigInt64Array) => void, thisArg?: any): void; /** * Determines whether an array includes a certain element, returning true or false as appropriate. @@ -277,7 +277,7 @@ interface BigInt64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (value: bigint, index: number, array: BigInt64Array) => bigint, thisArg?: any): BigInt64Array; + map(callbackfn: (value: bigint, index: number, array: BigInt64Array) => bigint, thisArg?: any): BigInt64Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -289,7 +289,7 @@ interface BigInt64Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; + reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -301,7 +301,7 @@ interface BigInt64Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U; + reduce(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -313,7 +313,7 @@ interface BigInt64Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; + reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -325,7 +325,7 @@ interface BigInt64Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduceRight(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U; + reduceRight(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U; /** Reverses the elements in the array. */ reverse(): this; @@ -342,7 +342,7 @@ interface BigInt64Array { * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ - slice(start?: number, end?: number): BigInt64Array; + slice(start?: number, end?: number): BigInt64Array; /** * Determines whether the specified callback function returns true for any element of an array. @@ -352,7 +352,7 @@ interface BigInt64Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - some(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean; + some(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean; /** * Sorts the array. @@ -366,7 +366,7 @@ interface BigInt64Array { * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ - subarray(begin?: number, end?: number): BigInt64Array; + subarray(begin?: number, end?: number): BigInt64Array; /** Converts the array to a string by using the current locale. */ toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string; @@ -375,7 +375,7 @@ interface BigInt64Array { toString(): string; /** Returns the primitive value of the specified object. */ - valueOf(): BigInt64Array; + valueOf(): BigInt64Array; /** Yields each value in the array. */ values(): ArrayIterator; @@ -386,12 +386,12 @@ interface BigInt64Array { [index: number]: bigint; } - interface BigInt64ArrayConstructor { - readonly prototype: BigInt64Array; - new (length?: number): BigInt64Array; - new (array: Iterable): BigInt64Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigInt64Array; + readonly prototype: BigInt64Array; + new (length?: number): BigInt64Array; + new (array: ArrayLike | Iterable): BigInt64Array; + new (buffer: TArrayBuffer, byteOffset?: number, length?: number): BigInt64Array; + new (array: ArrayLike | ArrayBuffer): BigInt64Array; /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; @@ -400,7 +400,7 @@ interface BigInt64ArrayConstructor { * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ - of(...items: bigint[]): BigInt64Array; + of(...items: bigint[]): BigInt64Array; /** * Creates an array from an array-like or iterable object. @@ -408,22 +408,27 @@ interface BigInt64ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: ArrayLike): BigInt64Array; - from(arrayLike: ArrayLike, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigInt64Array; + from(arrayLike: ArrayLike): BigInt64Array; + /** + * Creates an array from an array-like or iterable object. + * @param arrayLike An array-like or iterable object to convert to an array. + * @param mapfn A mapping function to call on every element of the array. + * @param thisArg Value of 'this' used to invoke the mapfn. + */ + from(arrayLike: ArrayLike, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigInt64Array; } - declare var BigInt64Array: BigInt64ArrayConstructor; /** * A typed array of 64-bit unsigned integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated, an exception is raised. */ -interface BigUint64Array { +interface BigUint64Array { /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBufferLike; + readonly buffer: TArrayBuffer; /** The length in bytes of the array. */ readonly byteLength: number; @@ -453,7 +458,7 @@ interface BigUint64Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - every(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean; + every(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean; /** * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array @@ -472,7 +477,7 @@ interface BigUint64Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - filter(predicate: (value: bigint, index: number, array: BigUint64Array) => any, thisArg?: any): BigUint64Array; + filter(predicate: (value: bigint, index: number, array: BigUint64Array) => any, thisArg?: any): BigUint64Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -483,7 +488,7 @@ interface BigUint64Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): bigint | undefined; + find(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): bigint | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -494,7 +499,7 @@ interface BigUint64Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -503,7 +508,7 @@ interface BigUint64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (value: bigint, index: number, array: BigUint64Array) => void, thisArg?: any): void; + forEach(callbackfn: (value: bigint, index: number, array: BigUint64Array) => void, thisArg?: any): void; /** * Determines whether an array includes a certain element, returning true or false as appropriate. @@ -549,7 +554,7 @@ interface BigUint64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (value: bigint, index: number, array: BigUint64Array) => bigint, thisArg?: any): BigUint64Array; + map(callbackfn: (value: bigint, index: number, array: BigUint64Array) => bigint, thisArg?: any): BigUint64Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -561,7 +566,7 @@ interface BigUint64Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; + reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -573,7 +578,7 @@ interface BigUint64Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U; + reduce(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -585,7 +590,7 @@ interface BigUint64Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; + reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -597,7 +602,7 @@ interface BigUint64Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduceRight(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U; + reduceRight(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U; /** Reverses the elements in the array. */ reverse(): this; @@ -614,7 +619,7 @@ interface BigUint64Array { * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ - slice(start?: number, end?: number): BigUint64Array; + slice(start?: number, end?: number): BigUint64Array; /** * Determines whether the specified callback function returns true for any element of an array. @@ -624,7 +629,7 @@ interface BigUint64Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - some(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean; + some(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean; /** * Sorts the array. @@ -638,7 +643,7 @@ interface BigUint64Array { * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ - subarray(begin?: number, end?: number): BigUint64Array; + subarray(begin?: number, end?: number): BigUint64Array; /** Converts the array to a string by using the current locale. */ toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string; @@ -647,7 +652,7 @@ interface BigUint64Array { toString(): string; /** Returns the primitive value of the specified object. */ - valueOf(): BigUint64Array; + valueOf(): BigUint64Array; /** Yields each value in the array. */ values(): ArrayIterator; @@ -658,12 +663,12 @@ interface BigUint64Array { [index: number]: bigint; } - interface BigUint64ArrayConstructor { - readonly prototype: BigUint64Array; - new (length?: number): BigUint64Array; - new (array: Iterable): BigUint64Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigUint64Array; + readonly prototype: BigUint64Array; + new (length?: number): BigUint64Array; + new (array: ArrayLike | Iterable): BigUint64Array; + new (buffer: TArrayBuffer, byteOffset?: number, length?: number): BigUint64Array; + new (array: ArrayLike | ArrayBuffer): BigUint64Array; /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; @@ -672,7 +677,7 @@ interface BigUint64ArrayConstructor { * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ - of(...items: bigint[]): BigUint64Array; + of(...items: bigint[]): BigUint64Array; /** * Creates an array from an array-like or iterable object. @@ -683,10 +688,9 @@ interface BigUint64ArrayConstructor { from(arrayLike: ArrayLike): BigUint64Array; from(arrayLike: ArrayLike, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigUint64Array; } - declare var BigUint64Array: BigUint64ArrayConstructor; -interface DataView { +interface DataView { /** * Gets the BigInt64 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. diff --git a/cli/tsc/dts/lib.es2020.intl.d.ts b/cli/tsc/dts/lib.es2020.intl.d.ts index 0da854e161c366..b945d3801c8975 100644 --- a/cli/tsc/dts/lib.es2020.intl.d.ts +++ b/cli/tsc/dts/lib.es2020.intl.d.ts @@ -23,14 +23,14 @@ declare namespace Intl { * * For example: "fa", "es-MX", "zh-Hant-TW". * - * See [MDN - Intl - locales argument](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument). + * See [MDN - Intl - locales argument](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument). */ type UnicodeBCP47LocaleIdentifier = string; /** * Unit to use in the relative time internationalized message. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/format#Parameters). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/format#Parameters). */ type RelativeTimeFormatUnit = | "year" @@ -57,7 +57,7 @@ declare namespace Intl { * but `formatToParts` only outputs singular (e.g. "day") not plural (e.g. * "days"). * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts#Using_formatToParts). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts#Using_formatToParts). */ type RelativeTimeFormatUnitSingular = | "year" @@ -79,21 +79,21 @@ declare namespace Intl { /** * The format of output message. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters). */ type RelativeTimeFormatNumeric = "always" | "auto"; /** * The length of the internationalized message. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters). */ type RelativeTimeFormatStyle = "long" | "short" | "narrow"; /** * The locale or locales to use * - * See [MDN - Intl - locales argument](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument). + * See [MDN - Intl - locales argument](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument). */ type LocalesArgument = UnicodeBCP47LocaleIdentifier | Locale | readonly (UnicodeBCP47LocaleIdentifier | Locale)[] | undefined; @@ -101,7 +101,7 @@ declare namespace Intl { * An object with some or all of properties of `options` parameter * of `Intl.RelativeTimeFormat` constructor. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters). */ interface RelativeTimeFormatOptions { /** The locale matching algorithm to use. For information about this option, see [Intl page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation). */ @@ -117,7 +117,7 @@ declare namespace Intl { * and formatting options computed during initialization * of the `Intl.RelativeTimeFormat` object * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/resolvedOptions#Description). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/resolvedOptions#Description). */ interface ResolvedRelativeTimeFormatOptions { locale: UnicodeBCP47LocaleIdentifier; @@ -130,7 +130,7 @@ declare namespace Intl { * An object representing the relative time format in parts * that can be used for custom locale-aware formatting. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts#Using_formatToParts). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts#Using_formatToParts). */ type RelativeTimeFormatPart = | { @@ -166,7 +166,7 @@ declare namespace Intl { * * @returns {string} Internationalized relative time message as string * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/format). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/format). */ format(value: number, unit: RelativeTimeFormatUnit): string; @@ -179,14 +179,14 @@ declare namespace Intl { * * @throws `RangeError` if `unit` was given something other than `unit` possible values * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts). */ formatToParts(value: number, unit: RelativeTimeFormatUnit): RelativeTimeFormatPart[]; /** * Provides access to the locale and options computed during initialization of this `Intl.RelativeTimeFormat` object. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/resolvedOptions). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/resolvedOptions). */ resolvedOptions(): ResolvedRelativeTimeFormatOptions; } @@ -195,22 +195,22 @@ declare namespace Intl { * The [`Intl.RelativeTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat) * object is a constructor for objects that enable language-sensitive relative time formatting. * - * [Compatibility](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat#Browser_compatibility). + * [Compatibility](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat#Browser_compatibility). */ const RelativeTimeFormat: { /** - * Creates [Intl.RelativeTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat) objects + * Creates [Intl.RelativeTimeFormat](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat) objects * * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings. * For the general form and interpretation of the locales argument, - * see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation). + * see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation). * - * @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters) + * @param options - An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters) * with some or all of options of `RelativeTimeFormatOptions`. * - * @returns [Intl.RelativeTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat) object. + * @returns [Intl.RelativeTimeFormat](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat) object. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat). */ new ( locales?: LocalesArgument, @@ -224,16 +224,16 @@ declare namespace Intl { * * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings. * For the general form and interpretation of the locales argument, - * see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation). + * see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation). * - * @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters) + * @param options - An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters) * with some or all of options of the formatting. * * @returns An array containing those of the provided locales * that are supported in date and time formatting * without having to fall back to the runtime's default locale. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/supportedLocalesOf). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/supportedLocalesOf). */ supportedLocalesOf( locales?: LocalesArgument, @@ -336,18 +336,18 @@ declare namespace Intl { } /** - * Constructor creates [Intl.Locale](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale) + * Constructor creates [Intl.Locale](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale) * objects * * @param tag - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646). * For the general form and interpretation of the locales argument, - * see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation). + * see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation). * - * @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/Locale#Parameters) with some or all of options of the locale. + * @param options - An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/Locale#Parameters) with some or all of options of the locale. * - * @returns [Intl.Locale](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale) object. + * @returns [Intl.Locale](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale) object. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale). */ const Locale: { new (tag: UnicodeBCP47LocaleIdentifier | Locale, options?: LocaleOptions): Locale; @@ -388,7 +388,7 @@ declare namespace Intl { interface DisplayNames { /** * Receives a code and returns a string based on the locale and options provided when instantiating - * [`Intl.DisplayNames()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames) + * [`Intl.DisplayNames()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames) * * @param code The `code` to provide depends on the `type` passed to display name during creation: * - If the type is `"region"`, code should be either an [ISO-3166 two letters region code](https://www.iso.org/iso-3166-country-codes.html), @@ -399,35 +399,35 @@ declare namespace Intl { * `languageCode` is either a two letters ISO 639-1 language code or a three letters ISO 639-2 language code. * - If the type is `"currency"`, code should be a [3-letter ISO 4217 currency code](https://www.iso.org/iso-4217-currency-codes.html). * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/of). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/of). */ of(code: string): string | undefined; /** * Returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current - * [`Intl/DisplayNames`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames) object. + * [`Intl/DisplayNames`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames) object. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/resolvedOptions). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/resolvedOptions). */ resolvedOptions(): ResolvedDisplayNamesOptions; } /** - * The [`Intl.DisplayNames()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames) + * The [`Intl.DisplayNames()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames) * object enables the consistent translation of language, region and script display names. * - * [Compatibility](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames#browser_compatibility). + * [Compatibility](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames#browser_compatibility). */ const DisplayNames: { prototype: DisplayNames; /** * @param locales A string with a BCP 47 language tag, or an array of such strings. - * For the general form and interpretation of the `locales` argument, see the [Intl](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation) + * For the general form and interpretation of the `locales` argument, see the [Intl](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation) * page. * * @param options An object for setting up a display name. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/DisplayNames). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/DisplayNames). */ new (locales: LocalesArgument, options: DisplayNamesOptions): DisplayNames; @@ -435,14 +435,14 @@ declare namespace Intl { * Returns an array containing those of the provided locales that are supported in display names without having to fall back to the runtime's default locale. * * @param locales A string with a BCP 47 language tag, or an array of such strings. - * For the general form and interpretation of the `locales` argument, see the [Intl](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation) + * For the general form and interpretation of the `locales` argument, see the [Intl](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation) * page. * * @param options An object with a locale matcher. * * @returns An array of strings representing a subset of the given locale tags that are supported in display names without having to fall back to the runtime's default locale. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/supportedLocalesOf). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/supportedLocalesOf). */ supportedLocalesOf(locales?: LocalesArgument, options?: { localeMatcher?: RelativeTimeFormatLocaleMatcher; }): UnicodeBCP47LocaleIdentifier[]; }; diff --git a/cli/tsc/dts/lib.es2020.sharedmemory.d.ts b/cli/tsc/dts/lib.es2020.sharedmemory.d.ts index 3c7c14f4bdf769..35641a6426e995 100644 --- a/cli/tsc/dts/lib.es2020.sharedmemory.d.ts +++ b/cli/tsc/dts/lib.es2020.sharedmemory.d.ts @@ -16,60 +16,62 @@ and limitations under the License. /// +/// + interface Atomics { /** * Adds a value to the value at the given position in the array, returning the original value. * Until this atomic operation completes, any other read or write operation against the array * will block. */ - add(typedArray: BigInt64Array | BigUint64Array, index: number, value: bigint): bigint; + add(typedArray: BigInt64Array | BigUint64Array, index: number, value: bigint): bigint; /** * Stores the bitwise AND of a value with the value at the given position in the array, * returning the original value. Until this atomic operation completes, any other read or * write operation against the array will block. */ - and(typedArray: BigInt64Array | BigUint64Array, index: number, value: bigint): bigint; + and(typedArray: BigInt64Array | BigUint64Array, index: number, value: bigint): bigint; /** * Replaces the value at the given position in the array if the original value equals the given * expected value, returning the original value. Until this atomic operation completes, any * other read or write operation against the array will block. */ - compareExchange(typedArray: BigInt64Array | BigUint64Array, index: number, expectedValue: bigint, replacementValue: bigint): bigint; + compareExchange(typedArray: BigInt64Array | BigUint64Array, index: number, expectedValue: bigint, replacementValue: bigint): bigint; /** * Replaces the value at the given position in the array, returning the original value. Until * this atomic operation completes, any other read or write operation against the array will * block. */ - exchange(typedArray: BigInt64Array | BigUint64Array, index: number, value: bigint): bigint; + exchange(typedArray: BigInt64Array | BigUint64Array, index: number, value: bigint): bigint; /** * Returns the value at the given position in the array. Until this atomic operation completes, * any other read or write operation against the array will block. */ - load(typedArray: BigInt64Array | BigUint64Array, index: number): bigint; + load(typedArray: BigInt64Array | BigUint64Array, index: number): bigint; /** * Stores the bitwise OR of a value with the value at the given position in the array, * returning the original value. Until this atomic operation completes, any other read or write * operation against the array will block. */ - or(typedArray: BigInt64Array | BigUint64Array, index: number, value: bigint): bigint; + or(typedArray: BigInt64Array | BigUint64Array, index: number, value: bigint): bigint; /** * Stores a value at the given position in the array, returning the new value. Until this * atomic operation completes, any other read or write operation against the array will block. */ - store(typedArray: BigInt64Array | BigUint64Array, index: number, value: bigint): bigint; + store(typedArray: BigInt64Array | BigUint64Array, index: number, value: bigint): bigint; /** * Subtracts a value from the value at the given position in the array, returning the original * value. Until this atomic operation completes, any other read or write operation against the * array will block. */ - sub(typedArray: BigInt64Array | BigUint64Array, index: number, value: bigint): bigint; + sub(typedArray: BigInt64Array | BigUint64Array, index: number, value: bigint): bigint; /** * If the value at the given position in the array is equal to the provided value, the current @@ -77,7 +79,7 @@ interface Atomics { * `"timed-out"`) or until the agent is awoken (returning `"ok"`); otherwise, returns * `"not-equal"`. */ - wait(typedArray: BigInt64Array, index: number, value: bigint, timeout?: number): "ok" | "not-equal" | "timed-out"; + wait(typedArray: BigInt64Array, index: number, value: bigint, timeout?: number): "ok" | "not-equal" | "timed-out"; /** * Wakes up sleeping agents that are waiting on the given index of the array, returning the @@ -86,12 +88,12 @@ interface Atomics { * @param index The position in the typedArray to wake up on. * @param count The number of sleeping agents to notify. Defaults to +Infinity. */ - notify(typedArray: BigInt64Array, index: number, count?: number): number; + notify(typedArray: BigInt64Array, index: number, count?: number): number; /** * Stores the bitwise XOR of a value with the value at the given position in the array, * returning the original value. Until this atomic operation completes, any other read or write * operation against the array will block. */ - xor(typedArray: BigInt64Array | BigUint64Array, index: number, value: bigint): bigint; + xor(typedArray: BigInt64Array | BigUint64Array, index: number, value: bigint): bigint; } diff --git a/cli/tsc/dts/lib.es2020.string.d.ts b/cli/tsc/dts/lib.es2020.string.d.ts index cdb38e0d869163..4c2a4ded060dee 100644 --- a/cli/tsc/dts/lib.es2020.string.d.ts +++ b/cli/tsc/dts/lib.es2020.string.d.ts @@ -16,6 +16,8 @@ and limitations under the License. /// +/// +/// /// interface String { diff --git a/cli/tsc/dts/lib.es2021.intl.d.ts b/cli/tsc/dts/lib.es2021.intl.d.ts index ec90ad1b2cf762..a0fe4825e7b770 100644 --- a/cli/tsc/dts/lib.es2021.intl.d.ts +++ b/cli/tsc/dts/lib.es2021.intl.d.ts @@ -50,28 +50,28 @@ declare namespace Intl { /** * The locale matching algorithm to use. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters). */ type ListFormatLocaleMatcher = "lookup" | "best fit"; /** * The format of output message. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters). */ type ListFormatType = "conjunction" | "disjunction" | "unit"; /** * The length of the formatted message. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters). */ type ListFormatStyle = "long" | "short" | "narrow"; /** * An object with some or all properties of the `Intl.ListFormat` constructor `options` parameter. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters). */ interface ListFormatOptions { /** The locale matching algorithm to use. For information about this option, see [Intl page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation). */ @@ -92,26 +92,26 @@ declare namespace Intl { /** * Returns a string with a language-specific representation of the list. * - * @param list - An iterable object, such as an [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). + * @param list - An iterable object, such as an [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array). * * @throws `TypeError` if `list` includes something other than the possible values. * * @returns {string} A language-specific formatted string representing the elements of the list. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/format). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/format). */ format(list: Iterable): string; /** * Returns an Array of objects representing the different components that can be used to format a list of values in a locale-aware fashion. * - * @param list - An iterable object, such as an [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array), to be formatted according to a locale. + * @param list - An iterable object, such as an [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array), to be formatted according to a locale. * * @throws `TypeError` if `list` includes something other than the possible values. * * @returns {{ type: "element" | "literal", value: string; }[]} An Array of components which contains the formatted parts from the list. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/formatToParts). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/formatToParts). */ formatToParts(list: Iterable): { type: "element" | "literal"; value: string; }[]; @@ -120,7 +120,7 @@ declare namespace Intl { * formatting options computed during the construction of the current * `Intl.ListFormat` object. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/resolvedOptions). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/resolvedOptions). */ resolvedOptions(): ResolvedListFormatOptions; } @@ -129,19 +129,19 @@ declare namespace Intl { prototype: ListFormat; /** - * Creates [Intl.ListFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat) objects that + * Creates [Intl.ListFormat](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat) objects that * enable language-sensitive list formatting. * * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings. * For the general form and interpretation of the `locales` argument, - * see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation). + * see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation). * - * @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters) + * @param options - An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters) * with some or all options of `ListFormatOptions`. * - * @returns [Intl.ListFormatOptions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat) object. + * @returns [Intl.ListFormatOptions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat) object. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat). */ new (locales?: LocalesArgument, options?: ListFormatOptions): ListFormat; @@ -151,15 +151,15 @@ declare namespace Intl { * * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings. * For the general form and interpretation of the `locales` argument, - * see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation). + * see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation). * - * @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/supportedLocalesOf#parameters). + * @param options - An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/supportedLocalesOf#parameters). * with some or all possible options. * * @returns An array of strings representing a subset of the given locale tags that are supported in list * formatting without having to fall back to the runtime's default locale. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/supportedLocalesOf). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/supportedLocalesOf). */ supportedLocalesOf(locales: LocalesArgument, options?: Pick): UnicodeBCP47LocaleIdentifier[]; }; diff --git a/cli/tsc/dts/lib.es2021.weakref.d.ts b/cli/tsc/dts/lib.es2021.weakref.d.ts index 48e76265a2c5fb..9e03365a20d65d 100644 --- a/cli/tsc/dts/lib.es2021.weakref.d.ts +++ b/cli/tsc/dts/lib.es2021.weakref.d.ts @@ -16,6 +16,8 @@ and limitations under the License. /// +/// + interface WeakRef { readonly [Symbol.toStringTag]: "WeakRef"; diff --git a/cli/tsc/dts/lib.es2022.array.d.ts b/cli/tsc/dts/lib.es2022.array.d.ts index 621857ba0878c1..6f4dc417a32bdc 100644 --- a/cli/tsc/dts/lib.es2022.array.d.ts +++ b/cli/tsc/dts/lib.es2022.array.d.ts @@ -32,7 +32,7 @@ interface ReadonlyArray { at(index: number): T | undefined; } -interface Int8Array { +interface Int8Array { /** * Returns the item located at the specified index. * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. @@ -40,7 +40,7 @@ interface Int8Array { at(index: number): number | undefined; } -interface Uint8Array { +interface Uint8Array { /** * Returns the item located at the specified index. * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. @@ -48,7 +48,7 @@ interface Uint8Array { at(index: number): number | undefined; } -interface Uint8ClampedArray { +interface Uint8ClampedArray { /** * Returns the item located at the specified index. * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. @@ -56,7 +56,7 @@ interface Uint8ClampedArray { at(index: number): number | undefined; } -interface Int16Array { +interface Int16Array { /** * Returns the item located at the specified index. * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. @@ -64,7 +64,7 @@ interface Int16Array { at(index: number): number | undefined; } -interface Uint16Array { +interface Uint16Array { /** * Returns the item located at the specified index. * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. @@ -72,7 +72,7 @@ interface Uint16Array { at(index: number): number | undefined; } -interface Int32Array { +interface Int32Array { /** * Returns the item located at the specified index. * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. @@ -80,7 +80,7 @@ interface Int32Array { at(index: number): number | undefined; } -interface Uint32Array { +interface Uint32Array { /** * Returns the item located at the specified index. * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. @@ -88,7 +88,7 @@ interface Uint32Array { at(index: number): number | undefined; } -interface Float32Array { +interface Float32Array { /** * Returns the item located at the specified index. * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. @@ -96,7 +96,7 @@ interface Float32Array { at(index: number): number | undefined; } -interface Float64Array { +interface Float64Array { /** * Returns the item located at the specified index. * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. @@ -104,7 +104,7 @@ interface Float64Array { at(index: number): number | undefined; } -interface BigInt64Array { +interface BigInt64Array { /** * Returns the item located at the specified index. * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. @@ -112,7 +112,7 @@ interface BigInt64Array { at(index: number): bigint | undefined; } -interface BigUint64Array { +interface BigUint64Array { /** * Returns the item located at the specified index. * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. diff --git a/cli/tsc/dts/lib.es2022.d.ts b/cli/tsc/dts/lib.es2022.d.ts index 2ae78aba3f6b67..ca7cc91ac95735 100644 --- a/cli/tsc/dts/lib.es2022.d.ts +++ b/cli/tsc/dts/lib.es2022.d.ts @@ -21,6 +21,5 @@ and limitations under the License. /// /// /// -/// -/// /// +/// diff --git a/cli/tsc/dts/lib.es2022.error.d.ts b/cli/tsc/dts/lib.es2022.error.d.ts index 782c485e7cbadc..5e02521b42b6de 100644 --- a/cli/tsc/dts/lib.es2022.error.d.ts +++ b/cli/tsc/dts/lib.es2022.error.d.ts @@ -16,6 +16,8 @@ and limitations under the License. /// +/// + interface ErrorOptions { cause?: unknown; } diff --git a/cli/tsc/dts/lib.es2022.intl.d.ts b/cli/tsc/dts/lib.es2022.intl.d.ts index cd8eb11408c57d..3f4a2ca1e44fe2 100644 --- a/cli/tsc/dts/lib.es2022.intl.d.ts +++ b/cli/tsc/dts/lib.es2022.intl.d.ts @@ -20,7 +20,7 @@ declare namespace Intl { /** * An object with some or all properties of the `Intl.Segmenter` constructor `options` parameter. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/Segmenter#parameters) + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/Segmenter#parameters) */ interface SegmenterOptions { /** The locale matching algorithm to use. For information about this option, see [Intl page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation). */ @@ -84,14 +84,14 @@ declare namespace Intl { * * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings. * For the general form and interpretation of the `locales` argument, - * see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation). + * see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation). * - * @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/Segmenter#parameters) + * @param options - An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/Segmenter#parameters) * with some or all options of `SegmenterOptions`. * - * @returns [Intl.Segmenter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segments) object. + * @returns [Intl.Segmenter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segments) object. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter). */ new (locales?: LocalesArgument, options?: SegmenterOptions): Segmenter; @@ -100,19 +100,19 @@ declare namespace Intl { * * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings. * For the general form and interpretation of the `locales` argument, - * see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation). + * see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation). * - * @param options An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/supportedLocalesOf#parameters). + * @param options An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/supportedLocalesOf#parameters). * with some or all possible options. * - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/supportedLocalesOf) + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/supportedLocalesOf) */ supportedLocalesOf(locales: LocalesArgument, options?: Pick): UnicodeBCP47LocaleIdentifier[]; }; /** * Returns a sorted array of the supported collation, calendar, currency, numbering system, timezones, and units by the implementation. - * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/supportedValuesOf) + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/supportedValuesOf) * * @param key A string indicating the category of values to return. * @returns A sorted array of the supported values. diff --git a/cli/tsc/dts/lib.es2023.array.d.ts b/cli/tsc/dts/lib.es2023.array.d.ts index 57362da53cf3d9..2fe8b55a0cc04b 100644 --- a/cli/tsc/dts/lib.es2023.array.d.ts +++ b/cli/tsc/dts/lib.es2023.array.d.ts @@ -163,7 +163,7 @@ interface ReadonlyArray { with(index: number, value: T): T[]; } -interface Int8Array { +interface Int8Array { /** * Returns the value of the last element in the array where predicate is true, and undefined * otherwise. @@ -177,12 +177,12 @@ interface Int8Array { predicate: ( value: number, index: number, - array: Int8Array, + array: this, ) => value is S, thisArg?: any, ): S | undefined; findLast( - predicate: (value: number, index: number, array: Int8Array) => unknown, + predicate: (value: number, index: number, array: this) => unknown, thisArg?: any, ): number | undefined; @@ -196,14 +196,14 @@ interface Int8Array { * predicate. If it is not provided, undefined is used instead. */ findLastIndex( - predicate: (value: number, index: number, array: Int8Array) => unknown, + predicate: (value: number, index: number, array: this) => unknown, thisArg?: any, ): number; /** * Copies the array and returns the copy with the elements in reverse order. */ - toReversed(): Int8Array; + toReversed(): Int8Array; /** * Copies and sorts the array. @@ -211,11 +211,11 @@ interface Int8Array { * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts - * const myNums = Int8Array.from([11, 2, 22, 1]); - * myNums.toSorted((a, b) => a - b) // Int8Array(4) [1, 2, 11, 22] + * const myNums = Int8Array.from([11, 2, 22, 1]); + * myNums.toSorted((a, b) => a - b) // Int8Array(4) [1, 2, 11, 22] * ``` */ - toSorted(compareFn?: (a: number, b: number) => number): Int8Array; + toSorted(compareFn?: (a: number, b: number) => number): Int8Array; /** * Copies the array and inserts the given number at the provided index. @@ -224,10 +224,10 @@ interface Int8Array { * @param value The value to insert into the copied array. * @returns A copy of the original array with the inserted value. */ - with(index: number, value: number): Int8Array; + with(index: number, value: number): Int8Array; } -interface Uint8Array { +interface Uint8Array { /** * Returns the value of the last element in the array where predicate is true, and undefined * otherwise. @@ -241,12 +241,12 @@ interface Uint8Array { predicate: ( value: number, index: number, - array: Uint8Array, + array: this, ) => value is S, thisArg?: any, ): S | undefined; findLast( - predicate: (value: number, index: number, array: Uint8Array) => unknown, + predicate: (value: number, index: number, array: this) => unknown, thisArg?: any, ): number | undefined; @@ -260,14 +260,14 @@ interface Uint8Array { * predicate. If it is not provided, undefined is used instead. */ findLastIndex( - predicate: (value: number, index: number, array: Uint8Array) => unknown, + predicate: (value: number, index: number, array: this) => unknown, thisArg?: any, ): number; /** * Copies the array and returns the copy with the elements in reverse order. */ - toReversed(): Uint8Array; + toReversed(): Uint8Array; /** * Copies and sorts the array. @@ -275,11 +275,11 @@ interface Uint8Array { * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts - * const myNums = Uint8Array.from([11, 2, 22, 1]); - * myNums.toSorted((a, b) => a - b) // Uint8Array(4) [1, 2, 11, 22] + * const myNums = Uint8Array.from([11, 2, 22, 1]); + * myNums.toSorted((a, b) => a - b) // Uint8Array(4) [1, 2, 11, 22] * ``` */ - toSorted(compareFn?: (a: number, b: number) => number): Uint8Array; + toSorted(compareFn?: (a: number, b: number) => number): Uint8Array; /** * Copies the array and inserts the given number at the provided index. @@ -288,10 +288,10 @@ interface Uint8Array { * @param value The value to insert into the copied array. * @returns A copy of the original array with the inserted value. */ - with(index: number, value: number): Uint8Array; + with(index: number, value: number): Uint8Array; } -interface Uint8ClampedArray { +interface Uint8ClampedArray { /** * Returns the value of the last element in the array where predicate is true, and undefined * otherwise. @@ -305,7 +305,7 @@ interface Uint8ClampedArray { predicate: ( value: number, index: number, - array: Uint8ClampedArray, + array: this, ) => value is S, thisArg?: any, ): S | undefined; @@ -313,7 +313,7 @@ interface Uint8ClampedArray { predicate: ( value: number, index: number, - array: Uint8ClampedArray, + array: this, ) => unknown, thisArg?: any, ): number | undefined; @@ -331,7 +331,7 @@ interface Uint8ClampedArray { predicate: ( value: number, index: number, - array: Uint8ClampedArray, + array: this, ) => unknown, thisArg?: any, ): number; @@ -339,7 +339,7 @@ interface Uint8ClampedArray { /** * Copies the array and returns the copy with the elements in reverse order. */ - toReversed(): Uint8ClampedArray; + toReversed(): Uint8ClampedArray; /** * Copies and sorts the array. @@ -347,11 +347,11 @@ interface Uint8ClampedArray { * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts - * const myNums = Uint8ClampedArray.from([11, 2, 22, 1]); - * myNums.toSorted((a, b) => a - b) // Uint8ClampedArray(4) [1, 2, 11, 22] + * const myNums = Uint8ClampedArray.from([11, 2, 22, 1]); + * myNums.toSorted((a, b) => a - b) // Uint8ClampedArray(4) [1, 2, 11, 22] * ``` */ - toSorted(compareFn?: (a: number, b: number) => number): Uint8ClampedArray; + toSorted(compareFn?: (a: number, b: number) => number): Uint8ClampedArray; /** * Copies the array and inserts the given number at the provided index. @@ -360,10 +360,10 @@ interface Uint8ClampedArray { * @param value The value to insert into the copied array. * @returns A copy of the original array with the inserted value. */ - with(index: number, value: number): Uint8ClampedArray; + with(index: number, value: number): Uint8ClampedArray; } -interface Int16Array { +interface Int16Array { /** * Returns the value of the last element in the array where predicate is true, and undefined * otherwise. @@ -377,12 +377,12 @@ interface Int16Array { predicate: ( value: number, index: number, - array: Int16Array, + array: this, ) => value is S, thisArg?: any, ): S | undefined; findLast( - predicate: (value: number, index: number, array: Int16Array) => unknown, + predicate: (value: number, index: number, array: this) => unknown, thisArg?: any, ): number | undefined; @@ -396,14 +396,14 @@ interface Int16Array { * predicate. If it is not provided, undefined is used instead. */ findLastIndex( - predicate: (value: number, index: number, array: Int16Array) => unknown, + predicate: (value: number, index: number, array: this) => unknown, thisArg?: any, ): number; /** * Copies the array and returns the copy with the elements in reverse order. */ - toReversed(): Int16Array; + toReversed(): Int16Array; /** * Copies and sorts the array. @@ -411,11 +411,11 @@ interface Int16Array { * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts - * const myNums = Int16Array.from([11, 2, -22, 1]); - * myNums.toSorted((a, b) => a - b) // Int16Array(4) [-22, 1, 2, 11] + * const myNums = Int16Array.from([11, 2, -22, 1]); + * myNums.toSorted((a, b) => a - b) // Int16Array(4) [-22, 1, 2, 11] * ``` */ - toSorted(compareFn?: (a: number, b: number) => number): Int16Array; + toSorted(compareFn?: (a: number, b: number) => number): Int16Array; /** * Copies the array and inserts the given number at the provided index. @@ -424,10 +424,10 @@ interface Int16Array { * @param value The value to insert into the copied array. * @returns A copy of the original array with the inserted value. */ - with(index: number, value: number): Int16Array; + with(index: number, value: number): Int16Array; } -interface Uint16Array { +interface Uint16Array { /** * Returns the value of the last element in the array where predicate is true, and undefined * otherwise. @@ -441,7 +441,7 @@ interface Uint16Array { predicate: ( value: number, index: number, - array: Uint16Array, + array: this, ) => value is S, thisArg?: any, ): S | undefined; @@ -449,7 +449,7 @@ interface Uint16Array { predicate: ( value: number, index: number, - array: Uint16Array, + array: this, ) => unknown, thisArg?: any, ): number | undefined; @@ -467,7 +467,7 @@ interface Uint16Array { predicate: ( value: number, index: number, - array: Uint16Array, + array: this, ) => unknown, thisArg?: any, ): number; @@ -475,7 +475,7 @@ interface Uint16Array { /** * Copies the array and returns the copy with the elements in reverse order. */ - toReversed(): Uint16Array; + toReversed(): Uint16Array; /** * Copies and sorts the array. @@ -483,11 +483,11 @@ interface Uint16Array { * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts - * const myNums = Uint16Array.from([11, 2, 22, 1]); - * myNums.toSorted((a, b) => a - b) // Uint16Array(4) [1, 2, 11, 22] + * const myNums = Uint16Array.from([11, 2, 22, 1]); + * myNums.toSorted((a, b) => a - b) // Uint16Array(4) [1, 2, 11, 22] * ``` */ - toSorted(compareFn?: (a: number, b: number) => number): Uint16Array; + toSorted(compareFn?: (a: number, b: number) => number): Uint16Array; /** * Copies the array and inserts the given number at the provided index. @@ -496,10 +496,10 @@ interface Uint16Array { * @param value The value to insert into the copied array. * @returns A copy of the original array with the inserted value. */ - with(index: number, value: number): Uint16Array; + with(index: number, value: number): Uint16Array; } -interface Int32Array { +interface Int32Array { /** * Returns the value of the last element in the array where predicate is true, and undefined * otherwise. @@ -513,12 +513,12 @@ interface Int32Array { predicate: ( value: number, index: number, - array: Int32Array, + array: this, ) => value is S, thisArg?: any, ): S | undefined; findLast( - predicate: (value: number, index: number, array: Int32Array) => unknown, + predicate: (value: number, index: number, array: this) => unknown, thisArg?: any, ): number | undefined; @@ -532,14 +532,14 @@ interface Int32Array { * predicate. If it is not provided, undefined is used instead. */ findLastIndex( - predicate: (value: number, index: number, array: Int32Array) => unknown, + predicate: (value: number, index: number, array: this) => unknown, thisArg?: any, ): number; /** * Copies the array and returns the copy with the elements in reverse order. */ - toReversed(): Int32Array; + toReversed(): Int32Array; /** * Copies and sorts the array. @@ -547,11 +547,11 @@ interface Int32Array { * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts - * const myNums = Int32Array.from([11, 2, -22, 1]); - * myNums.toSorted((a, b) => a - b) // Int32Array(4) [-22, 1, 2, 11] + * const myNums = Int32Array.from([11, 2, -22, 1]); + * myNums.toSorted((a, b) => a - b) // Int32Array(4) [-22, 1, 2, 11] * ``` */ - toSorted(compareFn?: (a: number, b: number) => number): Int32Array; + toSorted(compareFn?: (a: number, b: number) => number): Int32Array; /** * Copies the array and inserts the given number at the provided index. @@ -560,10 +560,10 @@ interface Int32Array { * @param value The value to insert into the copied array. * @returns A copy of the original array with the inserted value. */ - with(index: number, value: number): Int32Array; + with(index: number, value: number): Int32Array; } -interface Uint32Array { +interface Uint32Array { /** * Returns the value of the last element in the array where predicate is true, and undefined * otherwise. @@ -577,7 +577,7 @@ interface Uint32Array { predicate: ( value: number, index: number, - array: Uint32Array, + array: this, ) => value is S, thisArg?: any, ): S | undefined; @@ -585,7 +585,7 @@ interface Uint32Array { predicate: ( value: number, index: number, - array: Uint32Array, + array: this, ) => unknown, thisArg?: any, ): number | undefined; @@ -603,7 +603,7 @@ interface Uint32Array { predicate: ( value: number, index: number, - array: Uint32Array, + array: this, ) => unknown, thisArg?: any, ): number; @@ -611,7 +611,7 @@ interface Uint32Array { /** * Copies the array and returns the copy with the elements in reverse order. */ - toReversed(): Uint32Array; + toReversed(): Uint32Array; /** * Copies and sorts the array. @@ -619,11 +619,11 @@ interface Uint32Array { * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts - * const myNums = Uint32Array.from([11, 2, 22, 1]); - * myNums.toSorted((a, b) => a - b) // Uint32Array(4) [1, 2, 11, 22] + * const myNums = Uint32Array.from([11, 2, 22, 1]); + * myNums.toSorted((a, b) => a - b) // Uint32Array(4) [1, 2, 11, 22] * ``` */ - toSorted(compareFn?: (a: number, b: number) => number): Uint32Array; + toSorted(compareFn?: (a: number, b: number) => number): Uint32Array; /** * Copies the array and inserts the given number at the provided index. @@ -632,10 +632,10 @@ interface Uint32Array { * @param value The value to insert into the copied array. * @returns A copy of the original array with the inserted value. */ - with(index: number, value: number): Uint32Array; + with(index: number, value: number): Uint32Array; } -interface Float32Array { +interface Float32Array { /** * Returns the value of the last element in the array where predicate is true, and undefined * otherwise. @@ -649,7 +649,7 @@ interface Float32Array { predicate: ( value: number, index: number, - array: Float32Array, + array: this, ) => value is S, thisArg?: any, ): S | undefined; @@ -657,7 +657,7 @@ interface Float32Array { predicate: ( value: number, index: number, - array: Float32Array, + array: this, ) => unknown, thisArg?: any, ): number | undefined; @@ -675,7 +675,7 @@ interface Float32Array { predicate: ( value: number, index: number, - array: Float32Array, + array: this, ) => unknown, thisArg?: any, ): number; @@ -683,7 +683,7 @@ interface Float32Array { /** * Copies the array and returns the copy with the elements in reverse order. */ - toReversed(): Float32Array; + toReversed(): Float32Array; /** * Copies and sorts the array. @@ -691,11 +691,11 @@ interface Float32Array { * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts - * const myNums = Float32Array.from([11.25, 2, -22.5, 1]); - * myNums.toSorted((a, b) => a - b) // Float32Array(4) [-22.5, 1, 2, 11.5] + * const myNums = Float32Array.from([11.25, 2, -22.5, 1]); + * myNums.toSorted((a, b) => a - b) // Float32Array(4) [-22.5, 1, 2, 11.5] * ``` */ - toSorted(compareFn?: (a: number, b: number) => number): Float32Array; + toSorted(compareFn?: (a: number, b: number) => number): Float32Array; /** * Copies the array and inserts the given number at the provided index. @@ -704,10 +704,10 @@ interface Float32Array { * @param value The value to insert into the copied array. * @returns A copy of the original array with the inserted value. */ - with(index: number, value: number): Float32Array; + with(index: number, value: number): Float32Array; } -interface Float64Array { +interface Float64Array { /** * Returns the value of the last element in the array where predicate is true, and undefined * otherwise. @@ -721,7 +721,7 @@ interface Float64Array { predicate: ( value: number, index: number, - array: Float64Array, + array: this, ) => value is S, thisArg?: any, ): S | undefined; @@ -729,7 +729,7 @@ interface Float64Array { predicate: ( value: number, index: number, - array: Float64Array, + array: this, ) => unknown, thisArg?: any, ): number | undefined; @@ -747,7 +747,7 @@ interface Float64Array { predicate: ( value: number, index: number, - array: Float64Array, + array: this, ) => unknown, thisArg?: any, ): number; @@ -755,7 +755,7 @@ interface Float64Array { /** * Copies the array and returns the copy with the elements in reverse order. */ - toReversed(): Float64Array; + toReversed(): Float64Array; /** * Copies and sorts the array. @@ -763,11 +763,11 @@ interface Float64Array { * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts - * const myNums = Float64Array.from([11.25, 2, -22.5, 1]); - * myNums.toSorted((a, b) => a - b) // Float64Array(4) [-22.5, 1, 2, 11.5] + * const myNums = Float64Array.from([11.25, 2, -22.5, 1]); + * myNums.toSorted((a, b) => a - b) // Float64Array(4) [-22.5, 1, 2, 11.5] * ``` */ - toSorted(compareFn?: (a: number, b: number) => number): Float64Array; + toSorted(compareFn?: (a: number, b: number) => number): Float64Array; /** * Copies the array and inserts the given number at the provided index. @@ -776,10 +776,10 @@ interface Float64Array { * @param value The value to insert into the copied array. * @returns A copy of the original array with the inserted value. */ - with(index: number, value: number): Float64Array; + with(index: number, value: number): Float64Array; } -interface BigInt64Array { +interface BigInt64Array { /** * Returns the value of the last element in the array where predicate is true, and undefined * otherwise. @@ -793,7 +793,7 @@ interface BigInt64Array { predicate: ( value: bigint, index: number, - array: BigInt64Array, + array: this, ) => value is S, thisArg?: any, ): S | undefined; @@ -801,7 +801,7 @@ interface BigInt64Array { predicate: ( value: bigint, index: number, - array: BigInt64Array, + array: this, ) => unknown, thisArg?: any, ): bigint | undefined; @@ -819,7 +819,7 @@ interface BigInt64Array { predicate: ( value: bigint, index: number, - array: BigInt64Array, + array: this, ) => unknown, thisArg?: any, ): number; @@ -827,7 +827,7 @@ interface BigInt64Array { /** * Copies the array and returns the copy with the elements in reverse order. */ - toReversed(): BigInt64Array; + toReversed(): BigInt64Array; /** * Copies and sorts the array. @@ -835,11 +835,11 @@ interface BigInt64Array { * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts - * const myNums = BigInt64Array.from([11n, 2n, -22n, 1n]); - * myNums.toSorted((a, b) => Number(a - b)) // BigInt64Array(4) [-22n, 1n, 2n, 11n] + * const myNums = BigInt64Array.from([11n, 2n, -22n, 1n]); + * myNums.toSorted((a, b) => Number(a - b)) // BigInt64Array(4) [-22n, 1n, 2n, 11n] * ``` */ - toSorted(compareFn?: (a: bigint, b: bigint) => number): BigInt64Array; + toSorted(compareFn?: (a: bigint, b: bigint) => number): BigInt64Array; /** * Copies the array and inserts the given bigint at the provided index. @@ -848,10 +848,10 @@ interface BigInt64Array { * @param value The value to insert into the copied array. * @returns A copy of the original array with the inserted value. */ - with(index: number, value: bigint): BigInt64Array; + with(index: number, value: bigint): BigInt64Array; } -interface BigUint64Array { +interface BigUint64Array { /** * Returns the value of the last element in the array where predicate is true, and undefined * otherwise. @@ -865,7 +865,7 @@ interface BigUint64Array { predicate: ( value: bigint, index: number, - array: BigUint64Array, + array: this, ) => value is S, thisArg?: any, ): S | undefined; @@ -873,7 +873,7 @@ interface BigUint64Array { predicate: ( value: bigint, index: number, - array: BigUint64Array, + array: this, ) => unknown, thisArg?: any, ): bigint | undefined; @@ -891,7 +891,7 @@ interface BigUint64Array { predicate: ( value: bigint, index: number, - array: BigUint64Array, + array: this, ) => unknown, thisArg?: any, ): number; @@ -899,7 +899,7 @@ interface BigUint64Array { /** * Copies the array and returns the copy with the elements in reverse order. */ - toReversed(): BigUint64Array; + toReversed(): BigUint64Array; /** * Copies and sorts the array. @@ -907,11 +907,11 @@ interface BigUint64Array { * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive * value otherwise. If omitted, the elements are sorted in ascending order. * ```ts - * const myNums = BigUint64Array.from([11n, 2n, 22n, 1n]); - * myNums.toSorted((a, b) => Number(a - b)) // BigUint64Array(4) [1n, 2n, 11n, 22n] + * const myNums = BigUint64Array.from([11n, 2n, 22n, 1n]); + * myNums.toSorted((a, b) => Number(a - b)) // BigUint64Array(4) [1n, 2n, 11n, 22n] * ``` */ - toSorted(compareFn?: (a: bigint, b: bigint) => number): BigUint64Array; + toSorted(compareFn?: (a: bigint, b: bigint) => number): BigUint64Array; /** * Copies the array and inserts the given bigint at the provided index. @@ -920,5 +920,5 @@ interface BigUint64Array { * @param value The value to insert into the copied array. * @returns A copy of the original array with the inserted value. */ - with(index: number, value: bigint): BigUint64Array; + with(index: number, value: bigint): BigUint64Array; } diff --git a/cli/tsc/dts/lib.es2024.arraybuffer.d.ts b/cli/tsc/dts/lib.es2024.arraybuffer.d.ts new file mode 100644 index 00000000000000..2a5623d90c5b2a --- /dev/null +++ b/cli/tsc/dts/lib.es2024.arraybuffer.d.ts @@ -0,0 +1,65 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +/// + +interface ArrayBuffer { + /** + * If this ArrayBuffer is resizable, returns the maximum byte length given during construction; returns the byte length if not. + * + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/maxByteLength) + */ + get maxByteLength(): number; + + /** + * Returns true if this ArrayBuffer can be resized. + * + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/resizable) + */ + get resizable(): boolean; + + /** + * Resizes the ArrayBuffer to the specified size (in bytes). + * + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/resize) + */ + resize(newByteLength?: number): void; + + /** + * Returns a boolean indicating whether or not this buffer has been detached (transferred). + * + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/detached) + */ + get detached(): boolean; + + /** + * Creates a new ArrayBuffer with the same byte content as this buffer, then detaches this buffer. + * + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/transfer) + */ + transfer(newByteLength?: number): ArrayBuffer; + + /** + * Creates a new non-resizable ArrayBuffer with the same byte content as this buffer, then detaches this buffer. + * + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/transferToFixedLength) + */ + transferToFixedLength(newByteLength?: number): ArrayBuffer; +} + +interface ArrayBufferConstructor { + new (byteLength: number, options?: { maxByteLength?: number; }): ArrayBuffer; +} diff --git a/cli/tsc/dts/lib.es2024.collection.d.ts b/cli/tsc/dts/lib.es2024.collection.d.ts new file mode 100644 index 00000000000000..a48fd93d5f8065 --- /dev/null +++ b/cli/tsc/dts/lib.es2024.collection.d.ts @@ -0,0 +1,29 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +/// + +interface MapConstructor { + /** + * Groups members of an iterable according to the return value of the passed callback. + * @param items An iterable. + * @param keySelector A callback which will be invoked for each item in items. + */ + groupBy( + items: Iterable, + keySelector: (item: T, index: number) => K, + ): Map; +} diff --git a/cli/tsc/dts/lib.es2024.d.ts b/cli/tsc/dts/lib.es2024.d.ts new file mode 100644 index 00000000000000..44311afb001295 --- /dev/null +++ b/cli/tsc/dts/lib.es2024.d.ts @@ -0,0 +1,26 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +/// + +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/cli/tsc/dts/lib.es2024.full.d.ts b/cli/tsc/dts/lib.es2024.full.d.ts new file mode 100644 index 00000000000000..b8c6e74867a446 --- /dev/null +++ b/cli/tsc/dts/lib.es2024.full.d.ts @@ -0,0 +1,24 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +/// + +/// +/// +/// +/// +/// +/// diff --git a/cli/tsc/dts/lib.esnext.object.d.ts b/cli/tsc/dts/lib.es2024.object.d.ts similarity index 100% rename from cli/tsc/dts/lib.esnext.object.d.ts rename to cli/tsc/dts/lib.es2024.object.d.ts diff --git a/cli/tsc/dts/lib.esnext.promise.d.ts b/cli/tsc/dts/lib.es2024.promise.d.ts similarity index 100% rename from cli/tsc/dts/lib.esnext.promise.d.ts rename to cli/tsc/dts/lib.es2024.promise.d.ts diff --git a/cli/tsc/dts/lib.esnext.regexp.d.ts b/cli/tsc/dts/lib.es2024.regexp.d.ts similarity index 100% rename from cli/tsc/dts/lib.esnext.regexp.d.ts rename to cli/tsc/dts/lib.es2024.regexp.d.ts diff --git a/cli/tsc/dts/lib.es2022.sharedmemory.d.ts b/cli/tsc/dts/lib.es2024.sharedmemory.d.ts similarity index 67% rename from cli/tsc/dts/lib.es2022.sharedmemory.d.ts rename to cli/tsc/dts/lib.es2024.sharedmemory.d.ts index ea67b0081b1356..2c3cf94acaa3ed 100644 --- a/cli/tsc/dts/lib.es2022.sharedmemory.d.ts +++ b/cli/tsc/dts/lib.es2024.sharedmemory.d.ts @@ -16,6 +16,8 @@ and limitations under the License. /// +/// + interface Atomics { /** * A non-blocking, asynchronous version of wait which is usable on the main thread. @@ -37,3 +39,30 @@ interface Atomics { */ waitAsync(typedArray: BigInt64Array, index: number, value: bigint, timeout?: number): { async: false; value: "not-equal" | "timed-out"; } | { async: true; value: Promise<"ok" | "timed-out">; }; } + +interface SharedArrayBuffer { + /** + * Returns true if this SharedArrayBuffer can be grown. + * + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/growable) + */ + get growable(): boolean; + + /** + * If this SharedArrayBuffer is growable, returns the maximum byte length given during construction; returns the byte length if not. + * + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/maxByteLength) + */ + get maxByteLength(): number; + + /** + * Grows the SharedArrayBuffer to the specified size (in bytes). + * + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer/grow) + */ + grow(newByteLength?: number): void; +} + +interface SharedArrayBufferConstructor { + new (byteLength: number, options?: { maxByteLength?: number; }): SharedArrayBuffer; +} diff --git a/cli/tsc/dts/lib.esnext.string.d.ts b/cli/tsc/dts/lib.es2024.string.d.ts similarity index 100% rename from cli/tsc/dts/lib.esnext.string.d.ts rename to cli/tsc/dts/lib.es2024.string.d.ts diff --git a/cli/tsc/dts/lib.es5.d.ts b/cli/tsc/dts/lib.es5.d.ts index cf9adfe1e03d43..3e462978895657 100644 --- a/cli/tsc/dts/lib.es5.d.ts +++ b/cli/tsc/dts/lib.es5.d.ts @@ -1701,7 +1701,7 @@ interface ArrayBuffer { /** * Returns a section of an ArrayBuffer. */ - slice(begin: number, end?: number): ArrayBuffer; + slice(begin?: number, end?: number): ArrayBuffer; } /** @@ -1719,25 +1719,25 @@ interface ArrayBufferConstructor { } declare var ArrayBuffer: ArrayBufferConstructor; -interface ArrayBufferView { +interface ArrayBufferView { /** * The ArrayBuffer instance referenced by the array. */ - buffer: ArrayBufferLike; + readonly buffer: TArrayBuffer; /** * The length in bytes of the array. */ - byteLength: number; + readonly byteLength: number; /** * The offset in bytes of the array. */ - byteOffset: number; + readonly byteOffset: number; } -interface DataView { - readonly buffer: ArrayBuffer; +interface DataView { + readonly buffer: TArrayBuffer; readonly byteLength: number; readonly byteOffset: number; /** @@ -1863,10 +1863,9 @@ interface DataView { */ setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; } - interface DataViewConstructor { - readonly prototype: DataView; - new (buffer: ArrayBufferLike & { BYTES_PER_ELEMENT?: never; }, byteOffset?: number, byteLength?: number): DataView; + readonly prototype: DataView; + new (buffer: TArrayBuffer, byteOffset?: number, byteLength?: number): DataView; } declare var DataView: DataViewConstructor; @@ -1874,7 +1873,7 @@ declare var DataView: DataViewConstructor; * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested * number of bytes could not be allocated an exception is raised. */ -interface Int8Array { +interface Int8Array { /** * The size in bytes of each element in the array. */ @@ -1883,7 +1882,7 @@ interface Int8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBufferLike; + readonly buffer: TArrayBuffer; /** * The length in bytes of the array. @@ -1914,7 +1913,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - every(predicate: (value: number, index: number, array: Int8Array) => unknown, thisArg?: any): boolean; + every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array @@ -1933,7 +1932,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - filter(predicate: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array; + filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Int8Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -1944,7 +1943,7 @@ interface Int8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -1955,7 +1954,7 @@ interface Int8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -1964,7 +1963,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void; + forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -2002,7 +2001,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; + map(callbackfn: (value: number, index: number, array: this) => number, thisArg?: any): Int8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2014,8 +2013,8 @@ interface Int8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2027,7 +2026,7 @@ interface Int8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2039,8 +2038,8 @@ interface Int8Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2052,12 +2051,12 @@ interface Int8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ - reverse(): Int8Array; + reverse(): this; /** * Sets a value or an array of values. @@ -2071,7 +2070,7 @@ interface Int8Array { * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. */ - slice(start?: number, end?: number): Int8Array; + slice(start?: number, end?: number): Int8Array; /** * Determines whether the specified callback function returns true for any element of an array. @@ -2081,7 +2080,7 @@ interface Int8Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - some(predicate: (value: number, index: number, array: Int8Array) => unknown, thisArg?: any): boolean; + some(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Sorts an array. @@ -2100,7 +2099,7 @@ interface Int8Array { * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ - subarray(begin?: number, end?: number): Int8Array; + subarray(begin?: number, end?: number): Int8Array; /** * Converts a number to a string by using the current locale. @@ -2113,15 +2112,16 @@ interface Int8Array { toString(): string; /** Returns the primitive value of the specified object. */ - valueOf(): Int8Array; + valueOf(): this; [index: number]: number; } interface Int8ArrayConstructor { - readonly prototype: Int8Array; - new (length: number): Int8Array; - new (array: ArrayLike | ArrayBufferLike): Int8Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array; + readonly prototype: Int8Array; + new (length: number): Int8Array; + new (array: ArrayLike): Int8Array; + new (buffer: TArrayBuffer, byteOffset?: number, length?: number): Int8Array; + new (array: ArrayLike | ArrayBuffer): Int8Array; /** * The size in bytes of each element in the array. @@ -2132,13 +2132,13 @@ interface Int8ArrayConstructor { * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ - of(...items: number[]): Int8Array; + of(...items: number[]): Int8Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. */ - from(arrayLike: ArrayLike): Int8Array; + from(arrayLike: ArrayLike): Int8Array; /** * Creates an array from an array-like or iterable object. @@ -2146,7 +2146,7 @@ interface Int8ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int8Array; + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int8Array; } declare var Int8Array: Int8ArrayConstructor; @@ -2154,7 +2154,7 @@ declare var Int8Array: Int8ArrayConstructor; * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. */ -interface Uint8Array { +interface Uint8Array { /** * The size in bytes of each element in the array. */ @@ -2163,7 +2163,7 @@ interface Uint8Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBufferLike; + readonly buffer: TArrayBuffer; /** * The length in bytes of the array. @@ -2194,7 +2194,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - every(predicate: (value: number, index: number, array: Uint8Array) => unknown, thisArg?: any): boolean; + every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array @@ -2213,7 +2213,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - filter(predicate: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array; + filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Uint8Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -2224,7 +2224,7 @@ interface Uint8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2235,7 +2235,7 @@ interface Uint8Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2244,7 +2244,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; + forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -2282,7 +2282,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; + map(callbackfn: (value: number, index: number, array: this) => number, thisArg?: any): Uint8Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2294,8 +2294,8 @@ interface Uint8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2307,7 +2307,7 @@ interface Uint8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2319,8 +2319,8 @@ interface Uint8Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2332,12 +2332,12 @@ interface Uint8Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ - reverse(): Uint8Array; + reverse(): this; /** * Sets a value or an array of values. @@ -2351,7 +2351,7 @@ interface Uint8Array { * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. */ - slice(start?: number, end?: number): Uint8Array; + slice(start?: number, end?: number): Uint8Array; /** * Determines whether the specified callback function returns true for any element of an array. @@ -2361,7 +2361,7 @@ interface Uint8Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - some(predicate: (value: number, index: number, array: Uint8Array) => unknown, thisArg?: any): boolean; + some(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Sorts an array. @@ -2380,7 +2380,7 @@ interface Uint8Array { * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ - subarray(begin?: number, end?: number): Uint8Array; + subarray(begin?: number, end?: number): Uint8Array; /** * Converts a number to a string by using the current locale. @@ -2393,16 +2393,16 @@ interface Uint8Array { toString(): string; /** Returns the primitive value of the specified object. */ - valueOf(): Uint8Array; + valueOf(): this; [index: number]: number; } - interface Uint8ArrayConstructor { - readonly prototype: Uint8Array; - new (length: number): Uint8Array; - new (array: ArrayLike | ArrayBufferLike): Uint8Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8Array; + readonly prototype: Uint8Array; + new (length: number): Uint8Array; + new (array: ArrayLike): Uint8Array; + new (buffer: TArrayBuffer, byteOffset?: number, length?: number): Uint8Array; + new (array: ArrayLike | ArrayBuffer): Uint8Array; /** * The size in bytes of each element in the array. @@ -2413,13 +2413,13 @@ interface Uint8ArrayConstructor { * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ - of(...items: number[]): Uint8Array; + of(...items: number[]): Uint8Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. */ - from(arrayLike: ArrayLike): Uint8Array; + from(arrayLike: ArrayLike): Uint8Array; /** * Creates an array from an array-like or iterable object. @@ -2427,7 +2427,7 @@ interface Uint8ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8Array; + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8Array; } declare var Uint8Array: Uint8ArrayConstructor; @@ -2435,7 +2435,7 @@ declare var Uint8Array: Uint8ArrayConstructor; * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. * If the requested number of bytes could not be allocated an exception is raised. */ -interface Uint8ClampedArray { +interface Uint8ClampedArray { /** * The size in bytes of each element in the array. */ @@ -2444,7 +2444,7 @@ interface Uint8ClampedArray { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBufferLike; + readonly buffer: TArrayBuffer; /** * The length in bytes of the array. @@ -2475,7 +2475,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - every(predicate: (value: number, index: number, array: Uint8ClampedArray) => unknown, thisArg?: any): boolean; + every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array @@ -2494,7 +2494,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - filter(predicate: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray; + filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Uint8ClampedArray; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -2505,7 +2505,7 @@ interface Uint8ClampedArray { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2516,7 +2516,7 @@ interface Uint8ClampedArray { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2525,7 +2525,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void; + forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -2563,7 +2563,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; + map(callbackfn: (value: number, index: number, array: this) => number, thisArg?: any): Uint8ClampedArray; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2575,8 +2575,8 @@ interface Uint8ClampedArray { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2588,7 +2588,7 @@ interface Uint8ClampedArray { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2600,8 +2600,8 @@ interface Uint8ClampedArray { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2613,12 +2613,12 @@ interface Uint8ClampedArray { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ - reverse(): Uint8ClampedArray; + reverse(): this; /** * Sets a value or an array of values. @@ -2632,7 +2632,7 @@ interface Uint8ClampedArray { * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. */ - slice(start?: number, end?: number): Uint8ClampedArray; + slice(start?: number, end?: number): Uint8ClampedArray; /** * Determines whether the specified callback function returns true for any element of an array. @@ -2642,7 +2642,7 @@ interface Uint8ClampedArray { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - some(predicate: (value: number, index: number, array: Uint8ClampedArray) => unknown, thisArg?: any): boolean; + some(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Sorts an array. @@ -2661,7 +2661,7 @@ interface Uint8ClampedArray { * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ - subarray(begin?: number, end?: number): Uint8ClampedArray; + subarray(begin?: number, end?: number): Uint8ClampedArray; /** * Converts a number to a string by using the current locale. @@ -2674,16 +2674,16 @@ interface Uint8ClampedArray { toString(): string; /** Returns the primitive value of the specified object. */ - valueOf(): Uint8ClampedArray; + valueOf(): this; [index: number]: number; } - interface Uint8ClampedArrayConstructor { - readonly prototype: Uint8ClampedArray; - new (length: number): Uint8ClampedArray; - new (array: ArrayLike | ArrayBufferLike): Uint8ClampedArray; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint8ClampedArray; + readonly prototype: Uint8ClampedArray; + new (length: number): Uint8ClampedArray; + new (array: ArrayLike): Uint8ClampedArray; + new (buffer: TArrayBuffer, byteOffset?: number, length?: number): Uint8ClampedArray; + new (array: ArrayLike | ArrayBuffer): Uint8ClampedArray; /** * The size in bytes of each element in the array. @@ -2694,13 +2694,13 @@ interface Uint8ClampedArrayConstructor { * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ - of(...items: number[]): Uint8ClampedArray; + of(...items: number[]): Uint8ClampedArray; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. */ - from(arrayLike: ArrayLike): Uint8ClampedArray; + from(arrayLike: ArrayLike): Uint8ClampedArray; /** * Creates an array from an array-like or iterable object. @@ -2708,7 +2708,7 @@ interface Uint8ClampedArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8ClampedArray; + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8ClampedArray; } declare var Uint8ClampedArray: Uint8ClampedArrayConstructor; @@ -2716,7 +2716,7 @@ declare var Uint8ClampedArray: Uint8ClampedArrayConstructor; * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. */ -interface Int16Array { +interface Int16Array { /** * The size in bytes of each element in the array. */ @@ -2725,7 +2725,7 @@ interface Int16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBufferLike; + readonly buffer: TArrayBuffer; /** * The length in bytes of the array. @@ -2756,7 +2756,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - every(predicate: (value: number, index: number, array: Int16Array) => unknown, thisArg?: any): boolean; + every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array @@ -2775,7 +2775,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - filter(predicate: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; + filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Int16Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -2786,7 +2786,7 @@ interface Int16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -2797,7 +2797,7 @@ interface Int16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -2806,7 +2806,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void; + forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. @@ -2843,7 +2843,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; + map(callbackfn: (value: number, index: number, array: this) => number, thisArg?: any): Int16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2855,8 +2855,8 @@ interface Int16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -2868,7 +2868,7 @@ interface Int16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2880,8 +2880,8 @@ interface Int16Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -2893,12 +2893,12 @@ interface Int16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ - reverse(): Int16Array; + reverse(): this; /** * Sets a value or an array of values. @@ -2912,7 +2912,7 @@ interface Int16Array { * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. */ - slice(start?: number, end?: number): Int16Array; + slice(start?: number, end?: number): Int16Array; /** * Determines whether the specified callback function returns true for any element of an array. @@ -2922,7 +2922,7 @@ interface Int16Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - some(predicate: (value: number, index: number, array: Int16Array) => unknown, thisArg?: any): boolean; + some(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Sorts an array. @@ -2941,7 +2941,7 @@ interface Int16Array { * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ - subarray(begin?: number, end?: number): Int16Array; + subarray(begin?: number, end?: number): Int16Array; /** * Converts a number to a string by using the current locale. @@ -2954,16 +2954,16 @@ interface Int16Array { toString(): string; /** Returns the primitive value of the specified object. */ - valueOf(): Int16Array; + valueOf(): this; [index: number]: number; } - interface Int16ArrayConstructor { - readonly prototype: Int16Array; - new (length: number): Int16Array; - new (array: ArrayLike | ArrayBufferLike): Int16Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int16Array; + readonly prototype: Int16Array; + new (length: number): Int16Array; + new (array: ArrayLike): Int16Array; + new (buffer: TArrayBuffer, byteOffset?: number, length?: number): Int16Array; + new (array: ArrayLike | ArrayBuffer): Int16Array; /** * The size in bytes of each element in the array. @@ -2974,13 +2974,13 @@ interface Int16ArrayConstructor { * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ - of(...items: number[]): Int16Array; + of(...items: number[]): Int16Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. */ - from(arrayLike: ArrayLike): Int16Array; + from(arrayLike: ArrayLike): Int16Array; /** * Creates an array from an array-like or iterable object. @@ -2988,7 +2988,7 @@ interface Int16ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int16Array; + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int16Array; } declare var Int16Array: Int16ArrayConstructor; @@ -2996,7 +2996,7 @@ declare var Int16Array: Int16ArrayConstructor; * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. */ -interface Uint16Array { +interface Uint16Array { /** * The size in bytes of each element in the array. */ @@ -3005,7 +3005,7 @@ interface Uint16Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBufferLike; + readonly buffer: TArrayBuffer; /** * The length in bytes of the array. @@ -3036,7 +3036,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - every(predicate: (value: number, index: number, array: Uint16Array) => unknown, thisArg?: any): boolean; + every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array @@ -3055,7 +3055,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - filter(predicate: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array; + filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Uint16Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -3066,7 +3066,7 @@ interface Uint16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3077,7 +3077,7 @@ interface Uint16Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3086,7 +3086,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void; + forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -3124,7 +3124,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; + map(callbackfn: (value: number, index: number, array: this) => number, thisArg?: any): Uint16Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3136,8 +3136,8 @@ interface Uint16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3149,7 +3149,7 @@ interface Uint16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3161,8 +3161,8 @@ interface Uint16Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3174,12 +3174,12 @@ interface Uint16Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ - reverse(): Uint16Array; + reverse(): this; /** * Sets a value or an array of values. @@ -3193,7 +3193,7 @@ interface Uint16Array { * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. */ - slice(start?: number, end?: number): Uint16Array; + slice(start?: number, end?: number): Uint16Array; /** * Determines whether the specified callback function returns true for any element of an array. @@ -3203,7 +3203,7 @@ interface Uint16Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - some(predicate: (value: number, index: number, array: Uint16Array) => unknown, thisArg?: any): boolean; + some(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Sorts an array. @@ -3222,7 +3222,7 @@ interface Uint16Array { * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ - subarray(begin?: number, end?: number): Uint16Array; + subarray(begin?: number, end?: number): Uint16Array; /** * Converts a number to a string by using the current locale. @@ -3235,16 +3235,16 @@ interface Uint16Array { toString(): string; /** Returns the primitive value of the specified object. */ - valueOf(): Uint16Array; + valueOf(): this; [index: number]: number; } - interface Uint16ArrayConstructor { - readonly prototype: Uint16Array; - new (length: number): Uint16Array; - new (array: ArrayLike | ArrayBufferLike): Uint16Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint16Array; + readonly prototype: Uint16Array; + new (length: number): Uint16Array; + new (array: ArrayLike): Uint16Array; + new (buffer: TArrayBuffer, byteOffset?: number, length?: number): Uint16Array; + new (array: ArrayLike | ArrayBuffer): Uint16Array; /** * The size in bytes of each element in the array. @@ -3255,13 +3255,13 @@ interface Uint16ArrayConstructor { * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ - of(...items: number[]): Uint16Array; + of(...items: number[]): Uint16Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. */ - from(arrayLike: ArrayLike): Uint16Array; + from(arrayLike: ArrayLike): Uint16Array; /** * Creates an array from an array-like or iterable object. @@ -3269,14 +3269,14 @@ interface Uint16ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint16Array; + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint16Array; } declare var Uint16Array: Uint16ArrayConstructor; /** * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. */ -interface Int32Array { +interface Int32Array { /** * The size in bytes of each element in the array. */ @@ -3285,7 +3285,7 @@ interface Int32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBufferLike; + readonly buffer: TArrayBuffer; /** * The length in bytes of the array. @@ -3316,7 +3316,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - every(predicate: (value: number, index: number, array: Int32Array) => unknown, thisArg?: any): boolean; + every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array @@ -3335,7 +3335,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - filter(predicate: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array; + filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Int32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -3346,7 +3346,7 @@ interface Int32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3357,7 +3357,7 @@ interface Int32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3366,7 +3366,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void; + forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -3404,7 +3404,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array; + map(callbackfn: (value: number, index: number, array: this) => number, thisArg?: any): Int32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3416,8 +3416,8 @@ interface Int32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3429,7 +3429,7 @@ interface Int32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3441,8 +3441,8 @@ interface Int32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3454,12 +3454,12 @@ interface Int32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ - reverse(): Int32Array; + reverse(): this; /** * Sets a value or an array of values. @@ -3473,7 +3473,7 @@ interface Int32Array { * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. */ - slice(start?: number, end?: number): Int32Array; + slice(start?: number, end?: number): Int32Array; /** * Determines whether the specified callback function returns true for any element of an array. @@ -3483,7 +3483,7 @@ interface Int32Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - some(predicate: (value: number, index: number, array: Int32Array) => unknown, thisArg?: any): boolean; + some(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Sorts an array. @@ -3502,7 +3502,7 @@ interface Int32Array { * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ - subarray(begin?: number, end?: number): Int32Array; + subarray(begin?: number, end?: number): Int32Array; /** * Converts a number to a string by using the current locale. @@ -3515,16 +3515,16 @@ interface Int32Array { toString(): string; /** Returns the primitive value of the specified object. */ - valueOf(): Int32Array; + valueOf(): this; [index: number]: number; } - interface Int32ArrayConstructor { - readonly prototype: Int32Array; - new (length: number): Int32Array; - new (array: ArrayLike | ArrayBufferLike): Int32Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int32Array; + readonly prototype: Int32Array; + new (length: number): Int32Array; + new (array: ArrayLike): Int32Array; + new (buffer: TArrayBuffer, byteOffset?: number, length?: number): Int32Array; + new (array: ArrayLike | ArrayBuffer): Int32Array; /** * The size in bytes of each element in the array. @@ -3535,13 +3535,13 @@ interface Int32ArrayConstructor { * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ - of(...items: number[]): Int32Array; + of(...items: number[]): Int32Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. */ - from(arrayLike: ArrayLike): Int32Array; + from(arrayLike: ArrayLike): Int32Array; /** * Creates an array from an array-like or iterable object. @@ -3549,7 +3549,7 @@ interface Int32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int32Array; + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int32Array; } declare var Int32Array: Int32ArrayConstructor; @@ -3557,7 +3557,7 @@ declare var Int32Array: Int32ArrayConstructor; * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. */ -interface Uint32Array { +interface Uint32Array { /** * The size in bytes of each element in the array. */ @@ -3566,7 +3566,7 @@ interface Uint32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBufferLike; + readonly buffer: TArrayBuffer; /** * The length in bytes of the array. @@ -3597,7 +3597,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - every(predicate: (value: number, index: number, array: Uint32Array) => unknown, thisArg?: any): boolean; + every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array @@ -3616,7 +3616,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - filter(predicate: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array; + filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Uint32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -3627,7 +3627,7 @@ interface Uint32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3638,7 +3638,7 @@ interface Uint32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3647,7 +3647,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void; + forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. @@ -3684,7 +3684,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; + map(callbackfn: (value: number, index: number, array: this) => number, thisArg?: any): Uint32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3696,8 +3696,8 @@ interface Uint32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3709,7 +3709,7 @@ interface Uint32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3721,8 +3721,8 @@ interface Uint32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -3734,12 +3734,12 @@ interface Uint32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ - reverse(): Uint32Array; + reverse(): this; /** * Sets a value or an array of values. @@ -3753,7 +3753,7 @@ interface Uint32Array { * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. */ - slice(start?: number, end?: number): Uint32Array; + slice(start?: number, end?: number): Uint32Array; /** * Determines whether the specified callback function returns true for any element of an array. @@ -3763,7 +3763,7 @@ interface Uint32Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - some(predicate: (value: number, index: number, array: Uint32Array) => unknown, thisArg?: any): boolean; + some(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Sorts an array. @@ -3782,7 +3782,7 @@ interface Uint32Array { * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ - subarray(begin?: number, end?: number): Uint32Array; + subarray(begin?: number, end?: number): Uint32Array; /** * Converts a number to a string by using the current locale. @@ -3795,16 +3795,16 @@ interface Uint32Array { toString(): string; /** Returns the primitive value of the specified object. */ - valueOf(): Uint32Array; + valueOf(): this; [index: number]: number; } - interface Uint32ArrayConstructor { - readonly prototype: Uint32Array; - new (length: number): Uint32Array; - new (array: ArrayLike | ArrayBufferLike): Uint32Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Uint32Array; + readonly prototype: Uint32Array; + new (length: number): Uint32Array; + new (array: ArrayLike): Uint32Array; + new (buffer: TArrayBuffer, byteOffset?: number, length?: number): Uint32Array; + new (array: ArrayLike | ArrayBuffer): Uint32Array; /** * The size in bytes of each element in the array. @@ -3815,13 +3815,13 @@ interface Uint32ArrayConstructor { * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ - of(...items: number[]): Uint32Array; + of(...items: number[]): Uint32Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. */ - from(arrayLike: ArrayLike): Uint32Array; + from(arrayLike: ArrayLike): Uint32Array; /** * Creates an array from an array-like or iterable object. @@ -3829,7 +3829,7 @@ interface Uint32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint32Array; + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint32Array; } declare var Uint32Array: Uint32ArrayConstructor; @@ -3837,7 +3837,7 @@ declare var Uint32Array: Uint32ArrayConstructor; * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number * of bytes could not be allocated an exception is raised. */ -interface Float32Array { +interface Float32Array { /** * The size in bytes of each element in the array. */ @@ -3846,7 +3846,7 @@ interface Float32Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBufferLike; + readonly buffer: TArrayBuffer; /** * The length in bytes of the array. @@ -3877,7 +3877,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - every(predicate: (value: number, index: number, array: Float32Array) => unknown, thisArg?: any): boolean; + every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array @@ -3896,7 +3896,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - filter(predicate: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array; + filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Float32Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -3907,7 +3907,7 @@ interface Float32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -3918,7 +3918,7 @@ interface Float32Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -3927,7 +3927,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void; + forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -3965,7 +3965,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; + map(callbackfn: (value: number, index: number, array: this) => number, thisArg?: any): Float32Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3977,8 +3977,8 @@ interface Float32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -3990,7 +3990,7 @@ interface Float32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -4002,8 +4002,8 @@ interface Float32Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -4015,12 +4015,12 @@ interface Float32Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ - reverse(): Float32Array; + reverse(): this; /** * Sets a value or an array of values. @@ -4034,7 +4034,7 @@ interface Float32Array { * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. */ - slice(start?: number, end?: number): Float32Array; + slice(start?: number, end?: number): Float32Array; /** * Determines whether the specified callback function returns true for any element of an array. @@ -4044,7 +4044,7 @@ interface Float32Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - some(predicate: (value: number, index: number, array: Float32Array) => unknown, thisArg?: any): boolean; + some(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Sorts an array. @@ -4063,7 +4063,7 @@ interface Float32Array { * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ - subarray(begin?: number, end?: number): Float32Array; + subarray(begin?: number, end?: number): Float32Array; /** * Converts a number to a string by using the current locale. @@ -4076,16 +4076,16 @@ interface Float32Array { toString(): string; /** Returns the primitive value of the specified object. */ - valueOf(): Float32Array; + valueOf(): this; [index: number]: number; } - interface Float32ArrayConstructor { - readonly prototype: Float32Array; - new (length: number): Float32Array; - new (array: ArrayLike | ArrayBufferLike): Float32Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float32Array; + readonly prototype: Float32Array; + new (length: number): Float32Array; + new (array: ArrayLike): Float32Array; + new (buffer: TArrayBuffer, byteOffset?: number, length?: number): Float32Array; + new (array: ArrayLike | ArrayBuffer): Float32Array; /** * The size in bytes of each element in the array. @@ -4096,13 +4096,13 @@ interface Float32ArrayConstructor { * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ - of(...items: number[]): Float32Array; + of(...items: number[]): Float32Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. */ - from(arrayLike: ArrayLike): Float32Array; + from(arrayLike: ArrayLike): Float32Array; /** * Creates an array from an array-like or iterable object. @@ -4110,7 +4110,7 @@ interface Float32ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Float32Array; + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Float32Array; } declare var Float32Array: Float32ArrayConstructor; @@ -4118,7 +4118,7 @@ declare var Float32Array: Float32ArrayConstructor; * A typed array of 64-bit float values. The contents are initialized to 0. If the requested * number of bytes could not be allocated an exception is raised. */ -interface Float64Array { +interface Float64Array { /** * The size in bytes of each element in the array. */ @@ -4127,7 +4127,7 @@ interface Float64Array { /** * The ArrayBuffer instance referenced by the array. */ - readonly buffer: ArrayBufferLike; + readonly buffer: TArrayBuffer; /** * The length in bytes of the array. @@ -4158,7 +4158,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - every(predicate: (value: number, index: number, array: Float64Array) => unknown, thisArg?: any): boolean; + every(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Changes all array elements from `start` to `end` index to a static `value` and returns the modified array @@ -4177,7 +4177,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - filter(predicate: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array; + filter(predicate: (value: number, index: number, array: this) => any, thisArg?: any): Float64Array; /** * Returns the value of the first element in the array where predicate is true, and undefined @@ -4188,7 +4188,7 @@ interface Float64Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - find(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number | undefined; + find(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 @@ -4199,7 +4199,7 @@ interface Float64Array { * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ - findIndex(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number; + findIndex(predicate: (value: number, index: number, obj: this) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. @@ -4208,7 +4208,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void; + forEach(callbackfn: (value: number, index: number, array: this) => void, thisArg?: any): void; /** * Returns the index of the first occurrence of a value in an array. @@ -4246,7 +4246,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ - map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; + map(callbackfn: (value: number, index: number, array: this) => number, thisArg?: any): Float64Array; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -4258,8 +4258,8 @@ interface Float64Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; - reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array. The return value of @@ -4271,7 +4271,7 @@ interface Float64Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; + reduce(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -4283,8 +4283,8 @@ interface Float64Array { * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; - reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number): number; + reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: this) => number, initialValue: number): number; /** * Calls the specified callback function for all the elements in an array, in descending order. @@ -4296,12 +4296,12 @@ interface Float64Array { * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ - reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; + reduceRight(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: this) => U, initialValue: U): U; /** * Reverses the elements in an Array. */ - reverse(): Float64Array; + reverse(): this; /** * Sets a value or an array of values. @@ -4315,7 +4315,7 @@ interface Float64Array { * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. */ - slice(start?: number, end?: number): Float64Array; + slice(start?: number, end?: number): Float64Array; /** * Determines whether the specified callback function returns true for any element of an array. @@ -4325,7 +4325,7 @@ interface Float64Array { * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ - some(predicate: (value: number, index: number, array: Float64Array) => unknown, thisArg?: any): boolean; + some(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): boolean; /** * Sorts an array. @@ -4344,7 +4344,7 @@ interface Float64Array { * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ - subarray(begin?: number, end?: number): Float64Array; + subarray(begin?: number, end?: number): Float64Array; /** * Converts a number to a string by using the current locale. @@ -4357,16 +4357,16 @@ interface Float64Array { toString(): string; /** Returns the primitive value of the specified object. */ - valueOf(): Float64Array; + valueOf(): this; [index: number]: number; } - interface Float64ArrayConstructor { - readonly prototype: Float64Array; - new (length: number): Float64Array; - new (array: ArrayLike | ArrayBufferLike): Float64Array; - new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): Float64Array; + readonly prototype: Float64Array; + new (length: number): Float64Array; + new (array: ArrayLike): Float64Array; + new (buffer: TArrayBuffer, byteOffset?: number, length?: number): Float64Array; + new (array: ArrayLike | ArrayBuffer): Float64Array; /** * The size in bytes of each element in the array. @@ -4377,13 +4377,13 @@ interface Float64ArrayConstructor { * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ - of(...items: number[]): Float64Array; + of(...items: number[]): Float64Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. */ - from(arrayLike: ArrayLike): Float64Array; + from(arrayLike: ArrayLike): Float64Array; /** * Creates an array from an array-like or iterable object. @@ -4391,7 +4391,7 @@ interface Float64ArrayConstructor { * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ - from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Float64Array; + from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Float64Array; } declare var Float64Array: Float64ArrayConstructor; diff --git a/cli/tsc/dts/lib.esnext.array.d.ts b/cli/tsc/dts/lib.esnext.array.d.ts index 39efbba0ddfc28..44df2295368a9c 100644 --- a/cli/tsc/dts/lib.esnext.array.d.ts +++ b/cli/tsc/dts/lib.esnext.array.d.ts @@ -31,5 +31,5 @@ interface ArrayConstructor { * Each return value is awaited before being added to result array. * @param thisArg Value of 'this' used when executing mapfn. */ - fromAsync(iterableOrArrayLike: AsyncIterable | Iterable | ArrayLike, mapFn: (value: Awaited) => U, thisArg?: any): Promise[]>; + fromAsync(iterableOrArrayLike: AsyncIterable | Iterable | ArrayLike, mapFn: (value: Awaited, index: number) => U, thisArg?: any): Promise[]>; } diff --git a/cli/tsc/dts/lib.esnext.collection.d.ts b/cli/tsc/dts/lib.esnext.collection.d.ts index 1278a38f67a341..46b0b08951fb85 100644 --- a/cli/tsc/dts/lib.esnext.collection.d.ts +++ b/cli/tsc/dts/lib.esnext.collection.d.ts @@ -16,17 +16,7 @@ and limitations under the License. /// -interface MapConstructor { - /** - * Groups members of an iterable according to the return value of the passed callback. - * @param items An iterable. - * @param keySelector A callback which will be invoked for each item in items. - */ - groupBy( - items: Iterable, - keySelector: (item: T, index: number) => K, - ): Map; -} +/// interface ReadonlySetLike { /** diff --git a/cli/tsc/dts/lib.esnext.d.ts b/cli/tsc/dts/lib.esnext.d.ts index e0217b6c60d935..37b5ea5ed69100 100644 --- a/cli/tsc/dts/lib.esnext.d.ts +++ b/cli/tsc/dts/lib.esnext.d.ts @@ -16,14 +16,10 @@ and limitations under the License. /// -/// +/// /// /// /// -/// -/// /// /// -/// -/// /// diff --git a/cli/tsc/dts/lib.webworker.d.ts b/cli/tsc/dts/lib.webworker.d.ts index f0c5b320009aac..c7ee571c64bded 100644 --- a/cli/tsc/dts/lib.webworker.d.ts +++ b/cli/tsc/dts/lib.webworker.d.ts @@ -65,6 +65,59 @@ interface AudioConfiguration { spatialRendering?: boolean; } +interface AudioDataCopyToOptions { + format?: AudioSampleFormat; + frameCount?: number; + frameOffset?: number; + planeIndex: number; +} + +interface AudioDataInit { + data: BufferSource; + format: AudioSampleFormat; + numberOfChannels: number; + numberOfFrames: number; + sampleRate: number; + timestamp: number; + transfer?: ArrayBuffer[]; +} + +interface AudioDecoderConfig { + codec: string; + description?: BufferSource; + numberOfChannels: number; + sampleRate: number; +} + +interface AudioDecoderInit { + error: WebCodecsErrorCallback; + output: AudioDataOutputCallback; +} + +interface AudioDecoderSupport { + config?: AudioDecoderConfig; + supported?: boolean; +} + +interface AudioEncoderConfig { + bitrate?: number; + bitrateMode?: BitrateMode; + codec: string; + numberOfChannels: number; + opus?: OpusEncoderConfig; + sampleRate: number; +} + +interface AudioEncoderInit { + error: WebCodecsErrorCallback; + output: EncodedAudioChunkOutputCallback; +} + +interface AudioEncoderSupport { + config?: AudioEncoderConfig; + supported?: boolean; +} + interface AvcEncoderConfig { format?: AvcBitstreamFormat; } @@ -181,6 +234,18 @@ interface EcdsaParams extends Algorithm { hash: HashAlgorithmIdentifier; } +interface EncodedAudioChunkInit { + data: AllowSharedBufferSource; + duration?: number; + timestamp: number; + transfer?: ArrayBuffer[]; + type: EncodedAudioChunkType; +} + +interface EncodedAudioChunkMetadata { + decoderConfig?: AudioDecoderConfig; +} + interface EncodedVideoChunkInit { data: AllowSharedBufferSource; duration?: number; @@ -448,6 +513,15 @@ interface NotificationOptions { tag?: string; } +interface OpusEncoderConfig { + complexity?: number; + format?: OpusBitstreamFormat; + frameDuration?: number; + packetlossperc?: number; + usedtx?: boolean; + useinbandfec?: boolean; +} + interface Pbkdf2Params extends Algorithm { hash: HashAlgorithmIdentifier; iterations: number; @@ -768,6 +842,7 @@ interface VideoConfiguration { colorGamut?: ColorGamut; contentType: string; framerate: number; + hasAlphaChannel?: boolean; hdrMetadataType?: HdrMetadataType; height: number; scalabilityMode?: string; @@ -803,6 +878,7 @@ interface VideoEncoderConfig { bitrate?: number; bitrateMode?: VideoEncoderBitrateMode; codec: string; + contentHint?: string; displayHeight?: number; displayWidth?: number; framerate?: number; @@ -814,9 +890,14 @@ interface VideoEncoderConfig { } interface VideoEncoderEncodeOptions { + avc?: VideoEncoderEncodeOptionsForAvc; keyFrame?: boolean; } +interface VideoEncoderEncodeOptionsForAvc { + quantizer?: number | null; +} + interface VideoEncoderInit { error: WebCodecsErrorCallback; output: EncodedVideoChunkOutputCallback; @@ -841,6 +922,8 @@ interface VideoFrameBufferInit { } interface VideoFrameCopyToOptions { + colorSpace?: PredefinedColorSpace; + format?: VideoPixelFormat; layout?: PlaneLayout[]; rect?: DOMRectInit; } @@ -1008,6 +1091,113 @@ interface AnimationFrameProvider { requestAnimationFrame(callback: FrameRequestCallback): number; } +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData) */ +interface AudioData { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/duration) */ + readonly duration: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/format) */ + readonly format: AudioSampleFormat | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/numberOfChannels) */ + readonly numberOfChannels: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/numberOfFrames) */ + readonly numberOfFrames: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/sampleRate) */ + readonly sampleRate: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/timestamp) */ + readonly timestamp: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/allocationSize) */ + allocationSize(options: AudioDataCopyToOptions): number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/clone) */ + clone(): AudioData; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioData/copyTo) */ + copyTo(destination: AllowSharedBufferSource, options: AudioDataCopyToOptions): void; +} + +declare var AudioData: { + prototype: AudioData; + new(init: AudioDataInit): AudioData; +}; + +interface AudioDecoderEventMap { + "dequeue": Event; +} + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder) + */ +interface AudioDecoder extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/decodeQueueSize) */ + readonly decodeQueueSize: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/dequeue_event) */ + ondequeue: ((this: AudioDecoder, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/state) */ + readonly state: CodecState; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/configure) */ + configure(config: AudioDecoderConfig): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/decode) */ + decode(chunk: EncodedAudioChunk): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/flush) */ + flush(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/reset) */ + reset(): void; + addEventListener(type: K, listener: (this: AudioDecoder, ev: AudioDecoderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioDecoder, ev: AudioDecoderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AudioDecoder: { + prototype: AudioDecoder; + new(init: AudioDecoderInit): AudioDecoder; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioDecoder/isConfigSupported_static) */ + isConfigSupported(config: AudioDecoderConfig): Promise; +}; + +interface AudioEncoderEventMap { + "dequeue": Event; +} + +/** + * Available only in secure contexts. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder) + */ +interface AudioEncoder extends EventTarget { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/encodeQueueSize) */ + readonly encodeQueueSize: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/dequeue_event) */ + ondequeue: ((this: AudioEncoder, ev: Event) => any) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/state) */ + readonly state: CodecState; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/close) */ + close(): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/configure) */ + configure(config: AudioEncoderConfig): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/encode) */ + encode(data: AudioData): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/flush) */ + flush(): Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/reset) */ + reset(): void; + addEventListener(type: K, listener: (this: AudioEncoder, ev: AudioEncoderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; + addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; + removeEventListener(type: K, listener: (this: AudioEncoder, ev: AudioEncoderEventMap[K]) => any, options?: boolean | EventListenerOptions): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; +} + +declare var AudioEncoder: { + prototype: AudioEncoder; + new(init: AudioEncoderInit): AudioEncoder; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioEncoder/isConfigSupported_static) */ + isConfigSupported(config: AudioEncoderConfig): Promise; +}; + /** * A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. * @@ -1809,6 +1999,8 @@ declare var CloseEvent: { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) */ interface CompressionStream extends GenericTransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; } declare var CompressionStream: { @@ -1978,27 +2170,49 @@ declare var DOMException: { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix) */ interface DOMMatrix extends DOMMatrixReadOnly { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ a: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ b: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ c: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ d: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ e: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ f: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m11: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m12: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m13: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m14: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m21: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m22: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m23: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m24: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m31: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m32: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m33: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m34: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m41: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m42: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m43: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrix#instance_properties) */ m44: number; invertSelf(): DOMMatrix; multiplySelf(other?: DOMMatrixInit): DOMMatrix; @@ -2023,29 +2237,51 @@ declare var DOMMatrix: { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly) */ interface DOMMatrixReadOnly { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly a: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly b: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly c: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly d: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly e: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly f: number; readonly is2D: boolean; readonly isIdentity: boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m11: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m12: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m13: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m14: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m21: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m22: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m23: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m24: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m31: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m32: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m33: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m34: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m41: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m42: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m43: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly#instance_properties) */ readonly m44: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMMatrixReadOnly/flipX) */ flipX(): DOMMatrix; @@ -2213,6 +2449,8 @@ declare var DOMStringList: { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) */ interface DecompressionStream extends GenericTransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; } declare var DecompressionStream: { @@ -2223,7 +2461,7 @@ declare var DecompressionStream: { interface DedicatedWorkerGlobalScopeEventMap extends WorkerGlobalScopeEventMap { "message": MessageEvent; "messageerror": MessageEvent; - "rtctransform": Event; + "rtctransform": RTCTransformEvent; } /** @@ -2243,7 +2481,7 @@ interface DedicatedWorkerGlobalScope extends WorkerGlobalScope, AnimationFramePr /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DedicatedWorkerGlobalScope/messageerror_event) */ onmessageerror: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DedicatedWorkerGlobalScope/rtctransform_event) */ - onrtctransform: ((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null; + onrtctransform: ((this: DedicatedWorkerGlobalScope, ev: RTCTransformEvent) => any) | null; /** * Aborts dedicatedWorkerGlobal. * @@ -2348,6 +2586,25 @@ interface EXT_texture_norm16 { readonly RGBA16_SNORM_EXT: 0x8F9B; } +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk) */ +interface EncodedAudioChunk { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk/byteLength) */ + readonly byteLength: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk/duration) */ + readonly duration: number | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk/timestamp) */ + readonly timestamp: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk/type) */ + readonly type: EncodedAudioChunkType; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedAudioChunk/copyTo) */ + copyTo(destination: AllowSharedBufferSource): void; +} + +declare var EncodedAudioChunk: { + prototype: EncodedAudioChunk; + new(init: EncodedAudioChunkInit): EncodedAudioChunk; +}; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedVideoChunk) */ interface EncodedVideoChunk { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EncodedVideoChunk/byteLength) */ @@ -2948,23 +3205,23 @@ interface FontFace { declare var FontFace: { prototype: FontFace; - new(family: string, source: string | BinaryData, descriptors?: FontFaceDescriptors): FontFace; + new(family: string, source: string | BufferSource, descriptors?: FontFaceDescriptors): FontFace; }; interface FontFaceSetEventMap { - "loading": Event; - "loadingdone": Event; - "loadingerror": Event; + "loading": FontFaceSetLoadEvent; + "loadingdone": FontFaceSetLoadEvent; + "loadingerror": FontFaceSetLoadEvent; } /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet) */ interface FontFaceSet extends EventTarget { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet/loading_event) */ - onloading: ((this: FontFaceSet, ev: Event) => any) | null; + onloading: ((this: FontFaceSet, ev: FontFaceSetLoadEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet/loadingdone_event) */ - onloadingdone: ((this: FontFaceSet, ev: Event) => any) | null; + onloadingdone: ((this: FontFaceSet, ev: FontFaceSetLoadEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet/loadingerror_event) */ - onloadingerror: ((this: FontFaceSet, ev: Event) => any) | null; + onloadingerror: ((this: FontFaceSet, ev: FontFaceSetLoadEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet/ready) */ readonly ready: Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSet/status) */ @@ -2982,7 +3239,7 @@ interface FontFaceSet extends EventTarget { declare var FontFaceSet: { prototype: FontFaceSet; - new(initialFaces: FontFace[]): FontFaceSet; + new(): FontFaceSet; }; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/FontFaceSetLoadEvent) */ @@ -3693,7 +3950,7 @@ interface IDBTransaction extends EventTarget { /** * Returns a list of the names of object stores in the transaction's scope. For an upgrade transaction this is all object stores in the database. * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBTransaction/ObjectStoreNames) + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBTransaction/objectStoreNames) */ readonly objectStoreNames: DOMStringList; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBTransaction/abort_event) */ @@ -4258,7 +4515,7 @@ interface OES_vertex_array_object { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/OES_vertex_array_object/bindVertexArrayOES) */ bindVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/OES_vertex_array_object/createVertexArrayOES) */ - createVertexArrayOES(): WebGLVertexArrayObjectOES | null; + createVertexArrayOES(): WebGLVertexArrayObjectOES; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/OES_vertex_array_object/deleteVertexArrayOES) */ deleteVertexArrayOES(arrayObject: WebGLVertexArrayObjectOES | null): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/OES_vertex_array_object/isVertexArrayOES) */ @@ -4344,6 +4601,7 @@ declare var OffscreenCanvas: { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/OffscreenCanvasRenderingContext2D) */ interface OffscreenCanvasRenderingContext2D extends CanvasCompositing, CanvasDrawImage, CanvasDrawPath, CanvasFillStrokeStyles, CanvasFilters, CanvasImageData, CanvasImageSmoothing, CanvasPath, CanvasPathDrawingStyles, CanvasRect, CanvasShadowStyles, CanvasState, CanvasText, CanvasTextDrawingStyles, CanvasTransform { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/canvas) */ readonly canvas: OffscreenCanvas; } @@ -4537,6 +4795,8 @@ interface PerformanceResourceTiming extends PerformanceEntry { readonly responseEnd: DOMHighResTimeStamp; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/responseStart) */ readonly responseStart: DOMHighResTimeStamp; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/responseStatus) */ + readonly responseStatus: number; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/secureConnectionStart) */ readonly secureConnectionStart: DOMHighResTimeStamp; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PerformanceResourceTiming/serverTiming) */ @@ -4687,6 +4947,8 @@ interface PushMessageData { arrayBuffer(): ArrayBuffer; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PushMessageData/blob) */ blob(): Blob; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PushMessageData/bytes) */ + bytes(): Uint8Array; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PushMessageData/json) */ json(): any; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/PushMessageData/text) */ @@ -4849,6 +5111,7 @@ declare var ReadableStream: { new(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number }): ReadableStream; new(underlyingSource: UnderlyingDefaultSource, strategy?: QueuingStrategy): ReadableStream; new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + from(asyncIterable: AsyncIterable | Iterable>): ReadableStream; }; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) */ @@ -4861,7 +5124,7 @@ interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { declare var ReadableStreamBYOBReader: { prototype: ReadableStreamBYOBReader; - new(stream: ReadableStream): ReadableStreamBYOBReader; + new(stream: ReadableStream): ReadableStreamBYOBReader; }; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) */ @@ -5363,7 +5626,7 @@ declare var StylePropertyMapReadOnly: { }; /** - * This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via globalThis.crypto). + * This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto). * Available only in secure contexts. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) @@ -5372,7 +5635,7 @@ interface SubtleCrypto { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) */ decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) */ - deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise; + deriveBits(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length?: number | null): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) */ deriveKey(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params, extractable: boolean, keyUsages: KeyUsage[]): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) */ @@ -6641,13 +6904,13 @@ interface WebGL2RenderingContextBase { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/copyTexSubImage3D) */ copyTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/createQuery) */ - createQuery(): WebGLQuery | null; + createQuery(): WebGLQuery; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/createSampler) */ - createSampler(): WebGLSampler | null; + createSampler(): WebGLSampler; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/createTransformFeedback) */ - createTransformFeedback(): WebGLTransformFeedback | null; + createTransformFeedback(): WebGLTransformFeedback; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/createVertexArray) */ - createVertexArray(): WebGLVertexArrayObject | null; + createVertexArray(): WebGLVertexArrayObject; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/deleteQuery) */ deleteQuery(query: WebGLQuery | null): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/deleteSampler) */ @@ -7560,17 +7823,17 @@ interface WebGLRenderingContextBase { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/copyTexSubImage2D) */ copyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/createBuffer) */ - createBuffer(): WebGLBuffer | null; + createBuffer(): WebGLBuffer; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/createFramebuffer) */ - createFramebuffer(): WebGLFramebuffer | null; + createFramebuffer(): WebGLFramebuffer; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/createProgram) */ - createProgram(): WebGLProgram | null; + createProgram(): WebGLProgram; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/createRenderbuffer) */ - createRenderbuffer(): WebGLRenderbuffer | null; + createRenderbuffer(): WebGLRenderbuffer; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/createShader) */ createShader(type: GLenum): WebGLShader | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/createTexture) */ - createTexture(): WebGLTexture | null; + createTexture(): WebGLTexture; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/cullFace) */ cullFace(mode: GLenum): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/deleteBuffer) */ @@ -8458,7 +8721,7 @@ interface WindowOrWorkerGlobalScope { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/createImageBitmap) */ createImageBitmap(image: ImageBitmapSource, options?: ImageBitmapOptions): Promise; createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ fetch(input: RequestInfo | URL, init?: RequestInit): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ queueMicrotask(callback: VoidFunction): void; @@ -8882,7 +9145,7 @@ interface Console { clear(): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) */ count(label?: string): void; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countreset_static) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) */ countReset(label?: string): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) */ debug(...data: any[]): void; @@ -8894,9 +9157,9 @@ interface Console { error(...data: any[]): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) */ group(...data: any[]): void; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupcollapsed_static) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) */ groupCollapsed(...data: any[]): void; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupend_static) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) */ groupEnd(): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) */ info(...data: any[]): void; @@ -8906,9 +9169,9 @@ interface Console { table(tabularData?: any, properties?: string[]): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) */ time(label?: string): void; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeend_static) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) */ timeEnd(label?: string): void; - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timelog_static) */ + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) */ timeLog(label?: string, ...data: any[]): void; timeStamp(label?: string): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) */ @@ -9078,6 +9341,14 @@ declare namespace WebAssembly { function validate(bytes: BufferSource): boolean; } +interface AudioDataOutputCallback { + (output: AudioData): void; +} + +interface EncodedAudioChunkOutputCallback { + (output: EncodedAudioChunk, metadata?: EncodedAudioChunkMetadata): void; +} + interface EncodedVideoChunkOutputCallback { (chunk: EncodedVideoChunk, metadata?: EncodedVideoChunkMetadata): void; } @@ -9169,7 +9440,7 @@ declare var onmessage: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DedicatedWorkerGlobalScope/messageerror_event) */ declare var onmessageerror: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DedicatedWorkerGlobalScope/rtctransform_event) */ -declare var onrtctransform: ((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null; +declare var onrtctransform: ((this: DedicatedWorkerGlobalScope, ev: RTCTransformEvent) => any) | null; /** * Aborts dedicatedWorkerGlobal. * @@ -9262,7 +9533,7 @@ declare function clearTimeout(id: number | undefined): void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/createImageBitmap) */ declare function createImageBitmap(image: ImageBitmapSource, options?: ImageBitmapOptions): Promise; declare function createImageBitmap(image: ImageBitmapSource, sx: number, sy: number, sw: number, sh: number, options?: ImageBitmapOptions): Promise; -/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/fetch) */ +/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/queueMicrotask) */ declare function queueMicrotask(callback: VoidFunction): void; @@ -9285,7 +9556,6 @@ declare function removeEventListener(type: string, listener: EventListenerOrEven type AlgorithmIdentifier = Algorithm | string; type AllowSharedBufferSource = ArrayBuffer | ArrayBufferView; type BigInteger = Uint8Array; -type BinaryData = ArrayBuffer | ArrayBufferView; type BlobPart = BufferSource | Blob | string; type BodyInit = ReadableStream | XMLHttpRequestBodyInit; type BufferSource = ArrayBufferView | ArrayBuffer; @@ -9330,12 +9600,14 @@ type ReportList = Report[]; type RequestInfo = Request | string; type TexImageSource = ImageBitmap | ImageData | OffscreenCanvas | VideoFrame; type TimerHandler = string | Function; -type Transferable = OffscreenCanvas | ImageBitmap | MessagePort | MediaSourceHandle | ReadableStream | WritableStream | TransformStream | VideoFrame | ArrayBuffer; +type Transferable = OffscreenCanvas | ImageBitmap | MessagePort | MediaSourceHandle | ReadableStream | WritableStream | TransformStream | AudioData | VideoFrame | ArrayBuffer; type Uint32List = Uint32Array | GLuint[]; type XMLHttpRequestBodyInit = Blob | BufferSource | FormData | URLSearchParams | string; type AlphaOption = "discard" | "keep"; +type AudioSampleFormat = "f32" | "f32-planar" | "s16" | "s16-planar" | "s32" | "s32-planar" | "u8" | "u8-planar"; type AvcBitstreamFormat = "annexb" | "avc"; type BinaryType = "arraybuffer" | "blob"; +type BitrateMode = "constant" | "variable"; type CSSMathOperator = "clamp" | "invert" | "max" | "min" | "negate" | "product" | "sum"; type CSSNumericBaseType = "angle" | "flex" | "frequency" | "length" | "percent" | "resolution" | "time"; type CanvasDirection = "inherit" | "ltr" | "rtl"; @@ -9354,6 +9626,7 @@ type ColorGamut = "p3" | "rec2020" | "srgb"; type ColorSpaceConversion = "default" | "none"; type CompressionFormat = "deflate" | "deflate-raw" | "gzip"; type DocumentVisibilityState = "hidden" | "visible"; +type EncodedAudioChunkType = "delta" | "key"; type EncodedVideoChunkType = "delta" | "key"; type EndingType = "native" | "transparent"; type FileSystemHandleKind = "directory" | "file"; @@ -9380,7 +9653,8 @@ type MediaEncodingType = "record" | "webrtc"; type NotificationDirection = "auto" | "ltr" | "rtl"; type NotificationPermission = "default" | "denied" | "granted"; type OffscreenRenderingContextId = "2d" | "bitmaprenderer" | "webgl" | "webgl2" | "webgpu"; -type PermissionName = "geolocation" | "notifications" | "persistent-storage" | "push" | "screen-wake-lock" | "xr-spatial-tracking"; +type OpusBitstreamFormat = "ogg" | "opus"; +type PermissionName = "geolocation" | "midi" | "notifications" | "persistent-storage" | "push" | "screen-wake-lock" | "storage-access"; type PermissionState = "denied" | "granted" | "prompt"; type PredefinedColorSpace = "display-p3" | "srgb"; type PremultiplyAlpha = "default" | "none" | "premultiply"; diff --git a/cli/tsc/dts/typescript.d.ts b/cli/tsc/dts/typescript.d.ts index 5326c98dd0653f..f1c59cdd6ce5b6 100644 --- a/cli/tsc/dts/typescript.d.ts +++ b/cli/tsc/dts/typescript.d.ts @@ -14,2551 +14,39 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - namespace server { - namespace protocol { - export import ApplicableRefactorInfo = ts.ApplicableRefactorInfo; - export import ClassificationType = ts.ClassificationType; - export import CompletionsTriggerCharacter = ts.CompletionsTriggerCharacter; - export import CompletionTriggerKind = ts.CompletionTriggerKind; - export import InlayHintKind = ts.InlayHintKind; - export import OrganizeImportsMode = ts.OrganizeImportsMode; - export import RefactorActionInfo = ts.RefactorActionInfo; - export import RefactorTriggerReason = ts.RefactorTriggerReason; - export import RenameInfoFailure = ts.RenameInfoFailure; - export import SemicolonPreference = ts.SemicolonPreference; - export import SignatureHelpCharacterTypedReason = ts.SignatureHelpCharacterTypedReason; - export import SignatureHelpInvokedReason = ts.SignatureHelpInvokedReason; - export import SignatureHelpParameter = ts.SignatureHelpParameter; - export import SignatureHelpRetriggerCharacter = ts.SignatureHelpRetriggerCharacter; - export import SignatureHelpRetriggeredReason = ts.SignatureHelpRetriggeredReason; - export import SignatureHelpTriggerCharacter = ts.SignatureHelpTriggerCharacter; - export import SignatureHelpTriggerReason = ts.SignatureHelpTriggerReason; - export import SymbolDisplayPart = ts.SymbolDisplayPart; - export import UserPreferences = ts.UserPreferences; - type ChangePropertyTypes< - T, - Substitutions extends { - [K in keyof T]?: any; - }, - > = { - [K in keyof T]: K extends keyof Substitutions ? Substitutions[K] : T[K]; - }; - type ChangeStringIndexSignature = { - [K in keyof T]: string extends K ? NewStringIndexSignatureType : T[K]; - }; - export enum CommandTypes { - JsxClosingTag = "jsxClosingTag", - LinkedEditingRange = "linkedEditingRange", - Brace = "brace", - BraceCompletion = "braceCompletion", - GetSpanOfEnclosingComment = "getSpanOfEnclosingComment", - Change = "change", - Close = "close", - /** @deprecated Prefer CompletionInfo -- see comment on CompletionsResponse */ - Completions = "completions", - CompletionInfo = "completionInfo", - CompletionDetails = "completionEntryDetails", - CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList", - CompileOnSaveEmitFile = "compileOnSaveEmitFile", - Configure = "configure", - Definition = "definition", - DefinitionAndBoundSpan = "definitionAndBoundSpan", - Implementation = "implementation", - Exit = "exit", - FileReferences = "fileReferences", - Format = "format", - Formatonkey = "formatonkey", - Geterr = "geterr", - GeterrForProject = "geterrForProject", - SemanticDiagnosticsSync = "semanticDiagnosticsSync", - SyntacticDiagnosticsSync = "syntacticDiagnosticsSync", - SuggestionDiagnosticsSync = "suggestionDiagnosticsSync", - NavBar = "navbar", - Navto = "navto", - NavTree = "navtree", - NavTreeFull = "navtree-full", - DocumentHighlights = "documentHighlights", - Open = "open", - Quickinfo = "quickinfo", - References = "references", - Reload = "reload", - Rename = "rename", - Saveto = "saveto", - SignatureHelp = "signatureHelp", - FindSourceDefinition = "findSourceDefinition", - Status = "status", - TypeDefinition = "typeDefinition", - ProjectInfo = "projectInfo", - ReloadProjects = "reloadProjects", - Unknown = "unknown", - OpenExternalProject = "openExternalProject", - OpenExternalProjects = "openExternalProjects", - CloseExternalProject = "closeExternalProject", - UpdateOpen = "updateOpen", - GetOutliningSpans = "getOutliningSpans", - TodoComments = "todoComments", - Indentation = "indentation", - DocCommentTemplate = "docCommentTemplate", - CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", - GetCodeFixes = "getCodeFixes", - GetCombinedCodeFix = "getCombinedCodeFix", - ApplyCodeActionCommand = "applyCodeActionCommand", - GetSupportedCodeFixes = "getSupportedCodeFixes", - GetApplicableRefactors = "getApplicableRefactors", - GetEditsForRefactor = "getEditsForRefactor", - GetMoveToRefactoringFileSuggestions = "getMoveToRefactoringFileSuggestions", - GetPasteEdits = "getPasteEdits", - OrganizeImports = "organizeImports", - GetEditsForFileRename = "getEditsForFileRename", - ConfigurePlugin = "configurePlugin", - SelectionRange = "selectionRange", - ToggleLineComment = "toggleLineComment", - ToggleMultilineComment = "toggleMultilineComment", - CommentSelection = "commentSelection", - UncommentSelection = "uncommentSelection", - PrepareCallHierarchy = "prepareCallHierarchy", - ProvideCallHierarchyIncomingCalls = "provideCallHierarchyIncomingCalls", - ProvideCallHierarchyOutgoingCalls = "provideCallHierarchyOutgoingCalls", - ProvideInlayHints = "provideInlayHints", - WatchChange = "watchChange", - MapCode = "mapCode", - } - /** - * A TypeScript Server message - */ - export interface Message { - /** - * Sequence number of the message - */ - seq: number; - /** - * One of "request", "response", or "event" - */ - type: "request" | "response" | "event"; - } - /** - * Client-initiated request message - */ - export interface Request extends Message { - type: "request"; - /** - * The command to execute - */ - command: string; - /** - * Object containing arguments for the command - */ - arguments?: any; - } - /** - * Request to reload the project structure for all the opened files - */ - export interface ReloadProjectsRequest extends Request { - command: CommandTypes.ReloadProjects; - } - /** - * Server-initiated event message - */ - export interface Event extends Message { - type: "event"; - /** - * Name of event - */ - event: string; - /** - * Event-specific information - */ - body?: any; - } - /** - * Response by server to client request message. - */ - export interface Response extends Message { - type: "response"; - /** - * Sequence number of the request message. - */ - request_seq: number; - /** - * Outcome of the request. - */ - success: boolean; - /** - * The command requested. - */ - command: string; - /** - * If success === false, this should always be provided. - * Otherwise, may (or may not) contain a success message. - */ - message?: string; - /** - * Contains message body if success === true. - */ - body?: any; - /** - * Contains extra information that plugin can include to be passed on - */ - metadata?: unknown; - /** - * Exposes information about the performance of this request-response pair. - */ - performanceData?: PerformanceData; - } - export interface PerformanceData { - /** - * Time spent updating the program graph, in milliseconds. - */ - updateGraphDurationMs?: number; - /** - * The time spent creating or updating the auto-import program, in milliseconds. - */ - createAutoImportProviderProgramDurationMs?: number; - /** - * The time spent computing diagnostics, in milliseconds. - */ - diagnosticsDuration?: FileDiagnosticPerformanceData[]; - } - /** - * Time spent computing each kind of diagnostics, in milliseconds. - */ - export type DiagnosticPerformanceData = { - [Kind in DiagnosticEventKind]?: number; - }; - export interface FileDiagnosticPerformanceData extends DiagnosticPerformanceData { - /** - * The file for which the performance data is reported. - */ - file: string; - } - /** - * Arguments for FileRequest messages. - */ - export interface FileRequestArgs { - /** - * The file for the request (absolute pathname required). - */ - file: string; - projectFileName?: string; - } - export interface StatusRequest extends Request { - command: CommandTypes.Status; - } - export interface StatusResponseBody { - /** - * The TypeScript version (`ts.version`). - */ - version: string; - } - /** - * Response to StatusRequest - */ - export interface StatusResponse extends Response { - body: StatusResponseBody; - } - /** - * Requests a JS Doc comment template for a given position - */ - export interface DocCommentTemplateRequest extends FileLocationRequest { - command: CommandTypes.DocCommentTemplate; - } - /** - * Response to DocCommentTemplateRequest - */ - export interface DocCommandTemplateResponse extends Response { - body?: TextInsertion; - } - /** - * A request to get TODO comments from the file - */ - export interface TodoCommentRequest extends FileRequest { - command: CommandTypes.TodoComments; - arguments: TodoCommentRequestArgs; - } - /** - * Arguments for TodoCommentRequest request. - */ - export interface TodoCommentRequestArgs extends FileRequestArgs { - /** - * Array of target TodoCommentDescriptors that describes TODO comments to be found - */ - descriptors: TodoCommentDescriptor[]; - } - /** - * Response for TodoCommentRequest request. - */ - export interface TodoCommentsResponse extends Response { - body?: TodoComment[]; - } - /** - * A request to determine if the caret is inside a comment. - */ - export interface SpanOfEnclosingCommentRequest extends FileLocationRequest { - command: CommandTypes.GetSpanOfEnclosingComment; - arguments: SpanOfEnclosingCommentRequestArgs; - } - export interface SpanOfEnclosingCommentRequestArgs extends FileLocationRequestArgs { - /** - * Requires that the enclosing span be a multi-line comment, or else the request returns undefined. - */ - onlyMultiLine: boolean; - } - /** - * Request to obtain outlining spans in file. - */ - export interface OutliningSpansRequest extends FileRequest { - command: CommandTypes.GetOutliningSpans; - } - export type OutliningSpan = ChangePropertyTypes; - /** - * Response to OutliningSpansRequest request. - */ - export interface OutliningSpansResponse extends Response { - body?: OutliningSpan[]; - } - /** - * A request to get indentation for a location in file - */ - export interface IndentationRequest extends FileLocationRequest { - command: CommandTypes.Indentation; - arguments: IndentationRequestArgs; - } - /** - * Response for IndentationRequest request. - */ - export interface IndentationResponse extends Response { - body?: IndentationResult; - } - /** - * Indentation result representing where indentation should be placed - */ - export interface IndentationResult { - /** - * The base position in the document that the indent should be relative to - */ - position: number; - /** - * The number of columns the indent should be at relative to the position's column. - */ - indentation: number; - } - /** - * Arguments for IndentationRequest request. - */ - export interface IndentationRequestArgs extends FileLocationRequestArgs { - /** - * An optional set of settings to be used when computing indentation. - * If argument is omitted - then it will use settings for file that were previously set via 'configure' request or global settings. - */ - options?: EditorSettings; - } - /** - * Arguments for ProjectInfoRequest request. - */ - export interface ProjectInfoRequestArgs extends FileRequestArgs { - /** - * Indicate if the file name list of the project is needed - */ - needFileNameList: boolean; - } - /** - * A request to get the project information of the current file. - */ - export interface ProjectInfoRequest extends Request { - command: CommandTypes.ProjectInfo; - arguments: ProjectInfoRequestArgs; - } - /** - * A request to retrieve compiler options diagnostics for a project - */ - export interface CompilerOptionsDiagnosticsRequest extends Request { - arguments: CompilerOptionsDiagnosticsRequestArgs; - } - /** - * Arguments for CompilerOptionsDiagnosticsRequest request. - */ - export interface CompilerOptionsDiagnosticsRequestArgs { - /** - * Name of the project to retrieve compiler options diagnostics. - */ - projectFileName: string; - } - /** - * Response message body for "projectInfo" request - */ - export interface ProjectInfo { - /** - * For configured project, this is the normalized path of the 'tsconfig.json' file - * For inferred project, this is undefined - */ - configFileName: string; - /** - * The list of normalized file name in the project, including 'lib.d.ts' - */ - fileNames?: string[]; - /** - * Indicates if the project has a active language service instance - */ - languageServiceDisabled?: boolean; - } - /** - * Represents diagnostic info that includes location of diagnostic in two forms - * - start position and length of the error span - * - startLocation and endLocation - a pair of Location objects that store start/end line and offset of the error span. - */ - export interface DiagnosticWithLinePosition { - message: string; - start: number; - length: number; - startLocation: Location; - endLocation: Location; - category: string; - code: number; - /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */ - reportsUnnecessary?: {}; - reportsDeprecated?: {}; - relatedInformation?: DiagnosticRelatedInformation[]; - } - /** - * Response message for "projectInfo" request - */ - export interface ProjectInfoResponse extends Response { - body?: ProjectInfo; - } - /** - * Request whose sole parameter is a file name. - */ - export interface FileRequest extends Request { - arguments: FileRequestArgs; - } - /** - * Instances of this interface specify a location in a source file: - * (file, line, character offset), where line and character offset are 1-based. - */ - export interface FileLocationRequestArgs extends FileRequestArgs { - /** - * The line number for the request (1-based). - */ - line: number; - /** - * The character offset (on the line) for the request (1-based). - */ - offset: number; - } - export type FileLocationOrRangeRequestArgs = FileLocationRequestArgs | FileRangeRequestArgs; - /** - * Request refactorings at a given position or selection area. - */ - export interface GetApplicableRefactorsRequest extends Request { - command: CommandTypes.GetApplicableRefactors; - arguments: GetApplicableRefactorsRequestArgs; - } - export type GetApplicableRefactorsRequestArgs = FileLocationOrRangeRequestArgs & { - triggerReason?: RefactorTriggerReason; - kind?: string; - /** - * Include refactor actions that require additional arguments to be passed when - * calling 'GetEditsForRefactor'. When true, clients should inspect the - * `isInteractive` property of each returned `RefactorActionInfo` - * and ensure they are able to collect the appropriate arguments for any - * interactive refactor before offering it. - */ - includeInteractiveActions?: boolean; - }; - /** - * Response is a list of available refactorings. - * Each refactoring exposes one or more "Actions"; a user selects one action to invoke a refactoring - */ - export interface GetApplicableRefactorsResponse extends Response { - body?: ApplicableRefactorInfo[]; - } - /** - * Request refactorings at a given position or selection area to move to an existing file. - */ - export interface GetMoveToRefactoringFileSuggestionsRequest extends Request { - command: CommandTypes.GetMoveToRefactoringFileSuggestions; - arguments: GetMoveToRefactoringFileSuggestionsRequestArgs; - } - export type GetMoveToRefactoringFileSuggestionsRequestArgs = FileLocationOrRangeRequestArgs & { - kind?: string; - }; - /** - * Response is a list of available files. - * Each refactoring exposes one or more "Actions"; a user selects one action to invoke a refactoring - */ - export interface GetMoveToRefactoringFileSuggestions extends Response { - body: { - newFileName: string; - files: string[]; - }; - } - /** - * Request refactorings at a given position post pasting text from some other location. - */ - export interface GetPasteEditsRequest extends Request { - command: CommandTypes.GetPasteEdits; - arguments: GetPasteEditsRequestArgs; - } - export interface GetPasteEditsRequestArgs extends FileRequestArgs { - /** The text that gets pasted in a file. */ - pastedText: string[]; - /** Locations of where the `pastedText` gets added in a file. If the length of the `pastedText` and `pastedLocations` are not the same, - * then the `pastedText` is combined into one and added at all the `pastedLocations`. - */ - pasteLocations: TextSpan[]; - /** The source location of each `pastedText`. If present, the length of `spans` must be equal to the length of `pastedText`. */ - copiedFrom?: { - file: string; - spans: TextSpan[]; - }; - } - export interface GetPasteEditsResponse extends Response { - body: PasteEditsAction; - } - export interface PasteEditsAction { - edits: FileCodeEdits[]; - fixId?: {}; - } - export interface GetEditsForRefactorRequest extends Request { - command: CommandTypes.GetEditsForRefactor; - arguments: GetEditsForRefactorRequestArgs; - } - /** - * Request the edits that a particular refactoring action produces. - * Callers must specify the name of the refactor and the name of the action. - */ - export type GetEditsForRefactorRequestArgs = FileLocationOrRangeRequestArgs & { - refactor: string; - action: string; - interactiveRefactorArguments?: InteractiveRefactorArguments; - }; - export interface GetEditsForRefactorResponse extends Response { - body?: RefactorEditInfo; - } - export interface RefactorEditInfo { - edits: FileCodeEdits[]; - /** - * An optional location where the editor should start a rename operation once - * the refactoring edits have been applied - */ - renameLocation?: Location; - renameFilename?: string; - notApplicableReason?: string; - } - /** - * Organize imports by: - * 1) Removing unused imports - * 2) Coalescing imports from the same module - * 3) Sorting imports - */ - export interface OrganizeImportsRequest extends Request { - command: CommandTypes.OrganizeImports; - arguments: OrganizeImportsRequestArgs; - } - export type OrganizeImportsScope = GetCombinedCodeFixScope; - export interface OrganizeImportsRequestArgs { - scope: OrganizeImportsScope; - /** @deprecated Use `mode` instead */ - skipDestructiveCodeActions?: boolean; - mode?: OrganizeImportsMode; - } - export interface OrganizeImportsResponse extends Response { - body: readonly FileCodeEdits[]; - } - export interface GetEditsForFileRenameRequest extends Request { - command: CommandTypes.GetEditsForFileRename; - arguments: GetEditsForFileRenameRequestArgs; - } - /** Note: Paths may also be directories. */ - export interface GetEditsForFileRenameRequestArgs { - readonly oldFilePath: string; - readonly newFilePath: string; - } - export interface GetEditsForFileRenameResponse extends Response { - body: readonly FileCodeEdits[]; - } - /** - * Request for the available codefixes at a specific position. - */ - export interface CodeFixRequest extends Request { - command: CommandTypes.GetCodeFixes; - arguments: CodeFixRequestArgs; - } - export interface GetCombinedCodeFixRequest extends Request { - command: CommandTypes.GetCombinedCodeFix; - arguments: GetCombinedCodeFixRequestArgs; - } - export interface GetCombinedCodeFixResponse extends Response { - body: CombinedCodeActions; - } - export interface ApplyCodeActionCommandRequest extends Request { - command: CommandTypes.ApplyCodeActionCommand; - arguments: ApplyCodeActionCommandRequestArgs; - } - export interface ApplyCodeActionCommandResponse extends Response { - } - export interface FileRangeRequestArgs extends FileRequestArgs, FileRange { - } - /** - * Instances of this interface specify errorcodes on a specific location in a sourcefile. - */ - export interface CodeFixRequestArgs extends FileRangeRequestArgs { - /** - * Errorcodes we want to get the fixes for. - */ - errorCodes: readonly number[]; - } - export interface GetCombinedCodeFixRequestArgs { - scope: GetCombinedCodeFixScope; - fixId: {}; - } - export interface GetCombinedCodeFixScope { - type: "file"; - args: FileRequestArgs; - } - export interface ApplyCodeActionCommandRequestArgs { - /** May also be an array of commands. */ - command: {}; - } - /** - * Response for GetCodeFixes request. - */ - export interface GetCodeFixesResponse extends Response { - body?: CodeAction[]; - } - /** - * A request whose arguments specify a file location (file, line, col). - */ - export interface FileLocationRequest extends FileRequest { - arguments: FileLocationRequestArgs; - } - /** - * A request to get codes of supported code fixes. - */ - export interface GetSupportedCodeFixesRequest extends Request { - command: CommandTypes.GetSupportedCodeFixes; - arguments?: Partial; - } - /** - * A response for GetSupportedCodeFixesRequest request. - */ - export interface GetSupportedCodeFixesResponse extends Response { - /** - * List of error codes supported by the server. - */ - body?: string[]; - } - /** - * A request to get encoded semantic classifications for a span in the file - */ - export interface EncodedSemanticClassificationsRequest extends FileRequest { - arguments: EncodedSemanticClassificationsRequestArgs; - } - /** - * Arguments for EncodedSemanticClassificationsRequest request. - */ - export interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { - /** - * Start position of the span. - */ - start: number; - /** - * Length of the span. - */ - length: number; - /** - * Optional parameter for the semantic highlighting response, if absent it - * defaults to "original". - */ - format?: "original" | "2020"; - } - /** The response for a EncodedSemanticClassificationsRequest */ - export interface EncodedSemanticClassificationsResponse extends Response { - body?: EncodedSemanticClassificationsResponseBody; - } - /** - * Implementation response message. Gives series of text spans depending on the format ar. - */ - export interface EncodedSemanticClassificationsResponseBody { - endOfLineState: EndOfLineState; - spans: number[]; - } - /** - * Arguments in document highlight request; include: filesToSearch, file, - * line, offset. - */ - export interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { - /** - * List of files to search for document highlights. - */ - filesToSearch: string[]; - } - /** - * Go to definition request; value of command field is - * "definition". Return response giving the file locations that - * define the symbol found in file at location line, col. - */ - export interface DefinitionRequest extends FileLocationRequest { - command: CommandTypes.Definition; - } - export interface DefinitionAndBoundSpanRequest extends FileLocationRequest { - readonly command: CommandTypes.DefinitionAndBoundSpan; - } - export interface FindSourceDefinitionRequest extends FileLocationRequest { - readonly command: CommandTypes.FindSourceDefinition; - } - export interface DefinitionAndBoundSpanResponse extends Response { - readonly body: DefinitionInfoAndBoundSpan; - } - /** - * Go to type request; value of command field is - * "typeDefinition". Return response giving the file locations that - * define the type for the symbol found in file at location line, col. - */ - export interface TypeDefinitionRequest extends FileLocationRequest { - command: CommandTypes.TypeDefinition; - } - /** - * Go to implementation request; value of command field is - * "implementation". Return response giving the file locations that - * implement the symbol found in file at location line, col. - */ - export interface ImplementationRequest extends FileLocationRequest { - command: CommandTypes.Implementation; - } - /** - * Location in source code expressed as (one-based) line and (one-based) column offset. - */ - export interface Location { - line: number; - offset: number; - } - /** - * Object found in response messages defining a span of text in source code. - */ - export interface TextSpan { - /** - * First character of the definition. - */ - start: Location; - /** - * One character past last character of the definition. - */ - end: Location; - } - /** - * Object found in response messages defining a span of text in a specific source file. - */ - export interface FileSpan extends TextSpan { - /** - * File containing text span. - */ - file: string; - } - export interface JSDocTagInfo { - /** Name of the JSDoc tag */ - name: string; - /** - * Comment text after the JSDoc tag -- the text after the tag name until the next tag or end of comment - * Display parts when UserPreferences.displayPartsForJSDoc is true, flattened to string otherwise. - */ - text?: string | SymbolDisplayPart[]; - } - export interface TextSpanWithContext extends TextSpan { - contextStart?: Location; - contextEnd?: Location; - } - export interface FileSpanWithContext extends FileSpan, TextSpanWithContext { - } - export interface DefinitionInfo extends FileSpanWithContext { - /** - * When true, the file may or may not exist. - */ - unverified?: boolean; - } - export interface DefinitionInfoAndBoundSpan { - definitions: readonly DefinitionInfo[]; - textSpan: TextSpan; - } - /** - * Definition response message. Gives text range for definition. - */ - export interface DefinitionResponse extends Response { - body?: DefinitionInfo[]; - } - export interface DefinitionInfoAndBoundSpanResponse extends Response { - body?: DefinitionInfoAndBoundSpan; - } - /** @deprecated Use `DefinitionInfoAndBoundSpanResponse` instead. */ - export type DefinitionInfoAndBoundSpanReponse = DefinitionInfoAndBoundSpanResponse; - /** - * Definition response message. Gives text range for definition. - */ - export interface TypeDefinitionResponse extends Response { - body?: FileSpanWithContext[]; - } - /** - * Implementation response message. Gives text range for implementations. - */ - export interface ImplementationResponse extends Response { - body?: FileSpanWithContext[]; - } - /** - * Request to get brace completion for a location in the file. - */ - export interface BraceCompletionRequest extends FileLocationRequest { - command: CommandTypes.BraceCompletion; - arguments: BraceCompletionRequestArgs; - } - /** - * Argument for BraceCompletionRequest request. - */ - export interface BraceCompletionRequestArgs extends FileLocationRequestArgs { - /** - * Kind of opening brace - */ - openingBrace: string; - } - export interface JsxClosingTagRequest extends FileLocationRequest { - readonly command: CommandTypes.JsxClosingTag; - readonly arguments: JsxClosingTagRequestArgs; - } - export interface JsxClosingTagRequestArgs extends FileLocationRequestArgs { - } - export interface JsxClosingTagResponse extends Response { - readonly body: TextInsertion; - } - export interface LinkedEditingRangeRequest extends FileLocationRequest { - readonly command: CommandTypes.LinkedEditingRange; - } - export interface LinkedEditingRangesBody { - ranges: TextSpan[]; - wordPattern?: string; - } - export interface LinkedEditingRangeResponse extends Response { - readonly body: LinkedEditingRangesBody; - } - /** - * Get document highlights request; value of command field is - * "documentHighlights". Return response giving spans that are relevant - * in the file at a given line and column. - */ - export interface DocumentHighlightsRequest extends FileLocationRequest { - command: CommandTypes.DocumentHighlights; - arguments: DocumentHighlightsRequestArgs; - } - /** - * Span augmented with extra information that denotes the kind of the highlighting to be used for span. - */ - export interface HighlightSpan extends TextSpanWithContext { - kind: HighlightSpanKind; - } - /** - * Represents a set of highligh spans for a give name - */ - export interface DocumentHighlightsItem { - /** - * File containing highlight spans. - */ - file: string; - /** - * Spans to highlight in file. - */ - highlightSpans: HighlightSpan[]; - } - /** - * Response for a DocumentHighlightsRequest request. - */ - export interface DocumentHighlightsResponse extends Response { - body?: DocumentHighlightsItem[]; - } - /** - * Find references request; value of command field is - * "references". Return response giving the file locations that - * reference the symbol found in file at location line, col. - */ - export interface ReferencesRequest extends FileLocationRequest { - command: CommandTypes.References; - } - export interface ReferencesResponseItem extends FileSpanWithContext { - /** - * Text of line containing the reference. Including this - * with the response avoids latency of editor loading files - * to show text of reference line (the server already has loaded the referencing files). - * - * If {@link UserPreferences.disableLineTextInReferences} is enabled, the property won't be filled - */ - lineText?: string; - /** - * True if reference is a write location, false otherwise. - */ - isWriteAccess: boolean; - /** - * Present only if the search was triggered from a declaration. - * True indicates that the references refers to the same symbol - * (i.e. has the same meaning) as the declaration that began the - * search. - */ - isDefinition?: boolean; - } - /** - * The body of a "references" response message. - */ - export interface ReferencesResponseBody { - /** - * The file locations referencing the symbol. - */ - refs: readonly ReferencesResponseItem[]; - /** - * The name of the symbol. - */ - symbolName: string; - /** - * The start character offset of the symbol (on the line provided by the references request). - */ - symbolStartOffset: number; - /** - * The full display name of the symbol. - */ - symbolDisplayString: string; - } - /** - * Response to "references" request. - */ - export interface ReferencesResponse extends Response { - body?: ReferencesResponseBody; - } - export interface FileReferencesRequest extends FileRequest { - command: CommandTypes.FileReferences; - } - export interface FileReferencesResponseBody { - /** - * The file locations referencing the symbol. - */ - refs: readonly ReferencesResponseItem[]; - /** - * The name of the symbol. - */ - symbolName: string; - } - export interface FileReferencesResponse extends Response { - body?: FileReferencesResponseBody; - } - /** - * Argument for RenameRequest request. - */ - export interface RenameRequestArgs extends FileLocationRequestArgs { - /** - * Should text at specified location be found/changed in comments? - */ - findInComments?: boolean; - /** - * Should text at specified location be found/changed in strings? - */ - findInStrings?: boolean; - } - /** - * Rename request; value of command field is "rename". Return - * response giving the file locations that reference the symbol - * found in file at location line, col. Also return full display - * name of the symbol so that client can print it unambiguously. - */ - export interface RenameRequest extends FileLocationRequest { - command: CommandTypes.Rename; - arguments: RenameRequestArgs; - } - /** - * Information about the item to be renamed. - */ - export type RenameInfo = RenameInfoSuccess | RenameInfoFailure; - export type RenameInfoSuccess = ChangePropertyTypes; - /** - * A group of text spans, all in 'file'. - */ - export interface SpanGroup { - /** The file to which the spans apply */ - file: string; - /** The text spans in this group */ - locs: RenameTextSpan[]; - } - export interface RenameTextSpan extends TextSpanWithContext { - readonly prefixText?: string; - readonly suffixText?: string; - } - export interface RenameResponseBody { - /** - * Information about the item to be renamed. - */ - info: RenameInfo; - /** - * An array of span groups (one per file) that refer to the item to be renamed. - */ - locs: readonly SpanGroup[]; - } - /** - * Rename response message. - */ - export interface RenameResponse extends Response { - body?: RenameResponseBody; - } - /** - * Represents a file in external project. - * External project is project whose set of files, compilation options and open\close state - * is maintained by the client (i.e. if all this data come from .csproj file in Visual Studio). - * External project will exist even if all files in it are closed and should be closed explicitly. - * If external project includes one or more tsconfig.json/jsconfig.json files then tsserver will - * create configured project for every config file but will maintain a link that these projects were created - * as a result of opening external project so they should be removed once external project is closed. - */ - export interface ExternalFile { - /** - * Name of file file - */ - fileName: string; - /** - * Script kind of the file - */ - scriptKind?: ScriptKindName | ScriptKind; - /** - * Whether file has mixed content (i.e. .cshtml file that combines html markup with C#/JavaScript) - */ - hasMixedContent?: boolean; - /** - * Content of the file - */ - content?: string; - } - /** - * Represent an external project - */ - export interface ExternalProject { - /** - * Project name - */ - projectFileName: string; - /** - * List of root files in project - */ - rootFiles: ExternalFile[]; - /** - * Compiler options for the project - */ - options: ExternalProjectCompilerOptions; - /** - * Explicitly specified type acquisition for the project - */ - typeAcquisition?: TypeAcquisition; - } - export interface CompileOnSaveMixin { - /** - * If compile on save is enabled for the project - */ - compileOnSave?: boolean; - } - /** - * For external projects, some of the project settings are sent together with - * compiler settings. - */ - export type ExternalProjectCompilerOptions = CompilerOptions & CompileOnSaveMixin & WatchOptions; - export interface FileWithProjectReferenceRedirectInfo { - /** - * Name of file - */ - fileName: string; - /** - * True if the file is primarily included in a referenced project - */ - isSourceOfProjectReferenceRedirect: boolean; - } - /** - * Represents a set of changes that happen in project - */ - export interface ProjectChanges { - /** - * List of added files - */ - added: string[] | FileWithProjectReferenceRedirectInfo[]; - /** - * List of removed files - */ - removed: string[] | FileWithProjectReferenceRedirectInfo[]; - /** - * List of updated files - */ - updated: string[] | FileWithProjectReferenceRedirectInfo[]; - /** - * List of files that have had their project reference redirect status updated - * Only provided when the synchronizeProjectList request has includeProjectReferenceRedirectInfo set to true - */ - updatedRedirects?: FileWithProjectReferenceRedirectInfo[]; - } - /** - * Information found in a configure request. - */ - export interface ConfigureRequestArguments { - /** - * Information about the host, for example 'Emacs 24.4' or - * 'Sublime Text version 3075' - */ - hostInfo?: string; - /** - * If present, tab settings apply only to this file. - */ - file?: string; - /** - * The format options to use during formatting and other code editing features. - */ - formatOptions?: FormatCodeSettings; - preferences?: UserPreferences; - /** - * The host's additional supported .js file extensions - */ - extraFileExtensions?: FileExtensionInfo[]; - watchOptions?: WatchOptions; - } - export enum WatchFileKind { - FixedPollingInterval = "FixedPollingInterval", - PriorityPollingInterval = "PriorityPollingInterval", - DynamicPriorityPolling = "DynamicPriorityPolling", - FixedChunkSizePolling = "FixedChunkSizePolling", - UseFsEvents = "UseFsEvents", - UseFsEventsOnParentDirectory = "UseFsEventsOnParentDirectory", - } - export enum WatchDirectoryKind { - UseFsEvents = "UseFsEvents", - FixedPollingInterval = "FixedPollingInterval", - DynamicPriorityPolling = "DynamicPriorityPolling", - FixedChunkSizePolling = "FixedChunkSizePolling", - } - export enum PollingWatchKind { - FixedInterval = "FixedInterval", - PriorityInterval = "PriorityInterval", - DynamicPriority = "DynamicPriority", - FixedChunkSize = "FixedChunkSize", - } - export interface WatchOptions { - watchFile?: WatchFileKind | ts.WatchFileKind; - watchDirectory?: WatchDirectoryKind | ts.WatchDirectoryKind; - fallbackPolling?: PollingWatchKind | ts.PollingWatchKind; - synchronousWatchDirectory?: boolean; - excludeDirectories?: string[]; - excludeFiles?: string[]; - [option: string]: CompilerOptionsValue | undefined; - } - /** - * Configure request; value of command field is "configure". Specifies - * host information, such as host type, tab size, and indent size. - */ - export interface ConfigureRequest extends Request { - command: CommandTypes.Configure; - arguments: ConfigureRequestArguments; - } - /** - * Response to "configure" request. This is just an acknowledgement, so - * no body field is required. - */ - export interface ConfigureResponse extends Response { - } - export interface ConfigurePluginRequestArguments { - pluginName: string; - configuration: any; - } - export interface ConfigurePluginRequest extends Request { - command: CommandTypes.ConfigurePlugin; - arguments: ConfigurePluginRequestArguments; - } - export interface ConfigurePluginResponse extends Response { - } - export interface SelectionRangeRequest extends FileRequest { - command: CommandTypes.SelectionRange; - arguments: SelectionRangeRequestArgs; - } - export interface SelectionRangeRequestArgs extends FileRequestArgs { - locations: Location[]; - } - export interface SelectionRangeResponse extends Response { - body?: SelectionRange[]; - } - export interface SelectionRange { - textSpan: TextSpan; - parent?: SelectionRange; - } - export interface ToggleLineCommentRequest extends FileRequest { - command: CommandTypes.ToggleLineComment; - arguments: FileRangeRequestArgs; - } - export interface ToggleMultilineCommentRequest extends FileRequest { - command: CommandTypes.ToggleMultilineComment; - arguments: FileRangeRequestArgs; - } - export interface CommentSelectionRequest extends FileRequest { - command: CommandTypes.CommentSelection; - arguments: FileRangeRequestArgs; - } - export interface UncommentSelectionRequest extends FileRequest { - command: CommandTypes.UncommentSelection; - arguments: FileRangeRequestArgs; - } - /** - * Information found in an "open" request. - */ - export interface OpenRequestArgs extends FileRequestArgs { - /** - * Used when a version of the file content is known to be more up to date than the one on disk. - * Then the known content will be used upon opening instead of the disk copy - */ - fileContent?: string; - /** - * Used to specify the script kind of the file explicitly. It could be one of the following: - * "TS", "JS", "TSX", "JSX" - */ - scriptKindName?: ScriptKindName; - /** - * Used to limit the searching for project config file. If given the searching will stop at this - * root path; otherwise it will go all the way up to the dist root path. - */ - projectRootPath?: string; - } - export type ScriptKindName = "TS" | "JS" | "TSX" | "JSX"; - /** - * Open request; value of command field is "open". Notify the - * server that the client has file open. The server will not - * monitor the filesystem for changes in this file and will assume - * that the client is updating the server (using the change and/or - * reload messages) when the file changes. Server does not currently - * send a response to an open request. - */ - export interface OpenRequest extends Request { - command: CommandTypes.Open; - arguments: OpenRequestArgs; - } - /** - * Request to open or update external project - */ - export interface OpenExternalProjectRequest extends Request { - command: CommandTypes.OpenExternalProject; - arguments: OpenExternalProjectArgs; - } - /** - * Arguments to OpenExternalProjectRequest request - */ - export type OpenExternalProjectArgs = ExternalProject; - /** - * Request to open multiple external projects - */ - export interface OpenExternalProjectsRequest extends Request { - command: CommandTypes.OpenExternalProjects; - arguments: OpenExternalProjectsArgs; - } - /** - * Arguments to OpenExternalProjectsRequest - */ - export interface OpenExternalProjectsArgs { - /** - * List of external projects to open or update - */ - projects: ExternalProject[]; - } - /** - * Response to OpenExternalProjectRequest request. This is just an acknowledgement, so - * no body field is required. - */ - export interface OpenExternalProjectResponse extends Response { - } - /** - * Response to OpenExternalProjectsRequest request. This is just an acknowledgement, so - * no body field is required. - */ - export interface OpenExternalProjectsResponse extends Response { - } - /** - * Request to close external project. - */ - export interface CloseExternalProjectRequest extends Request { - command: CommandTypes.CloseExternalProject; - arguments: CloseExternalProjectRequestArgs; - } - /** - * Arguments to CloseExternalProjectRequest request - */ - export interface CloseExternalProjectRequestArgs { - /** - * Name of the project to close - */ - projectFileName: string; - } - /** - * Response to CloseExternalProjectRequest request. This is just an acknowledgement, so - * no body field is required. - */ - export interface CloseExternalProjectResponse extends Response { - } - /** - * Request to synchronize list of open files with the client - */ - export interface UpdateOpenRequest extends Request { - command: CommandTypes.UpdateOpen; - arguments: UpdateOpenRequestArgs; - } - /** - * Arguments to UpdateOpenRequest - */ - export interface UpdateOpenRequestArgs { - /** - * List of newly open files - */ - openFiles?: OpenRequestArgs[]; - /** - * List of open files files that were changes - */ - changedFiles?: FileCodeEdits[]; - /** - * List of files that were closed - */ - closedFiles?: string[]; - } - /** - * External projects have a typeAcquisition option so they need to be added separately to compiler options for inferred projects. - */ - export type InferredProjectCompilerOptions = ExternalProjectCompilerOptions & TypeAcquisition; - /** - * Request to set compiler options for inferred projects. - * External projects are opened / closed explicitly. - * Configured projects are opened when user opens loose file that has 'tsconfig.json' or 'jsconfig.json' anywhere in one of containing folders. - * This configuration file will be used to obtain a list of files and configuration settings for the project. - * Inferred projects are created when user opens a loose file that is not the part of external project - * or configured project and will contain only open file and transitive closure of referenced files if 'useOneInferredProject' is false, - * or all open loose files and its transitive closure of referenced files if 'useOneInferredProject' is true. - */ - export interface SetCompilerOptionsForInferredProjectsRequest extends Request { - command: CommandTypes.CompilerOptionsForInferredProjects; - arguments: SetCompilerOptionsForInferredProjectsArgs; - } - /** - * Argument for SetCompilerOptionsForInferredProjectsRequest request. - */ - export interface SetCompilerOptionsForInferredProjectsArgs { - /** - * Compiler options to be used with inferred projects. - */ - options: InferredProjectCompilerOptions; - /** - * Specifies the project root path used to scope compiler options. - * It is an error to provide this property if the server has not been started with - * `useInferredProjectPerProjectRoot` enabled. - */ - projectRootPath?: string; - } - /** - * Response to SetCompilerOptionsForInferredProjectsResponse request. This is just an acknowledgement, so - * no body field is required. - */ - export interface SetCompilerOptionsForInferredProjectsResponse extends Response { - } - /** - * Exit request; value of command field is "exit". Ask the server process - * to exit. - */ - export interface ExitRequest extends Request { - command: CommandTypes.Exit; - } - /** - * Close request; value of command field is "close". Notify the - * server that the client has closed a previously open file. If - * file is still referenced by open files, the server will resume - * monitoring the filesystem for changes to file. Server does not - * currently send a response to a close request. - */ - export interface CloseRequest extends FileRequest { - command: CommandTypes.Close; - } - export interface WatchChangeRequest extends Request { - command: CommandTypes.WatchChange; - arguments: WatchChangeRequestArgs | readonly WatchChangeRequestArgs[]; - } - export interface WatchChangeRequestArgs { - id: number; - created?: string[]; - deleted?: string[]; - updated?: string[]; - } - /** - * Request to obtain the list of files that should be regenerated if target file is recompiled. - * NOTE: this us query-only operation and does not generate any output on disk. - */ - export interface CompileOnSaveAffectedFileListRequest extends FileRequest { - command: CommandTypes.CompileOnSaveAffectedFileList; - } - /** - * Contains a list of files that should be regenerated in a project - */ - export interface CompileOnSaveAffectedFileListSingleProject { - /** - * Project name - */ - projectFileName: string; - /** - * List of files names that should be recompiled - */ - fileNames: string[]; - /** - * true if project uses outFile or out compiler option - */ - projectUsesOutFile: boolean; - } - /** - * Response for CompileOnSaveAffectedFileListRequest request; - */ - export interface CompileOnSaveAffectedFileListResponse extends Response { - body: CompileOnSaveAffectedFileListSingleProject[]; - } - /** - * Request to recompile the file. All generated outputs (.js, .d.ts or .js.map files) is written on disk. - */ - export interface CompileOnSaveEmitFileRequest extends FileRequest { - command: CommandTypes.CompileOnSaveEmitFile; - arguments: CompileOnSaveEmitFileRequestArgs; - } - /** - * Arguments for CompileOnSaveEmitFileRequest - */ - export interface CompileOnSaveEmitFileRequestArgs extends FileRequestArgs { - /** - * if true - then file should be recompiled even if it does not have any changes. - */ - forced?: boolean; - includeLinePosition?: boolean; - /** if true - return response as object with emitSkipped and diagnostics */ - richResponse?: boolean; - } - export interface CompileOnSaveEmitFileResponse extends Response { - body: boolean | EmitResult; - } - export interface EmitResult { - emitSkipped: boolean; - diagnostics: Diagnostic[] | DiagnosticWithLinePosition[]; - } - /** - * Quickinfo request; value of command field is - * "quickinfo". Return response giving a quick type and - * documentation string for the symbol found in file at location - * line, col. - */ - export interface QuickInfoRequest extends FileLocationRequest { - command: CommandTypes.Quickinfo; - arguments: FileLocationRequestArgs; - } - /** - * Body of QuickInfoResponse. - */ - export interface QuickInfoResponseBody { - /** - * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). - */ - kind: ScriptElementKind; - /** - * Optional modifiers for the kind (such as 'public'). - */ - kindModifiers: string; - /** - * Starting file location of symbol. - */ - start: Location; - /** - * One past last character of symbol. - */ - end: Location; - /** - * Type and kind of symbol. - */ - displayString: string; - /** - * Documentation associated with symbol. - * Display parts when UserPreferences.displayPartsForJSDoc is true, flattened to string otherwise. - */ - documentation: string | SymbolDisplayPart[]; - /** - * JSDoc tags associated with symbol. - */ - tags: JSDocTagInfo[]; - } - /** - * Quickinfo response message. - */ - export interface QuickInfoResponse extends Response { - body?: QuickInfoResponseBody; - } - /** - * Arguments for format messages. - */ - export interface FormatRequestArgs extends FileLocationRequestArgs { - /** - * Last line of range for which to format text in file. - */ - endLine: number; - /** - * Character offset on last line of range for which to format text in file. - */ - endOffset: number; - /** - * Format options to be used. - */ - options?: FormatCodeSettings; - } - /** - * Format request; value of command field is "format". Return - * response giving zero or more edit instructions. The edit - * instructions will be sorted in file order. Applying the edit - * instructions in reverse to file will result in correctly - * reformatted text. - */ - export interface FormatRequest extends FileLocationRequest { - command: CommandTypes.Format; - arguments: FormatRequestArgs; - } - /** - * Object found in response messages defining an editing - * instruction for a span of text in source code. The effect of - * this instruction is to replace the text starting at start and - * ending one character before end with newText. For an insertion, - * the text span is empty. For a deletion, newText is empty. - */ - export interface CodeEdit { - /** - * First character of the text span to edit. - */ - start: Location; - /** - * One character past last character of the text span to edit. - */ - end: Location; - /** - * Replace the span defined above with this string (may be - * the empty string). - */ - newText: string; - } - export interface FileCodeEdits { - fileName: string; - textChanges: CodeEdit[]; - } - export interface CodeFixResponse extends Response { - /** The code actions that are available */ - body?: CodeFixAction[]; - } - export interface CodeAction { - /** Description of the code action to display in the UI of the editor */ - description: string; - /** Text changes to apply to each file as part of the code action */ - changes: FileCodeEdits[]; - /** A command is an opaque object that should be passed to `ApplyCodeActionCommandRequestArgs` without modification. */ - commands?: {}[]; - } - export interface CombinedCodeActions { - changes: readonly FileCodeEdits[]; - commands?: readonly {}[]; - } - export interface CodeFixAction extends CodeAction { - /** Short name to identify the fix, for use by telemetry. */ - fixName: string; - /** - * If present, one may call 'getCombinedCodeFix' with this fixId. - * This may be omitted to indicate that the code fix can't be applied in a group. - */ - fixId?: {}; - /** Should be present if and only if 'fixId' is. */ - fixAllDescription?: string; - } - /** - * Format and format on key response message. - */ - export interface FormatResponse extends Response { - body?: CodeEdit[]; - } - /** - * Arguments for format on key messages. - */ - export interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { - /** - * Key pressed (';', '\n', or '}'). - */ - key: string; - options?: FormatCodeSettings; - } - /** - * Format on key request; value of command field is - * "formatonkey". Given file location and key typed (as string), - * return response giving zero or more edit instructions. The - * edit instructions will be sorted in file order. Applying the - * edit instructions in reverse to file will result in correctly - * reformatted text. - */ - export interface FormatOnKeyRequest extends FileLocationRequest { - command: CommandTypes.Formatonkey; - arguments: FormatOnKeyRequestArgs; - } - /** - * Arguments for completions messages. - */ - export interface CompletionsRequestArgs extends FileLocationRequestArgs { - /** - * Optional prefix to apply to possible completions. - */ - prefix?: string; - /** - * Character that was responsible for triggering completion. - * Should be `undefined` if a user manually requested completion. - */ - triggerCharacter?: CompletionsTriggerCharacter; - triggerKind?: CompletionTriggerKind; - /** - * @deprecated Use UserPreferences.includeCompletionsForModuleExports - */ - includeExternalModuleExports?: boolean; - /** - * @deprecated Use UserPreferences.includeCompletionsWithInsertText - */ - includeInsertTextCompletions?: boolean; - } - /** - * Completions request; value of command field is "completions". - * Given a file location (file, line, col) and a prefix (which may - * be the empty string), return the possible completions that - * begin with prefix. - */ - export interface CompletionsRequest extends FileLocationRequest { - command: CommandTypes.Completions | CommandTypes.CompletionInfo; - arguments: CompletionsRequestArgs; - } - /** - * Arguments for completion details request. - */ - export interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { - /** - * Names of one or more entries for which to obtain details. - */ - entryNames: (string | CompletionEntryIdentifier)[]; - } - export interface CompletionEntryIdentifier { - name: string; - source?: string; - data?: unknown; - } - /** - * Completion entry details request; value of command field is - * "completionEntryDetails". Given a file location (file, line, - * col) and an array of completion entry names return more - * detailed information for each completion entry. - */ - export interface CompletionDetailsRequest extends FileLocationRequest { - command: CommandTypes.CompletionDetails; - arguments: CompletionDetailsRequestArgs; - } - /** A part of a symbol description that links from a jsdoc @link tag to a declaration */ - export interface JSDocLinkDisplayPart extends SymbolDisplayPart { - /** The location of the declaration that the @link tag links to. */ - target: FileSpan; - } - export type CompletionEntry = ChangePropertyTypes, { - replacementSpan: TextSpan; - data: unknown; - }>; - /** - * Additional completion entry details, available on demand - */ - export type CompletionEntryDetails = ChangePropertyTypes; - /** @deprecated Prefer CompletionInfoResponse, which supports several top-level fields in addition to the array of entries. */ - export interface CompletionsResponse extends Response { - body?: CompletionEntry[]; - } - export interface CompletionInfoResponse extends Response { - body?: CompletionInfo; - } - export type CompletionInfo = ChangePropertyTypes; - export interface CompletionDetailsResponse extends Response { - body?: CompletionEntryDetails[]; - } - /** - * Represents a single signature to show in signature help. - */ - export type SignatureHelpItem = ChangePropertyTypes; - /** - * Signature help items found in the response of a signature help request. - */ - export interface SignatureHelpItems { - /** - * The signature help items. - */ - items: SignatureHelpItem[]; - /** - * The span for which signature help should appear on a signature - */ - applicableSpan: TextSpan; - /** - * The item selected in the set of available help items. - */ - selectedItemIndex: number; - /** - * The argument selected in the set of parameters. - */ - argumentIndex: number; - /** - * The argument count - */ - argumentCount: number; - } - /** - * Arguments of a signature help request. - */ - export interface SignatureHelpRequestArgs extends FileLocationRequestArgs { - /** - * Reason why signature help was invoked. - * See each individual possible - */ - triggerReason?: SignatureHelpTriggerReason; - } - /** - * Signature help request; value of command field is "signatureHelp". - * Given a file location (file, line, col), return the signature - * help. - */ - export interface SignatureHelpRequest extends FileLocationRequest { - command: CommandTypes.SignatureHelp; - arguments: SignatureHelpRequestArgs; - } - /** - * Response object for a SignatureHelpRequest. - */ - export interface SignatureHelpResponse extends Response { - body?: SignatureHelpItems; - } - export interface InlayHintsRequestArgs extends FileRequestArgs { - /** - * Start position of the span. - */ - start: number; - /** - * Length of the span. - */ - length: number; - } - export interface InlayHintsRequest extends Request { - command: CommandTypes.ProvideInlayHints; - arguments: InlayHintsRequestArgs; - } - export type InlayHintItem = ChangePropertyTypes; - export interface InlayHintItemDisplayPart { - text: string; - span?: FileSpan; - } - export interface InlayHintsResponse extends Response { - body?: InlayHintItem[]; - } - export interface MapCodeRequestArgs extends FileRequestArgs { - /** - * The files and changes to try and apply/map. - */ - mapping: MapCodeRequestDocumentMapping; - } - export interface MapCodeRequestDocumentMapping { - /** - * The specific code to map/insert/replace in the file. - */ - contents: string[]; - /** - * Areas of "focus" to inform the code mapper with. For example, cursor - * location, current selection, viewport, etc. Nested arrays denote - * priority: toplevel arrays are more important than inner arrays, and - * inner array priorities are based on items within that array. Items - * earlier in the arrays have higher priority. - */ - focusLocations?: TextSpan[][]; - } - export interface MapCodeRequest extends FileRequest { - command: CommandTypes.MapCode; - arguments: MapCodeRequestArgs; - } - export interface MapCodeResponse extends Response { - body: readonly FileCodeEdits[]; - } - /** - * Synchronous request for semantic diagnostics of one file. - */ - export interface SemanticDiagnosticsSyncRequest extends FileRequest { - command: CommandTypes.SemanticDiagnosticsSync; - arguments: SemanticDiagnosticsSyncRequestArgs; - } - export interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { - includeLinePosition?: boolean; - } - /** - * Response object for synchronous sematic diagnostics request. - */ - export interface SemanticDiagnosticsSyncResponse extends Response { - body?: Diagnostic[] | DiagnosticWithLinePosition[]; - } - export interface SuggestionDiagnosticsSyncRequest extends FileRequest { - command: CommandTypes.SuggestionDiagnosticsSync; - arguments: SuggestionDiagnosticsSyncRequestArgs; - } - export type SuggestionDiagnosticsSyncRequestArgs = SemanticDiagnosticsSyncRequestArgs; - export type SuggestionDiagnosticsSyncResponse = SemanticDiagnosticsSyncResponse; - /** - * Synchronous request for syntactic diagnostics of one file. - */ - export interface SyntacticDiagnosticsSyncRequest extends FileRequest { - command: CommandTypes.SyntacticDiagnosticsSync; - arguments: SyntacticDiagnosticsSyncRequestArgs; - } - export interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { - includeLinePosition?: boolean; - } - /** - * Response object for synchronous syntactic diagnostics request. - */ - export interface SyntacticDiagnosticsSyncResponse extends Response { - body?: Diagnostic[] | DiagnosticWithLinePosition[]; - } - /** - * Arguments for GeterrForProject request. - */ - export interface GeterrForProjectRequestArgs { - /** - * the file requesting project error list - */ - file: string; - /** - * Delay in milliseconds to wait before starting to compute - * errors for the files in the file list - */ - delay: number; - } - /** - * GeterrForProjectRequest request; value of command field is - * "geterrForProject". It works similarly with 'Geterr', only - * it request for every file in this project. - */ - export interface GeterrForProjectRequest extends Request { - command: CommandTypes.GeterrForProject; - arguments: GeterrForProjectRequestArgs; - } - /** - * Arguments for geterr messages. - */ - export interface GeterrRequestArgs { - /** - * List of file names for which to compute compiler errors. - * The files will be checked in list order. - */ - files: (string | FileRangesRequestArgs)[]; - /** - * Delay in milliseconds to wait before starting to compute - * errors for the files in the file list - */ - delay: number; - } - /** - * Geterr request; value of command field is "geterr". Wait for - * delay milliseconds and then, if during the wait no change or - * reload messages have arrived for the first file in the files - * list, get the syntactic errors for the file, field requests, - * and then get the semantic errors for the file. Repeat with a - * smaller delay for each subsequent file on the files list. Best - * practice for an editor is to send a file list containing each - * file that is currently visible, in most-recently-used order. - */ - export interface GeterrRequest extends Request { - command: CommandTypes.Geterr; - arguments: GeterrRequestArgs; - } - export interface FileRange { - /** - * The line number for the request (1-based). - */ - startLine: number; - /** - * The character offset (on the line) for the request (1-based). - */ - startOffset: number; - /** - * The line number for the request (1-based). - */ - endLine: number; - /** - * The character offset (on the line) for the request (1-based). - */ - endOffset: number; - } - export interface FileRangesRequestArgs extends Pick { - ranges: FileRange[]; - } - export type RequestCompletedEventName = "requestCompleted"; - /** - * Event that is sent when server have finished processing request with specified id. - */ - export interface RequestCompletedEvent extends Event { - event: RequestCompletedEventName; - body: RequestCompletedEventBody; - } - export interface RequestCompletedEventBody { - request_seq: number; - performanceData?: PerformanceData; - } - /** - * Item of diagnostic information found in a DiagnosticEvent message. - */ - export interface Diagnostic { - /** - * Starting file location at which text applies. - */ - start: Location; - /** - * The last file location at which the text applies. - */ - end: Location; - /** - * Text of diagnostic message. - */ - text: string; - /** - * The category of the diagnostic message, e.g. "error", "warning", or "suggestion". - */ - category: string; - reportsUnnecessary?: {}; - reportsDeprecated?: {}; - /** - * Any related spans the diagnostic may have, such as other locations relevant to an error, such as declarartion sites - */ - relatedInformation?: DiagnosticRelatedInformation[]; - /** - * The error code of the diagnostic message. - */ - code?: number; - /** - * The name of the plugin reporting the message. - */ - source?: string; - } - export interface DiagnosticWithFileName extends Diagnostic { - /** - * Name of the file the diagnostic is in - */ - fileName: string; - } - /** - * Represents additional spans returned with a diagnostic which are relevant to it - */ - export interface DiagnosticRelatedInformation { - /** - * The category of the related information message, e.g. "error", "warning", or "suggestion". - */ - category: string; - /** - * The code used ot identify the related information - */ - code: number; - /** - * Text of related or additional information. - */ - message: string; - /** - * Associated location - */ - span?: FileSpan; - } - export interface DiagnosticEventBody { - /** - * The file for which diagnostic information is reported. - */ - file: string; - /** - * An array of diagnostic information items. - */ - diagnostics: Diagnostic[]; - /** - * Spans where the region diagnostic was requested, if this is a region semantic diagnostic event. - */ - spans?: TextSpan[]; - } - export type DiagnosticEventKind = "semanticDiag" | "syntaxDiag" | "suggestionDiag" | "regionSemanticDiag"; - /** - * Event message for DiagnosticEventKind event types. - * These events provide syntactic and semantic errors for a file. - */ - export interface DiagnosticEvent extends Event { - body?: DiagnosticEventBody; - event: DiagnosticEventKind; - } - export interface ConfigFileDiagnosticEventBody { - /** - * The file which trigged the searching and error-checking of the config file - */ - triggerFile: string; - /** - * The name of the found config file. - */ - configFile: string; - /** - * An arry of diagnostic information items for the found config file. - */ - diagnostics: DiagnosticWithFileName[]; - } - /** - * Event message for "configFileDiag" event type. - * This event provides errors for a found config file. - */ - export interface ConfigFileDiagnosticEvent extends Event { - body?: ConfigFileDiagnosticEventBody; - event: "configFileDiag"; - } - export type ProjectLanguageServiceStateEventName = "projectLanguageServiceState"; - export interface ProjectLanguageServiceStateEvent extends Event { - event: ProjectLanguageServiceStateEventName; - body?: ProjectLanguageServiceStateEventBody; - } - export interface ProjectLanguageServiceStateEventBody { - /** - * Project name that has changes in the state of language service. - * For configured projects this will be the config file path. - * For external projects this will be the name of the projects specified when project was open. - * For inferred projects this event is not raised. - */ - projectName: string; - /** - * True if language service state switched from disabled to enabled - * and false otherwise. - */ - languageServiceEnabled: boolean; - } - export type ProjectsUpdatedInBackgroundEventName = "projectsUpdatedInBackground"; - export interface ProjectsUpdatedInBackgroundEvent extends Event { - event: ProjectsUpdatedInBackgroundEventName; - body: ProjectsUpdatedInBackgroundEventBody; - } - export interface ProjectsUpdatedInBackgroundEventBody { - /** - * Current set of open files - */ - openFiles: string[]; - } - export type ProjectLoadingStartEventName = "projectLoadingStart"; - export interface ProjectLoadingStartEvent extends Event { - event: ProjectLoadingStartEventName; - body: ProjectLoadingStartEventBody; - } - export interface ProjectLoadingStartEventBody { - /** name of the project */ - projectName: string; - /** reason for loading */ - reason: string; - } - export type ProjectLoadingFinishEventName = "projectLoadingFinish"; - export interface ProjectLoadingFinishEvent extends Event { - event: ProjectLoadingFinishEventName; - body: ProjectLoadingFinishEventBody; - } - export interface ProjectLoadingFinishEventBody { - /** name of the project */ - projectName: string; - } - export type SurveyReadyEventName = "surveyReady"; - export interface SurveyReadyEvent extends Event { - event: SurveyReadyEventName; - body: SurveyReadyEventBody; - } - export interface SurveyReadyEventBody { - /** Name of the survey. This is an internal machine- and programmer-friendly name */ - surveyId: string; - } - export type LargeFileReferencedEventName = "largeFileReferenced"; - export interface LargeFileReferencedEvent extends Event { - event: LargeFileReferencedEventName; - body: LargeFileReferencedEventBody; - } - export interface LargeFileReferencedEventBody { - /** - * name of the large file being loaded - */ - file: string; - /** - * size of the file - */ - fileSize: number; - /** - * max file size allowed on the server - */ - maxFileSize: number; - } - export type CreateFileWatcherEventName = "createFileWatcher"; - export interface CreateFileWatcherEvent extends Event { - readonly event: CreateFileWatcherEventName; - readonly body: CreateFileWatcherEventBody; - } - export interface CreateFileWatcherEventBody { - readonly id: number; - readonly path: string; - } - export type CreateDirectoryWatcherEventName = "createDirectoryWatcher"; - export interface CreateDirectoryWatcherEvent extends Event { - readonly event: CreateDirectoryWatcherEventName; - readonly body: CreateDirectoryWatcherEventBody; - } - export interface CreateDirectoryWatcherEventBody { - readonly id: number; - readonly path: string; - readonly recursive: boolean; - readonly ignoreUpdate?: boolean; - } - export type CloseFileWatcherEventName = "closeFileWatcher"; - export interface CloseFileWatcherEvent extends Event { - readonly event: CloseFileWatcherEventName; - readonly body: CloseFileWatcherEventBody; - } - export interface CloseFileWatcherEventBody { - readonly id: number; - } - /** - * Arguments for reload request. - */ - export interface ReloadRequestArgs extends FileRequestArgs { - /** - * Name of temporary file from which to reload file - * contents. May be same as file. - */ - tmpfile: string; - } - /** - * Reload request message; value of command field is "reload". - * Reload contents of file with name given by the 'file' argument - * from temporary file with name given by the 'tmpfile' argument. - * The two names can be identical. - */ - export interface ReloadRequest extends FileRequest { - command: CommandTypes.Reload; - arguments: ReloadRequestArgs; - } - /** - * Response to "reload" request. This is just an acknowledgement, so - * no body field is required. - */ - export interface ReloadResponse extends Response { - } - /** - * Arguments for saveto request. - */ - export interface SavetoRequestArgs extends FileRequestArgs { - /** - * Name of temporary file into which to save server's view of - * file contents. - */ - tmpfile: string; - } - /** - * Saveto request message; value of command field is "saveto". - * For debugging purposes, save to a temporaryfile (named by - * argument 'tmpfile') the contents of file named by argument - * 'file'. The server does not currently send a response to a - * "saveto" request. - */ - export interface SavetoRequest extends FileRequest { - command: CommandTypes.Saveto; - arguments: SavetoRequestArgs; - } - /** - * Arguments for navto request message. - */ - export interface NavtoRequestArgs { - /** - * Search term to navigate to from current location; term can - * be '.*' or an identifier prefix. - */ - searchValue: string; - /** - * Optional limit on the number of items to return. - */ - maxResultCount?: number; - /** - * The file for the request (absolute pathname required). - */ - file?: string; - /** - * Optional flag to indicate we want results for just the current file - * or the entire project. - */ - currentFileOnly?: boolean; - projectFileName?: string; - } - /** - * Navto request message; value of command field is "navto". - * Return list of objects giving file locations and symbols that - * match the search term given in argument 'searchTerm'. The - * context for the search is given by the named file. - */ - export interface NavtoRequest extends Request { - command: CommandTypes.Navto; - arguments: NavtoRequestArgs; - } - /** - * An item found in a navto response. - */ - export interface NavtoItem extends FileSpan { - /** - * The symbol's name. - */ - name: string; - /** - * The symbol's kind (such as 'className' or 'parameterName'). - */ - kind: ScriptElementKind; - /** - * exact, substring, or prefix. - */ - matchKind: string; - /** - * If this was a case sensitive or insensitive match. - */ - isCaseSensitive: boolean; - /** - * Optional modifiers for the kind (such as 'public'). - */ - kindModifiers?: string; - /** - * Name of symbol's container symbol (if any); for example, - * the class name if symbol is a class member. - */ - containerName?: string; - /** - * Kind of symbol's container symbol (if any). - */ - containerKind?: ScriptElementKind; - } - /** - * Navto response message. Body is an array of navto items. Each - * item gives a symbol that matched the search term. - */ - export interface NavtoResponse extends Response { - body?: NavtoItem[]; - } - /** - * Arguments for change request message. - */ - export interface ChangeRequestArgs extends FormatRequestArgs { - /** - * Optional string to insert at location (file, line, offset). - */ - insertString?: string; - } - /** - * Change request message; value of command field is "change". - * Update the server's view of the file named by argument 'file'. - * Server does not currently send a response to a change request. - */ - export interface ChangeRequest extends FileLocationRequest { - command: CommandTypes.Change; - arguments: ChangeRequestArgs; - } - /** - * Response to "brace" request. - */ - export interface BraceResponse extends Response { - body?: TextSpan[]; - } - /** - * Brace matching request; value of command field is "brace". - * Return response giving the file locations of matching braces - * found in file at location line, offset. - */ - export interface BraceRequest extends FileLocationRequest { - command: CommandTypes.Brace; - } - /** - * NavBar items request; value of command field is "navbar". - * Return response giving the list of navigation bar entries - * extracted from the requested file. - */ - export interface NavBarRequest extends FileRequest { - command: CommandTypes.NavBar; - } - /** - * NavTree request; value of command field is "navtree". - * Return response giving the navigation tree of the requested file. - */ - export interface NavTreeRequest extends FileRequest { - command: CommandTypes.NavTree; - } - export interface NavigationBarItem { - /** - * The item's display text. - */ - text: string; - /** - * The symbol's kind (such as 'className' or 'parameterName'). - */ - kind: ScriptElementKind; - /** - * Optional modifiers for the kind (such as 'public'). - */ - kindModifiers?: string; - /** - * The definition locations of the item. - */ - spans: TextSpan[]; - /** - * Optional children. - */ - childItems?: NavigationBarItem[]; - /** - * Number of levels deep this item should appear. - */ - indent: number; - } - /** protocol.NavigationTree is identical to ts.NavigationTree, except using protocol.TextSpan instead of ts.TextSpan */ - export interface NavigationTree { - text: string; - kind: ScriptElementKind; - kindModifiers: string; - spans: TextSpan[]; - nameSpan: TextSpan | undefined; - childItems?: NavigationTree[]; - } - export type TelemetryEventName = "telemetry"; - export interface TelemetryEvent extends Event { - event: TelemetryEventName; - body: TelemetryEventBody; - } - export interface TelemetryEventBody { - telemetryEventName: string; - payload: any; - } - export type TypesInstallerInitializationFailedEventName = "typesInstallerInitializationFailed"; - export interface TypesInstallerInitializationFailedEvent extends Event { - event: TypesInstallerInitializationFailedEventName; - body: TypesInstallerInitializationFailedEventBody; - } - export interface TypesInstallerInitializationFailedEventBody { - message: string; - } - export type TypingsInstalledTelemetryEventName = "typingsInstalled"; - export interface TypingsInstalledTelemetryEventBody extends TelemetryEventBody { - telemetryEventName: TypingsInstalledTelemetryEventName; - payload: TypingsInstalledTelemetryEventPayload; - } - export interface TypingsInstalledTelemetryEventPayload { - /** - * Comma separated list of installed typing packages - */ - installedPackages: string; - /** - * true if install request succeeded, otherwise - false - */ - installSuccess: boolean; - /** - * version of typings installer - */ - typingsInstallerVersion: string; - } - export type BeginInstallTypesEventName = "beginInstallTypes"; - export type EndInstallTypesEventName = "endInstallTypes"; - export interface BeginInstallTypesEvent extends Event { - event: BeginInstallTypesEventName; - body: BeginInstallTypesEventBody; - } - export interface EndInstallTypesEvent extends Event { - event: EndInstallTypesEventName; - body: EndInstallTypesEventBody; - } - export interface InstallTypesEventBody { - /** - * correlation id to match begin and end events - */ - eventId: number; - /** - * list of packages to install - */ - packages: readonly string[]; - } - export interface BeginInstallTypesEventBody extends InstallTypesEventBody { - } - export interface EndInstallTypesEventBody extends InstallTypesEventBody { - /** - * true if installation succeeded, otherwise false - */ - success: boolean; - } - export interface NavBarResponse extends Response { - body?: NavigationBarItem[]; - } - export interface NavTreeResponse extends Response { - body?: NavigationTree; - } - export type CallHierarchyItem = ChangePropertyTypes; - export interface CallHierarchyIncomingCall { - from: CallHierarchyItem; - fromSpans: TextSpan[]; - } - export interface CallHierarchyOutgoingCall { - to: CallHierarchyItem; - fromSpans: TextSpan[]; - } - export interface PrepareCallHierarchyRequest extends FileLocationRequest { - command: CommandTypes.PrepareCallHierarchy; - } - export interface PrepareCallHierarchyResponse extends Response { - readonly body: CallHierarchyItem | CallHierarchyItem[]; - } - export interface ProvideCallHierarchyIncomingCallsRequest extends FileLocationRequest { - command: CommandTypes.ProvideCallHierarchyIncomingCalls; - } - export interface ProvideCallHierarchyIncomingCallsResponse extends Response { - readonly body: CallHierarchyIncomingCall[]; - } - export interface ProvideCallHierarchyOutgoingCallsRequest extends FileLocationRequest { - command: CommandTypes.ProvideCallHierarchyOutgoingCalls; - } - export interface ProvideCallHierarchyOutgoingCallsResponse extends Response { - readonly body: CallHierarchyOutgoingCall[]; - } - export enum IndentStyle { - None = "None", - Block = "Block", - Smart = "Smart", - } - export type EditorSettings = ChangePropertyTypes; - export type FormatCodeSettings = ChangePropertyTypes; - export type CompilerOptions = ChangePropertyTypes, { - jsx: JsxEmit | ts.JsxEmit; - module: ModuleKind | ts.ModuleKind; - moduleResolution: ModuleResolutionKind | ts.ModuleResolutionKind; - newLine: NewLineKind | ts.NewLineKind; - target: ScriptTarget | ts.ScriptTarget; - }>; - export enum JsxEmit { - None = "none", - Preserve = "preserve", - ReactNative = "react-native", - React = "react", - ReactJSX = "react-jsx", - ReactJSXDev = "react-jsxdev", - } - export enum ModuleKind { - None = "none", - CommonJS = "commonjs", - AMD = "amd", - UMD = "umd", - System = "system", - ES6 = "es6", - ES2015 = "es2015", - ES2020 = "es2020", - ES2022 = "es2022", - ESNext = "esnext", - Node16 = "node16", - NodeNext = "nodenext", - Preserve = "preserve", - } - export enum ModuleResolutionKind { - Classic = "classic", - /** @deprecated Renamed to `Node10` */ - Node = "node", - /** @deprecated Renamed to `Node10` */ - NodeJs = "node", - Node10 = "node10", - Node16 = "node16", - NodeNext = "nodenext", - Bundler = "bundler", - } - export enum NewLineKind { - Crlf = "Crlf", - Lf = "Lf", - } - export enum ScriptTarget { - /** @deprecated */ - ES3 = "es3", - ES5 = "es5", - ES6 = "es6", - ES2015 = "es2015", - ES2016 = "es2016", - ES2017 = "es2017", - ES2018 = "es2018", - ES2019 = "es2019", - ES2020 = "es2020", - ES2021 = "es2021", - ES2022 = "es2022", - ES2023 = "es2023", - ESNext = "esnext", - JSON = "json", - Latest = "esnext", - } + namespace deno { + function setIsNodeSourceFileCallback(callback: IsNodeSourceFileCallback): void; + function setNodeOnlyGlobalNames(names: Set): void; + function setTypesNodeIgnorableNames(names: Set): void; + function createDenoForkContext({ mergeSymbol, globals, nodeGlobals }: { + mergeSymbol(target: ts.Symbol, source: ts.Symbol, unidirectional?: boolean): ts.Symbol; + globals: ts.SymbolTable; + nodeGlobals: ts.SymbolTable; + }): DenoForkContext; + function tryParseNpmPackageReference(text: string): NpmPackageReference | undefined; + function parseNpmPackageReference(text: string): NpmPackageReference; + type IsNodeSourceFileCallback = (sourceFile: ts.SourceFile) => boolean; + interface DenoForkContext { + hasNodeSourceFile: (node: ts.Node | undefined) => boolean; + getGlobalsForName: (id: ts.__String) => ts.SymbolTable; + mergeGlobalSymbolTable: (node: ts.Node, source: ts.SymbolTable, unidirectional?: boolean) => void; + combinedGlobals: ts.SymbolTable; } - namespace typingsInstaller { - interface Log { - isEnabled(): boolean; - writeLine(text: string): void; - } - type RequestCompletedAction = (success: boolean) => void; - interface PendingRequest { - requestId: number; - packageNames: string[]; - cwd: string; - onRequestCompleted: RequestCompletedAction; - } - abstract class TypingsInstaller { - protected readonly installTypingHost: InstallTypingHost; - private readonly globalCachePath; - private readonly safeListPath; - private readonly typesMapLocation; - private readonly throttleLimit; - protected readonly log: Log; - private readonly packageNameToTypingLocation; - private readonly missingTypingsSet; - private readonly knownCachesSet; - private readonly projectWatchers; - private safeList; - private pendingRunRequests; - private installRunCount; - private inFlightRequestCount; - abstract readonly typesRegistry: Map>; - constructor(installTypingHost: InstallTypingHost, globalCachePath: string, safeListPath: Path, typesMapLocation: Path, throttleLimit: number, log?: Log); - closeProject(req: CloseProject): void; - private closeWatchers; - install(req: DiscoverTypings): void; - private initializeSafeList; - private processCacheLocation; - private filterTypings; - protected ensurePackageDirectoryExists(directory: string): void; - private installTypings; - private ensureDirectoryExists; - private watchFiles; - private createSetTypings; - private installTypingsAsync; - private executeWithThrottling; - protected abstract installWorker(requestId: number, packageNames: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void; - protected abstract sendResponse(response: SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes | WatchTypingLocations): void; - protected readonly latestDistTag = "latest"; - } + interface NpmPackageReference { + name: string; + versionReq: string | undefined; + subPath: string | undefined; + } + } + namespace JsTyping { + interface TypingResolutionHost { + directoryExists(path: string): boolean; + fileExists(fileName: string): boolean; + readFile(path: string, encoding?: string): string | undefined; + readDirectory(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[] | undefined, depth?: number): string[]; } + } + namespace server { type ActionSet = "action::set"; type ActionInvalidate = "action::invalidate"; type ActionPackageInstalled = "action::packageInstalled"; @@ -2643,990 +131,8 @@ declare namespace ts { readonly files: readonly string[] | undefined; readonly kind: ActionWatchTypingLocations; } - interface CompressedData { - length: number; - compressionKind: string; - data: any; - } - type ModuleImportResult = { - module: {}; - error: undefined; - } | { - module: undefined; - error: { - stack?: string; - message?: string; - }; - }; - /** @deprecated Use {@link ModuleImportResult} instead. */ - type RequireResult = ModuleImportResult; - interface ServerHost extends System { - watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number, options?: WatchOptions): FileWatcher; - watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean, options?: WatchOptions): FileWatcher; - preferNonRecursiveWatch?: boolean; - setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - clearTimeout(timeoutId: any): void; - setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; - clearImmediate(timeoutId: any): void; - gc?(): void; - trace?(s: string): void; - require?(initialPath: string, moduleName: string): ModuleImportResult; - } - interface InstallPackageOptionsWithProject extends InstallPackageOptions { - projectName: string; - projectRootPath: Path; - } - interface ITypingsInstaller { - isKnownTypesPackageName(name: string): boolean; - installPackage(options: InstallPackageOptionsWithProject): Promise; - enqueueInstallTypingsRequest(p: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray | undefined): void; - attach(projectService: ProjectService): void; - onProjectClosed(p: Project): void; - readonly globalTypingsCacheLocation: string | undefined; - } - function createInstallTypingsRequest(project: Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray, cachePath?: string): DiscoverTypings; - function toNormalizedPath(fileName: string): NormalizedPath; - function normalizedPathToPath(normalizedPath: NormalizedPath, currentDirectory: string, getCanonicalFileName: (f: string) => string): Path; - function asNormalizedPath(fileName: string): NormalizedPath; - function createNormalizedPathMap(): NormalizedPathMap; - function isInferredProjectName(name: string): boolean; - function makeInferredProjectName(counter: number): string; - function createSortedArray(): SortedArray; - enum LogLevel { - terse = 0, - normal = 1, - requestTime = 2, - verbose = 3, - } - const emptyArray: SortedReadonlyArray; - interface Logger { - close(): void; - hasLevel(level: LogLevel): boolean; - loggingEnabled(): boolean; - perftrc(s: string): void; - info(s: string): void; - startGroup(): void; - endGroup(): void; - msg(s: string, type?: Msg): void; - getLogFileName(): string | undefined; - } - enum Msg { - Err = "Err", - Info = "Info", - Perf = "Perf", - } - namespace Errors { - function ThrowNoProject(): never; - function ThrowProjectLanguageServiceDisabled(): never; - function ThrowProjectDoesNotContainDocument(fileName: string, project: Project): never; - } - type NormalizedPath = string & { - __normalizedPathTag: any; - }; - interface NormalizedPathMap { - get(path: NormalizedPath): T | undefined; - set(path: NormalizedPath, value: T): void; - contains(path: NormalizedPath): boolean; - remove(path: NormalizedPath): void; - } - function isDynamicFileName(fileName: NormalizedPath): boolean; - class ScriptInfo { - private readonly host; - readonly fileName: NormalizedPath; - readonly scriptKind: ScriptKind; - readonly hasMixedContent: boolean; - readonly path: Path; - /** - * All projects that include this file - */ - readonly containingProjects: Project[]; - private formatSettings; - private preferences; - private realpath; - constructor(host: ServerHost, fileName: NormalizedPath, scriptKind: ScriptKind, hasMixedContent: boolean, path: Path, initialVersion?: number); - isScriptOpen(): boolean; - open(newText: string | undefined): void; - close(fileExists?: boolean): void; - getSnapshot(): IScriptSnapshot; - private ensureRealPath; - getFormatCodeSettings(): FormatCodeSettings | undefined; - getPreferences(): protocol.UserPreferences | undefined; - attachToProject(project: Project): boolean; - isAttached(project: Project): boolean; - detachFromProject(project: Project): void; - detachAllProjects(): void; - getDefaultProject(): Project; - registerFileUpdate(): void; - setOptions(formatSettings: FormatCodeSettings, preferences: protocol.UserPreferences | undefined): void; - getLatestVersion(): string; - saveTo(fileName: string): void; - reloadFromFile(tempFileName?: NormalizedPath): boolean; - editContent(start: number, end: number, newText: string): void; - markContainingProjectsAsDirty(): void; - isOrphan(): boolean; - /** - * @param line 1 based index - */ - lineToTextSpan(line: number): TextSpan; - /** - * @param line 1 based index - * @param offset 1 based index - */ - lineOffsetToPosition(line: number, offset: number): number; - positionToLineOffset(position: number): protocol.Location; - isJavaScript(): boolean; - } - function allRootFilesAreJsOrDts(project: Project): boolean; - function allFilesAreJsOrDts(project: Project): boolean; - enum ProjectKind { - Inferred = 0, - Configured = 1, - External = 2, - AutoImportProvider = 3, - Auxiliary = 4, - } - interface PluginCreateInfo { - project: Project; - languageService: LanguageService; - languageServiceHost: LanguageServiceHost; - serverHost: ServerHost; - session?: Session; - config: any; - } - interface PluginModule { - create(createInfo: PluginCreateInfo): LanguageService; - getExternalFiles?(proj: Project, updateLevel: ProgramUpdateLevel): string[]; - onConfigurationChanged?(config: any): void; - } - interface PluginModuleWithName { - name: string; - module: PluginModule; - } - type PluginModuleFactory = (mod: { - typescript: typeof ts; - }) => PluginModule; - abstract class Project implements LanguageServiceHost, ModuleResolutionHost { - readonly projectKind: ProjectKind; - readonly projectService: ProjectService; - private documentRegistry; - private compilerOptions; - compileOnSaveEnabled: boolean; - protected watchOptions: WatchOptions | undefined; - private rootFilesMap; - private program; - private externalFiles; - private missingFilesMap; - private generatedFilesMap; - private hasAddedorRemovedFiles; - private hasAddedOrRemovedSymlinks; - protected languageService: LanguageService; - languageServiceEnabled: boolean; - readonly trace?: (s: string) => void; - readonly realpath?: (path: string) => string; - private builderState; - private updatedFileNames; - private lastReportedFileNames; - private lastReportedVersion; - protected projectErrors: Diagnostic[] | undefined; - protected isInitialLoadPending: () => boolean; - private typingsCache; - private typingWatchers; - private readonly cancellationToken; - isNonTsProject(): boolean; - isJsOnlyProject(): boolean; - static resolveModule(moduleName: string, initialDir: string, host: ServerHost, log: (message: string) => void): {} | undefined; - private exportMapCache; - private changedFilesForExportMapCache; - private moduleSpecifierCache; - private symlinks; - readonly jsDocParsingMode: JSDocParsingMode | undefined; - isKnownTypesPackageName(name: string): boolean; - installPackage(options: InstallPackageOptions): Promise; - getCompilationSettings(): ts.CompilerOptions; - getCompilerOptions(): ts.CompilerOptions; - getNewLine(): string; - getProjectVersion(): string; - getProjectReferences(): readonly ProjectReference[] | undefined; - getScriptFileNames(): string[]; - private getOrCreateScriptInfoAndAttachToProject; - getScriptKind(fileName: string): ts.ScriptKind; - getScriptVersion(filename: string): string; - getScriptSnapshot(filename: string): IScriptSnapshot | undefined; - getCancellationToken(): HostCancellationToken; - getCurrentDirectory(): string; - getDefaultLibFileName(): string; - useCaseSensitiveFileNames(): boolean; - readDirectory(path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number): string[]; - readFile(fileName: string): string | undefined; - writeFile(fileName: string, content: string): void; - fileExists(file: string): boolean; - directoryExists(path: string): boolean; - getDirectories(path: string): string[]; - log(s: string): void; - error(s: string): void; - private setInternalCompilerOptionsForEmittingJsFiles; - /** - * Get the errors that dont have any file name associated - */ - getGlobalProjectErrors(): readonly Diagnostic[]; - /** - * Get all the project errors - */ - getAllProjectErrors(): readonly Diagnostic[]; - setProjectErrors(projectErrors: Diagnostic[] | undefined): void; - getLanguageService(ensureSynchronized?: boolean): LanguageService; - getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; - /** - * Returns true if emit was conducted - */ - emitFile(scriptInfo: ScriptInfo, writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => void): EmitResult; - enableLanguageService(): void; - disableLanguageService(lastFileExceededProgramSize?: string): void; - getProjectName(): string; - protected removeLocalTypingsFromTypeAcquisition(newTypeAcquisition: TypeAcquisition): TypeAcquisition; - getExternalFiles(updateLevel?: ProgramUpdateLevel): SortedReadonlyArray; - getSourceFile(path: Path): ts.SourceFile | undefined; - close(): void; - private detachScriptInfoIfNotRoot; - isClosed(): boolean; - hasRoots(): boolean; - getRootFiles(): NormalizedPath[]; - getRootScriptInfos(): ts.server.ScriptInfo[]; - getScriptInfos(): ScriptInfo[]; - getExcludedFiles(): readonly NormalizedPath[]; - getFileNames(excludeFilesFromExternalLibraries?: boolean, excludeConfigFiles?: boolean): ts.server.NormalizedPath[]; - hasConfigFile(configFilePath: NormalizedPath): boolean; - containsScriptInfo(info: ScriptInfo): boolean; - containsFile(filename: NormalizedPath, requireOpen?: boolean): boolean; - isRoot(info: ScriptInfo): boolean; - addRoot(info: ScriptInfo, fileName?: NormalizedPath): void; - addMissingFileRoot(fileName: NormalizedPath): void; - removeFile(info: ScriptInfo, fileExists: boolean, detachFromProject: boolean): void; - registerFileUpdate(fileName: string): void; - /** - * Updates set of files that contribute to this project - * @returns: true if set of files in the project stays the same and false - otherwise. - */ - updateGraph(): boolean; - private closeWatchingTypingLocations; - private onTypingInstallerWatchInvoke; - protected removeExistingTypings(include: string[]): string[]; - private updateGraphWorker; - private detachScriptInfoFromProject; - private addMissingFileWatcher; - private isWatchedMissingFile; - private createGeneratedFileWatcher; - private isValidGeneratedFileWatcher; - private clearGeneratedFileWatch; - getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined; - getScriptInfo(uncheckedFileName: string): ts.server.ScriptInfo | undefined; - filesToString(writeProjectFileNames: boolean): string; - private filesToStringWorker; - setCompilerOptions(compilerOptions: CompilerOptions): void; - setTypeAcquisition(newTypeAcquisition: TypeAcquisition | undefined): void; - getTypeAcquisition(): ts.TypeAcquisition; - protected removeRoot(info: ScriptInfo): void; - protected enableGlobalPlugins(options: CompilerOptions): void; - protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void; - /** Starts a new check for diagnostics. Call this if some file has updated that would cause diagnostics to be changed. */ - refreshDiagnostics(): void; - private isDefaultProjectForOpenFiles; - private getCompilerOptionsForNoDtsResolutionProject; - } - /** - * If a file is opened and no tsconfig (or jsconfig) is found, - * the file and its imports/references are put into an InferredProject. - */ - class InferredProject extends Project { - private _isJsInferredProject; - toggleJsInferredProject(isJsInferredProject: boolean): void; - setCompilerOptions(options?: CompilerOptions): void; - /** this is canonical project root path */ - readonly projectRootPath: string | undefined; - addRoot(info: ScriptInfo): void; - removeRoot(info: ScriptInfo): void; - isProjectWithSingleRoot(): boolean; - close(): void; - getTypeAcquisition(): TypeAcquisition; - } - class AutoImportProviderProject extends Project { - private hostProject; - private static readonly maxDependencies; - private rootFileNames; - updateGraph(): boolean; - hasRoots(): boolean; - getScriptFileNames(): string[]; - getLanguageService(): never; - getHostForAutoImportProvider(): never; - getProjectReferences(): readonly ts.ProjectReference[] | undefined; - } - /** - * If a file is opened, the server will look for a tsconfig (or jsconfig) - * and if successful create a ConfiguredProject for it. - * Otherwise it will create an InferredProject. - */ - class ConfiguredProject extends Project { - readonly canonicalConfigFilePath: NormalizedPath; - private projectReferences; - private compilerHost?; - private releaseParsedConfig; - /** - * If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph - * @returns: true if set of files in the project stays the same and false - otherwise. - */ - updateGraph(): boolean; - getConfigFilePath(): ts.server.NormalizedPath; - getProjectReferences(): readonly ProjectReference[] | undefined; - updateReferences(refs: readonly ProjectReference[] | undefined): void; - /** - * Get the errors that dont have any file name associated - */ - getGlobalProjectErrors(): readonly Diagnostic[]; - /** - * Get all the project errors - */ - getAllProjectErrors(): readonly Diagnostic[]; - setProjectErrors(projectErrors: Diagnostic[]): void; - close(): void; - getEffectiveTypeRoots(): string[]; - } - /** - * Project whose configuration is handled externally, such as in a '.csproj'. - * These are created only if a host explicitly calls `openExternalProject`. - */ - class ExternalProject extends Project { - externalProjectName: string; - compileOnSaveEnabled: boolean; - excludedFiles: readonly NormalizedPath[]; - updateGraph(): boolean; - getExcludedFiles(): readonly ts.server.NormalizedPath[]; - } - function convertFormatOptions(protocolOptions: protocol.FormatCodeSettings): FormatCodeSettings; - function convertCompilerOptions(protocolOptions: protocol.ExternalProjectCompilerOptions): CompilerOptions & protocol.CompileOnSaveMixin; - function convertWatchOptions(protocolOptions: protocol.ExternalProjectCompilerOptions, currentDirectory?: string): WatchOptionsAndErrors | undefined; - function convertTypeAcquisition(protocolOptions: protocol.InferredProjectCompilerOptions): TypeAcquisition | undefined; - function tryConvertScriptKindName(scriptKindName: protocol.ScriptKindName | ScriptKind): ScriptKind; - function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind.Unknown | ScriptKind.JS | ScriptKind.JSX | ScriptKind.TS | ScriptKind.TSX; - const maxProgramSizeForNonTsFiles: number; - const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; - interface ProjectsUpdatedInBackgroundEvent { - eventName: typeof ProjectsUpdatedInBackgroundEvent; - data: { - openFiles: string[]; - }; - } - const ProjectLoadingStartEvent = "projectLoadingStart"; - interface ProjectLoadingStartEvent { - eventName: typeof ProjectLoadingStartEvent; - data: { - project: Project; - reason: string; - }; - } - const ProjectLoadingFinishEvent = "projectLoadingFinish"; - interface ProjectLoadingFinishEvent { - eventName: typeof ProjectLoadingFinishEvent; - data: { - project: Project; - }; - } - const LargeFileReferencedEvent = "largeFileReferenced"; - interface LargeFileReferencedEvent { - eventName: typeof LargeFileReferencedEvent; - data: { - file: string; - fileSize: number; - maxFileSize: number; - }; - } - const ConfigFileDiagEvent = "configFileDiag"; - interface ConfigFileDiagEvent { - eventName: typeof ConfigFileDiagEvent; - data: { - triggerFile: string; - configFileName: string; - diagnostics: readonly Diagnostic[]; - }; - } - const ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; - interface ProjectLanguageServiceStateEvent { - eventName: typeof ProjectLanguageServiceStateEvent; - data: { - project: Project; - languageServiceEnabled: boolean; - }; - } - const ProjectInfoTelemetryEvent = "projectInfo"; - /** This will be converted to the payload of a protocol.TelemetryEvent in session.defaultEventHandler. */ - interface ProjectInfoTelemetryEvent { - readonly eventName: typeof ProjectInfoTelemetryEvent; - readonly data: ProjectInfoTelemetryEventData; - } - const OpenFileInfoTelemetryEvent = "openFileInfo"; - /** - * Info that we may send about a file that was just opened. - * Info about a file will only be sent once per session, even if the file changes in ways that might affect the info. - * Currently this is only sent for '.js' files. - */ - interface OpenFileInfoTelemetryEvent { - readonly eventName: typeof OpenFileInfoTelemetryEvent; - readonly data: OpenFileInfoTelemetryEventData; - } - const CreateFileWatcherEvent: protocol.CreateFileWatcherEventName; - interface CreateFileWatcherEvent { - readonly eventName: protocol.CreateFileWatcherEventName; - readonly data: protocol.CreateFileWatcherEventBody; - } - const CreateDirectoryWatcherEvent: protocol.CreateDirectoryWatcherEventName; - interface CreateDirectoryWatcherEvent { - readonly eventName: protocol.CreateDirectoryWatcherEventName; - readonly data: protocol.CreateDirectoryWatcherEventBody; - } - const CloseFileWatcherEvent: protocol.CloseFileWatcherEventName; - interface CloseFileWatcherEvent { - readonly eventName: protocol.CloseFileWatcherEventName; - readonly data: protocol.CloseFileWatcherEventBody; - } - interface ProjectInfoTelemetryEventData { - /** Cryptographically secure hash of project file location. */ - readonly projectId: string; - /** Count of file extensions seen in the project. */ - readonly fileStats: FileStats; - /** - * Any compiler options that might contain paths will be taken out. - * Enum compiler options will be converted to strings. - */ - readonly compilerOptions: CompilerOptions; - readonly extends: boolean | undefined; - readonly files: boolean | undefined; - readonly include: boolean | undefined; - readonly exclude: boolean | undefined; - readonly compileOnSave: boolean; - readonly typeAcquisition: ProjectInfoTypeAcquisitionData; - readonly configFileName: "tsconfig.json" | "jsconfig.json" | "other"; - readonly projectType: "external" | "configured"; - readonly languageServiceEnabled: boolean; - /** TypeScript version used by the server. */ - readonly version: string; - } - interface OpenFileInfoTelemetryEventData { - readonly info: OpenFileInfo; - } - interface ProjectInfoTypeAcquisitionData { - readonly enable: boolean | undefined; - readonly include: boolean; - readonly exclude: boolean; - } - interface FileStats { - readonly js: number; - readonly jsSize?: number; - readonly jsx: number; - readonly jsxSize?: number; - readonly ts: number; - readonly tsSize?: number; - readonly tsx: number; - readonly tsxSize?: number; - readonly dts: number; - readonly dtsSize?: number; - readonly deferred: number; - readonly deferredSize?: number; - } - interface OpenFileInfo { - readonly checkJs: boolean; - } - type ProjectServiceEvent = LargeFileReferencedEvent | ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent | CreateFileWatcherEvent | CreateDirectoryWatcherEvent | CloseFileWatcherEvent; - type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; - interface SafeList { - [name: string]: { - match: RegExp; - exclude?: (string | number)[][]; - types?: string[]; - }; - } - interface TypesMapFile { - typesMap: SafeList; - simpleMap: { - [libName: string]: string; - }; - } - interface HostConfiguration { - formatCodeOptions: FormatCodeSettings; - preferences: protocol.UserPreferences; - hostInfo: string; - extraFileExtensions?: FileExtensionInfo[]; - watchOptions?: WatchOptions; - } - interface OpenConfiguredProjectResult { - configFileName?: NormalizedPath; - configFileErrors?: readonly Diagnostic[]; - } - const nullTypingsInstaller: ITypingsInstaller; - interface ProjectServiceOptions { - host: ServerHost; - logger: Logger; - cancellationToken: HostCancellationToken; - useSingleInferredProject: boolean; - useInferredProjectPerProjectRoot: boolean; - typingsInstaller?: ITypingsInstaller; - eventHandler?: ProjectServiceEventHandler; - canUseWatchEvents?: boolean; - suppressDiagnosticEvents?: boolean; - throttleWaitMilliseconds?: number; - globalPlugins?: readonly string[]; - pluginProbeLocations?: readonly string[]; - allowLocalPluginLoads?: boolean; - typesMapLocation?: string; - serverMode?: LanguageServiceMode; - session: Session | undefined; - jsDocParsingMode?: JSDocParsingMode; - } - interface WatchOptionsAndErrors { - watchOptions: WatchOptions; - errors: Diagnostic[] | undefined; - } - class ProjectService { - private readonly nodeModulesWatchers; - private readonly filenameToScriptInfoVersion; - private readonly allJsFilesForOpenFileTelemetry; - private readonly externalProjectToConfiguredProjectMap; - /** - * external projects (configuration and list of root files is not controlled by tsserver) - */ - readonly externalProjects: ExternalProject[]; - /** - * projects built from openFileRoots - */ - readonly inferredProjects: InferredProject[]; - /** - * projects specified by a tsconfig.json file - */ - readonly configuredProjects: Map; - /** - * Open files: with value being project root path, and key being Path of the file that is open - */ - readonly openFiles: Map; - private readonly configFileForOpenFiles; - private rootOfInferredProjects; - private readonly openFilesWithNonRootedDiskPath; - private compilerOptionsForInferredProjects; - private compilerOptionsForInferredProjectsPerProjectRoot; - private watchOptionsForInferredProjects; - private watchOptionsForInferredProjectsPerProjectRoot; - private typeAcquisitionForInferredProjects; - private typeAcquisitionForInferredProjectsPerProjectRoot; - private readonly projectToSizeMap; - private readonly hostConfiguration; - private safelist; - private readonly legacySafelist; - private pendingProjectUpdates; - private pendingOpenFileProjectUpdates?; - readonly currentDirectory: NormalizedPath; - readonly toCanonicalFileName: (f: string) => string; - readonly host: ServerHost; - readonly logger: Logger; - readonly cancellationToken: HostCancellationToken; - readonly useSingleInferredProject: boolean; - readonly useInferredProjectPerProjectRoot: boolean; - readonly typingsInstaller: ITypingsInstaller; - private readonly globalCacheLocationDirectoryPath; - readonly throttleWaitMilliseconds?: number; - private readonly suppressDiagnosticEvents?; - readonly globalPlugins: readonly string[]; - readonly pluginProbeLocations: readonly string[]; - readonly allowLocalPluginLoads: boolean; - readonly typesMapLocation: string | undefined; - readonly serverMode: LanguageServiceMode; - private readonly seenProjects; - private readonly sharedExtendedConfigFileWatchers; - private readonly extendedConfigCache; - private packageJsonFilesMap; - private incompleteCompletionsCache; - private performanceEventHandler?; - private pendingPluginEnablements?; - private currentPluginEnablementPromise?; - readonly jsDocParsingMode: JSDocParsingMode | undefined; - constructor(opts: ProjectServiceOptions); - toPath(fileName: string): Path; - private loadTypesMap; - updateTypingsForProject(response: SetTypings | InvalidateCachedTypings | PackageInstalledResponse): void; - private delayUpdateProjectGraph; - private delayUpdateProjectGraphs; - setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.InferredProjectCompilerOptions, projectRootPath?: string): void; - findProject(projectName: string): Project | undefined; - getDefaultProjectForFile(fileName: NormalizedPath, ensureProject: boolean): Project | undefined; - private tryGetDefaultProjectForEnsuringConfiguredProjectForFile; - private doEnsureDefaultProjectForFile; - getScriptInfoEnsuringProjectsUptoDate(uncheckedFileName: string): ScriptInfo | undefined; - private ensureProjectStructuresUptoDate; - getFormatCodeOptions(file: NormalizedPath): FormatCodeSettings; - getPreferences(file: NormalizedPath): protocol.UserPreferences; - getHostFormatCodeOptions(): FormatCodeSettings; - getHostPreferences(): protocol.UserPreferences; - private onSourceFileChanged; - private handleSourceMapProjects; - private delayUpdateSourceInfoProjects; - private delayUpdateProjectsOfScriptInfoPath; - private handleDeletedFile; - private watchWildcardDirectory; - private onWildCardDirectoryWatcherInvoke; - private delayUpdateProjectsFromParsedConfigOnConfigFileChange; - private onConfigFileChanged; - private removeProject; - private assignOrphanScriptInfosToInferredProject; - private closeOpenFile; - private deleteScriptInfo; - private configFileExists; - private createConfigFileWatcherForParsedConfig; - private forEachConfigFileLocation; - private getConfigFileNameForFileFromCache; - private setConfigFileNameForFileInCache; - private printProjects; - private getConfiguredProjectByCanonicalConfigFilePath; - private findExternalProjectByProjectName; - private getFilenameForExceededTotalSizeLimitForNonTsFiles; - private createExternalProject; - private addFilesToNonInferredProject; - private loadConfiguredProject; - private updateNonInferredProjectFiles; - private updateRootAndOptionsOfNonInferredProject; - private reloadFileNamesOfParsedConfig; - private clearSemanticCache; - private getOrCreateInferredProjectForProjectRootPathIfEnabled; - private getOrCreateSingleInferredProjectIfEnabled; - private getOrCreateSingleInferredWithoutProjectRoot; - private createInferredProject; - getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined; - private watchClosedScriptInfo; - private createNodeModulesWatcher; - private watchClosedScriptInfoInNodeModules; - private getModifiedTime; - private refreshScriptInfo; - private refreshScriptInfosInDirectory; - private stopWatchingScriptInfo; - private getOrCreateScriptInfoNotOpenedByClientForNormalizedPath; - getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, hostToQueryFileExistsOn?: { - fileExists(path: string): boolean; - }): ScriptInfo | undefined; - private getOrCreateScriptInfoWorker; - /** - * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred - */ - getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined; - getScriptInfoForPath(fileName: Path): ScriptInfo | undefined; - private addSourceInfoToSourceMap; - private addMissingSourceMapFile; - setHostConfiguration(args: protocol.ConfigureRequestArguments): void; - private getWatchOptionsFromProjectWatchOptions; - closeLog(): void; - private sendSourceFileChange; - /** - * This function rebuilds the project for every file opened by the client - * This does not reload contents of open files from disk. But we could do that if needed - */ - reloadProjects(): void; - private removeRootOfInferredProjectIfNowPartOfOtherProject; - private ensureProjectForOpenFiles; - /** - * Open file whose contents is managed by the client - * @param filename is absolute pathname - * @param fileContent is a known version of the file content that is more up to date than the one on disk - */ - openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind, projectRootPath?: string): OpenConfiguredProjectResult; - private findExternalProjectContainingOpenScriptInfo; - private getOrCreateOpenScriptInfo; - private assignProjectToOpenedScriptInfo; - private tryFindDefaultConfiguredProjectForOpenScriptInfo; - private tryFindDefaultConfiguredProjectAndLoadAncestorsForOpenScriptInfo; - private ensureProjectChildren; - private cleanupConfiguredProjects; - private cleanupProjectsAndScriptInfos; - private tryInvokeWildCardDirectories; - openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult; - private removeOrphanScriptInfos; - private telemetryOnOpenFile; - /** - * Close file whose contents is managed by the client - * @param filename is absolute pathname - */ - closeClientFile(uncheckedFileName: string): void; - private collectChanges; - closeExternalProject(uncheckedFileName: string): void; - openExternalProjects(projects: protocol.ExternalProject[]): void; - private static readonly filenameEscapeRegexp; - private static escapeFilenameForRegex; - resetSafeList(): void; - applySafeList(proj: protocol.ExternalProject): NormalizedPath[]; - private applySafeListWorker; - openExternalProject(proj: protocol.ExternalProject): void; - hasDeferredExtension(): boolean; - private endEnablePlugin; - private enableRequestedPluginsAsync; - private enableRequestedPluginsWorker; - configurePlugin(args: protocol.ConfigurePluginRequestArguments): void; - private watchPackageJsonFile; - private onPackageJsonChange; - } - function formatMessage(msg: T, logger: Logger, byteLength: (s: string, encoding: BufferEncoding) => number, newLine: string): string; - interface ServerCancellationToken extends HostCancellationToken { - setRequest(requestId: number): void; - resetRequest(requestId: number): void; - } - const nullCancellationToken: ServerCancellationToken; - /** @deprecated use ts.server.protocol.CommandTypes */ - type CommandNames = protocol.CommandTypes; - /** @deprecated use ts.server.protocol.CommandTypes */ - const CommandNames: any; - type Event = (body: T, eventName: string) => void; - interface EventSender { - event: Event; - } - interface SessionOptions { - host: ServerHost; - cancellationToken: ServerCancellationToken; - useSingleInferredProject: boolean; - useInferredProjectPerProjectRoot: boolean; - typingsInstaller?: ITypingsInstaller; - byteLength: (buf: string, encoding?: BufferEncoding) => number; - hrtime: (start?: [ - number, - number, - ]) => [ - number, - number, - ]; - logger: Logger; - /** - * If falsy, all events are suppressed. - */ - canUseEvents: boolean; - canUseWatchEvents?: boolean; - eventHandler?: ProjectServiceEventHandler; - /** Has no effect if eventHandler is also specified. */ - suppressDiagnosticEvents?: boolean; - serverMode?: LanguageServiceMode; - throttleWaitMilliseconds?: number; - noGetErrOnBackgroundUpdate?: boolean; - globalPlugins?: readonly string[]; - pluginProbeLocations?: readonly string[]; - allowLocalPluginLoads?: boolean; - typesMapLocation?: string; - } - class Session implements EventSender { - private readonly gcTimer; - protected projectService: ProjectService; - private changeSeq; - private performanceData; - private currentRequestId; - private errorCheck; - protected host: ServerHost; - private readonly cancellationToken; - protected readonly typingsInstaller: ITypingsInstaller; - protected byteLength: (buf: string, encoding?: BufferEncoding) => number; - private hrtime; - protected logger: Logger; - protected canUseEvents: boolean; - private suppressDiagnosticEvents?; - private eventHandler; - private readonly noGetErrOnBackgroundUpdate?; - constructor(opts: SessionOptions); - private sendRequestCompletedEvent; - private addPerformanceData; - private addDiagnosticsPerformanceData; - private performanceEventHandler; - private defaultEventHandler; - private projectsUpdatedInBackgroundEvent; - logError(err: Error, cmd: string): void; - private logErrorWorker; - send(msg: protocol.Message): void; - protected writeMessage(msg: protocol.Message): void; - event(body: T, eventName: string): void; - private semanticCheck; - private syntacticCheck; - private suggestionCheck; - private regionSemanticCheck; - private sendDiagnosticsEvent; - private updateErrorCheck; - private cleanProjects; - private cleanup; - private getEncodedSyntacticClassifications; - private getEncodedSemanticClassifications; - private getProject; - private getConfigFileAndProject; - private getConfigFileDiagnostics; - private convertToDiagnosticsWithLinePositionFromDiagnosticFile; - private getCompilerOptionsDiagnostics; - private convertToDiagnosticsWithLinePosition; - private getDiagnosticsWorker; - private getDefinition; - private mapDefinitionInfoLocations; - private getDefinitionAndBoundSpan; - private findSourceDefinition; - private getEmitOutput; - private mapJSDocTagInfo; - private mapDisplayParts; - private mapSignatureHelpItems; - private mapDefinitionInfo; - private static mapToOriginalLocation; - private toFileSpan; - private toFileSpanWithContext; - private getTypeDefinition; - private mapImplementationLocations; - private getImplementation; - private getSyntacticDiagnosticsSync; - private getSemanticDiagnosticsSync; - private getSuggestionDiagnosticsSync; - private getJsxClosingTag; - private getLinkedEditingRange; - private getDocumentHighlights; - private provideInlayHints; - private mapCode; - private setCompilerOptionsForInferredProjects; - private getProjectInfo; - private getProjectInfoWorker; - private getRenameInfo; - private getProjects; - private getDefaultProject; - private getRenameLocations; - private mapRenameInfo; - private toSpanGroups; - private getReferences; - private getFileReferences; - private openClientFile; - private getPosition; - private getPositionInFile; - private getFileAndProject; - private getFileAndLanguageServiceForSyntacticOperation; - private getFileAndProjectWorker; - private getOutliningSpans; - private getTodoComments; - private getDocCommentTemplate; - private getSpanOfEnclosingComment; - private getIndentation; - private getBreakpointStatement; - private getNameOrDottedNameSpan; - private isValidBraceCompletion; - private getQuickInfoWorker; - private getFormattingEditsForRange; - private getFormattingEditsForRangeFull; - private getFormattingEditsForDocumentFull; - private getFormattingEditsAfterKeystrokeFull; - private getFormattingEditsAfterKeystroke; - private getCompletions; - private getCompletionEntryDetails; - private getCompileOnSaveAffectedFileList; - private emitFile; - private getSignatureHelpItems; - private toPendingErrorCheck; - private getDiagnostics; - private change; - private reload; - private saveToTmp; - private closeClientFile; - private mapLocationNavigationBarItems; - private getNavigationBarItems; - private toLocationNavigationTree; - private getNavigationTree; - private getNavigateToItems; - private getFullNavigateToItems; - private getSupportedCodeFixes; - private isLocation; - private extractPositionOrRange; - private getRange; - private getApplicableRefactors; - private getEditsForRefactor; - private getMoveToRefactoringFileSuggestions; - private getPasteEdits; - private organizeImports; - private getEditsForFileRename; - private getCodeFixes; - private getCombinedCodeFix; - private applyCodeActionCommand; - private getStartAndEndPosition; - private mapCodeAction; - private mapCodeFixAction; - private mapPasteEditsAction; - private mapTextChangesToCodeEdits; - private mapTextChangeToCodeEdit; - private convertTextChangeToCodeEdit; - private getBraceMatching; - private getDiagnosticsForProject; - private configurePlugin; - private getSmartSelectionRange; - private toggleLineComment; - private toggleMultilineComment; - private commentSelection; - private uncommentSelection; - private mapSelectionRange; - private getScriptInfoFromProjectService; - private toProtocolCallHierarchyItem; - private toProtocolCallHierarchyIncomingCall; - private toProtocolCallHierarchyOutgoingCall; - private prepareCallHierarchy; - private provideCallHierarchyIncomingCalls; - private provideCallHierarchyOutgoingCalls; - getCanonicalFileName(fileName: string): string; - exit(): void; - private notRequired; - private requiredResponse; - private handlers; - addProtocolHandler(command: string, handler: (request: protocol.Request) => HandlerResponse): void; - private setCurrentRequest; - private resetCurrentRequest; - executeWithRequestId(requestId: number, f: () => T): T; - executeCommand(request: protocol.Request): HandlerResponse; - onMessage(message: TMessage): void; - protected parseMessage(message: TMessage): protocol.Request; - protected toStringMessage(message: TMessage): string; - private getFormatOptions; - private getPreferences; - private getHostFormatOptions; - private getHostPreferences; - } - interface HandlerResponse { - response?: {}; - responseRequired?: boolean; - } } - namespace deno { - function setIsNodeSourceFileCallback(callback: IsNodeSourceFileCallback): void; - function setNodeOnlyGlobalNames(names: readonly string[]): void; - function createDenoForkContext({ mergeSymbol, globals, nodeGlobals }: { - mergeSymbol(target: ts.Symbol, source: ts.Symbol, unidirectional?: boolean): ts.Symbol; - globals: ts.SymbolTable; - nodeGlobals: ts.SymbolTable; - }): DenoForkContext; - function tryParseNpmPackageReference(text: string): { - name: string; - versionReq: string | undefined; - subPath: string | undefined; - } | undefined; - function parseNpmPackageReference(text: string): { - name: string; - versionReq: string | undefined; - subPath: string | undefined; - }; - type IsNodeSourceFileCallback = (sourceFile: ts.SourceFile) => boolean; - interface DenoForkContext { - hasNodeSourceFile: (node: ts.Node | undefined) => boolean; - getGlobalsForName: (id: ts.__String) => ts.SymbolTable; - mergeGlobalSymbolTable: (node: ts.Node, source: ts.SymbolTable, unidirectional?: boolean) => void; - combinedGlobals: ts.SymbolTable; - } - interface NpmPackageReference { - name: string; - versionReq: string; - subPath: string | undefined; - } - } - namespace JsTyping { - interface TypingResolutionHost { - directoryExists(path: string): boolean; - fileExists(fileName: string): boolean; - readFile(path: string, encoding?: string): string | undefined; - readDirectory(rootDir: string, extensions: readonly string[], excludes: readonly string[] | undefined, includes: readonly string[] | undefined, depth?: number): string[]; - } - } - const versionMajorMinor = "5.6"; + const versionMajorMinor = "5.7"; /** The version of the TypeScript compiler release */ const version: string; /** @@ -4014,10 +520,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, @@ -5129,7 +1636,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; @@ -5165,6 +1672,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; @@ -5243,6 +1751,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. */ @@ -6146,7 +2657,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[]; @@ -7013,6 +3524,7 @@ declare namespace ts { moduleDetection?: ModuleDetectionKind; newLine?: NewLineKind; noEmit?: boolean; + noCheck?: boolean; noEmitHelpers?: boolean; noEmitOnError?: boolean; noErrorTruncation?: boolean; @@ -7052,6 +3564,7 @@ declare namespace ts { removeComments?: boolean; resolvePackageJsonExports?: boolean; resolvePackageJsonImports?: boolean; + rewriteRelativeImportExtensions?: boolean; rootDir?: string; rootDirs?: string[]; skipLibCheck?: boolean; @@ -7162,6 +3675,7 @@ declare namespace ts { ES2021 = 8, ES2022 = 9, ES2023 = 10, + ES2024 = 11, ESNext = 99, JSON = 100, Latest = 99, @@ -7844,6 +4358,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; @@ -8725,6 +5240,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; @@ -8773,6 +5289,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; @@ -9151,6 +5668,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 */ @@ -9205,6 +5723,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 @@ -9932,6 +6457,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 @@ -10206,6 +6733,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/ext/net/lib.deno_net.d.ts b/ext/net/lib.deno_net.d.ts index f9dab79e688c8b..6300e66f9262b9 100644 --- a/ext/net/lib.deno_net.d.ts +++ b/ext/net/lib.deno_net.d.ts @@ -136,8 +136,8 @@ declare namespace Deno { /** Make the connection not block the event loop from finishing. */ unref(): void; - readonly readable: ReadableStream; - readonly writable: WritableStream; + readonly readable: ReadableStream>; + readonly writable: WritableStream>; } /** @category Network */ @@ -751,7 +751,7 @@ declare namespace Deno { * `maxDatagramSize`. */ sendDatagram(data: Uint8Array): Promise; /** Receive a datagram. */ - readDatagram(): Promise; + readDatagram(): Promise>; /** The endpoint for this connection. */ readonly endpoint: QuicEndpoint; @@ -800,7 +800,8 @@ declare namespace Deno { * @experimental * @category Network */ - export interface QuicSendStream extends WritableStream { + export interface QuicSendStream + extends WritableStream> { /** Indicates the send priority of this stream relative to other streams for * which the value has been set. */ sendOrder: number; @@ -817,7 +818,8 @@ declare namespace Deno { * @experimental * @category Network */ - export interface QuicReceiveStream extends ReadableStream { + export interface QuicReceiveStream + extends ReadableStream> { /** * 62-bit stream ID, unique within this connection. */ diff --git a/ext/node/ops/http.rs b/ext/node/ops/http.rs index 57bcf69a47cf3c..1da630f97edebd 100644 --- a/ext/node/ops/http.rs +++ b/ext/node/ops/http.rs @@ -113,6 +113,9 @@ pub enum ConnError { #[error("Invalid URL {0}")] InvalidUrl(Url), #[class(type)] + #[error("Invalid Path {0}")] + InvalidPath(String), + #[class(type)] #[error(transparent)] InvalidHeaderName(#[from] http::header::InvalidHeaderName), #[class(type)] @@ -150,6 +153,7 @@ pub async fn op_node_http_request_with_conn

( state: Rc>, #[serde] method: ByteString, #[string] url: String, + #[string] request_path: Option, #[serde] headers: Vec<(ByteString, ByteString)>, #[smi] body: Option, #[smi] conn_rid: ResourceId, @@ -247,11 +251,17 @@ where *request.method_mut() = method.clone(); let path = url_parsed.path(); let query = url_parsed.query(); - *request.uri_mut() = query - .map(|q| format!("{}?{}", path, q)) - .unwrap_or_else(|| path.to_string()) - .parse() - .map_err(|_| ConnError::InvalidUrl(url_parsed.clone()))?; + if let Some(request_path) = request_path { + *request.uri_mut() = request_path + .parse() + .map_err(|_| ConnError::InvalidPath(request_path.clone()))?; + } else { + *request.uri_mut() = query + .map(|q| format!("{}?{}", path, q)) + .unwrap_or_else(|| path.to_string()) + .parse() + .map_err(|_| ConnError::InvalidUrl(url_parsed.clone()))?; + } *request.headers_mut() = header_map; if let Some((username, password)) = maybe_authority { diff --git a/ext/node/ops/sqlite/statement.rs b/ext/node/ops/sqlite/statement.rs index b1e8fe84c4f16e..1fa8ade59903de 100644 --- a/ext/node/ops/sqlite/statement.rs +++ b/ext/node/ops/sqlite/statement.rs @@ -160,10 +160,10 @@ impl StatementSync { let size = ffi::sqlite3_column_bytes(self.inner, index); let value = std::slice::from_raw_parts(value as *const u8, size as usize); - let value = - v8::ArrayBuffer::new_backing_store_from_vec(value.to_vec()) - .make_shared(); - v8::ArrayBuffer::with_backing_store(scope, &value).into() + let bs = v8::ArrayBuffer::new_backing_store_from_vec(value.to_vec()) + .make_shared(); + let ab = v8::ArrayBuffer::with_backing_store(scope, &bs); + v8::Uint8Array::new(scope, ab, 0, size as _).unwrap().into() } ffi::SQLITE_NULL => v8::null(scope).into(), _ => v8::undefined(scope).into(), @@ -266,6 +266,20 @@ impl StatementSync { ffi::SQLITE_TRANSIENT(), ); } + } else if value.is_big_int() { + let value: v8::Local = value.try_into().unwrap(); + let (as_int, lossless) = value.i64_value(); + if !lossless { + return Err(SqliteError::FailedBind( + "BigInt value is too large to bind", + )); + } + + // SAFETY: `self.inner` is a valid pointer to a sqlite3_stmt + // as it lives as long as the StatementSync instance. + unsafe { + ffi::sqlite3_bind_int64(raw, i + 1, as_int); + } } else { return Err(SqliteError::FailedBind("Unsupported type")); } diff --git a/ext/node/polyfills/http.ts b/ext/node/polyfills/http.ts index dd94c9d025fd95..0438f9af22e6c7 100644 --- a/ext/node/polyfills/http.ts +++ b/ext/node/polyfills/http.ts @@ -479,6 +479,7 @@ class ClientRequest extends OutgoingMessage { this._req = await op_node_http_request_with_conn( this.method, url, + this._createRequestPath(), headers, this._bodyWriteRid, baseConnRid, @@ -817,6 +818,15 @@ class ClientRequest extends OutgoingMessage { return url.href; } + _createRequestPath(): string | undefined { + // If the path starts with protocol, pass this to op_node_http_request_with_conn + // This will be used as Request.uri in hyper for supporting http proxy + if (this.path?.startsWith("http://") || this.path?.startsWith("https://")) { + return this.path; + } + return undefined; + } + setTimeout(msecs: number, callback?: () => void) { if (msecs === 0) { if (this._timeout) { diff --git a/ext/node/polyfills/process.ts b/ext/node/polyfills/process.ts index e10f2d67d4a598..3e63b9a076d965 100644 --- a/ext/node/polyfills/process.ts +++ b/ext/node/polyfills/process.ts @@ -780,6 +780,7 @@ const process = new Process(); /* Set owned property */ process.versions = versions; +process.env = env; Object.defineProperty(process, Symbol.toStringTag, { enumerable: false, diff --git a/ext/url/lib.deno_url.d.ts b/ext/url/lib.deno_url.d.ts index b5dfd1cf058251..0bbfefa3b73d87 100644 --- a/ext/url/lib.deno_url.d.ts +++ b/ext/url/lib.deno_url.d.ts @@ -5,6 +5,12 @@ /// /// +/** @category URL */ +interface URLSearchParamsIterator + extends IteratorObject { + [Symbol.iterator](): URLSearchParamsIterator; +} + /** @category URL */ interface URLSearchParams { /** Appends a specified key/value pair as a new search parameter. @@ -102,7 +108,7 @@ interface URLSearchParams { * } * ``` */ - keys(): IterableIterator; + keys(): URLSearchParamsIterator; /** Returns an iterator allowing to go through all values contained * in this object. @@ -114,7 +120,7 @@ interface URLSearchParams { * } * ``` */ - values(): IterableIterator; + values(): URLSearchParamsIterator; /** Returns an iterator allowing to go through all key/value * pairs contained in this object. @@ -126,7 +132,7 @@ interface URLSearchParams { * } * ``` */ - entries(): IterableIterator<[string, string]>; + entries(): URLSearchParamsIterator<[string, string]>; /** Returns an iterator allowing to go through all key/value * pairs contained in this object. @@ -138,7 +144,7 @@ interface URLSearchParams { * } * ``` */ - [Symbol.iterator](): IterableIterator<[string, string]>; + [Symbol.iterator](): URLSearchParamsIterator<[string, string]>; /** Returns a query string suitable for use in a URL. * @@ -154,14 +160,18 @@ interface URLSearchParams { * searchParams.size * ``` */ - size: number; + readonly size: number; } /** @category URL */ declare var URLSearchParams: { readonly prototype: URLSearchParams; new ( - init?: Iterable | Record | string, + init?: + | Iterable + | Record + | string + | URLSearchParams, ): URLSearchParams; }; diff --git a/tests/integration/cache_tests.rs b/tests/integration/cache_tests.rs index 3fbed3cbd46df4..e3f5c8cacd699a 100644 --- a/tests/integration/cache_tests.rs +++ b/tests/integration/cache_tests.rs @@ -34,16 +34,16 @@ fn cache_matching_package_json_dep_should_not_install_all() { let temp_dir = context.temp_dir(); temp_dir.write( "package.json", - r#"{ "dependencies": { "@types/node": "18.8.2", "@denotest/esm-basic": "*" } }"#, + r#"{ "dependencies": { "@types/node": "22.12.0", "@denotest/esm-basic": "*" } }"#, ); let output = context .new_command() - .args("cache npm:@types/node@18.8.2") + .args("cache npm:@types/node@22.12.0") .run(); output.assert_matches_text(concat!( "Download http://localhost:4260/@types/node\n", "Download http://localhost:4260/@types/node/node-18.8.2.tgz\n", - "Initialize @types/node@18.8.2\n", + "Initialize @types/node@22.12.0\n", )); } diff --git a/tests/integration/run_tests.rs b/tests/integration/run_tests.rs index 5485c6e4eb386c..b127ddfd27e3df 100644 --- a/tests/integration/run_tests.rs +++ b/tests/integration/run_tests.rs @@ -250,7 +250,7 @@ fn permissions_prompt_allow_all() { )); console.human_delay(); console.write_line_raw("A"); - console.expect("✅ Granted all run access."); + console.expect("Granted all run access."); // "read" permissions console.expect(concat!( "┏ ⚠️ Deno requests read access to \"FOO\".\r\n", @@ -262,7 +262,7 @@ fn permissions_prompt_allow_all() { )); console.human_delay(); console.write_line_raw("A"); - console.expect("✅ Granted all read access."); + console.expect("Granted all read access."); // "write" permissions console.expect(concat!( "┏ ⚠️ Deno requests write access to \"FOO\".\r\n", @@ -274,7 +274,7 @@ fn permissions_prompt_allow_all() { )); console.human_delay(); console.write_line_raw("A"); - console.expect("✅ Granted all write access."); + console.expect("Granted all write access."); // "net" permissions console.expect(concat!( "┏ ⚠️ Deno requests net access to \"foo\".\r\n", @@ -286,7 +286,7 @@ fn permissions_prompt_allow_all() { )); console.human_delay(); console.write_line_raw("A"); - console.expect("✅ Granted all net access."); + console.expect("Granted all net access."); // "env" permissions console.expect(concat!( "┏ ⚠️ Deno requests env access to \"FOO\".\r\n", @@ -298,7 +298,7 @@ fn permissions_prompt_allow_all() { )); console.human_delay(); console.write_line_raw("A"); - console.expect("✅ Granted all env access."); + console.expect("Granted all env access."); // "sys" permissions console.expect(concat!( "┏ ⚠️ Deno requests sys access to \"loadavg\".\r\n", @@ -310,7 +310,7 @@ fn permissions_prompt_allow_all() { )); console.human_delay(); console.write_line_raw("A"); - console.expect("✅ Granted all sys access."); + console.expect("Granted all sys access."); // "ffi" permissions console.expect(concat!( "┏ ⚠️ Deno requests ffi access to \"FOO\".\r\n", @@ -322,7 +322,7 @@ fn permissions_prompt_allow_all() { )); console.human_delay(); console.write_line_raw("A"); - console.expect("✅ Granted all ffi access.") + console.expect("Granted all ffi access.") }, ); } @@ -343,7 +343,7 @@ fn permissions_prompt_allow_all_2() { )); console.human_delay(); console.write_line_raw("A"); - console.expect("✅ Granted all env access."); + console.expect("Granted all env access."); // "sys" permissions console.expect(concat!( @@ -356,7 +356,7 @@ fn permissions_prompt_allow_all_2() { )); console.human_delay(); console.write_line_raw("A"); - console.expect("✅ Granted all sys access."); + console.expect("Granted all sys access."); let text = console.read_until("Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all read permissions)"); // "read" permissions @@ -371,7 +371,7 @@ fn permissions_prompt_allow_all_2() { )); console.human_delay(); console.write_line_raw("A"); - console.expect("✅ Granted all read access."); + console.expect("Granted all read access."); }); } @@ -427,7 +427,7 @@ fn permissions_cache() { )); console.human_delay(); console.write_line_raw("y"); - console.expect("✅ Granted read access to \"foo\"."); + console.expect("Granted read access to \"foo\"."); console.expect("granted"); console.expect("prompt"); }); @@ -455,7 +455,7 @@ fn permissions_trace() { console.human_delay(); console.write_line_raw("y"); - console.expect("✅ Granted sys access to \"hostname\"."); + console.expect("Granted sys access to \"hostname\"."); }); } @@ -2762,20 +2762,38 @@ fn stdio_streams_are_locked_in_permission_prompt() { // The worker is blocked, so nothing else should get written here console.human_delay(); console.write_line_raw("i"); - // We ensure that nothing gets written here between the permission prompt and this text, despire the delay + // We ensure that nothing gets written here between the permission prompt and this text, despite the delay let newline = if cfg!(target_os = "linux") { "^J" } else { "\r\n" }; - console.expect_raw_next(format!("i{newline}\u{1b}[1A\u{1b}[0J┗ Unrecognized option. Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all read permissions) > ")); - console.human_delay(); - console.write_line_raw("y"); - // We ensure that nothing gets written here between the permission prompt and this text, despire the delay - console.expect_raw_next(format!("y{newline}\x1b[6A\x1b[0J✅ Granted read access to \"")); + if cfg!(windows) { + // it's too difficult to inspect the raw text on windows because the console + // outputs a bunch of control characters, so we instead rely on the last assertion + // in this test that checks to ensure we didn't receive any malicious output during + // the permission prompts + console.expect("Unrecognized option. Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all read permissions) >"); + console.human_delay(); + console.write_line_raw("y"); + console.expect("Granted read access to"); + } else { + console.expect_raw_next(format!("i{newline}\u{1b}[1A\u{1b}[0J┗ Unrecognized option. Allow? [y/n/A] (y = yes, allow; n = no, deny; A = allow all read permissions) > ")); + console.human_delay(); + console.write_line_raw("y"); + // We ensure that nothing gets written here between the permission prompt and this text, despite the delay + console.expect_raw_next(format!("y{newline}\x1b[6A\x1b[0J✅ Granted read access to \"")); + } // Back to spamming! console.expect(malicious_output); + + // Ensure during the permission prompt showing we didn't receive any malicious output + let all_text = console.all_output(); + let start_prompt_index = all_text.find("Allow?").unwrap(); + let end_prompt_index = all_text.find("Granted read access to").unwrap(); + let prompt_text = &all_text[start_prompt_index..end_prompt_index]; + assert!(!prompt_text.contains(malicious_output), "Prompt text: {:?}", prompt_text); }); } diff --git a/tests/registry/npm/@babel/parser/registry.json b/tests/registry/npm/@babel/parser/registry.json index a7e2b8c605a0b8..61ff9bc17c70d3 100644 --- a/tests/registry/npm/@babel/parser/registry.json +++ b/tests/registry/npm/@babel/parser/registry.json @@ -55,6 +55,5 @@ }, "author": "The Babel Team (https://babel.dev/team)", "license": "MIT", - "readmeFilename": "", "bugs": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A+parser+%28babylon%29%22+is%3Aopen" } diff --git a/tests/registry/npm/@isaacs/cliui/registry.json b/tests/registry/npm/@isaacs/cliui/registry.json index 9cef3f6e500886..53f6f14c74a129 100644 --- a/tests/registry/npm/@isaacs/cliui/registry.json +++ b/tests/registry/npm/@isaacs/cliui/registry.json @@ -112,6 +112,5 @@ "bugs": { "url": "https://github.com/yargs/cliui/issues" }, - "license": "ISC", - "readmeFilename": "README.md" + "license": "ISC" } diff --git a/tests/registry/npm/@ljharb/has-package-exports-patterns/registry.json b/tests/registry/npm/@ljharb/has-package-exports-patterns/registry.json index c4a6c51af0bd9a..e46e4abb0567d6 100644 --- a/tests/registry/npm/@ljharb/has-package-exports-patterns/registry.json +++ b/tests/registry/npm/@ljharb/has-package-exports-patterns/registry.json @@ -56,6 +56,5 @@ "bugs": { "url": "https://github.com/inspect-js/has-package-exports/issues" }, - "license": "MIT", - "readmeFilename": "" + "license": "MIT" } diff --git a/tests/registry/npm/@npmcli/agent/registry.json b/tests/registry/npm/@npmcli/agent/registry.json index 452ecb94ad47ad..872f297d8f4ada 100644 --- a/tests/registry/npm/@npmcli/agent/registry.json +++ b/tests/registry/npm/@npmcli/agent/registry.json @@ -93,6 +93,5 @@ "homepage": "https://github.com/npm/agent#readme", "bugs": { "url": "https://github.com/npm/agent/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/@npmcli/fs/registry.json b/tests/registry/npm/@npmcli/fs/registry.json index 3864ebd67e2ff3..f9e79f2383b1a0 100644 --- a/tests/registry/npm/@npmcli/fs/registry.json +++ b/tests/registry/npm/@npmcli/fs/registry.json @@ -79,6 +79,5 @@ "homepage": "https://github.com/npm/fs#readme", "bugs": { "url": "https://github.com/npm/fs/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/@opentelemetry/api/registry.json b/tests/registry/npm/@opentelemetry/api/registry.json index 11b8a35f87e468..c3de1632aa2bc8 100644 --- a/tests/registry/npm/@opentelemetry/api/registry.json +++ b/tests/registry/npm/@opentelemetry/api/registry.json @@ -127,6 +127,5 @@ "homepage": "https://github.com/open-telemetry/opentelemetry-js/tree/main/api", "bugs": { "url": "https://github.com/open-telemetry/opentelemetry-js/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/@pkgjs/parseargs/registry.json b/tests/registry/npm/@pkgjs/parseargs/registry.json index 035d6890f70d32..201e8fb9c07e44 100644 --- a/tests/registry/npm/@pkgjs/parseargs/registry.json +++ b/tests/registry/npm/@pkgjs/parseargs/registry.json @@ -61,6 +61,5 @@ "bugs": { "url": "https://github.com/pkgjs/parseargs/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/@types/lz-string/registry.json b/tests/registry/npm/@types/lz-string/registry.json index 261c43340504ac..eab29417cc5f73 100644 --- a/tests/registry/npm/@types/lz-string/registry.json +++ b/tests/registry/npm/@types/lz-string/registry.json @@ -54,6 +54,5 @@ "_hasShrinkwrap": false } }, - "license": "MIT", - "readmeFilename": "" + "license": "MIT" } diff --git a/tests/registry/npm/@types/node/node-18.16.19.tgz b/tests/registry/npm/@types/node/node-18.16.19.tgz deleted file mode 100644 index 00307ee080fdd4..00000000000000 Binary files a/tests/registry/npm/@types/node/node-18.16.19.tgz and /dev/null differ diff --git a/tests/registry/npm/@types/node/node-18.8.2.tgz b/tests/registry/npm/@types/node/node-18.8.2.tgz deleted file mode 100644 index 8afc9d21dfb299..00000000000000 Binary files a/tests/registry/npm/@types/node/node-18.8.2.tgz and /dev/null differ diff --git a/tests/registry/npm/@types/node/node-22.12.0.tgz b/tests/registry/npm/@types/node/node-22.12.0.tgz new file mode 100644 index 00000000000000..bb1a33560fee00 Binary files /dev/null and b/tests/registry/npm/@types/node/node-22.12.0.tgz differ diff --git a/tests/registry/npm/@types/node/node-22.5.4.tgz b/tests/registry/npm/@types/node/node-22.5.4.tgz deleted file mode 100644 index 2a7f1911a03e1d..00000000000000 Binary files a/tests/registry/npm/@types/node/node-22.5.4.tgz and /dev/null differ diff --git a/tests/registry/npm/@types/node/registry.json b/tests/registry/npm/@types/node/registry.json index 1590a9de624996..20dfc371884d6f 100644 --- a/tests/registry/npm/@types/node/registry.json +++ b/tests/registry/npm/@types/node/registry.json @@ -1,30 +1,29 @@ { "name": "@types/node", "dist-tags": { - "ts4.9": "22.5.4", - "ts5.5": "22.5.4", - "ts5.6": "22.5.4", - "ts5.7": "22.5.4", - "ts4.8": "22.5.4", - "ts5.2": "22.5.4", - "ts5.3": "22.5.4", - "ts5.4": "22.5.4", - "ts5.1": "22.5.4", - "ts5.0": "22.5.4", - "latest": "22.5.4" + "ts5.8": "22.12.0", + "ts5.0": "22.12.0", + "ts5.4": "22.12.0", + "ts5.6": "22.12.0", + "latest": "22.12.0", + "ts5.3": "22.12.0", + "ts5.7": "22.12.0", + "ts5.1": "22.12.0", + "ts5.5": "22.12.0", + "ts5.2": "22.12.0" }, "versions": { - "18.8.2": { + "22.12.0": { "name": "@types/node", - "version": "18.8.2", + "version": "22.12.0", "license": "MIT", - "_id": "@types/node@18.8.2", + "_id": "@types/node@22.12.0", "dist": { - "shasum": "17d42c6322d917764dd3d2d3a10d7884925de067", - "tarball": "http://localhost:4260/@types/node/node-18.8.2.tgz", - "fileCount": 124, - "integrity": "sha512-cRMwIgdDN43GO4xMWAfJAecYn8wV4JbsOGHNfNUIDiuYkUYAR5ec4Rj7IO2SAhFPEfpPtLtUTbbny/TCT7aDwA==", - "unpackedSize": 3524549 + "shasum": "bf8af3b2af0837b5a62a368756ff2b705ae0048c", + "tarball": "http://localhost:4260/@types/node/node-22.12.0.tgz", + "fileCount": 76, + "integrity": "sha512-Fll2FZ1riMjNmlmJOdAyY5pUbkftXslB5DgEzlIuNaiWhXd00FhWxVC/r4yV/4wBb9JfImTu+jiSvXTkJ7F/gA==", + "unpackedSize": 2296605 }, "main": "", "types": "index.d.ts", @@ -34,82 +33,22 @@ "type": "git", "directory": "types/node" }, - "description": "TypeScript definitions for Node.js", + "description": "TypeScript definitions for node", "directories": {}, - "dependencies": {}, - "typesVersions": { - "<4.9.0-0": { - "*": [ - "ts4.8/*" - ] - } - }, - "_hasShrinkwrap": false, - "typeScriptVersion": "4.1", - "typesPublisherContentHash": "034172ea945b66afc6502e6be34d6fb957c596091e39cf43672e8aca563a8c66" - }, - "18.16.19": { - "name": "@types/node", - "version": "18.16.19", - "license": "MIT", - "_id": "@types/node@18.16.19", - "dist": { - "shasum": "cb03fca8910fdeb7595b755126a8a78144714eea", - "tarball": "http://localhost:4260/@types/node/node-18.16.19.tgz", - "fileCount": 125, - "integrity": "sha512-IXl7o+R9iti9eBW4Wg2hx1xQDig183jj7YLn8F7udNceyfkbn1ZxmzZXuak20gR40D7pIkIY1kYGx5VIGbaHKA==", - "unpackedSize": 3677153 - }, - "main": "", - "types": "index.d.ts", - "scripts": {}, - "repository": { - "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", - "type": "git", - "directory": "types/node" + "dependencies": { + "undici-types": "~6.20.0" }, - "description": "TypeScript definitions for Node.js", - "directories": {}, - "dependencies": {}, "typesVersions": { - "<=4.8": { + "<=5.6": { "*": [ - "ts4.8/*" + "ts5.6/*" ] } }, "_hasShrinkwrap": false, - "typeScriptVersion": "4.3", - "typesPublisherContentHash": "e0763594b4075c74150a6024cd39f92797ea5c273540e3a5fe0a63a791ffa0c8" - }, - "22.5.4": { - "name": "@types/node", - "version": "22.5.4", - "license": "MIT", - "_id": "@types/node@22.5.4", - "dist": { - "shasum": "83f7d1f65bc2ed223bdbf57c7884f1d5a4fa84e8", - "tarball": "http://localhost:4260/@types/node/node-22.5.4.tgz", - "fileCount": 66, - "integrity": "sha512-FDuKUJQm/ju9fT/SeX/6+gBzoPzlVCzfzmGkwKvRHQVxi4BntVbyIwf6a4Xn62mrvndLiml6z/UBXIdEVjQLXg==", - "unpackedSize": 2203331 - }, - "main": "", - "types": "index.d.ts", - "scripts": {}, - "repository": { - "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", - "type": "git", - "directory": "types/node" - }, - "description": "TypeScript definitions for node", - "directories": {}, - "dependencies": { - "undici-types": "~6.19.2" - }, - "_hasShrinkwrap": false, - "typeScriptVersion": "4.8", - "typesPublisherContentHash": "6ee9a11eba834031423800320320aa873d6bf2b6f33603c13a2aa9d90b3803ee" + "peerDependencies": {}, + "typeScriptVersion": "5.0", + "typesPublisherContentHash": "d4bd811572964de73064ee6d85299d0dff56616e67d674f2ccdc3c824a4288b7" } }, "license": "MIT", @@ -119,6 +58,5 @@ "type": "git", "directory": "types/node" }, - "description": "TypeScript definitions for node", - "readmeFilename": "" + "description": "TypeScript definitions for node" } diff --git a/tests/registry/npm/@types/prop-types/registry.json b/tests/registry/npm/@types/prop-types/registry.json index b70910d7f62df3..e46cdafec6e2ca 100644 --- a/tests/registry/npm/@types/prop-types/registry.json +++ b/tests/registry/npm/@types/prop-types/registry.json @@ -39,6 +39,5 @@ "type": "git", "directory": "types/prop-types" }, - "description": "TypeScript definitions for prop-types", - "readmeFilename": "" + "description": "TypeScript definitions for prop-types" } diff --git a/tests/registry/npm/@types/react/registry.json b/tests/registry/npm/@types/react/registry.json index ed238b645cbb49..95f35be5137c10 100644 --- a/tests/registry/npm/@types/react/registry.json +++ b/tests/registry/npm/@types/react/registry.json @@ -85,6 +85,5 @@ "type": "git", "directory": "types/react" }, - "description": "TypeScript definitions for react", - "readmeFilename": "" + "description": "TypeScript definitions for react" } diff --git a/tests/registry/npm/@vue/compiler-core/registry.json b/tests/registry/npm/@vue/compiler-core/registry.json index 7ea5bd5b97a567..4e7fd4b23d7e55 100644 --- a/tests/registry/npm/@vue/compiler-core/registry.json +++ b/tests/registry/npm/@vue/compiler-core/registry.json @@ -66,6 +66,5 @@ "bugs": { "url": "https://github.com/vuejs/core/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/@vue/compiler-dom/registry.json b/tests/registry/npm/@vue/compiler-dom/registry.json index 84b40e80587767..8686bd9e17c099 100644 --- a/tests/registry/npm/@vue/compiler-dom/registry.json +++ b/tests/registry/npm/@vue/compiler-dom/registry.json @@ -66,6 +66,5 @@ "bugs": { "url": "https://github.com/vuejs/core/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/@vue/compiler-sfc/registry.json b/tests/registry/npm/@vue/compiler-sfc/registry.json index 3ac30a4a35c9e2..ef6b08d91a9b34 100644 --- a/tests/registry/npm/@vue/compiler-sfc/registry.json +++ b/tests/registry/npm/@vue/compiler-sfc/registry.json @@ -83,6 +83,5 @@ "bugs": { "url": "https://github.com/vuejs/core/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/@vue/compiler-ssr/registry.json b/tests/registry/npm/@vue/compiler-ssr/registry.json index 71e5658211becc..4a065352dc9cf5 100644 --- a/tests/registry/npm/@vue/compiler-ssr/registry.json +++ b/tests/registry/npm/@vue/compiler-ssr/registry.json @@ -58,6 +58,5 @@ "bugs": { "url": "https://github.com/vuejs/core/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/@vue/reactivity-transform/registry.json b/tests/registry/npm/@vue/reactivity-transform/registry.json index 1d32e4120eb62b..b29ecd9de41609 100644 --- a/tests/registry/npm/@vue/reactivity-transform/registry.json +++ b/tests/registry/npm/@vue/reactivity-transform/registry.json @@ -65,6 +65,5 @@ "bugs": { "url": "https://github.com/vuejs/core/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/@vue/reactivity/registry.json b/tests/registry/npm/@vue/reactivity/registry.json index 36f79f9eb68100..c965106bcbf568 100644 --- a/tests/registry/npm/@vue/reactivity/registry.json +++ b/tests/registry/npm/@vue/reactivity/registry.json @@ -64,6 +64,5 @@ "bugs": { "url": "https://github.com/vuejs/core/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/@vue/runtime-core/registry.json b/tests/registry/npm/@vue/runtime-core/registry.json index e5373e0682a34e..d201c168118b0d 100644 --- a/tests/registry/npm/@vue/runtime-core/registry.json +++ b/tests/registry/npm/@vue/runtime-core/registry.json @@ -61,6 +61,5 @@ "bugs": { "url": "https://github.com/vuejs/core/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/@vue/runtime-dom/registry.json b/tests/registry/npm/@vue/runtime-dom/registry.json index cc58c4096f6c18..71dd4959a977a1 100644 --- a/tests/registry/npm/@vue/runtime-dom/registry.json +++ b/tests/registry/npm/@vue/runtime-dom/registry.json @@ -65,6 +65,5 @@ "bugs": { "url": "https://github.com/vuejs/core/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/@vue/server-renderer/registry.json b/tests/registry/npm/@vue/server-renderer/registry.json index 2949b7c41f2ab1..ae344d2b25ea5f 100644 --- a/tests/registry/npm/@vue/server-renderer/registry.json +++ b/tests/registry/npm/@vue/server-renderer/registry.json @@ -64,6 +64,5 @@ "bugs": { "url": "https://github.com/vuejs/core/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/@vue/shared/registry.json b/tests/registry/npm/@vue/shared/registry.json index ad799d6e552913..a2ff415e6ef37d 100644 --- a/tests/registry/npm/@vue/shared/registry.json +++ b/tests/registry/npm/@vue/shared/registry.json @@ -56,6 +56,5 @@ "bugs": { "url": "https://github.com/vuejs/core/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/abbrev/registry.json b/tests/registry/npm/abbrev/registry.json index 812b0485c7d1cc..01d44c4a25d82f 100644 --- a/tests/registry/npm/abbrev/registry.json +++ b/tests/registry/npm/abbrev/registry.json @@ -74,6 +74,5 @@ "homepage": "https://github.com/npm/abbrev-js#readme", "bugs": { "url": "https://github.com/npm/abbrev-js/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/agent-base/registry.json b/tests/registry/npm/agent-base/registry.json index fd71f3c8136338..31e3a136ba5251 100644 --- a/tests/registry/npm/agent-base/registry.json +++ b/tests/registry/npm/agent-base/registry.json @@ -81,6 +81,5 @@ "bugs": { "url": "https://github.com/TooTallNate/proxy-agents/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/aggregate-error/registry.json b/tests/registry/npm/aggregate-error/registry.json index b9f626d401ff57..ac53e1253effa7 100644 --- a/tests/registry/npm/aggregate-error/registry.json +++ b/tests/registry/npm/aggregate-error/registry.json @@ -65,6 +65,5 @@ "bugs": { "url": "https://github.com/sindresorhus/aggregate-error/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/ajv-formats/registry.json b/tests/registry/npm/ajv-formats/registry.json index c2ce2560d9acf8..4171ea9e391cda 100644 --- a/tests/registry/npm/ajv-formats/registry.json +++ b/tests/registry/npm/ajv-formats/registry.json @@ -95,6 +95,5 @@ "bugs": { "url": "https://github.com/ajv-validator/ajv-formats/issues" }, - "license": "MIT", - "readmeFilename": "" + "license": "MIT" } diff --git a/tests/registry/npm/ajv/registry.json b/tests/registry/npm/ajv/registry.json index fb50ef891fb2f7..0e496031c600d2 100644 --- a/tests/registry/npm/ajv/registry.json +++ b/tests/registry/npm/ajv/registry.json @@ -147,6 +147,5 @@ "bugs": { "url": "https://github.com/ajv-validator/ajv/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/ansi-regex/registry.json b/tests/registry/npm/ansi-regex/registry.json index e60f9a7697effc..2fbaed4b6f1c36 100644 --- a/tests/registry/npm/ansi-regex/registry.json +++ b/tests/registry/npm/ansi-regex/registry.json @@ -156,6 +156,5 @@ "bugs": { "url": "https://github.com/chalk/ansi-regex/issues" }, - "license": "MIT", - "readmeFilename": "" + "license": "MIT" } diff --git a/tests/registry/npm/ansi-styles/registry.json b/tests/registry/npm/ansi-styles/registry.json index 702510b501ddf9..7d7bc3a1bcc510 100644 --- a/tests/registry/npm/ansi-styles/registry.json +++ b/tests/registry/npm/ansi-styles/registry.json @@ -115,6 +115,5 @@ "bugs": { "url": "https://github.com/chalk/ansi-styles/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/asn1/registry.json b/tests/registry/npm/asn1/registry.json index 3ebe6552420020..82f531ac0a9fb3 100644 --- a/tests/registry/npm/asn1/registry.json +++ b/tests/registry/npm/asn1/registry.json @@ -58,7 +58,6 @@ "type": "git", "url": "git+https://github.com/joyent/node-asn1.git" }, - "readmeFilename": "README.md", "homepage": "https://github.com/joyent/node-asn1#readme", "bugs": { "url": "https://github.com/joyent/node-asn1/issues" diff --git a/tests/registry/npm/assertion-error/registry.json b/tests/registry/npm/assertion-error/registry.json index 438e46c86097f1..bc7a7721667b82 100644 --- a/tests/registry/npm/assertion-error/registry.json +++ b/tests/registry/npm/assertion-error/registry.json @@ -60,6 +60,5 @@ "bugs": { "url": "https://github.com/chaijs/assertion-error/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/balanced-match/registry.json b/tests/registry/npm/balanced-match/registry.json index 1dc1cf15cf844b..c1275739f4c79d 100644 --- a/tests/registry/npm/balanced-match/registry.json +++ b/tests/registry/npm/balanced-match/registry.json @@ -75,6 +75,5 @@ "bugs": { "url": "https://github.com/juliangruber/balanced-match/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/bcrypt-pbkdf/registry.json b/tests/registry/npm/bcrypt-pbkdf/registry.json index 1c610cfb549d9a..738f90b5c399ac 100644 --- a/tests/registry/npm/bcrypt-pbkdf/registry.json +++ b/tests/registry/npm/bcrypt-pbkdf/registry.json @@ -41,7 +41,6 @@ } }, "license": "BSD-3-Clause", - "readmeFilename": "README.md", "homepage": "https://github.com/joyent/node-bcrypt-pbkdf#readme", "repository": { "type": "git", diff --git a/tests/registry/npm/brace-expansion/registry.json b/tests/registry/npm/brace-expansion/registry.json index f4852991f625e4..2b6b3e3294ed96 100644 --- a/tests/registry/npm/brace-expansion/registry.json +++ b/tests/registry/npm/brace-expansion/registry.json @@ -79,6 +79,5 @@ "bugs": { "url": "https://github.com/juliangruber/brace-expansion/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/bufferutil/registry.json b/tests/registry/npm/bufferutil/registry.json index 6b84d0435ad148..91d5965d251094 100644 --- a/tests/registry/npm/bufferutil/registry.json +++ b/tests/registry/npm/bufferutil/registry.json @@ -68,6 +68,5 @@ "type": "git", "url": "git+https://github.com/websockets/bufferutil.git" }, - "description": "WebSocket buffer utils", - "readmeFilename": "README.md" + "description": "WebSocket buffer utils" } diff --git a/tests/registry/npm/buildcheck/registry.json b/tests/registry/npm/buildcheck/registry.json index 161928b8cf91a5..53f4dc0a367ab4 100644 --- a/tests/registry/npm/buildcheck/registry.json +++ b/tests/registry/npm/buildcheck/registry.json @@ -66,6 +66,5 @@ }, "bugs": { "url": "https://github.com/mscdex/buildcheck/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/cacache/registry.json b/tests/registry/npm/cacache/registry.json index 6837725524c7d0..5d34575ead560a 100644 --- a/tests/registry/npm/cacache/registry.json +++ b/tests/registry/npm/cacache/registry.json @@ -104,6 +104,5 @@ "homepage": "https://github.com/npm/cacache#readme", "bugs": { "url": "https://github.com/npm/cacache/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/camelcase/registry.json b/tests/registry/npm/camelcase/registry.json index 850775e1d0b8d3..dbce861df286e4 100644 --- a/tests/registry/npm/camelcase/registry.json +++ b/tests/registry/npm/camelcase/registry.json @@ -61,6 +61,5 @@ "bugs": { "url": "https://github.com/sindresorhus/camelcase/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/chai/registry.json b/tests/registry/npm/chai/registry.json index ddf47de87765fb..2c7e2ee41e3b40 100644 --- a/tests/registry/npm/chai/registry.json +++ b/tests/registry/npm/chai/registry.json @@ -79,7 +79,6 @@ "type": "git", "url": "git+https://github.com/chaijs/chai.git" }, - "readmeFilename": "README.md", "homepage": "http://chaijs.com", "bugs": { "url": "https://github.com/chaijs/chai/issues" diff --git a/tests/registry/npm/chalk/registry.json b/tests/registry/npm/chalk/registry.json index e148e60fe8a7b0..e2a642879d89a9 100644 --- a/tests/registry/npm/chalk/registry.json +++ b/tests/registry/npm/chalk/registry.json @@ -145,6 +145,5 @@ "bugs": { "url": "https://github.com/chalk/chalk/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/check-error/registry.json b/tests/registry/npm/check-error/registry.json index 0fdecbfaea6d1f..fd05e0036a266c 100644 --- a/tests/registry/npm/check-error/registry.json +++ b/tests/registry/npm/check-error/registry.json @@ -111,6 +111,5 @@ "bugs": { "url": "https://github.com/chaijs/check-error/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/chownr/registry.json b/tests/registry/npm/chownr/registry.json index 3650b6b8fb8740..2140a88566933c 100644 --- a/tests/registry/npm/chownr/registry.json +++ b/tests/registry/npm/chownr/registry.json @@ -68,6 +68,5 @@ "bugs": { "url": "https://github.com/isaacs/chownr/issues" }, - "license": "BlueOak-1.0.0", - "readmeFilename": "README.md" + "license": "BlueOak-1.0.0" } diff --git a/tests/registry/npm/clean-stack/registry.json b/tests/registry/npm/clean-stack/registry.json index debc3b6fa36558..e0874003981f05 100644 --- a/tests/registry/npm/clean-stack/registry.json +++ b/tests/registry/npm/clean-stack/registry.json @@ -64,6 +64,5 @@ "bugs": { "url": "https://github.com/sindresorhus/clean-stack/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/cliui/registry.json b/tests/registry/npm/cliui/registry.json index 4006d074713579..a1a15b3b531811 100644 --- a/tests/registry/npm/cliui/registry.json +++ b/tests/registry/npm/cliui/registry.json @@ -83,7 +83,6 @@ "email": "ben@npmjs.com" }, "license": "ISC", - "readmeFilename": "README.md", "homepage": "https://github.com/yargs/cliui#readme", "repository": { "type": "git", diff --git a/tests/registry/npm/color-convert/registry.json b/tests/registry/npm/color-convert/registry.json index 5a294b0789194b..f7054a07fcbf8c 100644 --- a/tests/registry/npm/color-convert/registry.json +++ b/tests/registry/npm/color-convert/registry.json @@ -65,7 +65,6 @@ "type": "git", "url": "git+https://github.com/Qix-/color-convert.git" }, - "readmeFilename": "README.md", "homepage": "https://github.com/Qix-/color-convert#readme", "bugs": { "url": "https://github.com/Qix-/color-convert/issues" diff --git a/tests/registry/npm/color-name/registry.json b/tests/registry/npm/color-name/registry.json index cc49ad60b914a5..90768a27285b50 100644 --- a/tests/registry/npm/color-name/registry.json +++ b/tests/registry/npm/color-name/registry.json @@ -52,6 +52,5 @@ "bugs": { "url": "https://github.com/colorjs/color-name/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/cowsay/registry.json b/tests/registry/npm/cowsay/registry.json index d171f36f29249d..bca6e78a142136 100644 --- a/tests/registry/npm/cowsay/registry.json +++ b/tests/registry/npm/cowsay/registry.json @@ -81,6 +81,5 @@ "bugs": { "url": "https://github.com/piuccio/cowsay/issues" }, - "readmeFilename": "README.md", "license": "MIT" } diff --git a/tests/registry/npm/cpu-features/registry.json b/tests/registry/npm/cpu-features/registry.json index 6880c34e580ef4..7c157f4092ca70 100644 --- a/tests/registry/npm/cpu-features/registry.json +++ b/tests/registry/npm/cpu-features/registry.json @@ -72,6 +72,5 @@ }, "bugs": { "url": "https://github.com/mscdex/cpu-features/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/cross-spawn/registry.json b/tests/registry/npm/cross-spawn/registry.json index 462096714f3edb..1e26e9d3e88398 100644 --- a/tests/registry/npm/cross-spawn/registry.json +++ b/tests/registry/npm/cross-spawn/registry.json @@ -96,6 +96,5 @@ "bugs": { "url": "https://github.com/moxystudio/node-cross-spawn/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/crypto-js/registry.json b/tests/registry/npm/crypto-js/registry.json index f5569a4d9dbdc0..57bdb4e8c12910 100644 --- a/tests/registry/npm/crypto-js/registry.json +++ b/tests/registry/npm/crypto-js/registry.json @@ -53,6 +53,5 @@ "bugs": { "url": "https://github.com/brix/crypto-js/issues" }, - "readmeFilename": "README.md", "license": "MIT" } diff --git a/tests/registry/npm/csstype/registry.json b/tests/registry/npm/csstype/registry.json index 020c35dc265ed8..8d371006e348ee 100644 --- a/tests/registry/npm/csstype/registry.json +++ b/tests/registry/npm/csstype/registry.json @@ -155,7 +155,6 @@ "email": "fredrik.nicol@gmail.com" }, "license": "MIT", - "readmeFilename": "README.md", "repository": { "type": "git", "url": "git+https://github.com/frenic/csstype.git" diff --git a/tests/registry/npm/debug/registry.json b/tests/registry/npm/debug/registry.json index c6b9ab7ae2e1b2..3ee14513351aec 100644 --- a/tests/registry/npm/debug/registry.json +++ b/tests/registry/npm/debug/registry.json @@ -82,6 +82,5 @@ "homepage": "https://github.com/debug-js/debug#readme", "bugs": { "url": "https://github.com/debug-js/debug/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/decamelize/registry.json b/tests/registry/npm/decamelize/registry.json index a8621a20699384..02c29682b91bff 100644 --- a/tests/registry/npm/decamelize/registry.json +++ b/tests/registry/npm/decamelize/registry.json @@ -62,6 +62,5 @@ "bugs": { "url": "https://github.com/sindresorhus/decamelize/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/deep-eql/registry.json b/tests/registry/npm/deep-eql/registry.json index a15fd57fe8def3..0156076c6e4a47 100644 --- a/tests/registry/npm/deep-eql/registry.json +++ b/tests/registry/npm/deep-eql/registry.json @@ -113,6 +113,5 @@ "url": "https://github.com/chaijs/deep-eql/issues" }, "license": "MIT", - "readmeFilename": "README.md", "homepage": "https://github.com/chaijs/deep-eql#readme" } diff --git a/tests/registry/npm/define-properties/registry.json b/tests/registry/npm/define-properties/registry.json index d4a90167f7c6e9..5088617266ea67 100644 --- a/tests/registry/npm/define-properties/registry.json +++ b/tests/registry/npm/define-properties/registry.json @@ -115,6 +115,5 @@ "bugs": { "url": "https://github.com/ljharb/define-properties/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/eastasianwidth/registry.json b/tests/registry/npm/eastasianwidth/registry.json index b54a14058039de..bbe32da65095da 100644 --- a/tests/registry/npm/eastasianwidth/registry.json +++ b/tests/registry/npm/eastasianwidth/registry.json @@ -53,6 +53,5 @@ "bugs": { "url": "https://github.com/komagata/eastasianwidth/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/emoji-regex/registry.json b/tests/registry/npm/emoji-regex/registry.json index f879deb2d0fc71..44fa57afafc920 100644 --- a/tests/registry/npm/emoji-regex/registry.json +++ b/tests/registry/npm/emoji-regex/registry.json @@ -110,6 +110,5 @@ "bugs": { "url": "https://github.com/mathiasbynens/emoji-regex/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/encoding/registry.json b/tests/registry/npm/encoding/registry.json index 59ac150dbf0a0f..f0cb854a6ff40d 100644 --- a/tests/registry/npm/encoding/registry.json +++ b/tests/registry/npm/encoding/registry.json @@ -56,6 +56,5 @@ "bugs": { "url": "https://github.com/andris9/encoding/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/env-paths/registry.json b/tests/registry/npm/env-paths/registry.json index e60ab97028722e..8246e1b38b7be3 100644 --- a/tests/registry/npm/env-paths/registry.json +++ b/tests/registry/npm/env-paths/registry.json @@ -61,6 +61,5 @@ "bugs": { "url": "https://github.com/sindresorhus/env-paths/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/err-code/registry.json b/tests/registry/npm/err-code/registry.json index a46e9bf7877eea..51a27ff60f564e 100644 --- a/tests/registry/npm/err-code/registry.json +++ b/tests/registry/npm/err-code/registry.json @@ -63,6 +63,5 @@ "bugs": { "url": "https://github.com/IndigoUnited/js-err-code/issues/" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/estree-walker/registry.json b/tests/registry/npm/estree-walker/registry.json index 7ab971e5016f0f..d016ff912d5b50 100644 --- a/tests/registry/npm/estree-walker/registry.json +++ b/tests/registry/npm/estree-walker/registry.json @@ -59,7 +59,6 @@ "name": "Rich Harris" }, "license": "MIT", - "readmeFilename": "README.md", "homepage": "https://github.com/Rich-Harris/estree-walker#readme", "repository": { "type": "git", diff --git a/tests/registry/npm/exponential-backoff/registry.json b/tests/registry/npm/exponential-backoff/registry.json index 6ac5011df16b27..37b45388e1857b 100644 --- a/tests/registry/npm/exponential-backoff/registry.json +++ b/tests/registry/npm/exponential-backoff/registry.json @@ -84,6 +84,5 @@ "homepage": "https://github.com/coveo/exponential-backoff#readme", "bugs": { "url": "https://github.com/coveo/exponential-backoff/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/fast-deep-equal/registry.json b/tests/registry/npm/fast-deep-equal/registry.json index 3e0305d43c3c56..9b0f718706daae 100644 --- a/tests/registry/npm/fast-deep-equal/registry.json +++ b/tests/registry/npm/fast-deep-equal/registry.json @@ -80,6 +80,5 @@ "bugs": { "url": "https://github.com/epoberezkin/fast-deep-equal/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/find-up/registry.json b/tests/registry/npm/find-up/registry.json index 0304c60a2e5967..1c1689f7b03a3a 100644 --- a/tests/registry/npm/find-up/registry.json +++ b/tests/registry/npm/find-up/registry.json @@ -67,6 +67,5 @@ "bugs": { "url": "https://github.com/sindresorhus/find-up/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/foreground-child/registry.json b/tests/registry/npm/foreground-child/registry.json index ceac08a33a066d..d061182cbbb06b 100644 --- a/tests/registry/npm/foreground-child/registry.json +++ b/tests/registry/npm/foreground-child/registry.json @@ -147,6 +147,5 @@ "homepage": "https://github.com/tapjs/foreground-child#readme", "bugs": { "url": "https://github.com/tapjs/foreground-child/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/fs-extra/registry.json b/tests/registry/npm/fs-extra/registry.json index 886ae53d484234..a1dd1cb84166c0 100644 --- a/tests/registry/npm/fs-extra/registry.json +++ b/tests/registry/npm/fs-extra/registry.json @@ -75,6 +75,5 @@ "bugs": { "url": "https://github.com/jprichardson/node-fs-extra/issues" }, - "readmeFilename": "README.md", "license": "MIT" } diff --git a/tests/registry/npm/fs-minipass/registry.json b/tests/registry/npm/fs-minipass/registry.json index a09bfb236dfffe..579432dece4f9c 100644 --- a/tests/registry/npm/fs-minipass/registry.json +++ b/tests/registry/npm/fs-minipass/registry.json @@ -137,6 +137,5 @@ "bugs": { "url": "https://github.com/npm/fs-minipass/issues" }, - "license": "ISC", - "readmeFilename": "README.md" + "license": "ISC" } diff --git a/tests/registry/npm/fsevents/registry.json b/tests/registry/npm/fsevents/registry.json index 1784c7aae42947..3685c2473efdcb 100644 --- a/tests/registry/npm/fsevents/registry.json +++ b/tests/registry/npm/fsevents/registry.json @@ -104,6 +104,5 @@ "url": "git+https://github.com/fsevents/fsevents.git", "type": "git" }, - "description": "Native Access to MacOS FSEvents", - "readmeFilename": "README.md" + "description": "Native Access to MacOS FSEvents" } diff --git a/tests/registry/npm/function-bind/registry.json b/tests/registry/npm/function-bind/registry.json index 37c9f5b3edc874..fdff5e9b598d00 100644 --- a/tests/registry/npm/function-bind/registry.json +++ b/tests/registry/npm/function-bind/registry.json @@ -81,6 +81,5 @@ "url": "https://github.com/Raynos/function-bind/issues", "email": "raynos2@gmail.com" }, - "readmeFilename": "README.md", "license": "MIT" } diff --git a/tests/registry/npm/get-caller-file/registry.json b/tests/registry/npm/get-caller-file/registry.json index d3ac37ba82fbd4..bbddcb8b1c016d 100644 --- a/tests/registry/npm/get-caller-file/registry.json +++ b/tests/registry/npm/get-caller-file/registry.json @@ -67,6 +67,5 @@ "bugs": { "url": "https://github.com/stefanpenner/get-caller-file/issues" }, - "license": "ISC", - "readmeFilename": "README.md" + "license": "ISC" } diff --git a/tests/registry/npm/get-func-name/registry.json b/tests/registry/npm/get-func-name/registry.json index 359aee74390d2b..8193e419fd8e24 100644 --- a/tests/registry/npm/get-func-name/registry.json +++ b/tests/registry/npm/get-func-name/registry.json @@ -111,6 +111,5 @@ "bugs": { "url": "https://github.com/chaijs/get-func-name/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/get-intrinsic/registry.json b/tests/registry/npm/get-intrinsic/registry.json index e2316a06cffabf..d0ec951ae2934f 100644 --- a/tests/registry/npm/get-intrinsic/registry.json +++ b/tests/registry/npm/get-intrinsic/registry.json @@ -116,6 +116,5 @@ "bugs": { "url": "https://github.com/ljharb/get-intrinsic/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/get-stdin/registry.json b/tests/registry/npm/get-stdin/registry.json index 9b8ab9a50020d2..fb1d37ad67bb0e 100644 --- a/tests/registry/npm/get-stdin/registry.json +++ b/tests/registry/npm/get-stdin/registry.json @@ -51,7 +51,6 @@ "_hasShrinkwrap": false } }, - "readmeFilename": "readme.md", "homepage": "https://github.com/sindresorhus/get-stdin#readme", "repository": { "type": "git", diff --git a/tests/registry/npm/glob/registry.json b/tests/registry/npm/glob/registry.json index fe6c9f7ce8d8a9..46d6e960558b80 100644 --- a/tests/registry/npm/glob/registry.json +++ b/tests/registry/npm/glob/registry.json @@ -139,6 +139,5 @@ "type": "git", "url": "git://github.com/isaacs/node-glob.git" }, - "description": "the most correct and second fastest glob implementation in JavaScript", - "readmeFilename": "README.md" + "description": "the most correct and second fastest glob implementation in JavaScript" } diff --git a/tests/registry/npm/globals/registry.json b/tests/registry/npm/globals/registry.json index 6e8c2f90d8922b..5f213f1772eaae 100644 --- a/tests/registry/npm/globals/registry.json +++ b/tests/registry/npm/globals/registry.json @@ -79,6 +79,5 @@ "bugs": { "url": "https://github.com/sindresorhus/globals/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/graceful-fs/registry.json b/tests/registry/npm/graceful-fs/registry.json index 13d546033aa9e9..2dfdbc1da0d08c 100644 --- a/tests/registry/npm/graceful-fs/registry.json +++ b/tests/registry/npm/graceful-fs/registry.json @@ -52,7 +52,6 @@ "type": "git", "url": "git+https://github.com/isaacs/node-graceful-fs.git" }, - "readmeFilename": "README.md", "homepage": "https://github.com/isaacs/node-graceful-fs#readme", "bugs": { "url": "https://github.com/isaacs/node-graceful-fs/issues" diff --git a/tests/registry/npm/has-flag/registry.json b/tests/registry/npm/has-flag/registry.json index 198af78fade7d5..4bd3f6906d94b1 100644 --- a/tests/registry/npm/has-flag/registry.json +++ b/tests/registry/npm/has-flag/registry.json @@ -61,6 +61,5 @@ "bugs": { "url": "https://github.com/sindresorhus/has-flag/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/has-package-exports/registry.json b/tests/registry/npm/has-package-exports/registry.json index dbd462148229f0..6a76589a07cd21 100644 --- a/tests/registry/npm/has-package-exports/registry.json +++ b/tests/registry/npm/has-package-exports/registry.json @@ -115,6 +115,5 @@ "bugs": { "url": "https://github.com/inspect-js/has-package-exports/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/has-property-descriptors/registry.json b/tests/registry/npm/has-property-descriptors/registry.json index 9003b2b89b9563..51f1f5aa8dff6e 100644 --- a/tests/registry/npm/has-property-descriptors/registry.json +++ b/tests/registry/npm/has-property-descriptors/registry.json @@ -94,6 +94,5 @@ "bugs": { "url": "https://github.com/inspect-js/has-property-descriptors/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/has-symbols/registry.json b/tests/registry/npm/has-symbols/registry.json index 8d688376563d12..8d7e633f57e03a 100644 --- a/tests/registry/npm/has-symbols/registry.json +++ b/tests/registry/npm/has-symbols/registry.json @@ -115,6 +115,5 @@ "bugs": { "url": "https://github.com/ljharb/has-symbols/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/has/registry.json b/tests/registry/npm/has/registry.json index 9de4070c19efe3..c1ad9863095b73 100644 --- a/tests/registry/npm/has/registry.json +++ b/tests/registry/npm/has/registry.json @@ -71,6 +71,5 @@ "bugs": { "url": "https://github.com/tarruda/has/issues" }, - "readmeFilename": "README.md", "license": "MIT" } diff --git a/tests/registry/npm/http-cache-semantics/registry.json b/tests/registry/npm/http-cache-semantics/registry.json index ce3a72c1d265d1..baecfcc071ad06 100644 --- a/tests/registry/npm/http-cache-semantics/registry.json +++ b/tests/registry/npm/http-cache-semantics/registry.json @@ -57,6 +57,5 @@ "bugs": { "url": "https://github.com/kornelski/http-cache-semantics/issues" }, - "license": "BSD-2-Clause", - "readmeFilename": "README.md" + "license": "BSD-2-Clause" } diff --git a/tests/registry/npm/http-proxy-agent/registry.json b/tests/registry/npm/http-proxy-agent/registry.json index d1079a407601df..ef61bd2e009594 100644 --- a/tests/registry/npm/http-proxy-agent/registry.json +++ b/tests/registry/npm/http-proxy-agent/registry.json @@ -80,6 +80,5 @@ "bugs": { "url": "https://github.com/TooTallNate/proxy-agents/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/https-proxy-agent/registry.json b/tests/registry/npm/https-proxy-agent/registry.json index 9dfdd263aef39b..b218025f62514a 100644 --- a/tests/registry/npm/https-proxy-agent/registry.json +++ b/tests/registry/npm/https-proxy-agent/registry.json @@ -83,6 +83,5 @@ "homepage": "https://github.com/TooTallNate/proxy-agents#readme", "bugs": { "url": "https://github.com/TooTallNate/proxy-agents/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/iconv-lite/registry.json b/tests/registry/npm/iconv-lite/registry.json index 6a71a9c83a80f5..18b39883e3f2b8 100644 --- a/tests/registry/npm/iconv-lite/registry.json +++ b/tests/registry/npm/iconv-lite/registry.json @@ -73,6 +73,5 @@ "bugs": { "url": "https://github.com/ashtuchkin/iconv-lite/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/indent-string/registry.json b/tests/registry/npm/indent-string/registry.json index 6dac5c96b8eb7e..bb9034e715693c 100644 --- a/tests/registry/npm/indent-string/registry.json +++ b/tests/registry/npm/indent-string/registry.json @@ -61,6 +61,5 @@ "bugs": { "url": "https://github.com/sindresorhus/indent-string/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/ip-address/registry.json b/tests/registry/npm/ip-address/registry.json index 27f92c49e2e40e..6500377c01573a 100644 --- a/tests/registry/npm/ip-address/registry.json +++ b/tests/registry/npm/ip-address/registry.json @@ -116,6 +116,5 @@ "bugs": { "url": "https://github.com/beaugunderson/ip-address/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/is-fullwidth-code-point/registry.json b/tests/registry/npm/is-fullwidth-code-point/registry.json index 6ce84854f535c8..337a992d3d70ab 100644 --- a/tests/registry/npm/is-fullwidth-code-point/registry.json +++ b/tests/registry/npm/is-fullwidth-code-point/registry.json @@ -107,6 +107,5 @@ "bugs": { "url": "https://github.com/sindresorhus/is-fullwidth-code-point/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/is-lambda/registry.json b/tests/registry/npm/is-lambda/registry.json index 847c7a48f19903..9cfe7870edf18f 100644 --- a/tests/registry/npm/is-lambda/registry.json +++ b/tests/registry/npm/is-lambda/registry.json @@ -61,6 +61,5 @@ "bugs": { "url": "https://github.com/watson/is-lambda/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/isexe/registry.json b/tests/registry/npm/isexe/registry.json index f57bf81d410c76..f1008423935a6b 100644 --- a/tests/registry/npm/isexe/registry.json +++ b/tests/registry/npm/isexe/registry.json @@ -172,7 +172,6 @@ "url": "http://blog.izs.me/" }, "license": "ISC", - "readmeFilename": "README.md", "homepage": "https://github.com/isaacs/isexe#readme", "repository": { "type": "git", diff --git a/tests/registry/npm/jackspeak/registry.json b/tests/registry/npm/jackspeak/registry.json index d5da95d533aaa6..6b6b6edf17eb0b 100644 --- a/tests/registry/npm/jackspeak/registry.json +++ b/tests/registry/npm/jackspeak/registry.json @@ -117,6 +117,5 @@ "type": "git", "url": "git+https://github.com/isaacs/jackspeak.git" }, - "description": "A very strict and proper argument parser.", - "readmeFilename": "README.md" + "description": "A very strict and proper argument parser." } diff --git a/tests/registry/npm/js-tokens/registry.json b/tests/registry/npm/js-tokens/registry.json index df4e1469d3e353..5a5cd3dade1624 100644 --- a/tests/registry/npm/js-tokens/registry.json +++ b/tests/registry/npm/js-tokens/registry.json @@ -58,6 +58,5 @@ "bugs": { "url": "https://github.com/lydell/js-tokens/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/jsbn/registry.json b/tests/registry/npm/jsbn/registry.json index b70c34d6d7e7f9..a613a822a57d4e 100644 --- a/tests/registry/npm/jsbn/registry.json +++ b/tests/registry/npm/jsbn/registry.json @@ -48,6 +48,5 @@ "bugs": { "url": "https://github.com/andyperlitch/jsbn/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/json-schema-traverse/registry.json b/tests/registry/npm/json-schema-traverse/registry.json index 42cd33a51cc40f..5bdc5a5c66189f 100644 --- a/tests/registry/npm/json-schema-traverse/registry.json +++ b/tests/registry/npm/json-schema-traverse/registry.json @@ -69,6 +69,5 @@ "bugs": { "url": "https://github.com/epoberezkin/json-schema-traverse/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/jsonfile/registry.json b/tests/registry/npm/jsonfile/registry.json index 1e445639353ef0..3f3f25db713c3c 100644 --- a/tests/registry/npm/jsonfile/registry.json +++ b/tests/registry/npm/jsonfile/registry.json @@ -66,6 +66,5 @@ "bugs": { "url": "https://github.com/jprichardson/node-jsonfile/issues" }, - "readmeFilename": "README.md", "license": "MIT" } diff --git a/tests/registry/npm/locate-path/registry.json b/tests/registry/npm/locate-path/registry.json index f090b7a1d794c7..733059832c9374 100644 --- a/tests/registry/npm/locate-path/registry.json +++ b/tests/registry/npm/locate-path/registry.json @@ -64,6 +64,5 @@ "bugs": { "url": "https://github.com/sindresorhus/locate-path/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/loose-envify/registry.json b/tests/registry/npm/loose-envify/registry.json index 21f63716a9f6ff..04576120db79ef 100644 --- a/tests/registry/npm/loose-envify/registry.json +++ b/tests/registry/npm/loose-envify/registry.json @@ -63,6 +63,5 @@ "bugs": { "url": "https://github.com/zertosh/loose-envify/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/loupe/registry.json b/tests/registry/npm/loupe/registry.json index 56f8e52239cb5c..551d6d83111ce0 100644 --- a/tests/registry/npm/loupe/registry.json +++ b/tests/registry/npm/loupe/registry.json @@ -169,6 +169,5 @@ "bugs": { "url": "https://github.com/chaijs/loupe/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/lru-cache/registry.json b/tests/registry/npm/lru-cache/registry.json index d6b1734ede817d..194ca82b0b6ca5 100644 --- a/tests/registry/npm/lru-cache/registry.json +++ b/tests/registry/npm/lru-cache/registry.json @@ -145,6 +145,5 @@ "type": "git", "url": "git://github.com/isaacs/node-lru-cache.git" }, - "description": "A cache object that deletes the least-recently-used items.", - "readmeFilename": "README.md" + "description": "A cache object that deletes the least-recently-used items." } diff --git a/tests/registry/npm/lz-string/registry.json b/tests/registry/npm/lz-string/registry.json index d7c4ed7861f336..46e17d240fb11b 100644 --- a/tests/registry/npm/lz-string/registry.json +++ b/tests/registry/npm/lz-string/registry.json @@ -95,7 +95,6 @@ "repository": {}, "homepage": "http://pieroxy.net/blog/pages/lz-string/index.html", "license": "MIT", - "readmeFilename": "README.md", "author": { "name": "pieroxy", "email": "pieroxy@pieroxy.net" diff --git a/tests/registry/npm/magic-string/registry.json b/tests/registry/npm/magic-string/registry.json index 5f926511fcf9da..2c901b860141f6 100644 --- a/tests/registry/npm/magic-string/registry.json +++ b/tests/registry/npm/magic-string/registry.json @@ -71,7 +71,6 @@ "name": "Rich Harris" }, "license": "MIT", - "readmeFilename": "README.md", "homepage": "https://github.com/rich-harris/magic-string#readme", "repository": { "type": "git", diff --git a/tests/registry/npm/make-fetch-happen/registry.json b/tests/registry/npm/make-fetch-happen/registry.json index 235e56dbe7ce33..faf1eb20b1cb74 100644 --- a/tests/registry/npm/make-fetch-happen/registry.json +++ b/tests/registry/npm/make-fetch-happen/registry.json @@ -103,6 +103,5 @@ "homepage": "https://github.com/npm/make-fetch-happen#readme", "bugs": { "url": "https://github.com/npm/make-fetch-happen/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/minimatch/registry.json b/tests/registry/npm/minimatch/registry.json index 9094ccffdf7fec..043fcf170396bd 100644 --- a/tests/registry/npm/minimatch/registry.json +++ b/tests/registry/npm/minimatch/registry.json @@ -118,6 +118,5 @@ "type": "git", "url": "git://github.com/isaacs/minimatch.git" }, - "description": "a glob matcher in javascript", - "readmeFilename": "README.md" + "description": "a glob matcher in javascript" } diff --git a/tests/registry/npm/minipass-collect/registry.json b/tests/registry/npm/minipass-collect/registry.json index 372b5f206e0560..90174b4860efee 100644 --- a/tests/registry/npm/minipass-collect/registry.json +++ b/tests/registry/npm/minipass-collect/registry.json @@ -62,7 +62,6 @@ "url": "https://izs.me" }, "license": "ISC", - "readmeFilename": "README.md", "homepage": "https://github.com/isaacs/minipass-collect#readme", "repository": { "type": "git", diff --git a/tests/registry/npm/minipass-fetch/registry.json b/tests/registry/npm/minipass-fetch/registry.json index 9c5320c1a0aeca..8d91d6c628486e 100644 --- a/tests/registry/npm/minipass-fetch/registry.json +++ b/tests/registry/npm/minipass-fetch/registry.json @@ -100,6 +100,5 @@ "homepage": "https://github.com/npm/minipass-fetch#readme", "bugs": { "url": "https://github.com/npm/minipass-fetch/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/minipass-flush/registry.json b/tests/registry/npm/minipass-flush/registry.json index 52ddc966dcde19..6aa714de6c7303 100644 --- a/tests/registry/npm/minipass-flush/registry.json +++ b/tests/registry/npm/minipass-flush/registry.json @@ -63,7 +63,6 @@ "url": "https://izs.me" }, "license": "ISC", - "readmeFilename": "README.md", "homepage": "https://github.com/isaacs/minipass-flush#readme", "repository": { "type": "git", diff --git a/tests/registry/npm/minipass-pipeline/registry.json b/tests/registry/npm/minipass-pipeline/registry.json index 8eaf314844f318..d806eee2086789 100644 --- a/tests/registry/npm/minipass-pipeline/registry.json +++ b/tests/registry/npm/minipass-pipeline/registry.json @@ -54,6 +54,5 @@ "email": "i@izs.me", "url": "https://izs.me" }, - "license": "ISC", - "readmeFilename": "README.md" + "license": "ISC" } diff --git a/tests/registry/npm/minipass-sized/registry.json b/tests/registry/npm/minipass-sized/registry.json index 42a49cc607940d..7e2f6693a2d7e2 100644 --- a/tests/registry/npm/minipass-sized/registry.json +++ b/tests/registry/npm/minipass-sized/registry.json @@ -72,6 +72,5 @@ "bugs": { "url": "https://github.com/isaacs/minipass-sized/issues" }, - "license": "ISC", - "readmeFilename": "README.md" + "license": "ISC" } diff --git a/tests/registry/npm/minipass/registry.json b/tests/registry/npm/minipass/registry.json index 7cebe6a81f2bd8..f0a2ead155c2a2 100644 --- a/tests/registry/npm/minipass/registry.json +++ b/tests/registry/npm/minipass/registry.json @@ -272,6 +272,5 @@ "bugs": { "url": "https://github.com/isaacs/minipass/issues" }, - "license": "ISC", - "readmeFilename": "README.md" + "license": "ISC" } diff --git a/tests/registry/npm/minizlib/registry.json b/tests/registry/npm/minizlib/registry.json index b407bb19e6f2c8..e81a6daf46c372 100644 --- a/tests/registry/npm/minizlib/registry.json +++ b/tests/registry/npm/minizlib/registry.json @@ -67,6 +67,5 @@ "bugs": { "url": "https://github.com/isaacs/minizlib/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/mkdirp/registry.json b/tests/registry/npm/mkdirp/registry.json index d6bccdd9ca91a0..45b67ebfd168b6 100644 --- a/tests/registry/npm/mkdirp/registry.json +++ b/tests/registry/npm/mkdirp/registry.json @@ -59,7 +59,6 @@ "url": "git+https://github.com/isaacs/node-mkdirp.git" }, "license": "MIT", - "readmeFilename": "", "homepage": "https://github.com/isaacs/node-mkdirp#readme", "bugs": { "url": "https://github.com/isaacs/node-mkdirp/issues" diff --git a/tests/registry/npm/ms/registry.json b/tests/registry/npm/ms/registry.json index c7d162c55d3f8a..11c978186ac2c3 100644 --- a/tests/registry/npm/ms/registry.json +++ b/tests/registry/npm/ms/registry.json @@ -66,7 +66,6 @@ "bugs": { "url": "https://github.com/vercel/ms/issues" }, - "readmeFilename": "readme.md", "homepage": "https://github.com/vercel/ms#readme", "license": "MIT" } diff --git a/tests/registry/npm/nan/registry.json b/tests/registry/npm/nan/registry.json index 947a418b15ac43..d90f780feff0b7 100644 --- a/tests/registry/npm/nan/registry.json +++ b/tests/registry/npm/nan/registry.json @@ -57,6 +57,5 @@ "bugs": { "url": "https://github.com/nodejs/nan/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/nanoid/registry.json b/tests/registry/npm/nanoid/registry.json index 1a5b9d44b51546..9d3c312a498638 100644 --- a/tests/registry/npm/nanoid/registry.json +++ b/tests/registry/npm/nanoid/registry.json @@ -96,6 +96,5 @@ "bugs": { "url": "https://github.com/ai/nanoid/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/negotiator/registry.json b/tests/registry/npm/negotiator/registry.json index 9b87dc10ae7e94..7204f747be3e03 100644 --- a/tests/registry/npm/negotiator/registry.json +++ b/tests/registry/npm/negotiator/registry.json @@ -55,6 +55,5 @@ "bugs": { "url": "https://github.com/jshttp/negotiator/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/node-gyp/registry.json b/tests/registry/npm/node-gyp/registry.json index ec7ed18cdc871d..7a06c30442fbd5 100644 --- a/tests/registry/npm/node-gyp/registry.json +++ b/tests/registry/npm/node-gyp/registry.json @@ -83,6 +83,5 @@ "bugs": { "url": "https://github.com/nodejs/node-gyp/issues" }, - "readmeFilename": "README.md", "license": "MIT" } diff --git a/tests/registry/npm/nopt/registry.json b/tests/registry/npm/nopt/registry.json index 8fb40973e4c6ee..20a547e081487f 100644 --- a/tests/registry/npm/nopt/registry.json +++ b/tests/registry/npm/nopt/registry.json @@ -88,6 +88,5 @@ "homepage": "https://github.com/npm/nopt#readme", "bugs": { "url": "https://github.com/npm/nopt/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/npm-check-updates/registry.json b/tests/registry/npm/npm-check-updates/registry.json index 71d96fd83de077..4c77a45faae13b 100644 --- a/tests/registry/npm/npm-check-updates/registry.json +++ b/tests/registry/npm/npm-check-updates/registry.json @@ -196,6 +196,5 @@ "type": "git", "url": "git+https://github.com/raineorshine/npm-check-updates.git" }, - "description": "Find newer versions of dependencies than what your package.json allows", - "readmeFilename": "README.md" + "description": "Find newer versions of dependencies than what your package.json allows" } diff --git a/tests/registry/npm/object-keys/registry.json b/tests/registry/npm/object-keys/registry.json index 9d1c0f1d43e565..fb358209a5f987 100644 --- a/tests/registry/npm/object-keys/registry.json +++ b/tests/registry/npm/object-keys/registry.json @@ -90,7 +90,6 @@ "type": "git", "url": "git://github.com/ljharb/object-keys.git" }, - "readmeFilename": "README.md", "homepage": "https://github.com/ljharb/object-keys#readme", "bugs": { "url": "https://github.com/ljharb/object-keys/issues" diff --git a/tests/registry/npm/p-limit/registry.json b/tests/registry/npm/p-limit/registry.json index df87853d52fc5d..def370024fbf32 100644 --- a/tests/registry/npm/p-limit/registry.json +++ b/tests/registry/npm/p-limit/registry.json @@ -69,6 +69,5 @@ "bugs": { "url": "https://github.com/sindresorhus/p-limit/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/p-locate/registry.json b/tests/registry/npm/p-locate/registry.json index 19418e74ff1087..22225c614805d9 100644 --- a/tests/registry/npm/p-locate/registry.json +++ b/tests/registry/npm/p-locate/registry.json @@ -67,6 +67,5 @@ "bugs": { "url": "https://github.com/sindresorhus/p-locate/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/p-map/registry.json b/tests/registry/npm/p-map/registry.json index 33612950ab28fa..fa64fff4ec439b 100644 --- a/tests/registry/npm/p-map/registry.json +++ b/tests/registry/npm/p-map/registry.json @@ -69,6 +69,5 @@ "bugs": { "url": "https://github.com/sindresorhus/p-map/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/p-try/registry.json b/tests/registry/npm/p-try/registry.json index 34a113ec11bccf..4cd831dcb139d2 100644 --- a/tests/registry/npm/p-try/registry.json +++ b/tests/registry/npm/p-try/registry.json @@ -61,6 +61,5 @@ "bugs": { "url": "https://github.com/sindresorhus/p-try/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/package-json-from-dist/registry.json b/tests/registry/npm/package-json-from-dist/registry.json index 99c92d5c886db9..eb869510339e41 100644 --- a/tests/registry/npm/package-json-from-dist/registry.json +++ b/tests/registry/npm/package-json-from-dist/registry.json @@ -104,6 +104,5 @@ "bugs": { "url": "https://github.com/isaacs/package-json-from-dist/issues" }, - "license": "BlueOak-1.0.0", - "readmeFilename": "README.md" + "license": "BlueOak-1.0.0" } diff --git a/tests/registry/npm/path-exists/registry.json b/tests/registry/npm/path-exists/registry.json index 14e20d049d6856..bb8852875c318b 100644 --- a/tests/registry/npm/path-exists/registry.json +++ b/tests/registry/npm/path-exists/registry.json @@ -61,6 +61,5 @@ "bugs": { "url": "https://github.com/sindresorhus/path-exists/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/path-key/registry.json b/tests/registry/npm/path-key/registry.json index bd6185af7edba9..1a47e7e8563f98 100644 --- a/tests/registry/npm/path-key/registry.json +++ b/tests/registry/npm/path-key/registry.json @@ -62,6 +62,5 @@ "bugs": { "url": "https://github.com/sindresorhus/path-key/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/path-scurry/registry.json b/tests/registry/npm/path-scurry/registry.json index 7eb572ea32eabd..fc9d3cde144c38 100644 --- a/tests/registry/npm/path-scurry/registry.json +++ b/tests/registry/npm/path-scurry/registry.json @@ -125,6 +125,5 @@ "type": "git", "url": "git+https://github.com/isaacs/path-scurry.git" }, - "description": "walk paths fast and efficiently", - "readmeFilename": "README.md" + "description": "walk paths fast and efficiently" } diff --git a/tests/registry/npm/pathval/registry.json b/tests/registry/npm/pathval/registry.json index f291a5f3c1b525..0f21c85adb6039 100644 --- a/tests/registry/npm/pathval/registry.json +++ b/tests/registry/npm/pathval/registry.json @@ -107,6 +107,5 @@ "bugs": { "url": "https://github.com/chaijs/pathval/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/picocolors/registry.json b/tests/registry/npm/picocolors/registry.json index 8ad516162ea063..5a3a3b3675c4a9 100644 --- a/tests/registry/npm/picocolors/registry.json +++ b/tests/registry/npm/picocolors/registry.json @@ -45,7 +45,6 @@ "name": "Alexey Raspopov" }, "license": "ISC", - "readmeFilename": "README.md", "homepage": "https://github.com/alexeyraspopov/picocolors#readme", "repository": { "type": "git", diff --git a/tests/registry/npm/playwright-core/registry.json b/tests/registry/npm/playwright-core/registry.json index 521084d1ecf246..7949ed9613493f 100644 --- a/tests/registry/npm/playwright-core/registry.json +++ b/tests/registry/npm/playwright-core/registry.json @@ -82,6 +82,5 @@ "url": "git+https://github.com/microsoft/playwright.git", "type": "git" }, - "description": "A high-level API to automate web browsers", - "readmeFilename": "" + "description": "A high-level API to automate web browsers" } diff --git a/tests/registry/npm/playwright/registry.json b/tests/registry/npm/playwright/registry.json index a76a823676412b..9c0fd4349e1af2 100644 --- a/tests/registry/npm/playwright/registry.json +++ b/tests/registry/npm/playwright/registry.json @@ -103,6 +103,5 @@ "url": "git+https://github.com/microsoft/playwright.git", "type": "git" }, - "description": "A high-level API to automate web browsers", - "readmeFilename": "" + "description": "A high-level API to automate web browsers" } diff --git a/tests/registry/npm/postcss/registry.json b/tests/registry/npm/postcss/registry.json index 5f2cbe5ac70236..c00e758ac57d26 100644 --- a/tests/registry/npm/postcss/registry.json +++ b/tests/registry/npm/postcss/registry.json @@ -106,7 +106,6 @@ "type": "git", "url": "git+https://github.com/postcss/postcss.git" }, - "readmeFilename": "README.md", "bugs": { "url": "https://github.com/postcss/postcss/issues" }, diff --git a/tests/registry/npm/preact-render-to-string/registry.json b/tests/registry/npm/preact-render-to-string/registry.json index f9d97fe526896d..3a1acd69f823ba 100644 --- a/tests/registry/npm/preact-render-to-string/registry.json +++ b/tests/registry/npm/preact-render-to-string/registry.json @@ -171,7 +171,6 @@ "email": "jason@developit.ca" }, "license": "MIT", - "readmeFilename": "README.md", "homepage": "https://github.com/developit/preact-render-to-string", "repository": { "type": "git", diff --git a/tests/registry/npm/preact/registry.json b/tests/registry/npm/preact/registry.json index 5adb917ec5788e..73700cc60b2074 100644 --- a/tests/registry/npm/preact/registry.json +++ b/tests/registry/npm/preact/registry.json @@ -305,6 +305,5 @@ "bugs": { "url": "https://github.com/preactjs/preact/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/pretty-format/registry.json b/tests/registry/npm/pretty-format/registry.json index 27a6f83d64c0bb..96e921f2f091db 100644 --- a/tests/registry/npm/pretty-format/registry.json +++ b/tests/registry/npm/pretty-format/registry.json @@ -60,7 +60,6 @@ "email": "me@thejameskyle.com" }, "license": "MIT", - "readmeFilename": "", "homepage": "https://github.com/jestjs/jest#readme", "bugs": { "url": "https://github.com/jestjs/jest/issues" diff --git a/tests/registry/npm/proc-log/registry.json b/tests/registry/npm/proc-log/registry.json index 07bdfb21324fd8..d12995637c239c 100644 --- a/tests/registry/npm/proc-log/registry.json +++ b/tests/registry/npm/proc-log/registry.json @@ -140,6 +140,5 @@ "homepage": "https://github.com/npm/proc-log#readme", "bugs": { "url": "https://github.com/npm/proc-log/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/promise-retry/registry.json b/tests/registry/npm/promise-retry/registry.json index 3d3de4e343d4ec..e27aa6108882bb 100644 --- a/tests/registry/npm/promise-retry/registry.json +++ b/tests/registry/npm/promise-retry/registry.json @@ -66,6 +66,5 @@ "bugs": { "url": "https://github.com/IndigoUnited/node-promise-retry/issues/" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/punycode/registry.json b/tests/registry/npm/punycode/registry.json index 8ac4ddf2e3f7bf..513b96d961ab04 100644 --- a/tests/registry/npm/punycode/registry.json +++ b/tests/registry/npm/punycode/registry.json @@ -71,7 +71,6 @@ "type": "git", "url": "git+https://github.com/bestiejs/punycode.js.git" }, - "readmeFilename": "README.md", "homepage": "https://mths.be/punycode", "bugs": { "url": "https://github.com/bestiejs/punycode.js/issues" diff --git a/tests/registry/npm/react-dom/registry.json b/tests/registry/npm/react-dom/registry.json index c0139bcb648f58..cc044679fb070b 100644 --- a/tests/registry/npm/react-dom/registry.json +++ b/tests/registry/npm/react-dom/registry.json @@ -76,6 +76,5 @@ "bugs": { "url": "https://github.com/facebook/react/issues" }, - "license": "MIT", - "readmeFilename": "" + "license": "MIT" } diff --git a/tests/registry/npm/react/registry.json b/tests/registry/npm/react/registry.json index c64d0ac674b8b0..58a827669fb9ce 100644 --- a/tests/registry/npm/react/registry.json +++ b/tests/registry/npm/react/registry.json @@ -59,7 +59,6 @@ "url": "git+https://github.com/facebook/react.git", "directory": "packages/react" }, - "readmeFilename": "", "homepage": "https://reactjs.org/", "bugs": { "url": "https://github.com/facebook/react/issues" diff --git a/tests/registry/npm/require-directory/registry.json b/tests/registry/npm/require-directory/registry.json index 6aef61e67da40c..93cb0895246979 100644 --- a/tests/registry/npm/require-directory/registry.json +++ b/tests/registry/npm/require-directory/registry.json @@ -61,6 +61,5 @@ "bugs": { "url": "http://github.com/troygoode/node-require-directory/issues/" }, - "readmeFilename": "README.markdown", "license": "MIT" } diff --git a/tests/registry/npm/require-from-string/registry.json b/tests/registry/npm/require-from-string/registry.json index 25426e3ef608fc..36e9e65f378f1a 100644 --- a/tests/registry/npm/require-from-string/registry.json +++ b/tests/registry/npm/require-from-string/registry.json @@ -63,6 +63,5 @@ "bugs": { "url": "https://github.com/floatdrop/require-from-string/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/require-main-filename/registry.json b/tests/registry/npm/require-main-filename/registry.json index ca8a86f9283160..b0754acd98d5af 100644 --- a/tests/registry/npm/require-main-filename/registry.json +++ b/tests/registry/npm/require-main-filename/registry.json @@ -60,6 +60,5 @@ "bugs": { "url": "https://github.com/yargs/require-main-filename/issues" }, - "license": "ISC", - "readmeFilename": "README.md" + "license": "ISC" } diff --git a/tests/registry/npm/retry/registry.json b/tests/registry/npm/retry/registry.json index 3958d28db3f969..f8e867dbd84748 100644 --- a/tests/registry/npm/retry/registry.json +++ b/tests/registry/npm/retry/registry.json @@ -71,6 +71,5 @@ "bugs": { "url": "https://github.com/tim-kos/node-retry/issues" }, - "readmeFilename": "README.md", "license": "MIT" } diff --git a/tests/registry/npm/safer-buffer/registry.json b/tests/registry/npm/safer-buffer/registry.json index 7383f74ccd989f..836bd91b1cf3c5 100644 --- a/tests/registry/npm/safer-buffer/registry.json +++ b/tests/registry/npm/safer-buffer/registry.json @@ -66,6 +66,5 @@ "bugs": { "url": "https://github.com/ChALkeR/safer-buffer/issues" }, - "license": "MIT", - "readmeFilename": "Readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/scheduler/registry.json b/tests/registry/npm/scheduler/registry.json index 8e9b9452235782..6d5ebcfb4f4f45 100644 --- a/tests/registry/npm/scheduler/registry.json +++ b/tests/registry/npm/scheduler/registry.json @@ -51,6 +51,5 @@ "bugs": { "url": "https://github.com/facebook/react/issues" }, - "license": "MIT", - "readmeFilename": "" + "license": "MIT" } diff --git a/tests/registry/npm/semver/registry.json b/tests/registry/npm/semver/registry.json index 2a1dfdb0267cbe..99489461a418b7 100644 --- a/tests/registry/npm/semver/registry.json +++ b/tests/registry/npm/semver/registry.json @@ -107,6 +107,5 @@ "homepage": "https://github.com/npm/node-semver#readme", "bugs": { "url": "https://github.com/npm/node-semver/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/set-blocking/registry.json b/tests/registry/npm/set-blocking/registry.json index bd0cb932c960dc..5d6aad5bd9625c 100644 --- a/tests/registry/npm/set-blocking/registry.json +++ b/tests/registry/npm/set-blocking/registry.json @@ -65,6 +65,5 @@ "bugs": { "url": "https://github.com/yargs/set-blocking/issues" }, - "license": "ISC", - "readmeFilename": "README.md" + "license": "ISC" } diff --git a/tests/registry/npm/shebang-command/registry.json b/tests/registry/npm/shebang-command/registry.json index abd8ba2871bb2b..d502ce312c4aaa 100644 --- a/tests/registry/npm/shebang-command/registry.json +++ b/tests/registry/npm/shebang-command/registry.json @@ -63,6 +63,5 @@ "bugs": { "url": "https://github.com/kevva/shebang-command/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/shebang-regex/registry.json b/tests/registry/npm/shebang-regex/registry.json index 533cd68a3b4a27..8e13e1b98271ec 100644 --- a/tests/registry/npm/shebang-regex/registry.json +++ b/tests/registry/npm/shebang-regex/registry.json @@ -61,6 +61,5 @@ "bugs": { "url": "https://github.com/sindresorhus/shebang-regex/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/signal-exit/registry.json b/tests/registry/npm/signal-exit/registry.json index bc6f13df617ec6..73282dd3817803 100644 --- a/tests/registry/npm/signal-exit/registry.json +++ b/tests/registry/npm/signal-exit/registry.json @@ -136,6 +136,5 @@ "bugs": { "url": "https://github.com/tapjs/signal-exit/issues" }, - "license": "ISC", - "readmeFilename": "README.md" + "license": "ISC" } diff --git a/tests/registry/npm/smart-buffer/registry.json b/tests/registry/npm/smart-buffer/registry.json index 1c64950ef04e4e..0e748e9ec08ba9 100644 --- a/tests/registry/npm/smart-buffer/registry.json +++ b/tests/registry/npm/smart-buffer/registry.json @@ -95,7 +95,6 @@ "type": "git", "url": "git+https://github.com/JoshGlazebrook/smart-buffer.git" }, - "readmeFilename": "README.md", "homepage": "https://github.com/JoshGlazebrook/smart-buffer/", "bugs": { "url": "https://github.com/JoshGlazebrook/smart-buffer/issues" diff --git a/tests/registry/npm/socks-proxy-agent/registry.json b/tests/registry/npm/socks-proxy-agent/registry.json index 2bcae551ba1eb8..4e0eb205baedcd 100644 --- a/tests/registry/npm/socks-proxy-agent/registry.json +++ b/tests/registry/npm/socks-proxy-agent/registry.json @@ -88,6 +88,5 @@ "homepage": "https://github.com/TooTallNate/proxy-agents#readme", "bugs": { "url": "https://github.com/TooTallNate/proxy-agents/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/socks/registry.json b/tests/registry/npm/socks/registry.json index 8129b80eaa17a0..901b0c5cea4e57 100644 --- a/tests/registry/npm/socks/registry.json +++ b/tests/registry/npm/socks/registry.json @@ -73,7 +73,6 @@ "url": "git+https://github.com/JoshGlazebrook/socks.git" }, "license": "MIT", - "readmeFilename": "README.md", "homepage": "https://github.com/JoshGlazebrook/socks/", "bugs": { "url": "https://github.com/JoshGlazebrook/socks/issues" diff --git a/tests/registry/npm/source-map-js/registry.json b/tests/registry/npm/source-map-js/registry.json index 5d479b0026b86f..90b37d29e1bf9a 100644 --- a/tests/registry/npm/source-map-js/registry.json +++ b/tests/registry/npm/source-map-js/registry.json @@ -66,6 +66,5 @@ "bugs": { "url": "https://github.com/7rulnik/source-map-js/issues" }, - "license": "BSD-3-Clause", - "readmeFilename": "README.md" + "license": "BSD-3-Clause" } diff --git a/tests/registry/npm/source-map/registry.json b/tests/registry/npm/source-map/registry.json index e812d35324be62..02dd2e79a1a50f 100644 --- a/tests/registry/npm/source-map/registry.json +++ b/tests/registry/npm/source-map/registry.json @@ -64,7 +64,6 @@ "type": "git", "url": "git+ssh://git@github.com/mozilla/source-map.git" }, - "readmeFilename": "README.md", "homepage": "https://github.com/mozilla/source-map", "bugs": { "url": "https://github.com/mozilla/source-map/issues" diff --git a/tests/registry/npm/sourcemap-codec/registry.json b/tests/registry/npm/sourcemap-codec/registry.json index 755480e3d02c7e..2141fee9482340 100644 --- a/tests/registry/npm/sourcemap-codec/registry.json +++ b/tests/registry/npm/sourcemap-codec/registry.json @@ -74,6 +74,5 @@ "bugs": { "url": "https://github.com/Rich-Harris/sourcemap-codec/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/sprintf-js/registry.json b/tests/registry/npm/sprintf-js/registry.json index a83bba43821365..95ec0369f8d979 100644 --- a/tests/registry/npm/sprintf-js/registry.json +++ b/tests/registry/npm/sprintf-js/registry.json @@ -71,6 +71,5 @@ "bugs": { "url": "https://github.com/alexei/sprintf.js/issues" }, - "license": "BSD-3-Clause", - "readmeFilename": "README.md" + "license": "BSD-3-Clause" } diff --git a/tests/registry/npm/ssh2/registry.json b/tests/registry/npm/ssh2/registry.json index 554b67d194ac6d..7cbce86a62e22d 100644 --- a/tests/registry/npm/ssh2/registry.json +++ b/tests/registry/npm/ssh2/registry.json @@ -76,7 +76,6 @@ "type": "git", "url": "git+ssh://git@github.com/mscdex/ssh2.git" }, - "readmeFilename": "README.md", "homepage": "https://github.com/mscdex/ssh2#readme", "bugs": { "url": "https://github.com/mscdex/ssh2/issues" diff --git a/tests/registry/npm/ssri/registry.json b/tests/registry/npm/ssri/registry.json index 7dddf078b6a98e..bdcd5d7b428ec0 100644 --- a/tests/registry/npm/ssri/registry.json +++ b/tests/registry/npm/ssri/registry.json @@ -88,6 +88,5 @@ "homepage": "https://github.com/npm/ssri#readme", "bugs": { "url": "https://github.com/npm/ssri/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/string-width/registry.json b/tests/registry/npm/string-width/registry.json index 700db683b53288..2cb1cd02a77117 100644 --- a/tests/registry/npm/string-width/registry.json +++ b/tests/registry/npm/string-width/registry.json @@ -165,6 +165,5 @@ "bugs": { "url": "https://github.com/sindresorhus/string-width/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/strip-ansi/registry.json b/tests/registry/npm/strip-ansi/registry.json index b50a2b6382dd11..f064c3ff40f877 100644 --- a/tests/registry/npm/strip-ansi/registry.json +++ b/tests/registry/npm/strip-ansi/registry.json @@ -161,6 +161,5 @@ "bugs": { "url": "https://github.com/chalk/strip-ansi/issues" }, - "license": "MIT", - "readmeFilename": "" + "license": "MIT" } diff --git a/tests/registry/npm/strip-final-newline/registry.json b/tests/registry/npm/strip-final-newline/registry.json index a6416b010cc615..d7fd607ebe72d8 100644 --- a/tests/registry/npm/strip-final-newline/registry.json +++ b/tests/registry/npm/strip-final-newline/registry.json @@ -60,6 +60,5 @@ "bugs": { "url": "https://github.com/sindresorhus/strip-final-newline/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/supports-color/registry.json b/tests/registry/npm/supports-color/registry.json index 909165976e1d02..4025adf50f51de 100644 --- a/tests/registry/npm/supports-color/registry.json +++ b/tests/registry/npm/supports-color/registry.json @@ -65,6 +65,5 @@ "bugs": { "url": "https://github.com/chalk/supports-color/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/supports-esm/registry.json b/tests/registry/npm/supports-esm/registry.json index 3faf44387901c4..bf6a1a3b9863b4 100644 --- a/tests/registry/npm/supports-esm/registry.json +++ b/tests/registry/npm/supports-esm/registry.json @@ -59,6 +59,5 @@ "bugs": { "url": "https://github.com/targos/supports-esm/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/tar/registry.json b/tests/registry/npm/tar/registry.json index fa31f3a9509046..669934a9ff9c46 100644 --- a/tests/registry/npm/tar/registry.json +++ b/tests/registry/npm/tar/registry.json @@ -100,6 +100,5 @@ "homepage": "https://github.com/isaacs/node-tar#readme", "bugs": { "url": "https://github.com/isaacs/node-tar/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/trim_registry_files.js b/tests/registry/npm/trim_registry_files.js index e6fbe1353f02c4..dc0caf8927eef4 100644 --- a/tests/registry/npm/trim_registry_files.js +++ b/tests/registry/npm/trim_registry_files.js @@ -15,6 +15,11 @@ for (const dirPath of getPackageDirs()) { const data = JSON.parse(Deno.readTextFileSync(registryPath)); // this is to save data delete data.readme; + delete data.time; + delete data.contributors; + delete data.maintainers; + delete data.users; + delete data.readmeFilename; for (const version in data.versions) { if (!versions.includes(version)) { delete data.versions[version]; diff --git a/tests/registry/npm/tweetnacl/registry.json b/tests/registry/npm/tweetnacl/registry.json index 82e03387be79ff..d215d7940c06c6 100644 --- a/tests/registry/npm/tweetnacl/registry.json +++ b/tests/registry/npm/tweetnacl/registry.json @@ -73,6 +73,5 @@ "bugs": { "url": "https://github.com/dchest/tweetnacl-js/issues" }, - "license": "Unlicense", - "readmeFilename": "README.md" + "license": "Unlicense" } diff --git a/tests/registry/npm/type-detect/registry.json b/tests/registry/npm/type-detect/registry.json index 0ea3ddc108a7f9..7a5e98272aac44 100644 --- a/tests/registry/npm/type-detect/registry.json +++ b/tests/registry/npm/type-detect/registry.json @@ -120,6 +120,5 @@ "bugs": { "url": "https://github.com/chaijs/type-detect/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/type-fest/registry.json b/tests/registry/npm/type-fest/registry.json index b68a7e40950e72..6ad2abf2a4a787 100644 --- a/tests/registry/npm/type-fest/registry.json +++ b/tests/registry/npm/type-fest/registry.json @@ -79,6 +79,5 @@ "bugs": { "url": "https://github.com/sindresorhus/type-fest/issues" }, - "license": "(MIT OR CC0-1.0)", - "readmeFilename": "readme.md" + "license": "(MIT OR CC0-1.0)" } diff --git a/tests/registry/npm/undici-types/registry.json b/tests/registry/npm/undici-types/registry.json index 5b32c1f555aa27..d097f38111a4e0 100644 --- a/tests/registry/npm/undici-types/registry.json +++ b/tests/registry/npm/undici-types/registry.json @@ -1,34 +1,34 @@ { "name": "undici-types", "dist-tags": { - "latest": "6.19.8" + "latest": "6.20.0" }, "versions": { - "6.19.8": { + "6.20.0": { "name": "undici-types", - "version": "6.19.8", - "description": "A stand-alone types package for Undici", + "version": "6.20.0", + "license": "MIT", + "_id": "undici-types@6.20.0", "bugs": { "url": "https://github.com/nodejs/undici/issues" }, - "repository": { - "type": "git", - "url": "git+https://github.com/nodejs/undici.git" - }, - "license": "MIT", - "types": "index.d.ts", - "_id": "undici-types@6.19.8", - "gitHead": "3d3ce0695c8c3f9a8f3c8af90dd42d0569d3f0bb", - "_nodeVersion": "20.16.0", - "_npmVersion": "10.8.1", "dist": { - "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", - "shasum": "35111c9d1437ab83a7cdc0abae2f26d88eda0a02", - "tarball": "http://localhost:4260/undici-types/undici-types-6.19.8.tgz", + "shasum": "8171bf22c1f588d1554d55bf204bc624af388433", + "tarball": "http://localhost:4260/undici-types/undici-types-6.20.0.tgz", "fileCount": 41, - "unpackedSize": 84225 + "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==", + "unpackedSize": 83349 }, + "types": "index.d.ts", + "gitHead": "24b940329af4ad7b72fad89824a3d0cee924d23f", + "repository": { + "url": "git+https://github.com/nodejs/undici.git", + "type": "git" + }, + "_npmVersion": "10.8.2", + "description": "A stand-alone types package for Undici", "directories": {}, + "_nodeVersion": "20.17.0", "_hasShrinkwrap": false } }, @@ -41,6 +41,5 @@ "type": "git", "url": "git+https://github.com/nodejs/undici.git" }, - "description": "A stand-alone types package for Undici", - "readmeFilename": "README.md" + "description": "A stand-alone types package for Undici" } diff --git a/tests/registry/npm/undici-types/undici-types-6.19.8.tgz b/tests/registry/npm/undici-types/undici-types-6.19.8.tgz deleted file mode 100644 index 3fe4b9b9db8048..00000000000000 Binary files a/tests/registry/npm/undici-types/undici-types-6.19.8.tgz and /dev/null differ diff --git a/tests/registry/npm/undici-types/undici-types-6.20.0.tgz b/tests/registry/npm/undici-types/undici-types-6.20.0.tgz new file mode 100644 index 00000000000000..a5cf2d685eb9ad Binary files /dev/null and b/tests/registry/npm/undici-types/undici-types-6.20.0.tgz differ diff --git a/tests/registry/npm/unique-filename/registry.json b/tests/registry/npm/unique-filename/registry.json index 7821fb59ca9e50..d3d2b07ed7fd46 100644 --- a/tests/registry/npm/unique-filename/registry.json +++ b/tests/registry/npm/unique-filename/registry.json @@ -77,6 +77,5 @@ "homepage": "https://github.com/iarna/unique-filename", "bugs": { "url": "https://github.com/iarna/unique-filename/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/unique-slug/registry.json b/tests/registry/npm/unique-slug/registry.json index b32216a69499f8..25092bd591b4a1 100644 --- a/tests/registry/npm/unique-slug/registry.json +++ b/tests/registry/npm/unique-slug/registry.json @@ -77,6 +77,5 @@ "homepage": "https://github.com/npm/unique-slug#readme", "bugs": { "url": "https://github.com/npm/unique-slug/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/universalify/registry.json b/tests/registry/npm/universalify/registry.json index c26a344e302336..006e13da445a39 100644 --- a/tests/registry/npm/universalify/registry.json +++ b/tests/registry/npm/universalify/registry.json @@ -61,6 +61,5 @@ "bugs": { "url": "https://github.com/RyanZim/universalify/issues" }, - "license": "MIT", - "readmeFilename": "README.md" + "license": "MIT" } diff --git a/tests/registry/npm/uri-js/registry.json b/tests/registry/npm/uri-js/registry.json index 8f1d688e540050..77914746ea128a 100644 --- a/tests/registry/npm/uri-js/registry.json +++ b/tests/registry/npm/uri-js/registry.json @@ -77,6 +77,5 @@ "bugs": { "url": "https://github.com/garycourt/uri-js/issues" }, - "license": "BSD-2-Clause", - "readmeFilename": "README.md" + "license": "BSD-2-Clause" } diff --git a/tests/registry/npm/utf-8-validate/registry.json b/tests/registry/npm/utf-8-validate/registry.json index 43dc31378167f4..eb74315b0adf14 100644 --- a/tests/registry/npm/utf-8-validate/registry.json +++ b/tests/registry/npm/utf-8-validate/registry.json @@ -70,6 +70,5 @@ "type": "git", "url": "git+https://github.com/websockets/utf-8-validate.git" }, - "description": "Check if a buffer contains valid UTF-8", - "readmeFilename": "README.md" + "description": "Check if a buffer contains valid UTF-8" } diff --git a/tests/registry/npm/v8flags/registry.json b/tests/registry/npm/v8flags/registry.json index 66e1dd52ebe3d4..af79ddfd66f0c6 100644 --- a/tests/registry/npm/v8flags/registry.json +++ b/tests/registry/npm/v8flags/registry.json @@ -79,6 +79,5 @@ "bugs": { "url": "https://github.com/gulpjs/v8flags/issues" }, - "readmeFilename": "README.md", "license": "MIT" } diff --git a/tests/registry/npm/vue/registry.json b/tests/registry/npm/vue/registry.json index 827538ed34d9b1..ea0808a034a1dc 100644 --- a/tests/registry/npm/vue/registry.json +++ b/tests/registry/npm/vue/registry.json @@ -89,7 +89,6 @@ "type": "git", "url": "git+https://github.com/vuejs/core.git" }, - "readmeFilename": "README.md", "homepage": "https://github.com/vuejs/core/tree/main/packages/vue#readme", "bugs": { "url": "https://github.com/vuejs/core/issues" diff --git a/tests/registry/npm/which-module/registry.json b/tests/registry/npm/which-module/registry.json index 762e068c4449b0..46f42b46e415ea 100644 --- a/tests/registry/npm/which-module/registry.json +++ b/tests/registry/npm/which-module/registry.json @@ -61,6 +61,5 @@ "bugs": { "url": "https://github.com/nexdrew/which-module/issues" }, - "license": "ISC", - "readmeFilename": "README.md" + "license": "ISC" } diff --git a/tests/registry/npm/which/registry.json b/tests/registry/npm/which/registry.json index 855222fd3c51e5..fdd943d578b150 100644 --- a/tests/registry/npm/which/registry.json +++ b/tests/registry/npm/which/registry.json @@ -153,6 +153,5 @@ "homepage": "https://github.com/npm/node-which#readme", "bugs": { "url": "https://github.com/npm/node-which/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/wrap-ansi/registry.json b/tests/registry/npm/wrap-ansi/registry.json index f64be8385a0b7f..53cc2cb2f4d514 100644 --- a/tests/registry/npm/wrap-ansi/registry.json +++ b/tests/registry/npm/wrap-ansi/registry.json @@ -178,6 +178,5 @@ "bugs": { "url": "https://github.com/chalk/wrap-ansi/issues" }, - "license": "MIT", - "readmeFilename": "readme.md" + "license": "MIT" } diff --git a/tests/registry/npm/ws/registry.json b/tests/registry/npm/ws/registry.json index 1738dc57dda27d..39ab8dab671a02 100644 --- a/tests/registry/npm/ws/registry.json +++ b/tests/registry/npm/ws/registry.json @@ -92,6 +92,5 @@ "homepage": "https://github.com/websockets/ws", "bugs": { "url": "https://github.com/websockets/ws/issues" - }, - "readmeFilename": "README.md" + } } diff --git a/tests/registry/npm/y18n/registry.json b/tests/registry/npm/y18n/registry.json index dcb5f0f07adb3c..55e0fdd58972a8 100644 --- a/tests/registry/npm/y18n/registry.json +++ b/tests/registry/npm/y18n/registry.json @@ -67,6 +67,5 @@ "bugs": { "url": "https://github.com/yargs/y18n/issues" }, - "license": "ISC", - "readmeFilename": "README.md" + "license": "ISC" } diff --git a/tests/registry/npm/yallist/registry.json b/tests/registry/npm/yallist/registry.json index 02e10e5ae3e8bf..6839793164ed07 100644 --- a/tests/registry/npm/yallist/registry.json +++ b/tests/registry/npm/yallist/registry.json @@ -63,6 +63,5 @@ "bugs": { "url": "https://github.com/isaacs/yallist/issues" }, - "license": "BlueOak-1.0.0", - "readmeFilename": "README.md" + "license": "BlueOak-1.0.0" } diff --git a/tests/registry/npm/yargs-parser/registry.json b/tests/registry/npm/yargs-parser/registry.json index cf10f5e055db78..603e40a6ce9a69 100644 --- a/tests/registry/npm/yargs-parser/registry.json +++ b/tests/registry/npm/yargs-parser/registry.json @@ -60,7 +60,6 @@ "email": "ben@npmjs.com" }, "license": "ISC", - "readmeFilename": "README.md", "homepage": "https://github.com/yargs/yargs-parser#readme", "repository": { "type": "git", diff --git a/tests/registry/npm/yargs/registry.json b/tests/registry/npm/yargs/registry.json index 1d9797fd322e13..b42df8eb4f24c4 100644 --- a/tests/registry/npm/yargs/registry.json +++ b/tests/registry/npm/yargs/registry.json @@ -95,7 +95,6 @@ "type": "git", "url": "git+https://github.com/yargs/yargs.git" }, - "readmeFilename": "README.md", "homepage": "https://yargs.js.org/", "bugs": { "url": "https://github.com/yargs/yargs/issues" diff --git a/tests/specs/check/check_node_builtin_modules/mod.ts.out b/tests/specs/check/check_node_builtin_modules/mod.ts.out index 638dd640d4b7ea..4e14cdad44e8aa 100644 --- a/tests/specs/check/check_node_builtin_modules/mod.ts.out +++ b/tests/specs/check/check_node_builtin_modules/mod.ts.out @@ -1,14 +1,18 @@ TS2769 [ERROR]: No overload matches this call. - [WILDCARD] + Overload 1 of 3, '(path: PathOrFileDescriptor, options?: { encoding?: null | undefined; flag?: string | undefined; } | null | undefined): Buffer', gave the following error. + Type '123' has no properties in common with type '{ encoding?: null | undefined; flag?: string | undefined; }'. + Overload 2 of 3, '(path: PathOrFileDescriptor, options: { encoding: BufferEncoding; flag?: string | undefined; } | BufferEncoding): string', gave the following error. + Argument of type '123' is not assignable to parameter of type '{ encoding: BufferEncoding; flag?: string | undefined; } | BufferEncoding'. + Overload 3 of 3, '(path: PathOrFileDescriptor, options?: BufferEncoding | (ObjectEncodingOptions & { flag?: string | undefined; }) | null | undefined): string | Buffer<...>', gave the following error. + Argument of type '123' is not assignable to parameter of type 'BufferEncoding | (ObjectEncodingOptions & { flag?: string | undefined; }) | null | undefined'. const _data = fs.readFileSync("./node_builtin.js", 123); ~~~ - at file:///[WILDCARD]/mod.ts:2:52 + at file:///[WILDLINE]/mod.ts:2:52 -TS2322 [ERROR]: Type 'string[]' is not assignable to type 'number[]'. - Type 'string' is not assignable to type 'number'. +TS4104 [ERROR]: The type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type 'number[]'. const _testString: number[] = builtinModules; ~~~~~~~~~~~ - at file:///[WILDCARD]/mod.ts:9:7 + at file:///[WILDLINE]/mod.ts:9:7 Found 2 errors. diff --git a/tests/specs/npm/compare_globals/main.out b/tests/specs/npm/compare_globals/main.out index 290e9c3b23d18f..f4e08bfd1ac13d 100644 --- a/tests/specs/npm/compare_globals/main.out +++ b/tests/specs/npm/compare_globals/main.out @@ -5,8 +5,8 @@ Download http://localhost:4260/@denotest%2fglobals [UNORDERED_END] [UNORDERED_START] Download http://localhost:4260/@denotest/globals/1.0.0.tgz -Download http://localhost:4260/@types/node/node-22.5.4.tgz -Download http://localhost:4260/undici-types/undici-types-6.19.8.tgz +Download http://localhost:4260/@types/node/node-[WILDLINE].tgz +Download http://localhost:4260/undici-types/undici-types-[WILDLINE].tgz [UNORDERED_END] Check file:///[WILDCARD]/main.ts true diff --git a/tests/specs/publish/bare_node_builtins/bare_node_builtins.out b/tests/specs/publish/bare_node_builtins/bare_node_builtins.out index 6baedd906f767e..fb1d0361d85af3 100644 --- a/tests/specs/publish/bare_node_builtins/bare_node_builtins.out +++ b/tests/specs/publish/bare_node_builtins/bare_node_builtins.out @@ -3,8 +3,8 @@ Warning Resolving "url" as "node:url" at file:///[WILDLINE]/mod.ts:1:22. If you [UNORDERED_START] Download http://localhost:4260/@types%2fnode Download http://localhost:4260/undici-types -Download http://localhost:4260/@types/node/node-22.5.4.tgz -Download http://localhost:4260/undici-types/undici-types-6.19.8.tgz +Download http://localhost:4260/@types/node/node-[WILDLINE].tgz +Download http://localhost:4260/undici-types/undici-types-[WILDLINE].tgz [UNORDERED_END] Check file:///[WILDLINE]/mod.ts Checking for slow types in the public API... diff --git a/tests/specs/publish/node_specifier/node_specifier.out b/tests/specs/publish/node_specifier/node_specifier.out index 0ba14043df9fc7..ccfb861f3146fe 100644 --- a/tests/specs/publish/node_specifier/node_specifier.out +++ b/tests/specs/publish/node_specifier/node_specifier.out @@ -1,8 +1,8 @@ [UNORDERED_START] Download http://localhost:4260/@types%2fnode Download http://localhost:4260/undici-types -Download http://localhost:4260/@types/node/node-22.5.4.tgz -Download http://localhost:4260/undici-types/undici-types-6.19.8.tgz +Download http://localhost:4260/@types/node/node-[WILDLINE].tgz +Download http://localhost:4260/undici-types/undici-types-[WILDLINE].tgz [UNORDERED_END] Check file:///[WILDCARD]/mod.ts Checking for slow types in the public API... diff --git a/tests/specs/run/tls_connecttls/textproto.ts b/tests/specs/run/tls_connecttls/textproto.ts deleted file mode 100644 index 6b8ac92ecbfb15..00000000000000 --- a/tests/specs/run/tls_connecttls/textproto.ts +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2018-2025 the Deno authors. MIT license. -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/** **Deprecated**. Use `TextLineStream` from `std/steams` for line-by-line text reading instead. - * - * A reader for dealing with low level text based protocols. - * - * Based on - * [net/textproto](https://github.com/golang/go/tree/master/src/net/textproto). - * - * @deprecated (will be removed after 0.159.0) Use `TextLineStream` from `std/steams` for line-by-line text reading instead. - * @module - */ - -import type { BufReader, ReadLineResult } from "@std/io/buf-reader"; -import { concat } from "@std/bytes/concat"; - -// Constants created for DRY -const CHAR_SPACE: number = " ".charCodeAt(0); -const CHAR_TAB: number = "\t".charCodeAt(0); -const CHAR_COLON: number = ":".charCodeAt(0); - -const WHITESPACES: Array = [CHAR_SPACE, CHAR_TAB]; - -const decoder = new TextDecoder(); - -// FROM https://github.com/denoland/deno/blob/b34628a26ab0187a827aa4ebe256e23178e25d39/cli/js/web/headers.ts#L9 -const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/g; - -function str(buf: Uint8Array | null | undefined): string { - return !buf ? "" : decoder.decode(buf); -} - -/** - * @deprecated (will be removed after 0.159.0) Use `TextLineStream` from `std/steams` for line-by-line text reading instead. - */ -export class TextProtoReader { - constructor(readonly r: BufReader) {} - - /** readLine() reads a single line from the TextProtoReader, - * eliding the final \n or \r\n from the returned string. - */ - async readLine(): Promise { - const s = await this.readLineSlice(); - return s === null ? null : str(s); - } - - /** ReadMimeHeader reads a MIME-style header from r. - * The header is a sequence of possibly continued Key: Value lines - * ending in a blank line. - * The returned map m maps CanonicalMIMEHeaderKey(key) to a - * sequence of values in the same order encountered in the input. - * - * For example, consider this input: - * - * My-Key: Value 1 - * Long-Key: Even - * Longer Value - * My-Key: Value 2 - * - * Given that input, ReadMIMEHeader returns the map: - * - * map[string][]string{ - * "My-Key": {"Value 1", "Value 2"}, - * "Long-Key": {"Even Longer Value"}, - * } - */ - async readMimeHeader(): Promise { - const m = new Headers(); - let line: Uint8Array | undefined; - - // The first line cannot start with a leading space. - let buf = await this.r.peek(1); - if (buf === null) { - return null; - } else if (WHITESPACES.includes(buf[0])) { - line = (await this.readLineSlice()) as Uint8Array; - } - - buf = await this.r.peek(1); - if (buf === null) { - throw new Deno.errors.UnexpectedEof(); - } else if (WHITESPACES.includes(buf[0])) { - throw new Deno.errors.InvalidData( - `malformed MIME header initial line: ${str(line)}`, - ); - } - - while (true) { - const kv = await this.readLineSlice(); // readContinuedLineSlice - if (kv === null) throw new Deno.errors.UnexpectedEof(); - if (kv.byteLength === 0) return m; - - // Key ends at first colon - let i = kv.indexOf(CHAR_COLON); - if (i < 0) { - throw new Deno.errors.InvalidData( - `malformed MIME header line: ${str(kv)}`, - ); - } - - //let key = canonicalMIMEHeaderKey(kv.subarray(0, endKey)); - const key = str(kv.subarray(0, i)); - - // As per RFC 7230 field-name is a token, - // tokens consist of one or more chars. - // We could throw `Deno.errors.InvalidData` here, - // but better to be liberal in what we - // accept, so if we get an empty key, skip it. - if (key == "") { - continue; - } - - // Skip initial spaces in value. - i++; // skip colon - while ( - i < kv.byteLength && - (WHITESPACES.includes(kv[i])) - ) { - i++; - } - const value = str(kv.subarray(i)).replace( - invalidHeaderCharRegex, - encodeURI, - ); - - // In case of invalid header we swallow the error - // example: "Audio Mode" => invalid due to space in the key - try { - m.append(key, value); - } catch { - // Pass - } - } - } - - async readLineSlice(): Promise { - let line = new Uint8Array(0); - let r: ReadLineResult | null = null; - - do { - r = await this.r.readLine(); - // TODO(ry): - // This skipSpace() is definitely misplaced, but I don't know where it - // comes from nor how to fix it. - - //TODO(SmashingQuasar): Kept skipSpace to preserve behavior but it should be looked into to check if it makes sense when this is used. - - if (r !== null && this.skipSpace(r.line) !== 0) { - line = concat([line, r.line]); - } - } while (r !== null && r.more); - - return r === null ? null : line; - } - - skipSpace(l: Uint8Array): number { - let n = 0; - - for (const val of l) { - if (!WHITESPACES.includes(val)) { - n++; - } - } - - return n; - } -} diff --git a/tests/specs/run/tls_connecttls/tls_connecttls.js b/tests/specs/run/tls_connecttls/tls_connecttls.js index 686b13aea34afc..a417bd93b8d4d3 100644 --- a/tests/specs/run/tls_connecttls/tls_connecttls.js +++ b/tests/specs/run/tls_connecttls/tls_connecttls.js @@ -1,6 +1,6 @@ import { assert, assertEquals } from "@std/assert"; -import { BufReader, BufWriter } from "@std/io"; -import { TextProtoReader } from "./textproto.ts"; +import { BufReader, BufWriter } from "../../../unit/test_util.ts"; +import { TextProtoReader } from "../../../testdata/run/textproto.ts"; const encoder = new TextEncoder(); const decoder = new TextDecoder(); diff --git a/tests/specs/run/tls_starttls/textproto.ts b/tests/specs/run/tls_starttls/textproto.ts deleted file mode 100644 index 6b8ac92ecbfb15..00000000000000 --- a/tests/specs/run/tls_starttls/textproto.ts +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2018-2025 the Deno authors. MIT license. -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/** **Deprecated**. Use `TextLineStream` from `std/steams` for line-by-line text reading instead. - * - * A reader for dealing with low level text based protocols. - * - * Based on - * [net/textproto](https://github.com/golang/go/tree/master/src/net/textproto). - * - * @deprecated (will be removed after 0.159.0) Use `TextLineStream` from `std/steams` for line-by-line text reading instead. - * @module - */ - -import type { BufReader, ReadLineResult } from "@std/io/buf-reader"; -import { concat } from "@std/bytes/concat"; - -// Constants created for DRY -const CHAR_SPACE: number = " ".charCodeAt(0); -const CHAR_TAB: number = "\t".charCodeAt(0); -const CHAR_COLON: number = ":".charCodeAt(0); - -const WHITESPACES: Array = [CHAR_SPACE, CHAR_TAB]; - -const decoder = new TextDecoder(); - -// FROM https://github.com/denoland/deno/blob/b34628a26ab0187a827aa4ebe256e23178e25d39/cli/js/web/headers.ts#L9 -const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/g; - -function str(buf: Uint8Array | null | undefined): string { - return !buf ? "" : decoder.decode(buf); -} - -/** - * @deprecated (will be removed after 0.159.0) Use `TextLineStream` from `std/steams` for line-by-line text reading instead. - */ -export class TextProtoReader { - constructor(readonly r: BufReader) {} - - /** readLine() reads a single line from the TextProtoReader, - * eliding the final \n or \r\n from the returned string. - */ - async readLine(): Promise { - const s = await this.readLineSlice(); - return s === null ? null : str(s); - } - - /** ReadMimeHeader reads a MIME-style header from r. - * The header is a sequence of possibly continued Key: Value lines - * ending in a blank line. - * The returned map m maps CanonicalMIMEHeaderKey(key) to a - * sequence of values in the same order encountered in the input. - * - * For example, consider this input: - * - * My-Key: Value 1 - * Long-Key: Even - * Longer Value - * My-Key: Value 2 - * - * Given that input, ReadMIMEHeader returns the map: - * - * map[string][]string{ - * "My-Key": {"Value 1", "Value 2"}, - * "Long-Key": {"Even Longer Value"}, - * } - */ - async readMimeHeader(): Promise { - const m = new Headers(); - let line: Uint8Array | undefined; - - // The first line cannot start with a leading space. - let buf = await this.r.peek(1); - if (buf === null) { - return null; - } else if (WHITESPACES.includes(buf[0])) { - line = (await this.readLineSlice()) as Uint8Array; - } - - buf = await this.r.peek(1); - if (buf === null) { - throw new Deno.errors.UnexpectedEof(); - } else if (WHITESPACES.includes(buf[0])) { - throw new Deno.errors.InvalidData( - `malformed MIME header initial line: ${str(line)}`, - ); - } - - while (true) { - const kv = await this.readLineSlice(); // readContinuedLineSlice - if (kv === null) throw new Deno.errors.UnexpectedEof(); - if (kv.byteLength === 0) return m; - - // Key ends at first colon - let i = kv.indexOf(CHAR_COLON); - if (i < 0) { - throw new Deno.errors.InvalidData( - `malformed MIME header line: ${str(kv)}`, - ); - } - - //let key = canonicalMIMEHeaderKey(kv.subarray(0, endKey)); - const key = str(kv.subarray(0, i)); - - // As per RFC 7230 field-name is a token, - // tokens consist of one or more chars. - // We could throw `Deno.errors.InvalidData` here, - // but better to be liberal in what we - // accept, so if we get an empty key, skip it. - if (key == "") { - continue; - } - - // Skip initial spaces in value. - i++; // skip colon - while ( - i < kv.byteLength && - (WHITESPACES.includes(kv[i])) - ) { - i++; - } - const value = str(kv.subarray(i)).replace( - invalidHeaderCharRegex, - encodeURI, - ); - - // In case of invalid header we swallow the error - // example: "Audio Mode" => invalid due to space in the key - try { - m.append(key, value); - } catch { - // Pass - } - } - } - - async readLineSlice(): Promise { - let line = new Uint8Array(0); - let r: ReadLineResult | null = null; - - do { - r = await this.r.readLine(); - // TODO(ry): - // This skipSpace() is definitely misplaced, but I don't know where it - // comes from nor how to fix it. - - //TODO(SmashingQuasar): Kept skipSpace to preserve behavior but it should be looked into to check if it makes sense when this is used. - - if (r !== null && this.skipSpace(r.line) !== 0) { - line = concat([line, r.line]); - } - } while (r !== null && r.more); - - return r === null ? null : line; - } - - skipSpace(l: Uint8Array): number { - let n = 0; - - for (const val of l) { - if (!WHITESPACES.includes(val)) { - n++; - } - } - - return n; - } -} diff --git a/tests/specs/run/tls_starttls/tls_starttls.js b/tests/specs/run/tls_starttls/tls_starttls.js index cd5718ff5a076f..54550964338c17 100644 --- a/tests/specs/run/tls_starttls/tls_starttls.js +++ b/tests/specs/run/tls_starttls/tls_starttls.js @@ -1,7 +1,6 @@ import { assert, assertEquals } from "@std/assert"; -import { BufReader } from "@std/io/buf-reader"; -import { BufWriter } from "@std/io/buf-writer"; -import { TextProtoReader } from "./textproto.ts"; +import { BufReader, BufWriter } from "../../../unit/test_util.ts"; +import { TextProtoReader } from "../../../testdata/run/textproto.ts"; const encoder = new TextEncoder(); const decoder = new TextDecoder(); diff --git a/tests/testdata/run/textproto.ts b/tests/testdata/run/textproto.ts index 6b8ac92ecbfb15..1abe81e578582e 100644 --- a/tests/testdata/run/textproto.ts +++ b/tests/testdata/run/textproto.ts @@ -14,7 +14,7 @@ * @module */ -import type { BufReader, ReadLineResult } from "@std/io/buf-reader"; +import type { BufReader, ReadLineResult } from "../../unit/test_util.ts"; import { concat } from "@std/bytes/concat"; // Constants created for DRY diff --git a/tests/unit/body_test.ts b/tests/unit/body_test.ts index 28a1c697b1e953..63e702484c52f8 100644 --- a/tests/unit/body_test.ts +++ b/tests/unit/body_test.ts @@ -27,7 +27,7 @@ Deno.test(async function arrayBufferFromByteArrays() { const buffer = new TextEncoder().encode("ahoyhoy8").buffer; for (const type of intArrays) { - const body = buildBody(new type(buffer)); + const body = buildBody(new type(buffer as ArrayBuffer)); const text = new TextDecoder("utf-8").decode(await body.arrayBuffer()); assertEquals(text, "ahoyhoy8"); } diff --git a/tests/unit/fetch_test.ts b/tests/unit/fetch_test.ts index 094b963e19adf7..84d05ddb3c1c3b 100644 --- a/tests/unit/fetch_test.ts +++ b/tests/unit/fetch_test.ts @@ -553,7 +553,7 @@ Deno.test( const data = "Hello World"; const response = await fetch("http://localhost:4545/echo_server", { method: "POST", - body: new TextEncoder().encode(data).buffer, + body: new TextEncoder().encode(data).buffer as ArrayBuffer, }); const text = await response.text(); assertEquals(text, data); diff --git a/tests/unit/http_test.ts b/tests/unit/http_test.ts index 809b36227bf6c6..05d72bd2ffb420 100644 --- a/tests/unit/http_test.ts +++ b/tests/unit/http_test.ts @@ -3,7 +3,7 @@ // deno-lint-ignore-file no-deprecated-deno-api -import { Buffer, BufReader, BufWriter, type Reader } from "@std/io"; +import { Buffer, type Reader } from "@std/io"; import { TextProtoReader } from "../testdata/run/textproto.ts"; import { assert, @@ -11,6 +11,8 @@ import { assertRejects, assertStrictEquals, assertThrows, + BufReader, + BufWriter, delay, fail, } from "./test_util.ts"; diff --git a/tests/unit/serve_test.ts b/tests/unit/serve_test.ts index 09616b01519ad1..6373fbb3a73684 100644 --- a/tests/unit/serve_test.ts +++ b/tests/unit/serve_test.ts @@ -3,13 +3,15 @@ // deno-lint-ignore-file no-console import { assertIsError, assertMatch, assertRejects } from "@std/assert"; -import { Buffer, BufReader, BufWriter, type Reader } from "@std/io"; +import { Buffer, type Reader } from "@std/io"; import { TextProtoReader } from "../testdata/run/textproto.ts"; import { assert, assertEquals, assertStringIncludes, assertThrows, + BufReader, + BufWriter, curlRequest, curlRequestWithStdErr, execCode, diff --git a/tests/unit/structured_clone_test.ts b/tests/unit/structured_clone_test.ts index fc5d68e9dad4e9..9d52039e32731c 100644 --- a/tests/unit/structured_clone_test.ts +++ b/tests/unit/structured_clone_test.ts @@ -27,7 +27,10 @@ Deno.test("correct DataCloneError message", () => { assertThrows( () => { const sab = new SharedArrayBuffer(1024); - structuredClone(sab, { transfer: [sab] }); + structuredClone(sab, { + // @ts-expect-error cannot assign SharedArrayBuffer because it's not tranferable + transfer: [sab], + }); }, DOMException, "Value not transferable", diff --git a/tests/unit/test_util.ts b/tests/unit/test_util.ts index 6e7865ea7a43d4..9ddd4d9fb1e65b 100644 --- a/tests/unit/test_util.ts +++ b/tests/unit/test_util.ts @@ -22,8 +22,9 @@ export { unreachable, } from "@std/assert"; export { delay } from "@std/async/delay"; -export { readLines } from "@std/io/read-lines"; export { parseArgs } from "@std/cli/parse-args"; +import { copy } from "@std/bytes/copy"; +import type { Reader, Writer, WriterSync } from "@std/io/types"; export function pathToAbsoluteFileUrl(path: string): URL { path = resolve(path); @@ -117,3 +118,1234 @@ export async function curlRequestWithStdErr(args: string[]) { ); return [decoder.decode(stdout), decoder.decode(stderr)]; } + +const DEFAULT_BUF_SIZE = 4096; +const MIN_BUF_SIZE = 16; +const MAX_CONSECUTIVE_EMPTY_READS = 100; +const CR = "\r".charCodeAt(0); +const LF = "\n".charCodeAt(0); + +/** + * Thrown when a write operation is attempted on a full buffer. + * + * @example Usage + * ```ts + * import { BufWriter, BufferFullError, Writer } from "@std/io"; + * import { assert, assertEquals } from "@std/assert"; + * + * const writer: Writer = { + * write(p: Uint8Array): Promise { + * throw new BufferFullError(p); + * } + * }; + * const bufWriter = new BufWriter(writer); + * try { + * await bufWriter.write(new Uint8Array([1, 2, 3])); + * } catch (err) { + * assert(err instanceof BufferFullError); + * assertEquals(err.partial, new Uint8Array([3])); + * } + * ``` + */ +export class BufferFullError extends Error { + /** + * The partially read bytes + * + * @example Usage + * ```ts + * import { BufferFullError } from "@std/io"; + * import { assertEquals } from "@std/assert/equals"; + * + * const err = new BufferFullError(new Uint8Array(2)); + * assertEquals(err.partial, new Uint8Array(2)); + * ``` + */ + partial: Uint8Array; + + /** + * Construct a new instance. + * + * @param partial The bytes partially read + */ + constructor(partial: Uint8Array) { + super("Buffer full"); + this.name = this.constructor.name; + this.partial = partial; + } +} + +/** + * Thrown when a read from a stream fails to read the + * requested number of bytes. + * + * @example Usage + * ```ts + * import { PartialReadError } from "@std/io"; + * import { assertEquals } from "@std/assert/equals"; + * + * const err = new PartialReadError(new Uint8Array(2)); + * assertEquals(err.name, "PartialReadError"); + * + * ``` + */ +export class PartialReadError extends Error { + /** + * The partially read bytes + * + * @example Usage + * ```ts + * import { PartialReadError } from "@std/io"; + * import { assertEquals } from "@std/assert/equals"; + * + * const err = new PartialReadError(new Uint8Array(2)); + * assertEquals(err.partial, new Uint8Array(2)); + * ``` + */ + partial: Uint8Array; + + /** + * Construct a {@linkcode PartialReadError}. + * + * @param partial The bytes partially read + */ + constructor(partial: Uint8Array) { + super("Encountered UnexpectedEof, data only partially read"); + this.name = this.constructor.name; + this.partial = partial; + } +} + +/** + * Result type returned by of {@linkcode BufReader.readLine}. + */ +export interface ReadLineResult { + /** The line read */ + line: Uint8Array; + /** `true if the end of the line has not been reached, `false` otherwise. */ + more: boolean; +} + +/** + * Implements buffering for a {@linkcode Reader} object. + * + * @example Usage + * ```ts + * import { BufReader, Buffer } from "@std/io"; + * import { assertEquals } from "@std/assert/equals"; + * + * const encoder = new TextEncoder(); + * const decoder = new TextDecoder(); + * + * const reader = new BufReader(new Buffer(encoder.encode("hello world"))); + * const buf = new Uint8Array(11); + * await reader.read(buf); + * assertEquals(decoder.decode(buf), "hello world"); + * ``` + */ +export class BufReader implements Reader { + #buf!: Uint8Array; + #rd!: Reader; // Reader provided by caller. + #r = 0; // buf read position. + #w = 0; // buf write position. + #eof = false; + + /** + * Returns a new {@linkcode BufReader} if `r` is not already one. + * + * @example Usage + * ```ts + * import { BufReader, Buffer } from "@std/io"; + * import { assert } from "@std/assert/assert"; + * + * const reader = new Buffer(new TextEncoder().encode("hello world")); + * const bufReader = BufReader.create(reader); + * assert(bufReader instanceof BufReader); + * ``` + * + * @param r The reader to read from. + * @param size The size of the buffer. + * @returns A new {@linkcode BufReader} if `r` is not already one. + */ + static create(r: Reader, size: number = DEFAULT_BUF_SIZE): BufReader { + return r instanceof BufReader ? r : new BufReader(r, size); + } + + /** + * Constructs a new {@linkcode BufReader} for the given reader and buffer size. + * + * @param rd The reader to read from. + * @param size The size of the buffer. + */ + constructor(rd: Reader, size: number = DEFAULT_BUF_SIZE) { + if (size < MIN_BUF_SIZE) { + size = MIN_BUF_SIZE; + } + this.#reset(new Uint8Array(size), rd); + } + + /** + * Returns the size of the underlying buffer in bytes. + * + * @example Usage + * ```ts + * import { BufReader, Buffer } from "@std/io"; + * import { assertEquals } from "@std/assert/equals"; + * + * const reader = new Buffer(new TextEncoder().encode("hello world")); + * const bufReader = new BufReader(reader); + * + * assertEquals(bufReader.size(), 4096); + * ``` + * + * @returns The size of the underlying buffer in bytes. + */ + size(): number { + return this.#buf.byteLength; + } + + /** + * Returns the number of bytes that can be read from the current buffer. + * + * @example Usage + * ```ts + * import { BufReader, Buffer } from "@std/io"; + * import { assertEquals } from "@std/assert/equals"; + * + * const reader = new Buffer(new TextEncoder().encode("hello world")); + * const bufReader = new BufReader(reader); + * await bufReader.read(new Uint8Array(5)); + * assertEquals(bufReader.buffered(), 6); + * ``` + * + * @returns Number of bytes that can be read from the buffer + */ + buffered(): number { + return this.#w - this.#r; + } + + // Reads a new chunk into the buffer. + #fill = async () => { + // Slide existing data to beginning. + if (this.#r > 0) { + this.#buf.copyWithin(0, this.#r, this.#w); + this.#w -= this.#r; + this.#r = 0; + } + + if (this.#w >= this.#buf.byteLength) { + throw new Error("Buffer full while filling"); + } + + // Read new data: try a limited number of times. + for (let i = MAX_CONSECUTIVE_EMPTY_READS; i > 0; i--) { + const rr = await this.#rd.read(this.#buf.subarray(this.#w)); + if (rr === null) { + this.#eof = true; + return; + } + this.#w += rr; + if (rr > 0) { + return; + } + } + + throw new Error( + `No progress after ${MAX_CONSECUTIVE_EMPTY_READS} read() calls`, + ); + }; + + /** + * Discards any buffered data, resets all state, and switches + * the buffered reader to read from `r`. + * + * @example Usage + * ```ts + * import { BufReader, Buffer } from "@std/io"; + * import { assertEquals } from "@std/assert/equals"; + * + * const reader = new Buffer(new TextEncoder().encode("hello world")); + * const bufReader = new BufReader(reader); + * await bufReader.read(new Uint8Array(5)); + * bufReader.reset(reader); + * assertEquals(bufReader.buffered(), 6); + * ``` + * + * @param r The reader to read from. + */ + reset(r: Reader) { + this.#reset(this.#buf, r); + } + + #reset = (buf: Uint8Array, rd: Reader) => { + this.#buf = buf; + this.#rd = rd; + this.#eof = false; + // this.lastByte = -1; + // this.lastCharSize = -1; + }; + + /** + * Reads data into `p`. + * + * The bytes are taken from at most one `read()` on the underlying `Reader`, + * hence n may be less than `len(p)`. + * To read exactly `len(p)` bytes, use `io.ReadFull(b, p)`. + * + * @example Usage + * ```ts + * import { BufReader, Buffer } from "@std/io"; + * import { assertEquals } from "@std/assert/equals"; + * + * const reader = new Buffer(new TextEncoder().encode("hello world")); + * const bufReader = new BufReader(reader); + * const buf = new Uint8Array(5); + * await bufReader.read(buf); + * assertEquals(new TextDecoder().decode(buf), "hello"); + * ``` + * + * @param p The buffer to read data into. + * @returns The number of bytes read into `p`. + */ + async read(p: Uint8Array): Promise { + let rr: number | null = p.byteLength; + if (p.byteLength === 0) return rr; + + if (this.#r === this.#w) { + if (p.byteLength >= this.#buf.byteLength) { + // Large read, empty buffer. + // Read directly into p to avoid copy. + const rr = await this.#rd.read(p); + // if (rr.nread > 0) { + // this.lastByte = p[rr.nread - 1]; + // this.lastCharSize = -1; + // } + return rr; + } + + // One read. + // Do not use this.fill, which will loop. + this.#r = 0; + this.#w = 0; + rr = await this.#rd.read(this.#buf); + if (rr === 0 || rr === null) return rr; + this.#w += rr; + } + + // copy as much as we can + const copied = copy(this.#buf.subarray(this.#r, this.#w), p, 0); + this.#r += copied; + // this.lastByte = this.buf[this.r - 1]; + // this.lastCharSize = -1; + return copied; + } + + /** + * Reads exactly `p.length` bytes into `p`. + * + * If successful, `p` is returned. + * + * If the end of the underlying stream has been reached, and there are no more + * bytes available in the buffer, `readFull()` returns `null` instead. + * + * An error is thrown if some bytes could be read, but not enough to fill `p` + * entirely before the underlying stream reported an error or EOF. Any error + * thrown will have a `partial` property that indicates the slice of the + * buffer that has been successfully filled with data. + * + * Ported from https://golang.org/pkg/io/#ReadFull + * + * @example Usage + * ```ts + * import { BufReader, Buffer } from "@std/io"; + * import { assertEquals } from "@std/assert/equals"; + * + * const reader = new Buffer(new TextEncoder().encode("hello world")); + * const bufReader = new BufReader(reader); + * const buf = new Uint8Array(5); + * await bufReader.readFull(buf); + * assertEquals(new TextDecoder().decode(buf), "hello"); + * ``` + * + * @param p The buffer to read data into. + * @returns The buffer `p` if the read is successful, `null` if the end of the + * underlying stream has been reached, and there are no more bytes available in the buffer. + */ + async readFull(p: Uint8Array): Promise { + let bytesRead = 0; + while (bytesRead < p.length) { + const rr = await this.read(p.subarray(bytesRead)); + if (rr === null) { + if (bytesRead === 0) { + return null; + } else { + throw new PartialReadError(p.subarray(0, bytesRead)); + } + } + bytesRead += rr; + } + return p; + } + + /** + * Returns the next byte ([0, 255]) or `null`. + * + * @example Usage + * ```ts + * import { BufReader, Buffer } from "@std/io"; + * import { assertEquals } from "@std/assert/equals"; + * + * const reader = new Buffer(new TextEncoder().encode("hello world")); + * const bufReader = new BufReader(reader); + * const byte = await bufReader.readByte(); + * assertEquals(byte, 104); + * ``` + * + * @returns The next byte ([0, 255]) or `null`. + */ + async readByte(): Promise { + while (this.#r === this.#w) { + if (this.#eof) return null; + await this.#fill(); // buffer is empty. + } + const c = this.#buf[this.#r]!; + this.#r++; + // this.lastByte = c; + return c; + } + + /** + * Reads until the first occurrence of delim in the input, + * returning a string containing the data up to and including the delimiter. + * If ReadString encounters an error before finding a delimiter, + * it returns the data read before the error and the error itself + * (often `null`). + * ReadString returns err !== null if and only if the returned data does not end + * in delim. + * + * @example Usage + * ```ts + * import { BufReader, Buffer } from "@std/io"; + * import { assertEquals } from "@std/assert/equals"; + * + * const reader = new Buffer(new TextEncoder().encode("hello world")); + * const bufReader = new BufReader(reader); + * const str = await bufReader.readString(" "); + * assertEquals(str, "hello "); + * + * const str2 = await bufReader.readString(" "); + * assertEquals(str2, "world"); + * ``` + * + * @param delim The delimiter to read until. + * @returns The string containing the data up to and including the delimiter. + */ + async readString(delim: string): Promise { + if (delim.length !== 1) { + throw new Error("Delimiter should be a single character"); + } + const buffer = await this.readSlice(delim.charCodeAt(0)); + if (buffer === null) return null; + return new TextDecoder().decode(buffer); + } + + /** + * A low-level line-reading primitive. Most callers should use + * `readString('\n')` instead. + * + * `readLine()` tries to return a single line, not including the end-of-line + * bytes. If the line was too long for the buffer then `more` is set and the + * beginning of the line is returned. The rest of the line will be returned + * from future calls. `more` will be false when returning the last fragment + * of the line. The returned buffer is only valid until the next call to + * `readLine()`. + * + * The text returned from this method does not include the line end ("\r\n" or + * "\n"). + * + * When the end of the underlying stream is reached, the final bytes in the + * stream are returned. No indication or error is given if the input ends + * without a final line end. When there are no more trailing bytes to read, + * `readLine()` returns `null`. + * + * @example Usage + * ```ts + * import { BufReader, Buffer } from "@std/io"; + * import { assertEquals } from "@std/assert/equals"; + * + * const reader = new Buffer(new TextEncoder().encode("hello\nworld")); + * const bufReader = new BufReader(reader); + * const line1 = await bufReader.readLine(); + * assertEquals(new TextDecoder().decode(line1!.line), "hello"); + * const line2 = await bufReader.readLine(); + * assertEquals(new TextDecoder().decode(line2!.line), "world"); + * ``` + * + * @returns The line read. + */ + async readLine(): Promise { + let line: Uint8Array | null = null; + + try { + line = await this.readSlice(LF); + } catch (err) { + // Don't throw if `readSlice()` failed with `BufferFullError`, instead we + // just return whatever is available and set the `more` flag. + if (!(err instanceof BufferFullError)) { + throw err; + } + + let partial = err.partial; + + // Handle the case where "\r\n" straddles the buffer. + if ( + !this.#eof && partial && + partial.byteLength > 0 && + partial[partial.byteLength - 1] === CR + ) { + // Put the '\r' back on buf and drop it from line. + // Let the next call to ReadLine check for "\r\n". + if (this.#r <= 0) { + throw new Error("Tried to rewind past start of buffer"); + } + this.#r--; + partial = partial.subarray(0, partial.byteLength - 1); + } + + if (partial) { + return { line: partial, more: !this.#eof }; + } + } + + if (line === null) { + return null; + } + + if (line.byteLength === 0) { + return { line, more: false }; + } + + if (line[line.byteLength - 1] === LF) { + let drop = 1; + if (line.byteLength > 1 && line[line.byteLength - 2] === CR) { + drop = 2; + } + line = line.subarray(0, line.byteLength - drop); + } + return { line, more: false }; + } + + /** + * Reads until the first occurrence of `delim` in the input, + * returning a slice pointing at the bytes in the buffer. The bytes stop + * being valid at the next read. + * + * If `readSlice()` encounters an error before finding a delimiter, or the + * buffer fills without finding a delimiter, it throws an error with a + * `partial` property that contains the entire buffer. + * + * If `readSlice()` encounters the end of the underlying stream and there are + * any bytes left in the buffer, the rest of the buffer is returned. In other + * words, EOF is always treated as a delimiter. Once the buffer is empty, + * it returns `null`. + * + * Because the data returned from `readSlice()` will be overwritten by the + * next I/O operation, most clients should use `readString()` instead. + * + * @example Usage + * ```ts + * import { BufReader, Buffer } from "@std/io"; + * import { assertEquals } from "@std/assert/equals"; + * + * const reader = new Buffer(new TextEncoder().encode("hello world")); + * const bufReader = new BufReader(reader); + * const slice = await bufReader.readSlice(0x20); + * assertEquals(new TextDecoder().decode(slice!), "hello "); + * ``` + * + * @param delim The delimiter to read until. + * @returns A slice pointing at the bytes in the buffer. + */ + async readSlice(delim: number): Promise { + let s = 0; // search start index + let slice: Uint8Array | undefined; + + while (true) { + // Search buffer. + let i = this.#buf.subarray(this.#r + s, this.#w).indexOf(delim); + if (i >= 0) { + i += s; + slice = this.#buf.subarray(this.#r, this.#r + i + 1); + this.#r += i + 1; + break; + } + + // EOF? + if (this.#eof) { + if (this.#r === this.#w) { + return null; + } + slice = this.#buf.subarray(this.#r, this.#w); + this.#r = this.#w; + break; + } + + // Buffer full? + if (this.buffered() >= this.#buf.byteLength) { + this.#r = this.#w; + // #4521 The internal buffer should not be reused across reads because it causes corruption of data. + const oldbuf = this.#buf; + const newbuf = this.#buf.slice(0); + this.#buf = newbuf; + throw new BufferFullError(oldbuf); + } + + s = this.#w - this.#r; // do not rescan area we scanned before + + // Buffer is not full. + await this.#fill(); + } + + // Handle last byte, if any. + // const i = slice.byteLength - 1; + // if (i >= 0) { + // this.lastByte = slice[i]; + // this.lastCharSize = -1 + // } + + return slice; + } + + /** + * Returns the next `n` bytes without advancing the reader. The + * bytes stop being valid at the next read call. + * + * When the end of the underlying stream is reached, but there are unread + * bytes left in the buffer, those bytes are returned. If there are no bytes + * left in the buffer, it returns `null`. + * + * If an error is encountered before `n` bytes are available, `peek()` throws + * an error with the `partial` property set to a slice of the buffer that + * contains the bytes that were available before the error occurred. + * + * @example Usage + * ```ts + * import { BufReader, Buffer } from "@std/io"; + * import { assertEquals } from "@std/assert/equals"; + * + * const reader = new Buffer(new TextEncoder().encode("hello world")); + * const bufReader = new BufReader(reader); + * const peeked = await bufReader.peek(5); + * assertEquals(new TextDecoder().decode(peeked!), "hello"); + * ``` + * + * @param n The number of bytes to peek. + * @returns The next `n` bytes without advancing the reader. + */ + async peek(n: number): Promise { + if (n < 0) { + throw new Error("Peek count cannot be negative"); + } + + let avail = this.#w - this.#r; + while (avail < n && avail < this.#buf.byteLength && !this.#eof) { + await this.#fill(); + avail = this.#w - this.#r; + } + + if (avail === 0 && this.#eof) { + return null; + } else if (avail < n && this.#eof) { + return this.#buf.subarray(this.#r, this.#r + avail); + } else if (avail < n) { + throw new BufferFullError(this.#buf.subarray(this.#r, this.#w)); + } + + return this.#buf.subarray(this.#r, this.#r + n); + } +} + +/** + * AbstractBufBase is a base class which other classes can embed to + * implement the {@inkcode Reader} and {@linkcode Writer} interfaces. + * It provides basic implementations of those interfaces based on a buffer + * array. + * + * @example Usage + * ```ts no-assert + * import { AbstractBufBase } from "@std/io/buf-writer"; + * import { Reader } from "@std/io/types"; + * + * class MyBufReader extends AbstractBufBase { + * constructor(buf: Uint8Array) { + * super(buf); + * } + * } + * ``` + * + * @internal + */ +export abstract class AbstractBufBase { + /** + * The buffer + * + * @example Usage + * ```ts + * import { AbstractBufBase } from "@std/io/buf-writer"; + * import { assertEquals } from "@std/assert/equals"; + * + * class MyBuffer extends AbstractBufBase {} + * + * const buf = new Uint8Array(1024); + * const mb = new MyBuffer(buf); + * + * assertEquals(mb.buf, buf); + * ``` + */ + buf: Uint8Array; + /** + * The used buffer bytes + * + * @example Usage + * ```ts + * import { AbstractBufBase } from "@std/io/buf-writer"; + * import { assertEquals } from "@std/assert/equals"; + * + * class MyBuffer extends AbstractBufBase {} + * + * const buf = new Uint8Array(1024); + * const mb = new MyBuffer(buf); + * + * assertEquals(mb.usedBufferBytes, 0); + * ``` + */ + usedBufferBytes = 0; + /** + * The error + * + * @example Usage + * ```ts + * import { AbstractBufBase } from "@std/io/buf-writer"; + * import { assertEquals } from "@std/assert/equals"; + * + * class MyBuffer extends AbstractBufBase {} + * + * const buf = new Uint8Array(1024); + * const mb = new MyBuffer(buf); + * + * assertEquals(mb.err, null); + * ``` + */ + err: Error | null = null; + + /** + * Construct a {@linkcode AbstractBufBase} instance + * + * @param buf The buffer to use. + */ + constructor(buf: Uint8Array) { + this.buf = buf; + } + + /** + * Size returns the size of the underlying buffer in bytes. + * + * @example Usage + * ```ts + * import { AbstractBufBase } from "@std/io/buf-writer"; + * import { assertEquals } from "@std/assert/equals"; + * + * class MyBuffer extends AbstractBufBase {} + * + * const buf = new Uint8Array(1024); + * const mb = new MyBuffer(buf); + * + * assertEquals(mb.size(), 1024); + * ``` + * + * @return the size of the buffer in bytes. + */ + size(): number { + return this.buf.byteLength; + } + + /** + * Returns how many bytes are unused in the buffer. + * + * @example Usage + * ```ts + * import { AbstractBufBase } from "@std/io/buf-writer"; + * import { assertEquals } from "@std/assert/equals"; + * + * class MyBuffer extends AbstractBufBase {} + * + * const buf = new Uint8Array(1024); + * const mb = new MyBuffer(buf); + * + * assertEquals(mb.available(), 1024); + * ``` + * + * @return the number of bytes that are unused in the buffer. + */ + available(): number { + return this.buf.byteLength - this.usedBufferBytes; + } + + /** + * buffered returns the number of bytes that have been written into the + * current buffer. + * + * @example Usage + * ```ts + * import { AbstractBufBase } from "@std/io/buf-writer"; + * import { assertEquals } from "@std/assert/equals"; + * + * class MyBuffer extends AbstractBufBase {} + * + * const buf = new Uint8Array(1024); + * const mb = new MyBuffer(buf); + * + * assertEquals(mb.buffered(), 0); + * ``` + * + * @return the number of bytes that have been written into the current buffer. + */ + buffered(): number { + return this.usedBufferBytes; + } +} + +/** + * `BufWriter` implements buffering for an {@linkcode Writer} object. + * If an error occurs writing to a Writer, no more data will be + * accepted and all subsequent writes, and flush(), will return the error. + * After all data has been written, the client should call the + * flush() method to guarantee all data has been forwarded to + * the underlying deno.Writer. + * + * @example Usage + * ```ts + * import { BufWriter } from "@std/io/buf-writer"; + * import { assertEquals } from "@std/assert/equals"; + * + * const writer = { + * write(p: Uint8Array): Promise { + * return Promise.resolve(p.length); + * } + * }; + * + * const bufWriter = new BufWriter(writer); + * const data = new Uint8Array(1024); + * + * await bufWriter.write(data); + * await bufWriter.flush(); + * + * assertEquals(bufWriter.buffered(), 0); + * ``` + */ +export class BufWriter extends AbstractBufBase implements Writer { + #writer: Writer; + + /** + * return new BufWriter unless writer is BufWriter + * + * @example Usage + * ```ts + * import { BufWriter } from "@std/io/buf-writer"; + * import { Writer } from "@std/io/types"; + * import { assertEquals } from "@std/assert/equals"; + * + * const writer: Writer = { + * write(p: Uint8Array): Promise { + * return Promise.resolve(p.length); + * } + * }; + * + * const bufWriter = BufWriter.create(writer); + * const data = new Uint8Array(1024); + * + * await bufWriter.write(data); + * + * assertEquals(bufWriter.buffered(), 1024); + * ``` + * + * @param writer The writer to wrap. + * @param size The size of the buffer. + * + * @return a new {@linkcode BufWriter} instance. + */ + static create(writer: Writer, size: number = DEFAULT_BUF_SIZE): BufWriter { + return writer instanceof BufWriter ? writer : new BufWriter(writer, size); + } + + /** + * Construct a new {@linkcode BufWriter} + * + * @param writer The writer to wrap. + * @param size The size of the buffer. + */ + constructor(writer: Writer, size: number = DEFAULT_BUF_SIZE) { + super(new Uint8Array(size <= 0 ? DEFAULT_BUF_SIZE : size)); + this.#writer = writer; + } + + /** + * Discards any unflushed buffered data, clears any error, and + * resets buffer to write its output to w. + * + * @example Usage + * ```ts + * import { BufWriter } from "@std/io/buf-writer"; + * import { Writer } from "@std/io/types"; + * import { assertEquals } from "@std/assert/equals"; + * + * const writer: Writer = { + * write(p: Uint8Array): Promise { + * return Promise.resolve(p.length); + * } + * }; + * + * const bufWriter = new BufWriter(writer); + * const data = new Uint8Array(1024); + * + * await bufWriter.write(data); + * + * assertEquals(bufWriter.buffered(), 1024); + * + * bufWriter.reset(writer); + * + * assertEquals(bufWriter.buffered(), 0); + * ``` + * + * @param w The writer to write to. + */ + reset(w: Writer) { + this.err = null; + this.usedBufferBytes = 0; + this.#writer = w; + } + + /** + * Flush writes any buffered data to the underlying io.Writer. + * + * @example Usage + * ```ts + * import { BufWriter } from "@std/io/buf-writer"; + * import { Writer } from "@std/io/types"; + * import { assertEquals } from "@std/assert/equals"; + * + * const writer: Writer = { + * write(p: Uint8Array): Promise { + * return Promise.resolve(p.length); + * } + * }; + * + * const bufWriter = new BufWriter(writer); + * const data = new Uint8Array(1024); + * + * await bufWriter.write(data); + * await bufWriter.flush(); + * + * assertEquals(bufWriter.buffered(), 0); + * ``` + */ + async flush() { + if (this.err !== null) throw this.err; + if (this.usedBufferBytes === 0) return; + + try { + const p = this.buf.subarray(0, this.usedBufferBytes); + let nwritten = 0; + while (nwritten < p.length) { + nwritten += await this.#writer.write(p.subarray(nwritten)); + } + } catch (e) { + if (e instanceof Error) { + this.err = e; + } + throw e; + } + + this.buf = new Uint8Array(this.buf.length); + this.usedBufferBytes = 0; + } + + /** + * Writes the contents of `data` into the buffer. If the contents won't fully + * fit into the buffer, those bytes that are copied into the buffer will be flushed + * to the writer and the remaining bytes are then copied into the now empty buffer. + * + * @example Usage + * ```ts + * import { BufWriter } from "@std/io/buf-writer"; + * import { Writer } from "@std/io/types"; + * import { assertEquals } from "@std/assert/equals"; + * + * const writer: Writer = { + * write(p: Uint8Array): Promise { + * return Promise.resolve(p.length); + * } + * }; + * + * const bufWriter = new BufWriter(writer); + * const data = new Uint8Array(1024); + * + * await bufWriter.write(data); + * + * assertEquals(bufWriter.buffered(), 1024); + * ``` + * + * @param data The data to write to the buffer. + * @return the number of bytes written to the buffer. + */ + async write(data: Uint8Array): Promise { + if (this.err !== null) throw this.err; + if (data.length === 0) return 0; + + let totalBytesWritten = 0; + let numBytesWritten = 0; + while (data.byteLength > this.available()) { + if (this.buffered() === 0) { + // Large write, empty buffer. + // Write directly from data to avoid copy. + try { + numBytesWritten = await this.#writer.write(data); + } catch (e) { + if (e instanceof Error) { + this.err = e; + } + throw e; + } + } else { + numBytesWritten = copy(data, this.buf, this.usedBufferBytes); + this.usedBufferBytes += numBytesWritten; + await this.flush(); + } + totalBytesWritten += numBytesWritten; + data = data.subarray(numBytesWritten); + } + + numBytesWritten = copy(data, this.buf, this.usedBufferBytes); + this.usedBufferBytes += numBytesWritten; + totalBytesWritten += numBytesWritten; + return totalBytesWritten; + } +} + +/** + * BufWriterSync implements buffering for a deno.WriterSync object. + * If an error occurs writing to a WriterSync, no more data will be + * accepted and all subsequent writes, and flush(), will return the error. + * After all data has been written, the client should call the + * flush() method to guarantee all data has been forwarded to + * the underlying deno.WriterSync. + * + * @example Usage + * ```ts + * import { BufWriterSync } from "@std/io/buf-writer"; + * import { assertEquals } from "@std/assert/equals"; + * + * const writer = { + * writeSync(p: Uint8Array): number { + * return p.length; + * } + * }; + * + * const bufWriter = new BufWriterSync(writer); + * const data = new Uint8Array(1024); + * + * bufWriter.writeSync(data); + * bufWriter.flush(); + * + * assertEquals(bufWriter.buffered(), 0); + * ``` + */ +export class BufWriterSync extends AbstractBufBase implements WriterSync { + #writer: WriterSync; + + /** + * return new BufWriterSync unless writer is BufWriterSync + * + * @example Usage + * ```ts + * import { BufWriterSync } from "@std/io/buf-writer"; + * import { WriterSync } from "@std/io/types"; + * import { assertEquals } from "@std/assert/equals"; + * + * const writer: WriterSync = { + * writeSync(p: Uint8Array): number { + * return p.length; + * } + * }; + * + * const bufWriter = BufWriterSync.create(writer); + * const data = new Uint8Array(1024); + * bufWriter.writeSync(data); + * bufWriter.flush(); + * + * assertEquals(bufWriter.buffered(), 0); + * ``` + * + * @param writer The writer to wrap. + * @param size The size of the buffer. + * @returns a new {@linkcode BufWriterSync} instance. + */ + static create( + writer: WriterSync, + size: number = DEFAULT_BUF_SIZE, + ): BufWriterSync { + return writer instanceof BufWriterSync + ? writer + : new BufWriterSync(writer, size); + } + + /** + * Construct a new {@linkcode BufWriterSync} + * + * @param writer The writer to wrap. + * @param size The size of the buffer. + */ + constructor(writer: WriterSync, size: number = DEFAULT_BUF_SIZE) { + super(new Uint8Array(size <= 0 ? DEFAULT_BUF_SIZE : size)); + this.#writer = writer; + } + + /** + * Discards any unflushed buffered data, clears any error, and + * resets buffer to write its output to w. + * + * @example Usage + * ```ts + * import { BufWriterSync } from "@std/io/buf-writer"; + * import { WriterSync } from "@std/io/types"; + * import { assertEquals } from "@std/assert/equals"; + * + * const writer: WriterSync = { + * writeSync(p: Uint8Array): number { + * return p.length; + * } + * }; + * + * const bufWriter = new BufWriterSync(writer); + * const data = new Uint8Array(1024); + * + * bufWriter.writeSync(data); + * bufWriter.flush(); + * + * assertEquals(bufWriter.buffered(), 0); + * ``` + * + * @param w The writer to write to. + */ + reset(w: WriterSync) { + this.err = null; + this.usedBufferBytes = 0; + this.#writer = w; + } + + /** + * Flush writes any buffered data to the underlying io.WriterSync. + * + * @example Usage + * ```ts + * import { BufWriterSync } from "@std/io/buf-writer"; + * import { WriterSync } from "@std/io/types"; + * import { assertEquals } from "@std/assert/equals"; + * + * const writer: WriterSync = { + * writeSync(p: Uint8Array): number { + * return p.length; + * } + * }; + * + * const bufWriter = new BufWriterSync(writer); + * const data = new Uint8Array(1024); + * + * bufWriter.writeSync(data); + * bufWriter.flush(); + * + * assertEquals(bufWriter.buffered(), 0); + * ``` + */ + flush() { + if (this.err !== null) throw this.err; + if (this.usedBufferBytes === 0) return; + + try { + const p = this.buf.subarray(0, this.usedBufferBytes); + let nwritten = 0; + while (nwritten < p.length) { + nwritten += this.#writer.writeSync(p.subarray(nwritten)); + } + } catch (e) { + if (e instanceof Error) { + this.err = e; + } + throw e; + } + + this.buf = new Uint8Array(this.buf.length); + this.usedBufferBytes = 0; + } + + /** Writes the contents of `data` into the buffer. If the contents won't fully + * fit into the buffer, those bytes that can are copied into the buffer, the + * buffer is the flushed to the writer and the remaining bytes are copied into + * the now empty buffer. + * + * @example Usage + * ```ts + * import { BufWriterSync } from "@std/io/buf-writer"; + * import { WriterSync } from "@std/io/types"; + * import { assertEquals } from "@std/assert/equals"; + * + * const writer: WriterSync = { + * writeSync(p: Uint8Array): number { + * return p.length; + * } + * }; + * + * const bufWriter = new BufWriterSync(writer); + * const data = new Uint8Array(1024); + * + * bufWriter.writeSync(data); + * bufWriter.flush(); + * + * assertEquals(bufWriter.buffered(), 0); + * ``` + * + * @param data The data to write to the buffer. + * @return the number of bytes written to the buffer. + */ + writeSync(data: Uint8Array): number { + if (this.err !== null) throw this.err; + if (data.length === 0) return 0; + + let totalBytesWritten = 0; + let numBytesWritten = 0; + while (data.byteLength > this.available()) { + if (this.buffered() === 0) { + // Large write, empty buffer. + // Write directly from data to avoid copy. + try { + numBytesWritten = this.#writer.writeSync(data); + } catch (e) { + if (e instanceof Error) { + this.err = e; + } + throw e; + } + } else { + numBytesWritten = copy(data, this.buf, this.usedBufferBytes); + this.usedBufferBytes += numBytesWritten; + this.flush(); + } + totalBytesWritten += numBytesWritten; + data = data.subarray(numBytesWritten); + } + + numBytesWritten = copy(data, this.buf, this.usedBufferBytes); + this.usedBufferBytes += numBytesWritten; + totalBytesWritten += numBytesWritten; + return totalBytesWritten; + } +} diff --git a/tests/unit/tls_test.ts b/tests/unit/tls_test.ts index 53db347a131a8d..7a596c54305d2d 100644 --- a/tests/unit/tls_test.ts +++ b/tests/unit/tls_test.ts @@ -6,8 +6,9 @@ import { assertRejects, assertStrictEquals, assertThrows, + BufReader, + BufWriter, } from "./test_util.ts"; -import { BufReader, BufWriter } from "@std/io"; import { readAll } from "@std/io/read-all"; import { writeAll } from "@std/io/write-all"; import { TextProtoReader } from "../testdata/run/textproto.ts"; diff --git a/tests/unit/url_search_params_test.ts b/tests/unit/url_search_params_test.ts index 9846c7a91cd3ff..d72366a1a4e6cb 100644 --- a/tests/unit/url_search_params_test.ts +++ b/tests/unit/url_search_params_test.ts @@ -304,7 +304,9 @@ Deno.test(function urlSearchParamsDeletingAppendedMultiple() { // ref: https://github.com/web-platform-tests/wpt/blob/master/url/urlsearchparams-constructor.any.js#L176-L182 Deno.test(function urlSearchParamsCustomSymbolIterator() { const params = new URLSearchParams(); - params[Symbol.iterator] = function* (): IterableIterator<[string, string]> { + params[Symbol.iterator] = function* (): URLSearchParamsIterator< + [string, string] + > { yield ["a", "b"]; }; const params1 = new URLSearchParams((params as unknown) as string[][]); @@ -345,7 +347,7 @@ Deno.test( Deno.test(function urlSearchParamsOverridingEntriesNotChangeForEach() { class CustomSearchParams extends URLSearchParams { - override *entries(): IterableIterator<[string, string]> { + override *entries(): URLSearchParamsIterator<[string, string]> { yield* []; } } diff --git a/tests/unit/version_test.ts b/tests/unit/version_test.ts index fd570fb16d9725..07333812097174 100644 --- a/tests/unit/version_test.ts +++ b/tests/unit/version_test.ts @@ -6,5 +6,5 @@ Deno.test(function version() { const pattern = /^\d+\.\d+\.\d+/; assert(pattern.test(Deno.version.deno)); assert(pattern.test(Deno.version.v8)); - assertEquals(Deno.version.typescript, "5.6.2"); + assertEquals(Deno.version.typescript, "5.7.3"); }); diff --git a/tests/unit_node/_fs/_fs_read_test.ts b/tests/unit_node/_fs/_fs_read_test.ts index 6def1ff71daf67..aa236d46d10849 100644 --- a/tests/unit_node/_fs/_fs_read_test.ts +++ b/tests/unit_node/_fs/_fs_read_test.ts @@ -348,10 +348,11 @@ Deno.test({ for (const offset of offsets) { // test read resetBuffer(); - const buf = new constr( + // deno-lint-ignore no-explicit-any + const buf = new (constr as any)( buffer, innerOffset, - ); + ) as Int8Array | Uint8Array; await readTest( testData, buf, diff --git a/tests/unit_node/_fs/_fs_write_test.ts b/tests/unit_node/_fs/_fs_write_test.ts index 6a5d4c9c268202..5ceca169524ff8 100644 --- a/tests/unit_node/_fs/_fs_write_test.ts +++ b/tests/unit_node/_fs/_fs_write_test.ts @@ -117,7 +117,7 @@ Deno.test({ for (const innerOffset of offsets) { for (const offset of offsets) { resetBuffer(); - const buffer = new constr( + const buffer = new (constr as Uint8ArrayConstructor)( arrayBuffer, innerOffset, offset + bytes.length, diff --git a/tests/unit_node/http_test.ts b/tests/unit_node/http_test.ts index b4f0d260aa0906..54803ab995f511 100644 --- a/tests/unit_node/http_test.ts +++ b/tests/unit_node/http_test.ts @@ -1892,3 +1892,27 @@ Deno.test("[node/http] an error with DNS propagates to request object", async () }); await promise; }); + +Deno.test("[node/http] supports proxy http request", async () => { + const { promise, resolve } = Promise.withResolvers(); + const server = Deno.serve({ port: 0, onListen }, (req) => { + console.log("server received", req.url); + assertEquals(req.url, "http://example.com/"); + return new Response("ok"); + }); + + function onListen({ port }: { port: number }) { + http.request({ + host: "localhost", + port, + path: "http://example.com", + }, async (res) => { + assertEquals(res.statusCode, 200); + assertEquals(await text(res), "ok"); + resolve(); + server.shutdown(); + }).end(); + } + await promise; + await server.finished; +}); diff --git a/tests/unit_node/process_test.ts b/tests/unit_node/process_test.ts index 592bd6497fc956..fe6f43b3e5b9c9 100644 --- a/tests/unit_node/process_test.ts +++ b/tests/unit_node/process_test.ts @@ -390,6 +390,8 @@ Deno.test({ Deno.test({ name: "process.env", fn() { + assert(Object.prototype.hasOwnProperty.call(process, "env")); + Deno.env.set("HELLO", "WORLD"); assertObjectMatch(process.env, Deno.env.toObject()); diff --git a/tests/unit_node/sqlite_test.ts b/tests/unit_node/sqlite_test.ts index 46dc38eee7a7b6..43b6914f3c45f2 100644 --- a/tests/unit_node/sqlite_test.ts +++ b/tests/unit_node/sqlite_test.ts @@ -1,6 +1,6 @@ // Copyright 2018-2025 the Deno authors. MIT license. import { DatabaseSync } from "node:sqlite"; -import { assertEquals, assertThrows } from "@std/assert"; +import { assert, assertEquals, assertThrows } from "@std/assert"; Deno.test("[node/sqlite] in-memory databases", () => { const db1 = new DatabaseSync(":memory:"); @@ -52,6 +52,15 @@ Deno.test( }, ); +Deno.test("[node/sqlite] StatementSync bind bigints", () => { + const db = new DatabaseSync(":memory:"); + db.exec("CREATE TABLE data(key INTEGER PRIMARY KEY);"); + + const stmt = db.prepare("INSERT INTO data (key) VALUES (?)"); + assertEquals(stmt.run(100n), { lastInsertRowid: 100, changes: 1 }); + db.close(); +}); + Deno.test("[node/sqlite] StatementSync read bigints are supported", () => { const db = new DatabaseSync(":memory:"); db.exec("CREATE TABLE data(key INTEGER PRIMARY KEY);"); @@ -73,3 +82,12 @@ Deno.test("[node/sqlite] StatementSync integer too large", () => { assertThrows(() => db.prepare("SELECT * FROM data").get()); }); + +Deno.test("[node/sqlite] StatementSync blob are Uint8Array", () => { + const db = new DatabaseSync(":memory:"); + const obj = db.prepare("select cast('test' as blob)").all(); + + assertEquals(obj.length, 1); + const row = obj[0] as Record; + assert(row["cast('test' as blob)"] instanceof Uint8Array); +}); diff --git a/tests/unit_node/zlib_test.ts b/tests/unit_node/zlib_test.ts index cc8730c5465ca4..07e5beed97ec0b 100644 --- a/tests/unit_node/zlib_test.ts +++ b/tests/unit_node/zlib_test.ts @@ -76,7 +76,7 @@ Deno.test("brotli compression", { await Promise.all([ promise.promise, - new Promise((r) => stream.on("close", r)), + new Promise((r) => stream.on("close", r)), ]); const content = Deno.readTextFileSync("lorem_ipsum.txt"); diff --git a/tests/util/server/Cargo.toml b/tests/util/server/Cargo.toml index 6e31dd45871f5b..44aebf34998325 100644 --- a/tests/util/server/Cargo.toml +++ b/tests/util/server/Cargo.toml @@ -44,6 +44,7 @@ monch.workspace = true once_cell.workspace = true os_pipe.workspace = true parking_lot.workspace = true +percent-encoding.workspace = true pretty_assertions.workspace = true prost.workspace = true regex.workspace = true diff --git a/tests/util/server/src/servers/npm_registry.rs b/tests/util/server/src/servers/npm_registry.rs index c814b83340c9f4..df0d3734e3f718 100644 --- a/tests/util/server/src/servers/npm_registry.rs +++ b/tests/util/server/src/servers/npm_registry.rs @@ -301,9 +301,12 @@ fn replace_default_npm_registry_url_with_test_npm_registry_url( npm_registry: &npm::TestNpmRegistry, package_name: &str, ) -> String { + let package_name = percent_encoding::percent_decode_str(package_name) + .decode_utf8() + .unwrap(); text.replace( &format!("https://registry.npmjs.org/{}/-/", package_name), - &npm_registry.package_url(package_name), + &npm_registry.package_url(&package_name), ) } diff --git a/tests/util/std b/tests/util/std index c5d7930d5700db..1f032bb7e112ea 160000 --- a/tests/util/std +++ b/tests/util/std @@ -1 +1 @@ -Subproject commit c5d7930d5700dbbbedea607f9cf3e50acdc33e2d +Subproject commit 1f032bb7e112ea572ce9df5d83675220d331079e diff --git a/tools/release/release_doc_template.md b/tools/release/release_doc_template.md index b37218533783df..2a82b5b22bd0ff 100644 --- a/tools/release/release_doc_template.md +++ b/tools/release/release_doc_template.md @@ -122,7 +122,7 @@ verify on GitHub that everything looks correct. - ⛔ Verify that: - [ ] There are 24 assets on the [GitHub release draft](https://github.com/denoland/deno/releases/v$VERSION). - - [ ] There are 10 zip files for this version on + - [ ] There are 20 zip files for this version on [dl.deno.land](https://console.cloud.google.com/storage/browser/dl.deno.land/release/v$VERSION). - [ ] Publish the release on Github