diff --git a/scripts/errorCheck.mjs b/scripts/errorCheck.mjs index c2e031e5487..89c354a5671 100644 --- a/scripts/errorCheck.mjs +++ b/scripts/errorCheck.mjs @@ -71,7 +71,7 @@ async function checkSourceFiles() { let count = 0; console.log("== List of errors not used in source =="); for (const errName of errorNames) { - if (allSrc.indexOf(errName) < 0) { + if (!allSrc.includes(errName)) { console.log(errName); count++; } diff --git a/scripts/eslint/rules/argument-trivia.cjs b/scripts/eslint/rules/argument-trivia.cjs index 4e3b6011e76..289a97d79ee 100644 --- a/scripts/eslint/rules/argument-trivia.cjs +++ b/scripts/eslint/rules/argument-trivia.cjs @@ -157,7 +157,7 @@ module.exports = createRule({ } } - const hasNewLine = sourceCodeText.slice(commentRangeEnd, argRangeStart).indexOf("\n") >= 0; + const hasNewLine = sourceCodeText.slice(commentRangeEnd, argRangeStart).includes("\n"); if (argRangeStart !== commentRangeEnd + 1 && !hasNewLine) { // TODO(jakebailey): range should be whitespace context.report({ diff --git a/scripts/update-experimental-branches.mjs b/scripts/update-experimental-branches.mjs index 0b1fa533966..3f3493296c3 100644 --- a/scripts/update-experimental-branches.mjs +++ b/scripts/update-experimental-branches.mjs @@ -88,7 +88,7 @@ async function main() { const mergeTree = runSequence([ ["git", ["merge-tree", mergeBase.trim(), branch, "experimental"]], ]); - if (mergeTree.indexOf(`===${"="}===`) >= 0) { // 7 equals is the center of the merge conflict marker + if (mergeTree.includes(`===${"="}===`)) { // 7 equals is the center of the merge conflict marker throw new Error(`Merge conflict detected involving PR ${branch} with other experiment`); } // Merge (always producing a merge commit) diff --git a/src/cancellationToken/cancellationToken.ts b/src/cancellationToken/cancellationToken.ts index 8ea543e01d4..374dddacc80 100644 --- a/src/cancellationToken/cancellationToken.ts +++ b/src/cancellationToken/cancellationToken.ts @@ -39,7 +39,7 @@ function createCancellationToken(args: string[]): ServerCancellationToken { // in this case pipe name will be build dynamically as . if (cancellationPipeName.charAt(cancellationPipeName.length - 1) === "*") { const namePrefix = cancellationPipeName.slice(0, -1); - if (namePrefix.length === 0 || namePrefix.indexOf("*") >= 0) { + if (namePrefix.length === 0 || namePrefix.includes("*")) { throw new Error("Invalid name for template cancellation pipe: it should have length greater than 2 characters and contain only one '*'."); } let perRequestPipeName: string | undefined; diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 392883ae41f..21ed301c23e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -964,7 +964,6 @@ import { SpreadElement, startsWith, Statement, - stringContains, StringLiteral, StringLiteralLike, StringLiteralType, @@ -7908,14 +7907,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (!specifier) { specifier = getSpecifierForModuleSymbol(chain[0], context); } - if (!(context.flags & NodeBuilderFlags.AllowNodeModulesRelativePaths) && getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.Classic && specifier.indexOf("/node_modules/") >= 0) { + if (!(context.flags & NodeBuilderFlags.AllowNodeModulesRelativePaths) && getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.Classic && specifier.includes("/node_modules/")) { const oldSpecifier = specifier; if (getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Node16 || getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.NodeNext) { // We might be able to write a portable import type using a mode override; try specifier generation again, but with a different mode set const swappedMode = contextFile?.impliedNodeFormat === ModuleKind.ESNext ? ModuleKind.CommonJS : ModuleKind.ESNext; specifier = getSpecifierForModuleSymbol(chain[0], context, swappedMode); - if (specifier.indexOf("/node_modules/") >= 0) { + if (specifier.includes("/node_modules/")) { // Still unreachable :( specifier = oldSpecifier; } @@ -8661,7 +8660,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { if (group.length > 1) { // remove group members from statements and then merge group members and add back to statements statements = [ - ...filter(statements, s => group.indexOf(s as ExportDeclaration) === -1), + ...filter(statements, s => !group.includes(s as ExportDeclaration)), factory.createExportDeclaration( /*modifiers*/ undefined, /*isTypeOnly*/ false, @@ -24250,7 +24249,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { const originalKeywordKind = identifierToKeywordKind(param.name); if ( (isCallSignatureDeclaration(param.parent) || isMethodSignature(param.parent) || isFunctionTypeNode(param.parent)) && - param.parent.parameters.indexOf(param) > -1 && + param.parent.parameters.includes(param) && (resolveName(param, param.name.escapedText, SymbolFlags.Type, /*nameNotFoundMessage*/ undefined, param.name.escapedText, /*isUse*/ true) || originalKeywordKind && isTypeNodeKind(originalKeywordKind)) ) { @@ -30962,7 +30961,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { } function isHyphenatedJsxName(name: string | __String) { - return stringContains(name as string, "-"); + return (name as string).includes("-"); } /** @@ -49648,7 +49647,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker { // Realism (size) checking // We should test against `getTextOfNode(node)` rather than `node.text`, because `node.text` for large numeric literals can contain "." // e.g. `node.text` for numeric literal `1100000000000000000000` is `1.1e21`. - const isFractional = getTextOfNode(node).indexOf(".") !== -1; + const isFractional = getTextOfNode(node).includes("."); const isScientific = node.numericLiteralFlags & TokenFlags.Scientific; // Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 2bde2526ab0..61058f8e8be 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -104,7 +104,6 @@ import { returnTrue, ScriptTarget, startsWith, - stringContains, StringLiteral, SyntaxKind, sys, @@ -1710,7 +1709,7 @@ export function parseListTypeOption(opt: CommandLineOptionOfListType, value = "" if (startsWith(value, "-")) { return undefined; } - if (opt.type === "listOrElement" && !stringContains(value, ",")) { + if (opt.type === "listOrElement" && !value.includes(",")) { return validateJsonOptionValue(opt, value, errors); } if (value === "") { @@ -3078,7 +3077,7 @@ function parseConfig( basePath = normalizeSlashes(basePath); const resolvedPath = getNormalizedAbsolutePath(configFileName || "", basePath); - if (resolutionStack.indexOf(resolvedPath) >= 0) { + if (resolutionStack.includes(resolvedPath)) { errors.push(createCompilerDiagnostic(Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, [...resolutionStack, resolvedPath].join(" -> "))); return { raw: json || convertToObject(sourceFile!, errors) }; } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 340b49b134a..fbd2432e9b7 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -2484,11 +2484,6 @@ export function tryRemoveSuffix(str: string, suffix: string): string | undefined return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined; } -/** @internal */ -export function stringContains(str: string, substring: string): boolean { - return str.indexOf(substring) !== -1; -} - /** * Takes a string like "jquery-min.4.2.3" and returns "jquery" * diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index d407dadc246..4a0b03f7285 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -407,7 +407,6 @@ import { SpreadElement, stableSort, Statement, - stringContains, StringLiteral, supportedJSExtensionsFlat, SwitchStatement, @@ -3065,9 +3064,9 @@ export function createPrinter(printerOptions: PrinterOptions = {}, handlers: Pri // If the number will be printed verbatim and it doesn't already contain a dot or an exponent indicator, add one // if the expression doesn't have any comments that will be emitted. return !(expression.numericLiteralFlags & TokenFlags.WithSpecifier) - && !stringContains(text, tokenToString(SyntaxKind.DotToken)!) - && !stringContains(text, String.fromCharCode(CharacterCodes.E)) - && !stringContains(text, String.fromCharCode(CharacterCodes.e)); + && !text.includes(tokenToString(SyntaxKind.DotToken)!) + && !text.includes(String.fromCharCode(CharacterCodes.E)) + && !text.includes(String.fromCharCode(CharacterCodes.e)); } else if (isAccessExpression(expression)) { // check if constant enum value is a non-negative integer diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 4aedc4a4aa5..0a5088a4c34 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -100,7 +100,6 @@ import { sort, SourceFile, startsWith, - stringContains, supportedDeclarationExtensions, supportedJSExtensionsFlat, supportedTSImplementationExtensions, @@ -1808,7 +1807,7 @@ function nodeModuleNameResolverWorker(features: NodeResolutionFeatures, moduleNa && features & NodeResolutionFeatures.Exports && !isExternalModuleNameRelative(moduleName) && !extensionIsOk(Extensions.TypeScript | Extensions.Declaration, result.value.resolved.extension) - && conditions.indexOf("import") > -1 + && conditions.includes("import") ) { traceIfEnabled(state, Diagnostics.Resolution_of_non_relative_name_failed_trying_with_modern_Node_resolution_features_disabled_to_see_if_npm_library_needs_configuration_update); const diagnosticState = { @@ -1849,7 +1848,7 @@ function nodeModuleNameResolverWorker(features: NodeResolutionFeatures, moduleNa resolved = loadModuleFromSelfNameReference(extensions, moduleName, containingDirectory, state, cache, redirectedReference); } if (!resolved) { - if (moduleName.indexOf(":") > -1) { + if (moduleName.includes(":")) { if (traceEnabled) { trace(host, Diagnostics.Skipping_module_0_that_looks_like_an_absolute_URI_target_file_types_Colon_1, moduleName, formatExtensions(extensions)); } @@ -1944,7 +1943,7 @@ function nodeLoadModuleByRelativeName(extensions: Extensions, candidate: string, export const nodeModulesPathPart = "/node_modules/"; /** @internal */ export function pathContainsNodeModules(path: string): boolean { - return stringContains(path, nodeModulesPathPart); + return path.includes(nodeModulesPathPart); } /** @@ -2006,7 +2005,7 @@ function loadModuleFromFile(extensions: Extensions, candidate: string, onlyRecor function loadModuleFromFileNoImplicitExtensions(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined { const filename = getBaseFileName(candidate); - if (filename.indexOf(".") === -1) { + if (!filename.includes(".")) { return undefined; // extensionless import, no lookups performed, since we don't support extensionless files } let extensionless = removeFileExtension(candidate); @@ -2223,7 +2222,7 @@ function loadEntrypointsFromExportMap( function loadEntrypointsFromTargetExports(target: unknown): boolean | undefined { if (typeof target === "string" && startsWith(target, "./")) { - if (target.indexOf("*") >= 0 && state.host.readDirectory) { + if (target.includes("*") && state.host.readDirectory) { if (target.indexOf("*") !== target.lastIndexOf("*")) { return false; } @@ -2243,7 +2242,7 @@ function loadEntrypointsFromExportMap( } else { const partsAfterFirst = getPathComponents(target).slice(2); - if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) { + if (partsAfterFirst.includes("..") || partsAfterFirst.includes(".") || partsAfterFirst.includes("node_modules")) { return false; } const resolvedTarget = combinePaths(scope.packageDirectory, target); @@ -2609,11 +2608,11 @@ export function comparePatternKeys(a: string, b: string) { function loadModuleFromImportsOrExports(extensions: Extensions, state: ModuleResolutionState, cache: ModuleResolutionCache | undefined, redirectedReference: ResolvedProjectReference | undefined, moduleName: string, lookupTable: object, scope: PackageJsonInfo, isImports: boolean): SearchResult | undefined { const loadModuleFromTargetImportOrExport = getLoadModuleFromTargetImportOrExport(extensions, state, cache, redirectedReference, moduleName, scope, isImports); - if (!endsWith(moduleName, directorySeparator) && moduleName.indexOf("*") === -1 && hasProperty(lookupTable, moduleName)) { + if (!endsWith(moduleName, directorySeparator) && !moduleName.includes("*") && hasProperty(lookupTable, moduleName)) { const target = (lookupTable as { [idx: string]: unknown; })[moduleName]; return loadModuleFromTargetImportOrExport(target, /*subpath*/ "", /*pattern*/ false, moduleName); } - const expandingKeys = sort(filter(getOwnKeys(lookupTable as MapLike), k => k.indexOf("*") !== -1 || endsWith(k, "/")), comparePatternKeys); + const expandingKeys = sort(filter(getOwnKeys(lookupTable as MapLike), k => k.includes("*") || endsWith(k, "/")), comparePatternKeys); for (const potentialTarget of expandingKeys) { if (state.features & NodeResolutionFeatures.ExportsPatternTrailers && matchesPatternWithTrailer(potentialTarget, moduleName)) { const target = (lookupTable as { [idx: string]: unknown; })[potentialTarget]; @@ -2677,7 +2676,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo } const parts = pathIsRelative(target) ? getPathComponents(target).slice(1) : getPathComponents(target); const partsAfterFirst = parts.slice(1); - if (partsAfterFirst.indexOf("..") >= 0 || partsAfterFirst.indexOf(".") >= 0 || partsAfterFirst.indexOf("node_modules") >= 0) { + if (partsAfterFirst.includes("..") || partsAfterFirst.includes(".") || partsAfterFirst.includes("node_modules")) { if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); } @@ -2687,7 +2686,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo // TODO: Assert that `resolvedTarget` is actually within the package directory? That's what the spec says.... but I'm not sure we need // to be in the business of validating everyone's import and export map correctness. const subpathParts = getPathComponents(subpath); - if (subpathParts.indexOf("..") >= 0 || subpathParts.indexOf(".") >= 0 || subpathParts.indexOf("node_modules") >= 0) { + if (subpathParts.includes("..") || subpathParts.includes(".") || subpathParts.includes("node_modules")) { if (state.traceEnabled) { trace(state.host, Diagnostics.package_json_scope_0_has_invalid_type_for_target_of_specifier_1, scope.packageDirectory, moduleName); } @@ -2706,7 +2705,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo if (!Array.isArray(target)) { traceIfEnabled(state, Diagnostics.Entering_conditional_exports); for (const condition of getOwnKeys(target as MapLike)) { - if (condition === "default" || state.conditions.indexOf(condition) >= 0 || isApplicableVersionedTypesKey(state.conditions, condition)) { + 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 as MapLike)[condition]; const result = loadModuleFromTargetImportOrExport(subTarget, subpath, pattern, key); @@ -2772,7 +2771,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo if ( !state.isConfigLookup && (state.compilerOptions.declarationDir || state.compilerOptions.outDir) - && finalPath.indexOf("/node_modules/") === -1 + && !finalPath.includes("/node_modules/") && (state.compilerOptions.configFile ? containsPath(scope.packageDirectory, toAbsolutePath(state.compilerOptions.configFile.fileName), !useCaseSensitiveFileNames(state)) : true) ) { // So that all means we'll only try these guesses for files outside `node_modules` in a directory where the `package.json` and `tsconfig.json` are siblings. @@ -2876,7 +2875,7 @@ function getLoadModuleFromTargetImportOrExport(extensions: Extensions, state: Mo /** @internal */ export function isApplicableVersionedTypesKey(conditions: readonly string[], key: string) { - if (conditions.indexOf("types") === -1) return false; // only apply versioned types conditions if the types condition is applied + if (!conditions.includes("types")) return false; // only apply versioned types conditions if the types condition is applied if (!startsWith(key, "types@")) return false; const range = VersionRange.tryParse(key.substring("types@".length)); if (!range) return false; @@ -3099,7 +3098,7 @@ export function getPackageNameFromTypesPackageName(mangledName: string): string /** @internal */ export function unmangleScopedPackageName(typesPackageName: string): string { - return stringContains(typesPackageName, mangledScopedPackageSeparator) ? + return typesPackageName.includes(mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, directorySeparator) : typesPackageName; } diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts index cec0585ca36..2a59e6c5be8 100644 --- a/src/compiler/moduleSpecifiers.ts +++ b/src/compiler/moduleSpecifiers.ts @@ -101,7 +101,6 @@ import { SourceFile, startsWith, startsWithDirectory, - stringContains, StringLiteral, Symbol, SymbolFlags, @@ -866,7 +865,7 @@ function tryGetModuleNameFromExports(options: CompilerOptions, targetFilePath: s return forEach(getOwnKeys(exports as MapLike), k => { const subPackageName = getNormalizedAbsolutePath(combinePaths(packageName, k), /*currentDirectory*/ undefined); const mode = endsWith(k, "/") ? MatchingMode.Directory - : stringContains(k, "*") ? MatchingMode.Pattern + : k.includes("*") ? MatchingMode.Pattern : MatchingMode.Exact; return tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, subPackageName, (exports as MapLike)[k], conditions, mode); }); @@ -874,7 +873,7 @@ function tryGetModuleNameFromExports(options: CompilerOptions, targetFilePath: s else { // conditional mapping for (const key of getOwnKeys(exports as MapLike)) { - if (key === "default" || conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(conditions, key)) { + if (key === "default" || conditions.includes(key) || isApplicableVersionedTypesKey(conditions, key)) { const subTarget = (exports as MapLike)[key]; const result = tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, subTarget, conditions, mode); if (result) { @@ -1093,7 +1092,7 @@ function processEnding(fileName: string, allowedEndings: readonly ModuleSpecifie else if (fileExtensionIsOneOf(fileName, [Extension.Dmts, Extension.Mts, Extension.Dcts, Extension.Cts])) { return noExtension + getJSExtensionForFile(fileName, options); } - else if (!fileExtensionIsOneOf(fileName, [Extension.Dts]) && fileExtensionIsOneOf(fileName, [Extension.Ts]) && stringContains(fileName, ".d.")) { + else if (!fileExtensionIsOneOf(fileName, [Extension.Dts]) && fileExtensionIsOneOf(fileName, [Extension.Ts]) && fileName.includes(".d.")) { // `foo.d.json.ts` and the like - remap back to `foo.json` return tryGetRealFileNameForNonJsDeclarationFileName(fileName)!; } @@ -1129,7 +1128,7 @@ function processEnding(fileName: string, allowedEndings: readonly ModuleSpecifie /** @internal */ export function tryGetRealFileNameForNonJsDeclarationFileName(fileName: string) { const baseName = getBaseFileName(fileName); - if (!endsWith(fileName, Extension.Ts) || !stringContains(baseName, ".d.") || fileExtensionIsOneOf(baseName, [Extension.Dts])) return undefined; + if (!endsWith(fileName, Extension.Ts) || !baseName.includes(".d.") || fileExtensionIsOneOf(baseName, [Extension.Dts])) return undefined; const noExtension = removeExtension(fileName, Extension.Ts); const ext = noExtension.substring(noExtension.lastIndexOf(".")); return noExtension.substring(0, noExtension.indexOf(".d.")) + ext; diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 0e0b9a53b5d..ad0f132b4e5 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -338,7 +338,6 @@ import { SpreadElement, startsWith, Statement, - stringContains, StringLiteral, supportedDeclarationExtensions, SwitchStatement, @@ -10408,7 +10407,7 @@ namespace IncrementalParser { /** @internal */ export function isDeclarationFileName(fileName: string): boolean { - return fileExtensionIsOneOf(fileName, supportedDeclarationExtensions) || (fileExtensionIs(fileName, Extension.Ts) && stringContains(getBaseFileName(fileName), ".d.")); + return fileExtensionIsOneOf(fileName, supportedDeclarationExtensions) || (fileExtensionIs(fileName, Extension.Ts) && getBaseFileName(fileName).includes(".d.")); } function parseResolutionMode(mode: string | undefined, pos: number, end: number, reportDiagnostic: PragmaDiagnosticReporter): ResolutionMode { diff --git a/src/compiler/path.ts b/src/compiler/path.ts index c77fa141f07..685f2815890 100644 --- a/src/compiler/path.ts +++ b/src/compiler/path.ts @@ -15,7 +15,6 @@ import { Path, some, startsWith, - stringContains, } from "./_namespaces/ts"; /** @@ -113,7 +112,7 @@ export function pathIsBareSpecifier(path: string): boolean { /** @internal */ export function hasExtension(fileName: string): boolean { - return stringContains(getBaseFileName(fileName), "."); + return getBaseFileName(fileName).includes("."); } /** @internal */ @@ -524,7 +523,7 @@ export function getPathFromPathComponents(pathComponents: read * @internal */ export function normalizeSlashes(path: string): string { - return path.indexOf("\\") !== -1 + return path.includes("\\") ? path.replace(backslashRegExp, directorySeparator) : path; } diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 9e8af35bf4e..294a0e72007 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -304,7 +304,6 @@ import { stableSort, startsWith, Statement, - stringContains, StringLiteral, StringLiteralLike, StructureIsReused, @@ -2016,7 +2015,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg // but the resolved real path may be the .d.ts from project reference // Note:: Currently we try the real path only if the // file is from node_modules to avoid having to run real path on all file paths - if (!host.realpath || !options.preserveSymlinks || !stringContains(file.originalFileName, nodeModulesPathPart)) return undefined; + if (!host.realpath || !options.preserveSymlinks || !file.originalFileName.includes(nodeModulesPathPart)) return undefined; const realDeclarationPath = toPath(host.realpath(file.originalFileName)); return realDeclarationPath === file.path ? undefined : getRedirectReferenceForResolutionFromSourceOfProject(realDeclarationPath); } @@ -3565,7 +3564,7 @@ export function createProgram(rootNamesOrOptions: readonly string[] | CreateProg host.realpath && options.preserveSymlinks && isDeclarationFileName(fileName) && - stringContains(fileName, nodeModulesPathPart) + fileName.includes(nodeModulesPathPart) ) { const realPath = toPath(host.realpath(fileName)); if (realPath !== path) source = getSourceOfProjectReferenceRedirect(realPath); @@ -5090,7 +5089,7 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host: HostForUseSource if (!host.getResolvedProjectReferences() || containsIgnoredPath(directory)) return; // Because we already watch node_modules, handle symlinks in there - if (!originalRealpath || !stringContains(directory, nodeModulesPathPart)) return; + if (!originalRealpath || !directory.includes(nodeModulesPathPart)) return; const symlinkCache = host.getSymlinkCache(); const directoryPath = ensureTrailingDirectorySeparator(host.toPath(directory)); if (symlinkCache.getSymlinkedDirectories()?.has(directoryPath)) return; @@ -5124,7 +5123,7 @@ function updateHostForUseSourceOfProjectReferenceRedirect(host: HostForUseSource const symlinkedDirectories = symlinkCache.getSymlinkedDirectories(); if (!symlinkedDirectories) return false; const fileOrDirectoryPath = host.toPath(fileOrDirectory); - if (!stringContains(fileOrDirectoryPath, nodeModulesPathPart)) return false; + if (!fileOrDirectoryPath.includes(nodeModulesPathPart)) return false; if (isFile && symlinkCache.getSymlinkedFiles()?.has(fileOrDirectoryPath)) return true; // If it contains node_modules check if its one of the symlinked path we know of diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index fccc476dbfb..0c12c996c84 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -72,7 +72,6 @@ import { some, SourceFile, startsWith, - stringContains, StringLiteralLike, trace, updateResolutionField, @@ -219,7 +218,7 @@ export function removeIgnoredPath(path: Path): Path | undefined { return removeSuffix(path, "/.staging") as Path; } - return some(ignoredPaths, searchPath => stringContains(path, searchPath)) ? + return some(ignoredPaths, searchPath => path.includes(searchPath)) ? undefined : path; } diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 14e6f04b77a..d888a3d599b 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -39,7 +39,6 @@ import { resolveJSModule, some, startsWith, - stringContains, timestamp, unorderedRemoveItem, WatchDirectoryKind, @@ -814,9 +813,9 @@ function createDirectoryWatcherSupportingRecursive({ } function isInPath(path: string, searchPath: string) { - if (stringContains(path, searchPath)) return true; + if (path.includes(searchPath)) return true; if (useCaseSensitiveFileNames) return false; - return stringContains(toCanonicalFilePath(path), searchPath); + return toCanonicalFilePath(path).includes(searchPath); } } diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index 8fb87a7b281..048615abb1f 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -202,7 +202,6 @@ import { SourceFile, startsWith, Statement, - stringContains, StringLiteral, Symbol, SymbolAccessibility, @@ -241,7 +240,7 @@ export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver function hasInternalAnnotation(range: CommentRange, currentSourceFile: SourceFile) { const comment = currentSourceFile.text.substring(range.pos, range.end); - return stringContains(comment, "@internal"); + return comment.includes("@internal"); } /** @internal */ diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 02b2278e93b..bd5958feaf6 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -492,7 +492,6 @@ import { startsWith, startsWithUseStrict, Statement, - stringContains, StringLiteral, StringLiteralLike, StringLiteralType, @@ -802,7 +801,7 @@ export function createModuleNotFoundChain(sourceFile: SourceFile, host: TypeChec /*details*/ undefined, Diagnostics.There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The_1_library_may_need_to_update_its_package_json_or_typings, node10Result, - node10Result.indexOf(nodeModulesPathPart + "@types/") > -1 ? `@types/${mangleScopedPackageName(packageName)}` : packageName, + node10Result.includes(nodeModulesPathPart + "@types/") ? `@types/${mangleScopedPackageName(packageName)}` : packageName, ) : host.typesPackageExists(packageName) ? chainDiagnosticMessages( @@ -5986,7 +5985,7 @@ function isQuoteOrBacktick(charCode: number) { /** @internal */ export function isIntrinsicJsxName(name: __String | string) { const ch = (name as string).charCodeAt(0); - return (ch >= CharacterCodes.a && ch <= CharacterCodes.z) || stringContains(name as string, "-"); + return (ch >= CharacterCodes.a && ch <= CharacterCodes.z) || (name as string).includes("-"); } const indentStrings: string[] = ["", " "]; @@ -6007,7 +6006,7 @@ export function getIndentSize() { /** @internal */ export function isNightly() { - return stringContains(version, "-dev") || stringContains(version, "-insiders"); + return version.includes("-dev") || version.includes("-insiders"); } /** @internal */ @@ -6236,7 +6235,7 @@ export function getExternalModuleNameFromDeclaration(host: ResolveModuleNameReso const specifier = getExternalModuleName(declaration); if ( specifier && isStringLiteralLike(specifier) && !pathIsRelative(specifier.text) && - getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1 + !getCanonicalAbsolutePath(host, file.path).includes(getCanonicalAbsolutePath(host, ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) ) { return undefined; } @@ -9335,7 +9334,7 @@ export function getSupportedExtensions(options?: CompilerOptions, extraFileExten const flatBuiltins = flatten(builtins); const extensions = [ ...builtins, - ...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJSLike(x.scriptKind) && flatBuiltins.indexOf(x.extension as Extension) === -1 ? [x.extension] : undefined), + ...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJSLike(x.scriptKind) && !flatBuiltins.includes(x.extension as Extension) ? [x.extension] : undefined), ]; return extensions; @@ -10052,7 +10051,7 @@ export function expressionResultIsUnused(node: Expression): boolean { /** @internal */ export function containsIgnoredPath(path: string) { - return some(ignoredPaths, p => stringContains(path, p)); + return some(ignoredPaths, p => path.includes(p)); } /** @internal */ diff --git a/src/executeCommandLine/executeCommandLine.ts b/src/executeCommandLine/executeCommandLine.ts index 075cbae2c3b..8417f159442 100644 --- a/src/executeCommandLine/executeCommandLine.ts +++ b/src/executeCommandLine/executeCommandLine.ts @@ -77,7 +77,6 @@ import { SourceFile, startsWith, startTracing, - stringContains, supportedJSExtensionsFlat, supportedTSExtensionsFlat, sys, @@ -193,7 +192,7 @@ function createColors(sys: System) { return `\x1b[1m${str}\x1b[22m`; } - const isWindows = sys.getEnvironmentVariable("OS") && stringContains(sys.getEnvironmentVariable("OS").toLowerCase(), "windows"); + const isWindows = sys.getEnvironmentVariable("OS") && sys.getEnvironmentVariable("OS").toLowerCase().includes("windows"); const isWindowsTerminal = sys.getEnvironmentVariable("WT_SESSION"); const isVSCode = sys.getEnvironmentVariable("TERM_PROGRAM") && sys.getEnvironmentVariable("TERM_PROGRAM") === "vscode"; diff --git a/src/harness/compilerImpl.ts b/src/harness/compilerImpl.ts index 1a37603da1e..370f09bcf69 100644 --- a/src/harness/compilerImpl.ts +++ b/src/harness/compilerImpl.ts @@ -213,7 +213,7 @@ export class CompilationResult { } else { path = vpath.resolve(this.vfs.cwd(), path); - const outDir = ext === ".d.ts" || ext === ".d.mts" || ext === ".d.cts" || (ext.endsWith(".ts") || ts.stringContains(ext, ".d.")) ? this.options.declarationDir || this.options.outDir : this.options.outDir; + const outDir = ext === ".d.ts" || ext === ".d.mts" || ext === ".d.cts" || (ext.endsWith(".ts") || ext.includes(".d.")) ? this.options.declarationDir || this.options.outDir : this.options.outDir; if (outDir) { const common = this.commonSourceDirectory; if (common) { diff --git a/src/harness/fourslashImpl.ts b/src/harness/fourslashImpl.ts index 4ff4e17e664..8f9a5e5738f 100644 --- a/src/harness/fourslashImpl.ts +++ b/src/harness/fourslashImpl.ts @@ -440,7 +440,7 @@ export class TestState { const keys = ts.getAllKeys(ls); for (const k of keys) { const key = k as keyof typeof ls; - if (cacheableMembers.indexOf(key) === -1) { + if (!cacheableMembers.includes(key)) { proxy[key] = (...args: any[]) => (ls[key] as (...args: any[]) => any)(...args); continue; } @@ -4321,7 +4321,7 @@ export class TestState { private tryFindFileWorker(name: string): { readonly file: FourSlashFile | undefined; readonly availableNames: readonly string[]; } { name = ts.normalizePath(name); // names are stored in the compiler with this relative path, this allows people to use goTo.file on just the fileName - name = name.indexOf("/") === -1 ? (this.basePath + "/" + name) : name; + name = name.includes("/") ? name : (this.basePath + "/" + name); const availableNames: string[] = []; const file = ts.forEach(this.testData.files, file => { @@ -4905,7 +4905,7 @@ function parseFileContent(content: string, fileName: string, markerMap: Map -1 && referencedExtensions.indexOf(".d.ts") === -1) { + if (extension === ".ts" || referencedExtensions && referencedExtensions.includes(".ts") && !referencedExtensions.includes(".d.ts")) { // special-case and filter .d.ts out of .ts results existing = existing.filter(f => !ts.endsWith(f, ".d.ts")); } diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index 96db9786a56..1fed0e38ef4 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -846,7 +846,7 @@ class SessionServerHost implements ts.server.ServerHost, ts.server.Logger { } readFile(fileName: string): string | undefined { - if (ts.stringContains(fileName, Compiler.defaultLibFileName)) { + if (fileName.includes(Compiler.defaultLibFileName)) { fileName = Compiler.defaultLibFileName; } diff --git a/src/harness/harnessUtils.ts b/src/harness/harnessUtils.ts index 95c6068ab07..752e52bdba9 100644 --- a/src/harness/harnessUtils.ts +++ b/src/harness/harnessUtils.ts @@ -33,7 +33,7 @@ export function splitContentByNewlines(content: string) { /** Reads a file under /tests */ export function readTestFile(path: string) { - if (path.indexOf("tests") < 0) { + if (!path.includes("tests")) { path = "tests/" + path; } @@ -138,7 +138,7 @@ export function assertInvariants(node: ts.Node | undefined, parent: ts.Node | un } const child = (node as any)[childName]; if (isNodeOrArray(child)) { - assert.isFalse(childNodesAndArrays.indexOf(child) < 0, "Missing child when forEach'ing over node: " + ts.Debug.formatSyntaxKind(node.kind) + "-" + childName); + assert.isFalse(!childNodesAndArrays.includes(child), "Missing child when forEach'ing over node: " + ts.Debug.formatSyntaxKind(node.kind) + "-" + childName); } } } diff --git a/src/harness/vpathUtil.ts b/src/harness/vpathUtil.ts index 0e84144cf09..9b9d5e79fdf 100644 --- a/src/harness/vpathUtil.ts +++ b/src/harness/vpathUtil.ts @@ -133,5 +133,5 @@ export function isDefaultLibrary(path: string) { } export function isTsConfigFile(path: string): boolean { - return path.indexOf("tsconfig") !== -1 && path.indexOf("json") !== -1; + return path.includes("tsconfig") && path.includes("json"); } diff --git a/src/jsTyping/shared.ts b/src/jsTyping/shared.ts index 5ae0e09354c..3330d12afb1 100644 --- a/src/jsTyping/shared.ts +++ b/src/jsTyping/shared.ts @@ -49,7 +49,7 @@ export namespace Arguments { /** @internal */ export function hasArgument(argumentName: string) { - return sys.args.indexOf(argumentName) >= 0; + return sys.args.includes(argumentName); } /** @internal */ diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 158e08f25d3..ab02f3548d4 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -4093,7 +4093,7 @@ export class ProjectService { for (const type of rule.types) { // Best-effort de-duping here - doesn't need to be unduplicated but // we don't want the list to become a 400-element array of just 'kendo' - if (typeAcqInclude.indexOf(type) < 0) { + if (!typeAcqInclude.includes(type)) { typeAcqInclude.push(type); } } @@ -4118,7 +4118,7 @@ export class ProjectService { }).join(""); }); - if (excludeRules.indexOf(processedRule) === -1) { + if (!excludeRules.includes(processedRule)) { excludeRules.push(processedRule); } } @@ -4126,7 +4126,7 @@ export class ProjectService { else { // If not rules listed, add the default rule to exclude the matched file const escaped = ProjectService.escapeFilenameForRegex(root); - if (excludeRules.indexOf(escaped) < 0) { + if (!excludeRules.includes(escaped)) { excludeRules.push(escaped); } } @@ -4155,7 +4155,7 @@ export class ProjectService { exclude = true; // ... but *include* it in the list of types to acquire // Same best-effort dedupe as above - if (typeAcqInclude.indexOf(typeName) < 0) { + if (!typeAcqInclude.includes(typeName)) { typeAcqInclude.push(typeName); } } diff --git a/src/server/project.ts b/src/server/project.ts index 97451f224c7..8df08a36cd7 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -1503,7 +1503,7 @@ export abstract class Project implements LanguageServiceHost, ModuleResolutionHo protected removeExistingTypings(include: string[]): string[] { const existing = getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost); - return include.filter(i => existing.indexOf(i) < 0); + return include.filter(i => !existing.includes(i)); } private updateGraphWorker() { diff --git a/src/server/scriptInfo.ts b/src/server/scriptInfo.ts index 57a9d06c911..ca9f11d2e61 100644 --- a/src/server/scriptInfo.ts +++ b/src/server/scriptInfo.ts @@ -31,7 +31,6 @@ import { some, SourceFile, SourceFileLike, - stringContains, TextSpan, unorderedRemoveItem, } from "./_namespaces/ts"; @@ -339,9 +338,9 @@ export class TextStorage { export function isDynamicFileName(fileName: NormalizedPath) { return fileName[0] === "^" || - ((stringContains(fileName, "walkThroughSnippet:/") || stringContains(fileName, "untitled:/")) && + ((fileName.includes("walkThroughSnippet:/") || fileName.includes("untitled:/")) && getBaseFileName(fileName)[0] === "^") || - (stringContains(fileName, ":^") && !stringContains(fileName, directorySeparator)); + (fileName.includes(":^") && !fileName.includes(directorySeparator)); } /** @internal */ diff --git a/src/server/session.ts b/src/server/session.ts index 5a95d12e26d..39a57df5ebf 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -124,7 +124,6 @@ import { some, SourceFile, startsWith, - stringContains, SymbolDisplayPart, SyntaxKind, TextChange, @@ -2960,7 +2959,7 @@ export class Session implements EventSender { } // No need to analyze lib.d.ts - const fileNamesInProject = fileNames!.filter(value => !stringContains(value, "lib.d.ts")); // TODO: GH#18217 + const fileNamesInProject = fileNames!.filter(value => !value.includes("lib.d.ts")); // TODO: GH#18217 if (fileNamesInProject.length === 0) { return; } diff --git a/src/services/codefixes/fixUnusedIdentifier.ts b/src/services/codefixes/fixUnusedIdentifier.ts index 494721afb5c..44f7dec2607 100644 --- a/src/services/codefixes/fixUnusedIdentifier.ts +++ b/src/services/codefixes/fixUnusedIdentifier.ts @@ -415,7 +415,7 @@ function mayDeleteParameter(checker: TypeChecker, sourceFile: SourceFile, parame } function isCallbackLike(checker: TypeChecker, sourceFile: SourceFile, name: Identifier): boolean { - return !!FindAllReferences.Core.eachSymbolReferenceInFile(name, checker, sourceFile, reference => isIdentifier(reference) && isCallExpression(reference.parent) && reference.parent.arguments.indexOf(reference) >= 0); + return !!FindAllReferences.Core.eachSymbolReferenceInFile(name, checker, sourceFile, reference => isIdentifier(reference) && isCallExpression(reference.parent) && reference.parent.arguments.includes(reference)); } function isLastParameter(func: FunctionLikeDeclaration, parameter: ParameterDeclaration, isFixAll: boolean): boolean { diff --git a/src/services/exportInfoMap.ts b/src/services/exportInfoMap.ts index 9a4d9cf1d2b..1b8cfe67f55 100644 --- a/src/services/exportInfoMap.ts +++ b/src/services/exportInfoMap.ts @@ -49,7 +49,6 @@ import { SourceFile, startsWith, Statement, - stringContains, stripQuotes, Symbol, SymbolFlags, @@ -443,7 +442,7 @@ export function forEachExternalModuleToImportFrom( function forEachExternalModule(checker: TypeChecker, allSourceFiles: readonly SourceFile[], excludePatterns: readonly RegExp[] | undefined, cb: (module: Symbol, sourceFile: SourceFile | undefined) => void) { const isExcluded = excludePatterns && ((fileName: string) => excludePatterns.some(p => p.test(fileName))); for (const ambient of checker.getAmbientModules()) { - if (!stringContains(ambient.name, "*") && !(excludePatterns && ambient.declarations?.every(d => isExcluded!(d.getSourceFile().fileName)))) { + if (!ambient.name.includes("*") && !(excludePatterns && ambient.declarations?.every(d => isExcluded!(d.getSourceFile().fileName)))) { cb(ambient, /*sourceFile*/ undefined); } } diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts index f57de9336d9..98b8be1fe8c 100644 --- a/src/services/formatting/rules.ts +++ b/src/services/formatting/rules.ts @@ -971,5 +971,5 @@ function isSemicolonInsertionContext(context: FormattingContext): boolean { function isNotPropertyAccessOnIntegerLiteral(context: FormattingContext): boolean { return !isPropertyAccessExpression(context.contextNode) || !isNumericLiteral(context.contextNode.expression) - || context.contextNode.expression.getText().indexOf(".") !== -1; + || context.contextNode.expression.getText().includes("."); } diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index d2468b1b2e1..da411914dff 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -150,7 +150,7 @@ export namespace SmartIndenter { const containerList = getListByPosition(position, precedingToken.parent, sourceFile); // use list position if the preceding token is before any list items if (containerList && !rangeContainsRange(containerList, precedingToken)) { - const useTheSameBaseIndentation = [SyntaxKind.FunctionExpression, SyntaxKind.ArrowFunction].indexOf(currentToken.parent.kind) !== -1; + const useTheSameBaseIndentation = [SyntaxKind.FunctionExpression, SyntaxKind.ArrowFunction].includes(currentToken.parent.kind); const indentSize = useTheSameBaseIndentation ? 0 : options.indentSize!; return getActualIndentationForListStartLine(containerList, sourceFile, options) + indentSize; // TODO: GH#18217 } diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 906ddefbcd1..f25098e2c06 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -2128,7 +2128,7 @@ function collectReadsAndWrites( function checkForUsedDeclarations(node: Node) { // If this node is entirely within the original extraction range, we don't need to do anything. - if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.indexOf(node as Statement) >= 0)) { + if (node === targetRange.range || (isReadonlyArray(targetRange.range) && targetRange.range.includes(node as Statement))) { return; } diff --git a/src/services/services.ts b/src/services/services.ts index efb12ce4b77..44d93e544d0 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -283,7 +283,6 @@ import { SourceMapSource, startsWith, Statement, - stringContains, StringLiteral, StringLiteralLike, StringLiteralType, @@ -2959,7 +2958,7 @@ export function createLanguageService( } function isNodeModulesFile(path: string): boolean { - return stringContains(path, "/node_modules/"); + return path.includes("/node_modules/"); } } diff --git a/src/services/stringCompletions.ts b/src/services/stringCompletions.ts index 657f104418f..76326ad5ed9 100644 --- a/src/services/stringCompletions.ts +++ b/src/services/stringCompletions.ts @@ -125,7 +125,6 @@ import { skipParentheses, SourceFile, startsWith, - stringContains, StringLiteralLike, StringLiteralType, stripQuotes, @@ -572,7 +571,7 @@ function directoryResult(name: string): NameAndKind { function addReplacementSpans(text: string, textStart: number, names: readonly NameAndKind[]): readonly PathCompletion[] { const span = getDirectoryFragmentTextSpan(text, textStart); const wholeSpan = text.length === 0 ? undefined : createTextSpan(textStart, text.length); - return names.map(({ name, kind, extension }): PathCompletion => Math.max(name.indexOf(directorySeparator), name.indexOf(altDirectorySeparator)) !== -1 ? { name, kind, extension, span: wholeSpan } : { name, kind, extension, span }); + return names.map(({ name, kind, extension }): PathCompletion => (name.includes(directorySeparator) || name.includes(altDirectorySeparator)) ? { name, kind, extension, span: wholeSpan } : { name, kind, extension, span }); } function getStringLiteralCompletionsFromModuleNames(sourceFile: SourceFile, node: LiteralExpression, compilerOptions: CompilerOptions, host: LanguageServiceHost, typeChecker: TypeChecker, preferences: UserPreferences): readonly PathCompletion[] { @@ -979,7 +978,7 @@ function getPatternFromFirstMatchingCondition(target: unknown, conditions: reado } if (target && typeof target === "object" && !isArray(target)) { for (const condition in target) { - if (condition === "default" || conditions.indexOf(condition) > -1 || isApplicableVersionedTypesKey(conditions, condition)) { + if (condition === "default" || conditions.includes(condition) || isApplicableVersionedTypesKey(conditions, condition)) { const pattern = (target as MapLike)[condition]; return getPatternFromFirstMatchingCondition(pattern, conditions); } @@ -1001,7 +1000,7 @@ function getCompletionsForPathMapping( ): readonly NameAndKind[] { if (!endsWith(path, "*")) { // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. - return !stringContains(path, "*") ? justPathMappingName(path, ScriptElementKind.scriptElement) : emptyArray; + return !path.includes("*") ? justPathMappingName(path, ScriptElementKind.scriptElement) : emptyArray; } const pathPrefix = path.slice(0, path.length - 1); @@ -1102,7 +1101,7 @@ function removeLeadingDirectorySeparator(path: string): string { function getAmbientModuleCompletions(fragment: string, fragmentDirectory: string | undefined, checker: TypeChecker): readonly string[] { // Get modules that the type checker picked up const ambientModules = checker.getAmbientModules().map(sym => stripQuotes(sym.name)); - const nonRelativeModuleNames = ambientModules.filter(moduleName => startsWith(moduleName, fragment) && moduleName.indexOf("*") < 0); + const nonRelativeModuleNames = ambientModules.filter(moduleName => startsWith(moduleName, fragment) && !moduleName.includes("*")); // Nested modules of the form "module-name/sub" need to be adjusted to only return the string // after the last '/' that appears in the fragment because that's where the replacement span @@ -1233,7 +1232,7 @@ const tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*= 0) { + if (this.fileName.includes("APISample")) { return; } diff --git a/src/testRunner/runner.ts b/src/testRunner/runner.ts index 396c9da080b..4c8151d4c36 100644 --- a/src/testRunner/runner.ts +++ b/src/testRunner/runner.ts @@ -161,7 +161,7 @@ function handleTestConfig() { const runnerConfig = testConfig.runners || testConfig.test; if (runnerConfig && runnerConfig.length > 0) { if (testConfig.runners) { - runUnitTests = runnerConfig.indexOf("unittest") !== -1; + runUnitTests = runnerConfig.includes("unittest"); } for (const option of runnerConfig) { if (!option) { diff --git a/src/testRunner/unittests/helpers/vfs.ts b/src/testRunner/unittests/helpers/vfs.ts index e0f16f4adc1..31ef31e8b09 100644 --- a/src/testRunner/unittests/helpers/vfs.ts +++ b/src/testRunner/unittests/helpers/vfs.ts @@ -60,7 +60,7 @@ export function replaceText(fs: vfs.FileSystem, path: string, oldText: string, n throw new Error(`File ${path} does not exist`); } const old = fs.readFileSync(path, "utf-8"); - if (old.indexOf(oldText) < 0) { + if (!old.includes(oldText)) { throw new Error(`Text "${oldText}" does not exist in file ${path}`); } const newContent = old.replace(oldText, newText); diff --git a/src/testRunner/unittests/moduleResolution.ts b/src/testRunner/unittests/moduleResolution.ts index 332ecb96d22..1d349555399 100644 --- a/src/testRunner/unittests/moduleResolution.ts +++ b/src/testRunner/unittests/moduleResolution.ts @@ -63,7 +63,7 @@ function runBaseline(scenario: string, baselines: readonly string[]) { describe("unittests:: moduleResolution:: Node module resolution - relative paths", () => { // node module resolution does _not_ implicitly append these extensions to an extensionless path (though will still attempt to load them if explicitly) const nonImplicitExtensions = [ts.Extension.Mts, ts.Extension.Dmts, ts.Extension.Mjs, ts.Extension.Cts, ts.Extension.Dcts, ts.Extension.Cjs]; - const autoExtensions = ts.filter(ts.supportedTSExtensionsFlat, e => nonImplicitExtensions.indexOf(e) === -1); + const autoExtensions = ts.filter(ts.supportedTSExtensionsFlat, e => !nonImplicitExtensions.includes(e)); it("load as file", () => { const baselines: string[] = []; diff --git a/src/testRunner/unittests/tsbuild/graphOrdering.ts b/src/testRunner/unittests/tsbuild/graphOrdering.ts index 0adf5d3b269..26e87c266a6 100644 --- a/src/testRunner/unittests/tsbuild/graphOrdering.ts +++ b/src/testRunner/unittests/tsbuild/graphOrdering.ts @@ -59,7 +59,7 @@ describe("unittests:: tsbuild - graph-ordering", () => { if (!circular) { for (const dep of deps) { const child = getProjectFileName(dep[0]); - if (buildQueue.indexOf(child) < 0) continue; + if (!buildQueue.includes(child)) continue; const parent = getProjectFileName(dep[1]); assert.isAbove(buildQueue.indexOf(child), buildQueue.indexOf(parent), `Expecting child ${child} to be built after parent ${parent}`); } @@ -73,8 +73,8 @@ describe("unittests:: tsbuild - graph-ordering", () => { function writeProjects(fileSystem: vfs.FileSystem, projectNames: string[], deps: [string, string][]): string[] { const projFileNames: string[] = []; for (const dep of deps) { - if (projectNames.indexOf(dep[0]) < 0) throw new Error(`Invalid dependency - project ${dep[0]} does not exist`); - if (projectNames.indexOf(dep[1]) < 0) throw new Error(`Invalid dependency - project ${dep[1]} does not exist`); + if (!projectNames.includes(dep[0])) throw new Error(`Invalid dependency - project ${dep[0]} does not exist`); + if (!projectNames.includes(dep[1])) throw new Error(`Invalid dependency - project ${dep[1]} does not exist`); } for (const proj of projectNames) { fileSystem.mkdirpSync(`/project/${proj}`); diff --git a/src/testRunner/unittests/tsc/declarationEmit.ts b/src/testRunner/unittests/tsc/declarationEmit.ts index 87383cad99c..097f86d3080 100644 --- a/src/testRunner/unittests/tsc/declarationEmit.ts +++ b/src/testRunner/unittests/tsc/declarationEmit.ts @@ -1,4 +1,3 @@ -import * as ts from "../../_namespaces/ts"; import * as Utils from "../../_namespaces/Utils"; import { verifyTscWatch, @@ -131,7 +130,7 @@ describe("unittests:: tsc:: declarationEmit::", () => { { path: `/user/username/projects/myproject/plugin-one/node_modules/plugin-two`, symLink: `/user/username/projects/myproject/plugin-two` }, libFile, ], - changeCaseFileTestPath: str => ts.stringContains(str, "/plugin-two"), + changeCaseFileTestPath: str => str.includes("/plugin-two"), }); verifyDeclarationEmit({ @@ -161,7 +160,7 @@ ${pluginOneAction()}`, { path: `/user/username/projects/myproject/plugin-one/node_modules/plugin-two`, symLink: `/temp/yarn/data/link/plugin-two` }, libFile, ], - changeCaseFileTestPath: str => ts.stringContains(str, "/plugin-two"), + changeCaseFileTestPath: str => str.includes("/plugin-two"), }); }); @@ -254,6 +253,6 @@ ${pluginOneAction()}`, }, libFile, ], - changeCaseFileTestPath: str => ts.stringContains(str, "/pkg1"), + changeCaseFileTestPath: str => str.includes("/pkg1"), }); }); diff --git a/src/testRunner/unittests/tscWatch/resolutionCache.ts b/src/testRunner/unittests/tscWatch/resolutionCache.ts index 0ab9c2bbf0c..854f294a758 100644 --- a/src/testRunner/unittests/tscWatch/resolutionCache.ts +++ b/src/testRunner/unittests/tscWatch/resolutionCache.ts @@ -69,7 +69,7 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution return false; } fileExistsIsCalled = true; - assert.isTrue(fileName.indexOf("/f2.") !== -1); + assert.isTrue(fileName.includes("/f2.")); return originalFileExists.call(host, fileName); }; sys.writeFile(root.path, `import {x} from "f2"`); @@ -88,7 +88,7 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution return false; } fileExistsIsCalled = true; - assert.isTrue(fileName.indexOf("/f1.") !== -1); + assert.isTrue(fileName.includes("/f1.")); return originalFileExists.call(host, fileName); }; sys.writeFile(root.path, `import {x} from "f1"`); @@ -129,7 +129,7 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution return false; } if (!fileExistsCalledForBar) { - fileExistsCalledForBar = fileName.indexOf("/bar.") !== -1; + fileExistsCalledForBar = fileName.includes("/bar."); } return originalFileExists.call(host, fileName); @@ -187,7 +187,7 @@ describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution return false; } if (!fileExistsCalledForBar) { - fileExistsCalledForBar = fileName.indexOf("/bar.") !== -1; + fileExistsCalledForBar = fileName.includes("/bar."); } return originalFileExists.call(host, fileName); }; diff --git a/src/testRunner/unittests/tsserver/typingsInstaller.ts b/src/testRunner/unittests/tsserver/typingsInstaller.ts index 1befbe4b6f1..8abd6474a9f 100644 --- a/src/testRunner/unittests/tsserver/typingsInstaller.ts +++ b/src/testRunner/unittests/tsserver/typingsInstaller.ts @@ -717,7 +717,7 @@ describe("unittests:: tsserver:: typingsInstaller:: General functionality", () = logger, (installer, requestId, packageNames, cb) => { let typingFiles: (File & { typings: string; })[] = []; - if (packageNames.indexOf(ts.server.typingsInstaller.typingsName("commander")) >= 0) { + if (packageNames.includes(ts.server.typingsInstaller.typingsName("commander"))) { typingFiles = [commander, jquery, lodash, cordova]; } else { @@ -1243,7 +1243,7 @@ describe("unittests:: tsserver:: typingsInstaller:: General functionality", () = logger, (installer, requestId, packageNames, cb) => { let typingFiles: (File & { typings: string; })[] = []; - if (packageNames.indexOf(ts.server.typingsInstaller.typingsName("commander")) >= 0) { + if (packageNames.includes(ts.server.typingsInstaller.typingsName("commander"))) { typingFiles = [commander]; } else { diff --git a/src/typingsInstaller/nodeTypingsInstaller.ts b/src/typingsInstaller/nodeTypingsInstaller.ts index 841e106ef92..fcf8b61cf5b 100644 --- a/src/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/typingsInstaller/nodeTypingsInstaller.ts @@ -10,7 +10,6 @@ import { MapLike, normalizePath, normalizeSlashes, - stringContains, sys, toPath, version, @@ -123,7 +122,7 @@ export class NodeTypingsInstaller extends TypingsInstaller { this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0], validateDefaultNpmLocation, this.installTypingHost); // If the NPM path contains spaces and isn't wrapped in quotes, do so. - if (stringContains(this.npmPath, " ") && this.npmPath[0] !== `"`) { + if (this.npmPath.includes(" ") && this.npmPath[0] !== `"`) { this.npmPath = `"${this.npmPath}"`; } if (this.log.isEnabled()) {