diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 587f7eb4837..d30387e43da 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -680,9 +680,9 @@ namespace ts { function emitTextWriterWrapper(underlying: SymbolWriter): EmitTextWriter { return { - write: ts.noop, - writeTextOfNode: ts.noop, - writeLine: ts.noop, + write: noop, + writeTextOfNode: noop, + writeLine: noop, increaseIndent() { return underlying.increaseIndent(); }, @@ -692,7 +692,7 @@ namespace ts { getText() { return ""; }, - rawWrite: ts.noop, + rawWrite: noop, writeLiteral(s) { return underlying.writeStringLiteral(s); }, @@ -3449,7 +3449,7 @@ namespace ts { // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols. endOfChain || // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.) - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && + !(!parentSymbol && forEach(symbol.declarations, hasExternalModuleSymbol)) && // If a parent symbol is an anonymous type, don't write it. !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral))) { @@ -16308,7 +16308,7 @@ namespace ts { function isValidPropertyAccessForCompletions(node: PropertyAccessExpression, type: Type, property: Symbol): boolean { return isValidPropertyAccessWithType(node, node.expression, property.escapedName, type) - && (!(property.flags & ts.SymbolFlags.Method) || isValidMethodAccess(property, type)); + && (!(property.flags & SymbolFlags.Method) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method: Symbol, type: Type) { const propType = getTypeOfFuncClassEnumModule(method); diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 89e6961e455..feb605551d6 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -1739,7 +1739,7 @@ namespace ts { function getExtendedConfig( sourceFile: JsonSourceFile, extendedConfigPath: string, - host: ts.ParseConfigHost, + host: ParseConfigHost, basePath: string, resolutionStack: string[], errors: Push, @@ -2115,7 +2115,7 @@ namespace ts { } } - function specToDiagnostic(spec: string, allowTrailingRecursion: boolean): ts.DiagnosticMessage | undefined { + function specToDiagnostic(spec: string, allowTrailingRecursion: boolean): DiagnosticMessage | undefined { if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) { return Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0; } @@ -2142,7 +2142,7 @@ namespace ts { // /a/b/a?z - Watch /a/b directly to catch any new file matching a?z const rawExcludeRegex = getRegularExpressionForWildcard(exclude, path, "exclude"); const excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i"); - const wildcardDirectories: ts.MapLike = {}; + const wildcardDirectories: MapLike = {}; if (include !== undefined) { const recursiveKeys: string[] = []; for (const file of include) { @@ -2256,8 +2256,8 @@ namespace ts { * Also converts enum values back to strings. */ /* @internal */ - export function convertCompilerOptionsForTelemetry(opts: ts.CompilerOptions): ts.CompilerOptions { - const out: ts.CompilerOptions = {}; + export function convertCompilerOptionsForTelemetry(opts: CompilerOptions): CompilerOptions { + const out: CompilerOptions = {}; for (const key in opts) { if (opts.hasOwnProperty(key)) { const type = getOptionFromName(key); @@ -2281,9 +2281,9 @@ namespace ts { return typeof value === "boolean" ? value : ""; case "list": const elementType = (option as CommandLineOptionOfListType).element; - return ts.isArray(value) ? value.map(v => getOptionValueWithEmptyStrings(v, elementType)) : ""; + return isArray(value) ? value.map(v => getOptionValueWithEmptyStrings(v, elementType)) : ""; default: - return ts.forEachEntry(option.type, (optionEnumValue, optionStringValue) => { + return forEachEntry(option.type, (optionEnumValue, optionStringValue) => { if (optionEnumValue === value) { return optionStringValue; } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index ecf667237c5..c3bfe55b40b 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -2618,7 +2618,7 @@ namespace ts { // Iterate over each include base path and include unique base paths that are not a // subpath of an existing base path for (const includeBasePath of includeBasePaths) { - if (ts.every(basePaths, basePath => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames))) { + if (every(basePaths, basePath => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames))) { basePaths.push(includeBasePath); } } diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index de59e640192..534f44cfb7a 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -161,7 +161,7 @@ namespace ts { } let typeRoots: string[]; - forEachAncestorDirectory(ts.normalizePath(currentDirectory), directory => { + forEachAncestorDirectory(normalizePath(currentDirectory), directory => { const atTypes = combinePaths(directory, nodeModulesAtTypes); if (host.directoryExists(atTypes)) { (typeRoots || (typeRoots = [])).push(atTypes); @@ -729,7 +729,7 @@ namespace ts { /* @internal */ export function resolveJavaScriptModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string { const { resolvedModule, failedLookupLocations } = - nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); + nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); if (!resolvedModule) { throw new Error(`Could not resolve JS module '${moduleName}' starting at '${initialDir}'. Looked in: ${failedLookupLocations.join(", ")}`); } @@ -1172,7 +1172,7 @@ namespace ts { /* @internal */ export function getMangledNameForScopedPackage(packageName: string): string { if (startsWith(packageName, "@")) { - const replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator); + const replaceSlash = packageName.replace(directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { return replaceSlash.slice(1); // Take off the "@" } @@ -1192,7 +1192,7 @@ namespace ts { /* @internal */ export function getUnmangledNameForScopedPackage(typesPackageName: string): string { return stringContains(typesPackageName, mangledScopedPackageSeparator) ? - "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + "@" + typesPackageName.replace(mangledScopedPackageSeparator, directorySeparator) : typesPackageName; } diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index b350af01bb0..13c00867372 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -5927,7 +5927,7 @@ namespace ts { return finishNode(node); } - function parseImportEqualsDeclaration(node: ImportEqualsDeclaration, identifier: ts.Identifier): ImportEqualsDeclaration { + function parseImportEqualsDeclaration(node: ImportEqualsDeclaration, identifier: Identifier): ImportEqualsDeclaration { node.kind = SyntaxKind.ImportEqualsDeclaration; node.name = identifier; parseExpected(SyntaxKind.EqualsToken); diff --git a/src/compiler/sourcemap.ts b/src/compiler/sourcemap.ts index 2dabb97b08d..f6ad5e5c52f 100644 --- a/src/compiler/sourcemap.ts +++ b/src/compiler/sourcemap.ts @@ -159,7 +159,7 @@ namespace ts { // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the // relative paths of the sources list in the sourcemap - sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); + sourceMapData.sourceMapSourceRoot = normalizeSlashes(sourceMapData.sourceMapSourceRoot); if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== CharacterCodes.slash) { sourceMapData.sourceMapSourceRoot += directorySeparator; } diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 8cafd8c0138..c0159797efe 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -212,7 +212,7 @@ namespace ts { // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined" const fileName = !isString(relativeFileName) ? undefined - : ts.getNormalizedAbsolutePath(relativeFileName, baseDirPath); + : getNormalizedAbsolutePath(relativeFileName, baseDirPath); // Some applications save a working file via rename operations if ((eventName === "change" || eventName === "rename")) { const callbacks = fileWatcherCallbacks.get(fileName); diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts index 15e4867d7f7..245d5c2219c 100644 --- a/src/compiler/tsc.ts +++ b/src/compiler/tsc.ts @@ -167,7 +167,7 @@ namespace ts { } function createWatchOfConfigFile(configParseResult: ParsedCommandLine, optionsToExtend: CompilerOptions) { - const watchCompilerHost = ts.createWatchCompilerHostOfConfigFile(configParseResult.options.configFilePath, optionsToExtend, sys, /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(configParseResult.options)); + const watchCompilerHost = createWatchCompilerHostOfConfigFile(configParseResult.options.configFilePath, optionsToExtend, sys, /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(configParseResult.options)); updateWatchCompilationHost(watchCompilerHost); watchCompilerHost.rootFiles = configParseResult.fileNames; watchCompilerHost.options = configParseResult.options; @@ -177,7 +177,7 @@ namespace ts { } function createWatchOfFilesAndCompilerOptions(rootFiles: string[], options: CompilerOptions) { - const watchCompilerHost = ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, sys, /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(options)); + const watchCompilerHost = createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, sys, /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(options)); updateWatchCompilationHost(watchCompilerHost); createWatchProgram(watchCompilerHost); } @@ -262,7 +262,7 @@ namespace ts { } function printVersion() { - sys.write(getDiagnosticText(Diagnostics.Version_0, ts.version) + sys.newLine); + sys.write(getDiagnosticText(Diagnostics.Version_0, version) + sys.newLine); } function printHelp(showAllOptions: boolean) { diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 36dabb5632e..040001c4fdd 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1545,7 +1545,7 @@ namespace ts { return SpecialPropertyAssignmentKind.None; } - export function isSpecialPropertyDeclaration(expr: ts.PropertyAccessExpression): boolean { + export function isSpecialPropertyDeclaration(expr: PropertyAccessExpression): boolean { return isInJavaScriptFile(expr) && expr.parent && expr.parent.kind === SyntaxKind.ExpressionStatement && !!getJSDocTypeTag(expr.parent); @@ -1619,10 +1619,10 @@ namespace ts { function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node: Node): Expression | undefined { switch (node.kind) { - case ts.SyntaxKind.VariableStatement: + case SyntaxKind.VariableStatement: const v = getSingleVariableOfVariableStatement(node); return v && v.initializer; - case ts.SyntaxKind.PropertyDeclaration: + case SyntaxKind.PropertyDeclaration: return (node as PropertyDeclaration).initializer; } } @@ -1717,7 +1717,7 @@ namespace ts { export function getTypeParameterFromJsDoc(node: TypeParameterDeclaration & { parent: JSDocTemplateTag }): TypeParameterDeclaration | undefined { const name = node.name.escapedText; - const { typeParameters } = (node.parent.parent.parent as ts.SignatureDeclaration | ts.InterfaceDeclaration | ts.ClassDeclaration); + const { typeParameters } = (node.parent.parent.parent as SignatureDeclaration | InterfaceDeclaration | ClassDeclaration); return find(typeParameters, p => p.name.escapedText === name); } @@ -4097,6 +4097,7 @@ namespace ts { return false; } try { + // tslint:disable-next-line no-unnecessary-qualifier (making clear this is a global mutation!) ts.localizedDiagnosticMessages = JSON.parse(fileContents); } catch (e) { diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 8494323a60d..552316d7751 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -20,7 +20,7 @@ namespace ts { getCanonicalFileName: createGetCanonicalFileName(system.useCaseSensitiveFileNames), }; if (!pretty) { - return diagnostic => system.write(ts.formatDiagnostic(diagnostic, host)); + return diagnostic => system.write(formatDiagnostic(diagnostic, host)); } const diagnostics: Diagnostic[] = new Array(1); @@ -485,9 +485,9 @@ namespace ts { const trace = host.trace && ((s: string) => { host.trace(s + newLine); }); const loggingEnabled = trace && (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics); const writeLog = loggingEnabled ? trace : noop; - const watchFile = compilerOptions.extendedDiagnostics ? ts.addFileWatcherWithLogging : loggingEnabled ? ts.addFileWatcherWithOnlyTriggerLogging : ts.addFileWatcher; - const watchFilePath = compilerOptions.extendedDiagnostics ? ts.addFilePathWatcherWithLogging : ts.addFilePathWatcher; - const watchDirectoryWorker = compilerOptions.extendedDiagnostics ? ts.addDirectoryWatcherWithLogging : ts.addDirectoryWatcher; + const watchFile = compilerOptions.extendedDiagnostics ? addFileWatcherWithLogging : loggingEnabled ? addFileWatcherWithOnlyTriggerLogging : addFileWatcher; + const watchFilePath = compilerOptions.extendedDiagnostics ? addFilePathWatcherWithLogging : addFilePathWatcher; + const watchDirectoryWorker = compilerOptions.extendedDiagnostics ? addDirectoryWatcherWithLogging : addDirectoryWatcher; const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); let newLine = updateNewLine(); @@ -827,7 +827,7 @@ namespace ts { } function parseConfigFile() { - const configParseResult = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost); + const configParseResult = getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost); rootFileNames = configParseResult.fileNames; compilerOptions = configParseResult.options; configFileSpecs = configParseResult.configFileSpecs; diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index f5efa233a61..d52bc304770 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -418,7 +418,7 @@ namespace FourSlash { this.goToPosition(marker.position); } - public goToEachMarker(markers: ReadonlyArray, action: (marker: FourSlash.Marker, index: number) => void) { + public goToEachMarker(markers: ReadonlyArray, action: (marker: Marker, index: number) => void) { assert(markers.length); for (let i = 0; i < markers.length; i++) { this.goToMarker(markers[i]); @@ -2356,7 +2356,7 @@ Actual: ${stringify(fullActual)}`); this.verifyClassifications(expected, actual, this.activeFile.content); } - public verifyOutliningSpans(spans: FourSlash.Range[]) { + public verifyOutliningSpans(spans: Range[]) { const actual = this.languageService.getOutliningSpans(this.activeFile.fileName); if (actual.length !== spans.length) { @@ -3290,7 +3290,7 @@ ${code} const format = new FourSlashInterface.Format(state); const cancellation = new FourSlashInterface.Cancellation(state); const f = eval(wrappedCode); - f(test, goTo, verify, edit, debug, format, cancellation, FourSlashInterface.Classification, FourSlash.verifyOperationIsCancelled); + f(test, goTo, verify, edit, debug, format, cancellation, FourSlashInterface.Classification, verifyOperationIsCancelled); } catch (err) { throw err; @@ -3963,7 +3963,7 @@ namespace FourSlashInterface { this.state.verifySpanOfEnclosingComment(this.negative, onlyMultiLineDiverges); } - public codeFix(options: FourSlashInterface.VerifyCodeFixOptions) { + public codeFix(options: VerifyCodeFixOptions) { this.state.verifyCodeFix(options); } diff --git a/src/harness/harness.ts b/src/harness/harness.ts index e2bed4f0318..12ebf4c4baf 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -336,7 +336,7 @@ namespace Utils { case "referenceDiagnostics": case "parseDiagnostics": - o[propertyName] = Utils.convertDiagnostics((n)[propertyName]); + o[propertyName] = convertDiagnostics((n)[propertyName]); break; case "nextContainer": @@ -852,7 +852,7 @@ namespace Harness { sourceText: string, languageVersion: ts.ScriptTarget) { // We'll only assert invariants outside of light mode. - const shouldAssertInvariants = !Harness.lightMode; + const shouldAssertInvariants = !lightMode; // Only set the parent nodes if we're asserting invariants. We don't need them otherwise. const result = ts.createSourceFile(fileName, sourceText, languageVersion, /*setParentNodes:*/ shouldAssertInvariants); @@ -984,7 +984,7 @@ namespace Harness { } else if (fileName === fourslashFileName) { const tsFn = "tests/cases/fourslash/" + fourslashFileName; - fourslashSourceFile = fourslashSourceFile || createSourceFileAndAssertInvariants(tsFn, Harness.IO.readFile(tsFn), scriptTarget); + fourslashSourceFile = fourslashSourceFile || createSourceFileAndAssertInvariants(tsFn, IO.readFile(tsFn), scriptTarget); return fourslashSourceFile; } else if (ts.startsWith(fileName, "tests/lib/")) { @@ -1000,7 +1000,7 @@ namespace Harness { const newLine = newLineKind === ts.NewLineKind.CarriageReturnLineFeed ? carriageReturnLineFeed : newLineKind === ts.NewLineKind.LineFeed ? lineFeed : - Harness.IO.newLine(); + IO.newLine(); function toPath(fileName: string): ts.Path { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); @@ -1103,7 +1103,7 @@ namespace Harness { return optionsIndex.get(name.toLowerCase()); } - export function setCompilerOptionsFromHarnessSetting(settings: Harness.TestCaseParser.CompilerSettings, options: ts.CompilerOptions & HarnessOptions): void { + export function setCompilerOptionsFromHarnessSetting(settings: TestCaseParser.CompilerSettings, options: ts.CompilerOptions & HarnessOptions): void { for (const name in settings) { if (settings.hasOwnProperty(name)) { const value = settings[name]; @@ -1171,7 +1171,7 @@ namespace Harness { options.skipDefaultLibCheck = typeof options.skipDefaultLibCheck === "undefined" ? true : options.skipDefaultLibCheck; if (typeof currentDirectory === "undefined") { - currentDirectory = Harness.IO.getCurrentDirectory(); + currentDirectory = IO.getCurrentDirectory(); } // Parse settings @@ -1182,7 +1182,7 @@ namespace Harness { options.rootDirs = ts.map(options.rootDirs, d => ts.getNormalizedAbsolutePath(d, currentDirectory)); } - const useCaseSensitiveFileNames = options.useCaseSensitiveFileNames !== undefined ? options.useCaseSensitiveFileNames : Harness.IO.useCaseSensitiveFileNames(); + const useCaseSensitiveFileNames = options.useCaseSensitiveFileNames !== undefined ? options.useCaseSensitiveFileNames : IO.useCaseSensitiveFileNames(); const programFiles: TestFile[] = inputFiles.slice(); // Files from built\local that are requested by test "@includeBuiltFiles" to be in the context. // Treat them as library files, so include them in build, but not in baselines. @@ -1190,7 +1190,7 @@ namespace Harness { const builtFileName = ts.combinePaths(libFolder, options.includeBuiltFile); const builtFile: TestFile = { unitName: builtFileName, - content: normalizeLineEndings(IO.readFile(builtFileName), Harness.IO.newLine()), + content: normalizeLineEndings(IO.readFile(builtFileName), IO.newLine()), }; programFiles.push(builtFile); } @@ -1232,7 +1232,7 @@ namespace Harness { const errors = ts.getPreEmitDiagnostics(program); - const result = new CompilerResult(fileOutputs, errors, program, Harness.IO.getCurrentDirectory(), emitResult.sourceMaps, traceResults); + const result = new CompilerResult(fileOutputs, errors, program, IO.getCurrentDirectory(), emitResult.sourceMaps, traceResults); return { result, options }; } @@ -1336,7 +1336,7 @@ namespace Harness { } export function minimalDiagnosticsToString(diagnostics: ReadonlyArray, pretty?: boolean) { - const host = { getCanonicalFileName, getCurrentDirectory: () => "", getNewLine: () => Harness.IO.newLine() }; + const host = { getCanonicalFileName, getCurrentDirectory: () => "", getNewLine: () => IO.newLine() }; return (pretty ? ts.formatDiagnosticsWithColorAndContext : ts.formatDiagnostics)(diagnostics, host); } @@ -1370,7 +1370,7 @@ namespace Harness { } function outputErrorText(error: ts.Diagnostic) { - const message = ts.flattenDiagnosticMessageText(error.messageText, Harness.IO.newLine()); + const message = ts.flattenDiagnosticMessageText(error.messageText, IO.newLine()); const errLines = RunnerBase.removeFullPaths(message) .split("\n") @@ -1390,7 +1390,7 @@ namespace Harness { } } - yield [diagnosticSummaryMarker, minimalDiagnosticsToString(diagnostics, pretty) + Harness.IO.newLine() + Harness.IO.newLine(), diagnostics.length]; + yield [diagnosticSummaryMarker, minimalDiagnosticsToString(diagnostics, pretty) + IO.newLine() + IO.newLine(), diagnostics.length]; // Report global errors const globalErrors = diagnostics.filter(err => !err.file); @@ -1486,7 +1486,7 @@ namespace Harness { } export function doErrorBaseline(baselinePath: string, inputFiles: TestFile[], errors: ts.Diagnostic[], pretty?: boolean) { - Harness.Baseline.runBaseline(baselinePath.replace(/\.tsx?$/, ".errors.txt"), (): string => { + Baseline.runBaseline(baselinePath.replace(/\.tsx?$/, ".errors.txt"), (): string => { if (!errors || (errors.length === 0)) { /* tslint:disable:no-null-keyword */ return null; @@ -1496,7 +1496,7 @@ namespace Harness { }); } - export function doTypeAndSymbolBaseline(baselinePath: string, program: ts.Program, allFiles: {unitName: string, content: string}[], opts?: Harness.Baseline.BaselineOptions, multifile?: boolean, skipTypeBaselines?: boolean, skipSymbolBaselines?: boolean) { + export function doTypeAndSymbolBaseline(baselinePath: string, program: ts.Program, allFiles: {unitName: string, content: string}[], opts?: Baseline.BaselineOptions, multifile?: boolean, skipTypeBaselines?: boolean, skipSymbolBaselines?: boolean) { // The full walker simulates the types that you would get from doing a full // compile. The pull walker simulates the types you get when you just do // a type query for a random node (like how the LS would do it). Most of the @@ -1532,7 +1532,7 @@ namespace Harness { } if (typesError && symbolsError) { - throw new Error(typesError.stack + Harness.IO.newLine() + symbolsError.stack); + throw new Error(typesError.stack + IO.newLine() + symbolsError.stack); } if (typesError) { @@ -1555,10 +1555,10 @@ namespace Harness { if (!multifile) { const fullBaseLine = generateBaseLine(isSymbolBaseLine, isSymbolBaseLine ? skipSymbolBaselines : skipTypeBaselines); - Harness.Baseline.runBaseline(outputFileName + fullExtension, () => fullBaseLine, opts); + Baseline.runBaseline(outputFileName + fullExtension, () => fullBaseLine, opts); } else { - Harness.Baseline.runMultifileBaseline(outputFileName, fullExtension, () => { + Baseline.runMultifileBaseline(outputFileName, fullExtension, () => { return iterateBaseLine(isSymbolBaseLine, isSymbolBaseLine ? skipSymbolBaselines : skipTypeBaselines); }, opts); } @@ -1627,11 +1627,11 @@ namespace Harness { } } - function getByteOrderMarkText(file: Harness.Compiler.GeneratedFile): string { + function getByteOrderMarkText(file: GeneratedFile): string { return file.writeByteOrderMark ? "\u00EF\u00BB\u00BF" : ""; } - export function doSourcemapBaseline(baselinePath: string, options: ts.CompilerOptions, result: CompilerResult, harnessSettings: Harness.TestCaseParser.CompilerSettings) { + export function doSourcemapBaseline(baselinePath: string, options: ts.CompilerOptions, result: CompilerResult, harnessSettings: TestCaseParser.CompilerSettings) { if (options.inlineSourceMap) { if (result.sourceMaps.length > 0) { throw new Error("No sourcemap files should be generated if inlineSourceMaps was set."); @@ -1643,7 +1643,7 @@ namespace Harness { throw new Error("Number of sourcemap files should be same as js files."); } - Harness.Baseline.runBaseline(baselinePath.replace(/\.tsx?/, ".js.map"), () => { + Baseline.runBaseline(baselinePath.replace(/\.tsx?/, ".js.map"), () => { if ((options.noEmitOnError && result.errors.length !== 0) || result.sourceMaps.length === 0) { // We need to return null here or the runBaseLine will actually create a empty file. // Baselining isn't required here because there is no output. @@ -1662,13 +1662,13 @@ namespace Harness { } } - export function doJsEmitBaseline(baselinePath: string, header: string, options: ts.CompilerOptions, result: CompilerResult, tsConfigFiles: Harness.Compiler.TestFile[], toBeCompiled: Harness.Compiler.TestFile[], otherFiles: Harness.Compiler.TestFile[], harnessSettings: Harness.TestCaseParser.CompilerSettings) { + export function doJsEmitBaseline(baselinePath: string, header: string, options: ts.CompilerOptions, result: CompilerResult, tsConfigFiles: TestFile[], toBeCompiled: TestFile[], otherFiles: TestFile[], harnessSettings: TestCaseParser.CompilerSettings) { if (!options.noEmit && !options.emitDeclarationOnly && result.files.length === 0 && result.errors.length === 0) { throw new Error("Expected at least one js file to be emitted or at least one error to be created."); } // check js output - Harness.Baseline.runBaseline(baselinePath.replace(/\.tsx?/, ts.Extension.Js), () => { + Baseline.runBaseline(baselinePath.replace(/\.tsx?/, ts.Extension.Js), () => { let tsCode = ""; const tsSources = otherFiles.concat(toBeCompiled); if (tsSources.length > 1) { @@ -1691,15 +1691,15 @@ namespace Harness { } } - const declFileContext = Harness.Compiler.prepareDeclarationCompilationContext( + const declFileContext = prepareDeclarationCompilationContext( toBeCompiled, otherFiles, result, harnessSettings, options, /*currentDirectory*/ undefined ); - const declFileCompilationResult = Harness.Compiler.compileDeclarationFiles(declFileContext); + const declFileCompilationResult = compileDeclarationFiles(declFileContext); if (declFileCompilationResult && declFileCompilationResult.declResult.errors.length) { jsCode += "\r\n\r\n//// [DtsFileErrors]\r\n"; jsCode += "\r\n\r\n"; - jsCode += Harness.Compiler.getErrorBaseline(tsConfigFiles.concat(declFileCompilationResult.declInputFiles, declFileCompilationResult.declOtherFiles), declFileCompilationResult.declResult.errors); + jsCode += getErrorBaseline(tsConfigFiles.concat(declFileCompilationResult.declInputFiles, declFileCompilationResult.declOtherFiles), declFileCompilationResult.declResult.errors); } if (jsCode.length > 0) { @@ -1713,12 +1713,12 @@ namespace Harness { }); } - function fileOutput(file: GeneratedFile, harnessSettings: Harness.TestCaseParser.CompilerSettings): string { + function fileOutput(file: GeneratedFile, harnessSettings: TestCaseParser.CompilerSettings): string { const fileName = harnessSettings.fullEmitPaths ? file.fileName : ts.getBaseFileName(file.fileName); return "//// [" + fileName + "]\r\n" + getByteOrderMarkText(file) + file.code; } - export function collateOutputs(outputFiles: Harness.Compiler.GeneratedFile[]): string { + export function collateOutputs(outputFiles: GeneratedFile[]): string { const gen = iterateOutputs(outputFiles); // Emit them let result = ""; @@ -1734,7 +1734,7 @@ namespace Harness { return result; } - export function *iterateOutputs(outputFiles: Harness.Compiler.GeneratedFile[]): IterableIterator<[string, string]> { + export function *iterateOutputs(outputFiles: GeneratedFile[]): IterableIterator<[string, string]> { // Collect, test, and sort the fileNames outputFiles.sort((a, b) => ts.compareStringsCaseSensitive(cleanName(a.fileName), cleanName(b.fileName))); const dupeCase = ts.createMap(); @@ -1839,7 +1839,7 @@ namespace Harness { public getSourceMapRecord() { if (this.sourceMapData && this.sourceMapData.length > 0) { - return Harness.SourceMapRecorder.getSourceMapRecord(this.sourceMapData, this.program, this.files); + return SourceMapRecorder.getSourceMapRecord(this.sourceMapData, this.program, this.files); } } } @@ -2020,10 +2020,10 @@ namespace Harness { function baselinePath(fileName: string, type: string, baselineFolder: string, subfolder?: string) { if (subfolder !== undefined) { - return Harness.userSpecifiedRoot + baselineFolder + "/" + subfolder + "/" + type + "/" + fileName; + return userSpecifiedRoot + baselineFolder + "/" + subfolder + "/" + type + "/" + fileName; } else { - return Harness.userSpecifiedRoot + baselineFolder + "/" + type + "/" + fileName; + return userSpecifiedRoot + baselineFolder + "/" + type + "/" + fileName; } } @@ -2082,7 +2082,7 @@ namespace Harness { } // Create folders if needed - createDirectoryStructure(Harness.IO.directoryName(actualFileName)); + createDirectoryStructure(IO.directoryName(actualFileName)); // Delete the actual file in case it fails if (IO.fileExists(actualFileName)) { @@ -2131,7 +2131,7 @@ namespace Harness { } const referenceDir = referencePath(relativeFileBase, opts && opts.Baselinefolder, opts && opts.Subfolder); - let existing = Harness.IO.readDirectory(referenceDir, referencedExtensions || [extension]); + let existing = IO.readDirectory(referenceDir, referencedExtensions || [extension]); if (extension === ".ts" || referencedExtensions && referencedExtensions.indexOf(".ts") > -1 && referencedExtensions.indexOf(".d.ts") === -1) { // special-case and filter .d.ts out of .ts results existing = existing.filter(f => !ts.endsWith(f, ".d.ts")); @@ -2173,11 +2173,11 @@ namespace Harness { } export function isBuiltFile(filePath: string): boolean { - return filePath.indexOf(Harness.libFolder) === 0; + return ts.startsWith(filePath, libFolder); } - export function getDefaultLibraryFile(filePath: string, io: Harness.Io): Harness.Compiler.TestFile { - const libFile = Harness.userSpecifiedRoot + Harness.libFolder + ts.getBaseFileName(ts.normalizeSlashes(filePath)); + export function getDefaultLibraryFile(filePath: string, io: Io): Compiler.TestFile { + const libFile = userSpecifiedRoot + libFolder + ts.getBaseFileName(ts.normalizeSlashes(filePath)); return { unitName: libFile, content: io.readFile(libFile) }; } diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index 503246c72ca..23aa5ee2b8d 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -192,7 +192,7 @@ namespace Harness.LanguageService { return dir && dir.isDirectory() ? dir.getDirectories().map(d => d.name) : []; } getCurrentDirectory(): string { return virtualFileSystemRoot; } - getDefaultLibFileName(): string { return Harness.Compiler.defaultLibFileName; } + getDefaultLibFileName(): string { return Compiler.defaultLibFileName; } getScriptFileNames(): string[] { return this.getFilenames().filter(ts.isAnySupportedFileExtension); } @@ -641,8 +641,8 @@ namespace Harness.LanguageService { } readFile(fileName: string): string | undefined { - if (fileName.indexOf(Harness.Compiler.defaultLibFileName) >= 0) { - fileName = Harness.Compiler.defaultLibFileName; + if (ts.stringContains(fileName, Compiler.defaultLibFileName)) { + fileName = Compiler.defaultLibFileName; } const snapshot = this.host.getScriptSnapshot(fileName); diff --git a/src/harness/parallel/host.ts b/src/harness/parallel/host.ts index 59105cd5b08..49e7aaa6bd3 100644 --- a/src/harness/parallel/host.ts +++ b/src/harness/parallel/host.ts @@ -33,7 +33,7 @@ namespace Harness.Parallel.Host { return `${perfdataFileNameFragment}${target ? `.${target}` : ""}.json`; } function readSavedPerfData(target?: string): {[testHash: string]: number} { - const perfDataContents = Harness.IO.readFile(perfdataFileName(target)); + const perfDataContents = IO.readFile(perfdataFileName(target)); if (perfDataContents) { return JSON.parse(perfDataContents); } @@ -90,7 +90,7 @@ namespace Harness.Parallel.Host { catch { // May be a directory try { - size = Harness.IO.listFiles(path.join(runner.workingDirectory, file), /.*/g, { recursive: true }).reduce((acc, elem) => acc + statSync(elem).size, 0); + size = IO.listFiles(path.join(runner.workingDirectory, file), /.*/g, { recursive: true }).reduce((acc, elem) => acc + statSync(elem).size, 0); } catch { // Unknown test kind, just return 0 and let the historical analysis take over after one run @@ -144,9 +144,9 @@ namespace Harness.Parallel.Host { let closedWorkers = 0; for (let i = 0; i < workerCount; i++) { // TODO: Just send the config over the IPC channel or in the command line arguments - const config: TestConfig = { light: Harness.lightMode, listenForWork: true, runUnitTests }; + const config: TestConfig = { light: lightMode, listenForWork: true, runUnitTests }; const configPath = ts.combinePaths(taskConfigsFolder, `task-config${i}.json`); - Harness.IO.writeFile(configPath, JSON.stringify(config)); + IO.writeFile(configPath, JSON.stringify(config)); const child = fork(__filename, [`--config="${configPath}"`]); let currentTimeout = defaultTimeout; const killChild = () => { @@ -364,7 +364,7 @@ namespace Harness.Parallel.Host { reporter.epilogue(); } - Harness.IO.writeFile(perfdataFileName(configOption), JSON.stringify(newPerfData, null, 4)); // tslint:disable-line:no-null-keyword + IO.writeFile(perfdataFileName(configOption), JSON.stringify(newPerfData, null, 4)); // tslint:disable-line:no-null-keyword process.exit(errorResults.length); } diff --git a/src/harness/unittests/commandLineParsing.ts b/src/harness/unittests/commandLineParsing.ts index eebbf4a7a24..dbfa128b365 100644 --- a/src/harness/unittests/commandLineParsing.ts +++ b/src/harness/unittests/commandLineParsing.ts @@ -4,8 +4,8 @@ namespace ts { describe("parseCommandLine", () => { - function assertParseResult(commandLine: string[], expectedParsedCommandLine: ts.ParsedCommandLine) { - const parsed = ts.parseCommandLine(commandLine); + function assertParseResult(commandLine: string[], expectedParsedCommandLine: ParsedCommandLine) { + const parsed = parseCommandLine(commandLine); const parsedCompilerOptions = JSON.stringify(parsed.options); const expectedCompilerOptions = JSON.stringify(expectedParsedCommandLine.options); assert.equal(parsedCompilerOptions, expectedCompilerOptions); @@ -61,8 +61,8 @@ namespace ts { { errors: [{ messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.regexp', 'esnext.array', 'esnext.asynciterable', 'esnext.promise'.", - category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, - code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, + category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, + code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, start: undefined, @@ -80,16 +80,16 @@ namespace ts { { errors: [{ messageText: "Compiler option 'jsx' expects an argument.", - category: ts.Diagnostics.Compiler_option_0_expects_an_argument.category, - code: ts.Diagnostics.Compiler_option_0_expects_an_argument.code, + category: Diagnostics.Compiler_option_0_expects_an_argument.category, + code: Diagnostics.Compiler_option_0_expects_an_argument.code, file: undefined, start: undefined, length: undefined, }, { messageText: "Argument for '--jsx' option must be: 'preserve', 'react-native', 'react'.", - category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, - code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, + category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, + code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, start: undefined, @@ -106,16 +106,16 @@ namespace ts { { errors: [{ messageText: "Compiler option 'module' expects an argument.", - category: ts.Diagnostics.Compiler_option_0_expects_an_argument.category, - code: ts.Diagnostics.Compiler_option_0_expects_an_argument.code, + category: Diagnostics.Compiler_option_0_expects_an_argument.category, + code: Diagnostics.Compiler_option_0_expects_an_argument.code, file: undefined, start: undefined, length: undefined, }, { messageText: "Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'esnext'.", - category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, - code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, + category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, + code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, start: undefined, @@ -132,16 +132,16 @@ namespace ts { { errors: [{ messageText: "Compiler option 'newLine' expects an argument.", - category: ts.Diagnostics.Compiler_option_0_expects_an_argument.category, - code: ts.Diagnostics.Compiler_option_0_expects_an_argument.code, + category: Diagnostics.Compiler_option_0_expects_an_argument.category, + code: Diagnostics.Compiler_option_0_expects_an_argument.code, file: undefined, start: undefined, length: undefined, }, { messageText: "Argument for '--newLine' option must be: 'crlf', 'lf'.", - category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, - code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, + category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, + code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, start: undefined, @@ -158,16 +158,16 @@ namespace ts { { errors: [{ messageText: "Compiler option 'target' expects an argument.", - category: ts.Diagnostics.Compiler_option_0_expects_an_argument.category, - code: ts.Diagnostics.Compiler_option_0_expects_an_argument.code, + category: Diagnostics.Compiler_option_0_expects_an_argument.category, + code: Diagnostics.Compiler_option_0_expects_an_argument.code, file: undefined, start: undefined, length: undefined, }, { messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'esnext'.", - category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, - code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, + category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, + code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, start: undefined, @@ -184,16 +184,16 @@ namespace ts { { errors: [{ messageText: "Compiler option 'moduleResolution' expects an argument.", - category: ts.Diagnostics.Compiler_option_0_expects_an_argument.category, - code: ts.Diagnostics.Compiler_option_0_expects_an_argument.code, + category: Diagnostics.Compiler_option_0_expects_an_argument.category, + code: Diagnostics.Compiler_option_0_expects_an_argument.code, file: undefined, start: undefined, length: undefined, }, { messageText: "Argument for '--moduleResolution' option must be: 'node', 'classic'.", - category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, - code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, + category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, + code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, start: undefined, @@ -210,8 +210,8 @@ namespace ts { { errors: [{ messageText: "Compiler option 'lib' expects an argument.", - category: ts.Diagnostics.Compiler_option_0_expects_an_argument.category, - code: ts.Diagnostics.Compiler_option_0_expects_an_argument.code, + category: Diagnostics.Compiler_option_0_expects_an_argument.category, + code: Diagnostics.Compiler_option_0_expects_an_argument.code, file: undefined, start: undefined, @@ -231,8 +231,8 @@ namespace ts { { errors: [{ messageText: "Compiler option 'lib' expects an argument.", - category: ts.Diagnostics.Compiler_option_0_expects_an_argument.category, - code: ts.Diagnostics.Compiler_option_0_expects_an_argument.code, + category: Diagnostics.Compiler_option_0_expects_an_argument.category, + code: Diagnostics.Compiler_option_0_expects_an_argument.code, file: undefined, start: undefined, @@ -264,8 +264,8 @@ namespace ts { { errors: [{ messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.regexp', 'esnext.array', 'esnext.asynciterable', 'esnext.promise'.", - category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, - code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, + category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, + code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, start: undefined, @@ -284,8 +284,8 @@ namespace ts { { errors: [{ messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'scripthost', 'es2015.core', 'es2015.collection', 'es2015.generator', 'es2015.iterable', 'es2015.promise', 'es2015.proxy', 'es2015.reflect', 'es2015.symbol', 'es2015.symbol.wellknown', 'es2016.array.include', 'es2017.object', 'es2017.sharedmemory', 'es2017.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.regexp', 'esnext.array', 'esnext.asynciterable', 'esnext.promise'.", - category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, - code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, + category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, + code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, start: undefined, @@ -306,7 +306,7 @@ namespace ts { fileNames: ["0.ts"], options: { lib: ["lib.es5.d.ts", "lib.es2015.symbol.wellknown.d.ts"], - target: ts.ScriptTarget.ES5, + target: ScriptTarget.ES5, } }); }); @@ -318,8 +318,8 @@ namespace ts { errors: [], fileNames: ["0.ts"], options: { - module: ts.ModuleKind.CommonJS, - target: ts.ScriptTarget.ES5, + module: ModuleKind.CommonJS, + target: ScriptTarget.ES5, lib: ["lib.es5.d.ts", "lib.es2015.symbol.wellknown.d.ts"], } }); @@ -332,8 +332,8 @@ namespace ts { errors: [], fileNames: ["0.ts"], options: { - module: ts.ModuleKind.CommonJS, - target: ts.ScriptTarget.ES5, + module: ModuleKind.CommonJS, + target: ScriptTarget.ES5, lib: ["lib.es2015.core.d.ts", "lib.es2015.symbol.wellknown.d.ts"], } }); diff --git a/src/harness/unittests/compileOnSave.ts b/src/harness/unittests/compileOnSave.ts index a64d7bdd2a5..0efd8662cf1 100644 --- a/src/harness/unittests/compileOnSave.ts +++ b/src/harness/unittests/compileOnSave.ts @@ -13,8 +13,8 @@ namespace ts.projectSystem { describe("CompileOnSave affected list", () => { function sendAffectedFileRequestAndCheckResult(session: server.Session, request: server.protocol.Request, expectedFileList: { projectFileName: string, files: FileOrFolder[] }[]) { const response = session.executeCommand(request).response as server.protocol.CompileOnSaveAffectedFileListSingleProject[]; - const actualResult = response.sort((list1, list2) => ts.compareStringsCaseSensitive(list1.projectFileName, list2.projectFileName)); - expectedFileList = expectedFileList.sort((list1, list2) => ts.compareStringsCaseSensitive(list1.projectFileName, list2.projectFileName)); + const actualResult = response.sort((list1, list2) => compareStringsCaseSensitive(list1.projectFileName, list2.projectFileName)); + expectedFileList = expectedFileList.sort((list1, list2) => compareStringsCaseSensitive(list1.projectFileName, list2.projectFileName)); assert.equal(actualResult.length, expectedFileList.length, `Actual result project number is different from the expected project number`); @@ -517,7 +517,7 @@ namespace ts.projectSystem { const lines = ["var x = 1;", "var y = 2;"]; const path = "/a/app"; const f = { - path: path + ts.Extension.Ts, + path: path + Extension.Ts, content: lines.join(newLine) }; const host = createServerHost([f], { newLine }); @@ -536,7 +536,7 @@ namespace ts.projectSystem { arguments: { file: f.path } }; session.executeCommand(emitFileRequest); - const emitOutput = host.readFile(path + ts.Extension.Js); + const emitOutput = host.readFile(path + Extension.Js); assert.equal(emitOutput, f.content + newLine, "content of emit output should be identical with the input + newline"); } }); diff --git a/src/harness/unittests/configurationExtension.ts b/src/harness/unittests/configurationExtension.ts index 5a1b155fbcf..7e0eb5bad7e 100644 --- a/src/harness/unittests/configurationExtension.ts +++ b/src/harness/unittests/configurationExtension.ts @@ -129,17 +129,17 @@ namespace ts { ["under a case sensitive host", caseSensitiveBasePath, caseSensitiveHost] ], ([testName, basePath, host]) => { function getParseCommandLine(entry: string) { - const {config, error} = ts.readConfigFile(entry, name => host.readFile(name)); + const {config, error} = readConfigFile(entry, name => host.readFile(name)); assert(config && !error, flattenDiagnosticMessageText(error && error.messageText, "\n")); - return ts.parseJsonConfigFileContent(config, host, basePath, {}, entry); + return parseJsonConfigFileContent(config, host, basePath, {}, entry); } function getParseCommandLineJsonSourceFile(entry: string) { - const jsonSourceFile = ts.readJsonConfigFile(entry, name => host.readFile(name)); + const jsonSourceFile = readJsonConfigFile(entry, name => host.readFile(name)); assert(jsonSourceFile.endOfFileToken && !jsonSourceFile.parseDiagnostics.length, flattenDiagnosticMessageText(jsonSourceFile.parseDiagnostics[0] && jsonSourceFile.parseDiagnostics[0].messageText, "\n")); return { jsonSourceFile, - parsed: ts.parseJsonSourceFileConfigFileContent(jsonSourceFile, host, basePath, {}, entry) + parsed: parseJsonSourceFileConfigFileContent(jsonSourceFile, host, basePath, {}, entry) }; } diff --git a/src/harness/unittests/convertToBase64.ts b/src/harness/unittests/convertToBase64.ts index 975d21a3838..93c149c72ee 100644 --- a/src/harness/unittests/convertToBase64.ts +++ b/src/harness/unittests/convertToBase64.ts @@ -3,7 +3,7 @@ namespace ts { describe("convertToBase64", () => { function runTest(input: string): void { - const actual = ts.convertToBase64(input); + const actual = convertToBase64(input); const expected = new Buffer(input).toString("base64"); assert.equal(actual, expected, "Encoded string using convertToBase64 does not match buffer.toString('base64')"); } diff --git a/src/harness/unittests/extractRanges.ts b/src/harness/unittests/extractRanges.ts index ce9d18815bf..68d8289d206 100644 --- a/src/harness/unittests/extractRanges.ts +++ b/src/harness/unittests/extractRanges.ts @@ -27,9 +27,9 @@ namespace ts { const expectedRange = t.ranges.get("extracted"); if (expectedRange) { let pos: number, end: number; - if (ts.isArray(result.targetRange.range)) { + if (isArray(result.targetRange.range)) { pos = result.targetRange.range[0].getStart(f); - end = ts.lastOrUndefined(result.targetRange.range).getEnd(); + end = lastOrUndefined(result.targetRange.range).getEnd(); } else { pos = result.targetRange.range.getStart(f); diff --git a/src/harness/unittests/extractTestHelpers.ts b/src/harness/unittests/extractTestHelpers.ts index 8970990326c..1e3e3c8c81a 100644 --- a/src/harness/unittests/extractTestHelpers.ts +++ b/src/harness/unittests/extractTestHelpers.ts @@ -67,12 +67,12 @@ namespace ts { } export const newLineCharacter = "\n"; - export const testFormatOptions: ts.FormatCodeSettings = { + export const testFormatOptions: FormatCodeSettings = { indentSize: 4, tabSize: 4, newLineCharacter, convertTabsToSpaces: true, - indentStyle: ts.IndentStyle.Smart, + indentStyle: IndentStyle.Smart, insertSpaceAfterConstructor: false, insertSpaceAfterCommaDelimiter: true, insertSpaceAfterSemicolonInForStatements: true, diff --git a/src/harness/unittests/hostNewLineSupport.ts b/src/harness/unittests/hostNewLineSupport.ts index e7e5c11e33e..34543f2ec6f 100644 --- a/src/harness/unittests/hostNewLineSupport.ts +++ b/src/harness/unittests/hostNewLineSupport.ts @@ -17,7 +17,7 @@ namespace ts { getDefaultLibFileName: () => "lib.d.ts", getCurrentDirectory: () => "", }; - return ts.createLanguageService(lshost); + return createLanguageService(lshost); } function verifyNewLines(content: string, options: CompilerOptions) { diff --git a/src/harness/unittests/incrementalParser.ts b/src/harness/unittests/incrementalParser.ts index cdccce418bc..3792664601e 100644 --- a/src/harness/unittests/incrementalParser.ts +++ b/src/harness/unittests/incrementalParser.ts @@ -2,7 +2,7 @@ /// namespace ts { - ts.disableIncrementalParsing = false; + ts.disableIncrementalParsing = false; // tslint:disable-line no-unnecessary-qualifier (make clear this is a global mutation!) function withChange(text: IScriptSnapshot, start: number, length: number, newText: string): { text: IScriptSnapshot; textChangeRange: TextChangeRange; } { const contents = getSnapshotText(text); diff --git a/src/harness/unittests/jsDocParsing.ts b/src/harness/unittests/jsDocParsing.ts index b7215f5ea35..2d670a2b647 100644 --- a/src/harness/unittests/jsDocParsing.ts +++ b/src/harness/unittests/jsDocParsing.ts @@ -6,7 +6,7 @@ namespace ts { describe("TypeExpressions", () => { function parsesCorrectly(name: string, content: string) { it(name, () => { - const typeAndDiagnostics = ts.parseJSDocTypeExpressionForTests(content); + const typeAndDiagnostics = parseJSDocTypeExpressionForTests(content); assert.isTrue(typeAndDiagnostics && typeAndDiagnostics.diagnostics.length === 0, "no errors issued"); Harness.Baseline.runBaseline("JSDocParsing/TypeExpressions.parsesCorrectly." + name + ".json", @@ -16,7 +16,7 @@ namespace ts { function parsesIncorrectly(name: string, content: string) { it(name, () => { - const type = ts.parseJSDocTypeExpressionForTests(content); + const type = parseJSDocTypeExpressionForTests(content); assert.isTrue(!type || type.diagnostics.length > 0); }); } @@ -309,21 +309,21 @@ namespace ts { }); describe("getFirstToken", () => { it("gets jsdoc", () => { - const root = ts.createSourceFile("foo.ts", "/** comment */var a = true;", ts.ScriptTarget.ES5, /*setParentNodes*/ true); + const root = createSourceFile("foo.ts", "/** comment */var a = true;", ScriptTarget.ES5, /*setParentNodes*/ true); assert.isDefined(root); - assert.equal(root.kind, ts.SyntaxKind.SourceFile); + assert.equal(root.kind, SyntaxKind.SourceFile); const first = root.getFirstToken(); assert.isDefined(first); - assert.equal(first.kind, ts.SyntaxKind.VarKeyword); + assert.equal(first.kind, SyntaxKind.VarKeyword); }); }); describe("getLastToken", () => { it("gets jsdoc", () => { - const root = ts.createSourceFile("foo.ts", "var a = true;/** comment */", ts.ScriptTarget.ES5, /*setParentNodes*/ true); + const root = createSourceFile("foo.ts", "var a = true;/** comment */", ScriptTarget.ES5, /*setParentNodes*/ true); assert.isDefined(root); const last = root.getLastToken(); assert.isDefined(last); - assert.equal(last.kind, ts.SyntaxKind.EndOfFileToken); + assert.equal(last.kind, SyntaxKind.EndOfFileToken); }); }); }); diff --git a/src/harness/unittests/languageService.ts b/src/harness/unittests/languageService.ts index f14b9daad82..14bdff9867e 100644 --- a/src/harness/unittests/languageService.ts +++ b/src/harness/unittests/languageService.ts @@ -20,7 +20,7 @@ export function Component(x: Config): any;` // Regression test for GH #18245 - bug in single line comment writer caused a debug assertion when attempting // to write an alias to a module's default export was referrenced across files and had no default export it("should be able to create a language service which can respond to deinition requests without throwing", () => { - const languageService = ts.createLanguageService({ + const languageService = createLanguageService({ getCompilationSettings() { return {}; }, @@ -32,13 +32,13 @@ export function Component(x: Config): any;` }, getScriptSnapshot(fileName) { if (fileName === ".ts") { - return ts.ScriptSnapshot.fromString(""); + return ScriptSnapshot.fromString(""); } - return ts.ScriptSnapshot.fromString(files[fileName] || ""); + return ScriptSnapshot.fromString(files[fileName] || ""); }, getCurrentDirectory: () => ".", getDefaultLibFileName(options) { - return ts.getDefaultLibFilePath(options); + return getDefaultLibFilePath(options); }, }); const definitions = languageService.getDefinitionAtPosition("foo.ts", 160); // 160 is the latter `vueTemplateHtml` position diff --git a/src/harness/unittests/matchFiles.ts b/src/harness/unittests/matchFiles.ts index 17a0db04fdf..bbefd24bb57 100644 --- a/src/harness/unittests/matchFiles.ts +++ b/src/harness/unittests/matchFiles.ts @@ -91,17 +91,17 @@ namespace ts { "c:/dev/g.min.js/.g/g.ts" ]); - function assertParsed(actual: ts.ParsedCommandLine, expected: ts.ParsedCommandLine): void { + function assertParsed(actual: ParsedCommandLine, expected: ParsedCommandLine): void { assert.deepEqual(actual.fileNames, expected.fileNames); assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories); assert.deepEqual(actual.errors, expected.errors); } - function validateMatches(expected: ts.ParsedCommandLine, json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]) { + function validateMatches(expected: ParsedCommandLine, json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]) { { const jsonText = JSON.stringify(json); const result = parseJsonText(caseInsensitiveTsconfigPath, jsonText); - const actual = ts.parseJsonSourceFileConfigFileContent(result, host, basePath, existingOptions, configFileName, resolutionStack); + const actual = parseJsonSourceFileConfigFileContent(result, host, basePath, existingOptions, configFileName, resolutionStack); for (const error of expected.errors) { if (error.file) { error.file = result; @@ -110,7 +110,7 @@ namespace ts { assertParsed(actual, expected); } { - const actual = ts.parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack); + const actual = parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack); expected.errors = expected.errors.map(error => ({ category: error.category, code: error.code, @@ -130,13 +130,13 @@ namespace ts { kind: SyntaxKind.SourceFile, text }; - return ts.createFileDiagnostic(file, start, length, diagnosticMessage, arg0); + return createFileDiagnostic(file, start, length, diagnosticMessage, arg0); } describe("matchFiles", () => { it("with defaults", () => { const json = {}; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -145,7 +145,7 @@ namespace ts { "c:/dev/x/a.ts" ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive }, }; validateMatches(expected, json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); @@ -159,7 +159,7 @@ namespace ts { "b.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -177,7 +177,7 @@ namespace ts { "x.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -198,7 +198,7 @@ namespace ts { "b.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -219,7 +219,7 @@ namespace ts { "b.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -237,10 +237,10 @@ namespace ts { "b.js" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [ - ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + createCompilerDiagnostic(Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]") ], fileNames: [], @@ -255,10 +255,10 @@ namespace ts { "x.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [ - ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + createCompilerDiagnostic(Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]") ], fileNames: [], @@ -276,7 +276,7 @@ namespace ts { "b.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -302,7 +302,7 @@ namespace ts { "*/b.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -327,7 +327,7 @@ namespace ts { "**/b.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -348,7 +348,7 @@ namespace ts { "**/b.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -368,7 +368,7 @@ namespace ts { "jspm_packages/a.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -396,7 +396,7 @@ namespace ts { "b.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -418,7 +418,7 @@ namespace ts { "jspm_packages/a.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -442,7 +442,7 @@ namespace ts { "x/*.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -457,8 +457,8 @@ namespace ts { "c:/dev/x/b.ts" ], wildcardDirectories: { - "c:/dev/z": ts.WatchDirectoryFlags.None, - "c:/dev/x": ts.WatchDirectoryFlags.None + "c:/dev/z": WatchDirectoryFlags.None, + "c:/dev/x": WatchDirectoryFlags.None }, }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -469,7 +469,7 @@ namespace ts { "*.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -478,7 +478,7 @@ namespace ts { "c:/dev/c.d.ts" ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.None + "c:/dev": WatchDirectoryFlags.None }, }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -489,7 +489,7 @@ namespace ts { "*" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -498,7 +498,7 @@ namespace ts { "c:/dev/c.d.ts" ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.None + "c:/dev": WatchDirectoryFlags.None }, }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -509,7 +509,7 @@ namespace ts { "x/?.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -517,7 +517,7 @@ namespace ts { "c:/dev/x/b.ts" ], wildcardDirectories: { - "c:/dev/x": ts.WatchDirectoryFlags.None + "c:/dev/x": WatchDirectoryFlags.None }, }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -528,7 +528,7 @@ namespace ts { "**/a.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -538,7 +538,7 @@ namespace ts { "c:/dev/z/a.ts" ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive }, }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -551,7 +551,7 @@ namespace ts { "z/**/a.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -560,8 +560,8 @@ namespace ts { "c:/dev/z/a.ts" ], wildcardDirectories: { - "c:/dev/x": ts.WatchDirectoryFlags.Recursive, - "c:/dev/z": ts.WatchDirectoryFlags.Recursive + "c:/dev/x": WatchDirectoryFlags.Recursive, + "c:/dev/z": WatchDirectoryFlags.Recursive }, }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -572,14 +572,14 @@ namespace ts { "**/A.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ "/dev/A.ts" ], wildcardDirectories: { - "/dev": ts.WatchDirectoryFlags.Recursive + "/dev": WatchDirectoryFlags.Recursive }, }; validateMatches(expected, json, caseSensitiveHost, caseSensitiveBasePath); @@ -590,15 +590,15 @@ namespace ts { "*/z.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [ - ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + createCompilerDiagnostic(Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]") ], fileNames: [], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive }, }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath, /*existingOptions*/ undefined, caseInsensitiveTsconfigPath); @@ -615,14 +615,14 @@ namespace ts { "**/a.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ "c:/dev/a.ts" ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive }, }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -637,7 +637,7 @@ namespace ts { "x" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -646,7 +646,7 @@ namespace ts { "c:/dev/c.d.ts" ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -658,7 +658,7 @@ namespace ts { "**/a.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -666,7 +666,7 @@ namespace ts { "c:/dev/x/a.ts" ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive }, }; validateMatches(expected, json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); @@ -680,7 +680,7 @@ namespace ts { "a.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -688,7 +688,7 @@ namespace ts { "c:/dev/x/a.ts" ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive }, }; validateMatches(expected, json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); @@ -700,7 +700,7 @@ namespace ts { ], exclude: [] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -708,7 +708,7 @@ namespace ts { "c:/dev/x/a.ts" ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive }, }; validateMatches(expected, json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); @@ -720,7 +720,7 @@ namespace ts { "**/node_modules/a.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -729,7 +729,7 @@ namespace ts { "c:/dev/node_modules/a.ts" ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive }, }; validateMatches(expected, json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); @@ -740,14 +740,14 @@ namespace ts { "*/a.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ "c:/dev/x/a.ts" ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive }, }; validateMatches(expected, json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); @@ -759,7 +759,7 @@ namespace ts { "node_modules/a.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -767,7 +767,7 @@ namespace ts { "c:/dev/node_modules/a.ts" ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive }, }; validateMatches(expected, json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath); @@ -782,17 +782,17 @@ namespace ts { "js/*" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: { allowJs: false }, errors: [ - ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + createCompilerDiagnostic(Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]") ], fileNames: [], wildcardDirectories: { - "c:/dev/js": ts.WatchDirectoryFlags.None + "c:/dev/js": WatchDirectoryFlags.None } }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath, /*existingOptions*/ undefined, caseInsensitiveTsconfigPath); @@ -806,7 +806,7 @@ namespace ts { "js/*" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: { allowJs: true }, @@ -816,7 +816,7 @@ namespace ts { "c:/dev/js/b.js" ], wildcardDirectories: { - "c:/dev/js": ts.WatchDirectoryFlags.None + "c:/dev/js": WatchDirectoryFlags.None } }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -830,7 +830,7 @@ namespace ts { "js/*.min.js" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: { allowJs: true }, @@ -840,7 +840,7 @@ namespace ts { "c:/dev/js/d.min.js" ], wildcardDirectories: { - "c:/dev/js": ts.WatchDirectoryFlags.None + "c:/dev/js": WatchDirectoryFlags.None } }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -852,7 +852,7 @@ namespace ts { "c:/ext/*" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -862,8 +862,8 @@ namespace ts { "c:/ext/ext.ts" ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.None, - "c:/ext": ts.WatchDirectoryFlags.None + "c:/dev": WatchDirectoryFlags.None, + "c:/ext": WatchDirectoryFlags.None } }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -878,14 +878,14 @@ namespace ts { "**" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ "c:/ext/ext.ts" ], wildcardDirectories: { - "c:/ext": ts.WatchDirectoryFlags.None + "c:/ext": WatchDirectoryFlags.None } }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -899,10 +899,10 @@ namespace ts { "../**" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [ - ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + createCompilerDiagnostic(Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(json.exclude))] , fileNames: [], @@ -919,7 +919,7 @@ namespace ts { "**" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -938,14 +938,14 @@ namespace ts { "c:/ext/b/a..b.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ "c:/ext/ext.ts", ], wildcardDirectories: { - "c:/ext": ts.WatchDirectoryFlags.Recursive + "c:/ext": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -956,7 +956,7 @@ namespace ts { allowJs: false } }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: { allowJs: false }, @@ -967,7 +967,7 @@ namespace ts { "c:/dev/c.tsx", ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath); @@ -979,9 +979,9 @@ namespace ts { allowJs: false } }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: { - jsx: ts.JsxEmit.Preserve, + jsx: JsxEmit.Preserve, allowJs: false }, errors: [], @@ -991,7 +991,7 @@ namespace ts { "c:/dev/c.tsx", ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath); @@ -1003,9 +1003,9 @@ namespace ts { allowJs: false } }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: { - jsx: ts.JsxEmit.ReactNative, + jsx: JsxEmit.ReactNative, allowJs: false }, errors: [], @@ -1015,7 +1015,7 @@ namespace ts { "c:/dev/c.tsx", ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath); @@ -1026,7 +1026,7 @@ namespace ts { allowJs: true } }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: { allowJs: true }, @@ -1039,7 +1039,7 @@ namespace ts { "c:/dev/e.jsx", ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath); @@ -1051,9 +1051,9 @@ namespace ts { allowJs: true } }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: { - jsx: ts.JsxEmit.Preserve, + jsx: JsxEmit.Preserve, allowJs: true }, errors: [], @@ -1065,7 +1065,7 @@ namespace ts { "c:/dev/e.jsx", ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath); @@ -1077,9 +1077,9 @@ namespace ts { allowJs: true } }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: { - jsx: ts.JsxEmit.ReactNative, + jsx: JsxEmit.ReactNative, allowJs: true }, errors: [], @@ -1091,7 +1091,7 @@ namespace ts { "c:/dev/e.jsx", ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath); @@ -1108,7 +1108,7 @@ namespace ts { "js/a*" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: { allowJs: true }, @@ -1117,7 +1117,7 @@ namespace ts { "c:/dev/js/d.min.js" ], wildcardDirectories: { - "c:/dev/js": ts.WatchDirectoryFlags.None + "c:/dev/js": WatchDirectoryFlags.None } }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -1130,11 +1130,11 @@ namespace ts { "**" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [ - createDiagnosticForConfigFile(json, 12, 4, ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**"), - ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + createDiagnosticForConfigFile(json, 12, 4, Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**"), + createCompilerDiagnostic(Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]") ], fileNames: [], @@ -1151,10 +1151,10 @@ namespace ts { "**" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [ - ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + createCompilerDiagnostic(Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(json.exclude)) ], fileNames: [], @@ -1170,7 +1170,7 @@ namespace ts { "**/x/**/*" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -1181,7 +1181,7 @@ namespace ts { "c:/dev/x/y/b.ts", ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath, /*existingOptions*/ undefined, caseInsensitiveTsconfigPath); @@ -1195,7 +1195,7 @@ namespace ts { "**/x/**" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -1203,7 +1203,7 @@ namespace ts { "c:/dev/z/a.ts" ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -1217,11 +1217,11 @@ namespace ts { "**/../*" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [ - createDiagnosticForConfigFile(json, 12, 9, ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/../*"), - ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + createDiagnosticForConfigFile(json, 12, 9, Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/../*"), + createCompilerDiagnostic(Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]") ], fileNames: [], @@ -1236,11 +1236,11 @@ namespace ts { "**/y/../*" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [ - createDiagnosticForConfigFile(json, 12, 11, ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/y/../*"), - ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + createDiagnosticForConfigFile(json, 12, 11, Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/y/../*"), + createCompilerDiagnostic(Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, caseInsensitiveTsconfigPath, JSON.stringify(json.include), "[]") ], fileNames: [], @@ -1258,10 +1258,10 @@ namespace ts { "**/.." ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [ - createDiagnosticForConfigFile(json, 34, 7, ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/..") + createDiagnosticForConfigFile(json, 34, 7, Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/..") ], fileNames: [ "c:/dev/a.ts", @@ -1270,7 +1270,7 @@ namespace ts { "c:/dev/z/a.ts" ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -1285,10 +1285,10 @@ namespace ts { "**/y/.." ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [ - createDiagnosticForConfigFile(json, 34, 9, ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/y/..") + createDiagnosticForConfigFile(json, 34, 9, Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/y/..") ], fileNames: [ "c:/dev/a.ts", @@ -1297,7 +1297,7 @@ namespace ts { "c:/dev/z/a.ts" ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -1309,12 +1309,12 @@ namespace ts { const json = { include: ["z"] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ "a.ts", "aba.ts", "abz.ts", "b.ts", "bba.ts", "bbz.ts" ].map(x => `c:/dev/z/${x}`), wildcardDirectories: { - "c:/dev/z": ts.WatchDirectoryFlags.Recursive + "c:/dev/z": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseInsensitiveHost, caseInsensitiveBasePath); @@ -1330,7 +1330,7 @@ namespace ts { "w/*/*" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -1338,8 +1338,8 @@ namespace ts { "c:/dev/x/y/d.ts", ], wildcardDirectories: { - "c:/dev/x": ts.WatchDirectoryFlags.Recursive, - "c:/dev/w": ts.WatchDirectoryFlags.Recursive + "c:/dev/x": WatchDirectoryFlags.Recursive, + "c:/dev/w": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath); @@ -1352,7 +1352,7 @@ namespace ts { "c:/dev/.z/.b.ts" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -1369,7 +1369,7 @@ namespace ts { "**/.*/*" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -1379,7 +1379,7 @@ namespace ts { "c:/dev/x/.y/a.ts" ], wildcardDirectories: { - "c:/dev": ts.WatchDirectoryFlags.Recursive + "c:/dev": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath); @@ -1391,7 +1391,7 @@ namespace ts { ".z/**/.*" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -1399,8 +1399,8 @@ namespace ts { "c:/dev/.z/.b.ts" ], wildcardDirectories: { - "c:/dev/.z": ts.WatchDirectoryFlags.Recursive, - "c:/dev/x": ts.WatchDirectoryFlags.Recursive + "c:/dev/.z": WatchDirectoryFlags.Recursive, + "c:/dev/x": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath); @@ -1414,10 +1414,10 @@ namespace ts { "**/*" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [ - ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, + createCompilerDiagnostic(Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(json.exclude)) ], fileNames: [], @@ -1435,7 +1435,7 @@ namespace ts { "**/x" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -1453,7 +1453,7 @@ namespace ts { "/dev/z/bbz.ts", ], wildcardDirectories: { - "/dev": ts.WatchDirectoryFlags.Recursive + "/dev": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseSensitiveHost, caseSensitiveBasePath); @@ -1465,7 +1465,7 @@ namespace ts { "**/a/**/b" ] }; - const expected: ts.ParsedCommandLine = { + const expected: ParsedCommandLine = { options: {}, errors: [], fileNames: [ @@ -1476,7 +1476,7 @@ namespace ts { "/dev/q/a/c/b/d.ts", ], wildcardDirectories: { - "/dev": ts.WatchDirectoryFlags.Recursive + "/dev": WatchDirectoryFlags.Recursive } }; validateMatches(expected, json, caseSensitiveHost, caseSensitiveBasePath); diff --git a/src/harness/unittests/moduleResolution.ts b/src/harness/unittests/moduleResolution.ts index 0dd016b2f22..13ff6776a1f 100644 --- a/src/harness/unittests/moduleResolution.ts +++ b/src/harness/unittests/moduleResolution.ts @@ -441,7 +441,7 @@ export = C; "/a/b/c.ts": `/// `, "/a/b/d.ts": "var x" }); - test(files, { module: ts.ModuleKind.AMD }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "/a/b/d.ts"], []); + test(files, { module: ModuleKind.AMD }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "/a/b/d.ts"], []); }); it("should fail when two files used in program differ only in casing (tripleslash references)", () => { @@ -449,7 +449,7 @@ export = C; "/a/b/c.ts": `/// `, "/a/b/d.ts": "var x" }); - test(files, { module: ts.ModuleKind.AMD, forceConsistentCasingInFileNames: true }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "d.ts"], [1149]); + test(files, { module: ModuleKind.AMD, forceConsistentCasingInFileNames: true }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "d.ts"], [1149]); }); it("should fail when two files used in program differ only in casing (imports)", () => { @@ -457,7 +457,7 @@ export = C; "/a/b/c.ts": `import {x} from "D"`, "/a/b/d.ts": "export var x" }); - test(files, { module: ts.ModuleKind.AMD, forceConsistentCasingInFileNames: true }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "d.ts"], [1149]); + test(files, { module: ModuleKind.AMD, forceConsistentCasingInFileNames: true }, "/a/b", /*useCaseSensitiveFileNames*/ false, ["c.ts", "d.ts"], [1149]); }); it("should fail when two files used in program differ only in casing (imports, relative module names)", () => { @@ -465,7 +465,7 @@ export = C; "moduleA.ts": `import {x} from "./ModuleB"`, "moduleB.ts": "export var x" }); - test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "", /*useCaseSensitiveFileNames*/ false, ["moduleA.ts", "moduleB.ts"], [1149]); + test(files, { module: ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "", /*useCaseSensitiveFileNames*/ false, ["moduleA.ts", "moduleB.ts"], [1149]); }); it("should fail when two files exist on disk that differs only in casing", () => { @@ -474,7 +474,7 @@ export = C; "/a/b/D.ts": "export var x", "/a/b/d.ts": "export var y" }); - test(files, { module: ts.ModuleKind.AMD }, "/a/b", /*useCaseSensitiveFileNames*/ true, ["c.ts", "d.ts"], [1149]); + test(files, { module: ModuleKind.AMD }, "/a/b", /*useCaseSensitiveFileNames*/ true, ["c.ts", "d.ts"], [1149]); }); it("should fail when module name in 'require' calls has inconsistent casing", () => { @@ -483,7 +483,7 @@ export = C; "moduleB.ts": `import a = require("./moduleC")`, "moduleC.ts": "export var x" }); - test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "", /*useCaseSensitiveFileNames*/ false, ["moduleA.ts", "moduleB.ts", "moduleC.ts"], [1149, 1149]); + test(files, { module: ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "", /*useCaseSensitiveFileNames*/ false, ["moduleA.ts", "moduleB.ts", "moduleC.ts"], [1149, 1149]); }); it("should fail when module names in 'require' calls has inconsistent casing and current directory has uppercase chars", () => { @@ -496,7 +496,7 @@ import a = require("./moduleA"); import b = require("./moduleB"); ` }); - test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", /*useCaseSensitiveFileNames*/ false, ["moduleD.ts"], [1149]); + test(files, { module: ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", /*useCaseSensitiveFileNames*/ false, ["moduleD.ts"], [1149]); }); it("should not fail when module names in 'require' calls has consistent casing and current directory has uppercase chars", () => { const files = createMapFromTemplate({ @@ -508,7 +508,7 @@ import a = require("./moduleA"); import b = require("./moduleB"); ` }); - test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", /*useCaseSensitiveFileNames*/ false, ["moduleD.ts"], []); + test(files, { module: ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", /*useCaseSensitiveFileNames*/ false, ["moduleD.ts"], []); }); }); diff --git a/src/harness/unittests/reuseProgramStructure.ts b/src/harness/unittests/reuseProgramStructure.ts index 70325831f51..0ba9e6f6351 100644 --- a/src/harness/unittests/reuseProgramStructure.ts +++ b/src/harness/unittests/reuseProgramStructure.ts @@ -884,9 +884,9 @@ namespace ts { }); }); - type FileOrFolder = ts.TestFSWithWatch.FileOrFolder; - import createTestSystem = ts.TestFSWithWatch.createWatchedSystem; - import libFile = ts.TestFSWithWatch.libFile; + type FileOrFolder = TestFSWithWatch.FileOrFolder; + import createTestSystem = TestFSWithWatch.createWatchedSystem; + import libFile = TestFSWithWatch.libFile; describe("isProgramUptoDate should return true when there is no change in compiler options and", () => { function verifyProgramIsUptoDate( diff --git a/src/harness/unittests/session.ts b/src/harness/unittests/session.ts index b690045d7c1..7ba8019e2bd 100644 --- a/src/harness/unittests/session.ts +++ b/src/harness/unittests/session.ts @@ -42,7 +42,7 @@ namespace ts.server { let lastSent: protocol.Message; function createSession(): TestSession { - const opts: server.SessionOptions = { + const opts: SessionOptions = { host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, @@ -181,9 +181,7 @@ namespace ts.server { type: "request" }; - const expected: protocol.StatusResponseBody = { - version: ts.version - }; + const expected: protocol.StatusResponseBody = { version }; assert.deepEqual(session.executeCommand(req).response, expected); }); }); @@ -330,7 +328,7 @@ namespace ts.server { describe("send", () => { it("is an overrideable handle which sends protocol messages over the wire", () => { - const msg: server.protocol.Request = { seq: 0, type: "request", command: "" }; + const msg: protocol.Request = { seq: 0, type: "request", command: "" }; const strmsg = JSON.stringify(msg); const len = 1 + Utils.byteLength(strmsg, "utf8"); const resultMsg = `Content-Length: ${len}\r\n\r\n${strmsg}\n`; @@ -348,7 +346,7 @@ namespace ts.server { item: false }; const command = "newhandle"; - const result: ts.server.HandlerResponse = { + const result: HandlerResponse = { response: respBody, responseRequired: true }; @@ -365,7 +363,7 @@ namespace ts.server { const respBody = { item: false }; - const resp: ts.server.HandlerResponse = { + const resp: HandlerResponse = { response: respBody, responseRequired: true }; @@ -712,7 +710,7 @@ namespace ts.server { const text = `// blank line\nconst x = 0;`; const renameLocationInOldText = text.indexOf("0"); const fileName = "/a.ts"; - const edits: ts.FileTextChanges = { + const edits: FileTextChanges = { fileName, textChanges: [ { diff --git a/src/harness/unittests/telemetry.ts b/src/harness/unittests/telemetry.ts index 5cea42efcf5..27512ba1e8c 100644 --- a/src/harness/unittests/telemetry.ts +++ b/src/harness/unittests/telemetry.ts @@ -7,7 +7,7 @@ namespace ts.projectSystem { const file = makeFile("/a.js"); const et = new TestServerEventManager([file]); et.service.openClientFile(file.path); - et.hasZeroEvent(ts.server.ProjectInfoTelemetryEvent); + et.hasZeroEvent(server.ProjectInfoTelemetryEvent); }); it("only sends an event once", () => { @@ -25,18 +25,18 @@ namespace ts.projectSystem { et.service.openClientFile(file2.path); checkNumberOfProjects(et.service, { inferredProjects: 1 }); - et.hasZeroEvent(ts.server.ProjectInfoTelemetryEvent); + et.hasZeroEvent(server.ProjectInfoTelemetryEvent); et.service.openClientFile(file.path); checkNumberOfProjects(et.service, { configuredProjects: 1, inferredProjects: 1 }); - et.hasZeroEvent(ts.server.ProjectInfoTelemetryEvent); + et.hasZeroEvent(server.ProjectInfoTelemetryEvent); }); it("counts files by extension", () => { const files = ["ts.ts", "tsx.tsx", "moo.ts", "dts.d.ts", "jsx.jsx", "js.js", "badExtension.badExtension"].map(f => makeFile(`/src/${f}`)); const notIncludedFile = makeFile("/bin/ts.js"); - const compilerOptions: ts.CompilerOptions = { allowJs: true }; + const compilerOptions: CompilerOptions = { allowJs: true }; const tsconfig = makeFile("/tsconfig.json", { compilerOptions, include: ["src"] }); const et = new TestServerEventManager([...files, notIncludedFile, tsconfig]); @@ -51,7 +51,7 @@ namespace ts.projectSystem { it("works with external project", () => { const file1 = makeFile("/a.ts"); const et = new TestServerEventManager([file1]); - const compilerOptions: ts.server.protocol.CompilerOptions = { strict: true }; + const compilerOptions: server.protocol.CompilerOptions = { strict: true }; const projectFileName = "/hunter2/foo.csproj"; @@ -92,7 +92,7 @@ namespace ts.projectSystem { it("does not expose paths", () => { const file = makeFile("/a.ts"); - const compilerOptions: ts.CompilerOptions = { + const compilerOptions: CompilerOptions = { project: "", outFile: "hunter2.js", outDir: "hunter2", @@ -122,7 +122,7 @@ namespace ts.projectSystem { // Sensitive data doesn't get through even if sent to an option of safe type checkJs: "hunter2" as any as boolean, }; - const safeCompilerOptions: ts.CompilerOptions = { + const safeCompilerOptions: CompilerOptions = { project: "", outFile: "", outDir: "", @@ -236,7 +236,7 @@ namespace ts.projectSystem { }); }); - function makeFile(path: string, content: {} = ""): projectSystem.FileOrFolder { + function makeFile(path: string, content: {} = ""): FileOrFolder { return { path, content: isString(content) ? "" : JSON.stringify(content) }; } } diff --git a/src/harness/unittests/textStorage.ts b/src/harness/unittests/textStorage.ts index aa8231aa31a..755766bd02f 100644 --- a/src/harness/unittests/textStorage.ts +++ b/src/harness/unittests/textStorage.ts @@ -16,7 +16,7 @@ namespace ts.textStorage { it("text based storage should be have exactly the same as script version cache", () => { - const host = ts.projectSystem.createServerHost([f]); + const host = projectSystem.createServerHost([f]); const ts1 = new server.TextStorage(host, server.asNormalizedPath(f.path)); const ts2 = new server.TextStorage(host, server.asNormalizedPath(f.path)); @@ -51,7 +51,7 @@ namespace ts.textStorage { }); it("should switch to script version cache if necessary", () => { - const host = ts.projectSystem.createServerHost([f]); + const host = projectSystem.createServerHost([f]); const ts1 = new server.TextStorage(host, server.asNormalizedPath(f.path)); ts1.getSnapshot(); diff --git a/src/harness/unittests/transform.ts b/src/harness/unittests/transform.ts index 64f0a19b32d..3cca8f6210c 100644 --- a/src/harness/unittests/transform.ts +++ b/src/harness/unittests/transform.ts @@ -3,7 +3,7 @@ namespace ts { describe("TransformAPI", () => { - function replaceUndefinedWithVoid0(context: ts.TransformationContext) { + function replaceUndefinedWithVoid0(context: TransformationContext) { const previousOnSubstituteNode = context.onSubstituteNode; context.enableSubstitution(SyntaxKind.Identifier); context.onSubstituteNode = (hint, node) => { @@ -18,19 +18,19 @@ namespace ts { } return node; }; - return (file: ts.SourceFile) => file; + return (file: SourceFile) => file; } - function replaceNumberWith2(context: ts.TransformationContext) { + function replaceNumberWith2(context: TransformationContext) { function visitor(node: Node): Node { if (isNumericLiteral(node)) { return createNumericLiteral("2"); } return visitEachChild(node, visitor, context); } - return (file: ts.SourceFile) => visitNode(file, visitor); + return (file: SourceFile) => visitNode(file, visitor); } - function replaceIdentifiersNamedOldNameWithNewName(context: ts.TransformationContext) { + function replaceIdentifiersNamedOldNameWithNewName(context: TransformationContext) { const previousOnSubstituteNode = context.onSubstituteNode; context.enableSubstitution(SyntaxKind.Identifier); context.onSubstituteNode = (hint, node) => { @@ -40,7 +40,7 @@ namespace ts { } return node; }; - return (file: ts.SourceFile) => file; + return (file: SourceFile) => file; } function transformSourceFile(sourceText: string, transformers: TransformerFactory[]) { @@ -73,7 +73,7 @@ namespace ts { }); testBaseline("fromTranspileModule", () => { - return ts.transpileModule(`var oldName = undefined;`, { + return transpileModule(`var oldName = undefined;`, { transformers: { before: [replaceUndefinedWithVoid0], after: [replaceIdentifiersNamedOldNameWithNewName] @@ -85,7 +85,7 @@ namespace ts { }); testBaseline("rewrittenNamespace", () => { - return ts.transpileModule(`namespace Reflect { const x = 1; }`, { + return transpileModule(`namespace Reflect { const x = 1; }`, { transformers: { before: [forceNamespaceRewrite], }, @@ -96,7 +96,7 @@ namespace ts { }); testBaseline("rewrittenNamespaceFollowingClass", () => { - return ts.transpileModule(` + return transpileModule(` class C { foo = 10; static bar = 20 } namespace C { export let x = 10; } `, { @@ -104,90 +104,90 @@ namespace ts { before: [forceNamespaceRewrite], }, compilerOptions: { - target: ts.ScriptTarget.ESNext, + target: ScriptTarget.ESNext, newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; }); testBaseline("transformTypesInExportDefault", () => { - return ts.transpileModule(` + return transpileModule(` export default (foo: string) => { return 1; } `, { transformers: { before: [replaceNumberWith2], }, compilerOptions: { - target: ts.ScriptTarget.ESNext, + target: ScriptTarget.ESNext, newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; }); testBaseline("synthesizedClassAndNamespaceCombination", () => { - return ts.transpileModule("", { + return transpileModule("", { transformers: { before: [replaceWithClassAndNamespace], }, compilerOptions: { - target: ts.ScriptTarget.ESNext, + target: ScriptTarget.ESNext, newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; function replaceWithClassAndNamespace() { - return (sourceFile: ts.SourceFile) => { + return (sourceFile: SourceFile) => { const result = getMutableClone(sourceFile); - result.statements = ts.createNodeArray([ - ts.createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, "Foo", /*typeParameters*/ undefined, /*heritageClauses*/ undefined, /*members*/ undefined), - ts.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createIdentifier("Foo"), createModuleBlock([createEmptyStatement()])) + result.statements = createNodeArray([ + createClassDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, "Foo", /*typeParameters*/ undefined, /*heritageClauses*/ undefined, /*members*/ undefined), + createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createIdentifier("Foo"), createModuleBlock([createEmptyStatement()])) ]); return result; }; } }); - function forceNamespaceRewrite(context: ts.TransformationContext) { - return (sourceFile: ts.SourceFile): ts.SourceFile => { + function forceNamespaceRewrite(context: TransformationContext) { + return (sourceFile: SourceFile): SourceFile => { return visitNode(sourceFile); - function visitNode(node: T): T { - if (node.kind === ts.SyntaxKind.ModuleBlock) { - const block = node as T & ts.ModuleBlock; - const statements = ts.createNodeArray([...block.statements]); - return ts.updateModuleBlock(block, statements) as typeof block; + function visitNode(node: T): T { + if (node.kind === SyntaxKind.ModuleBlock) { + const block = node as T & ModuleBlock; + const statements = createNodeArray([...block.statements]); + return updateModuleBlock(block, statements) as typeof block; } - return ts.visitEachChild(node, visitNode, context); + return visitEachChild(node, visitNode, context); } }; } testBaseline("transformAwayExportStar", () => { - return ts.transpileModule("export * from './helper';", { + return transpileModule("export * from './helper';", { transformers: { before: [expandExportStar], }, compilerOptions: { - target: ts.ScriptTarget.ESNext, + target: ScriptTarget.ESNext, newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; - function expandExportStar(context: ts.TransformationContext) { - return (sourceFile: ts.SourceFile): ts.SourceFile => { + function expandExportStar(context: TransformationContext) { + return (sourceFile: SourceFile): SourceFile => { return visitNode(sourceFile); - function visitNode(node: T): T { - if (node.kind === ts.SyntaxKind.ExportDeclaration) { - const ed = node as ts.Node as ts.ExportDeclaration; + function visitNode(node: T): T { + if (node.kind === SyntaxKind.ExportDeclaration) { + const ed = node as Node as ExportDeclaration; const exports = [{ name: "x" }]; - const exportSpecifiers = exports.map(e => ts.createExportSpecifier(e.name, e.name)); - const exportClause = ts.createNamedExports(exportSpecifiers); - const newEd = ts.updateExportDeclaration(ed, ed.decorators, ed.modifiers, exportClause, ed.moduleSpecifier); + const exportSpecifiers = exports.map(e => createExportSpecifier(e.name, e.name)); + const exportClause = createNamedExports(exportSpecifiers); + const newEd = updateExportDeclaration(ed, ed.decorators, ed.modifiers, exportClause, ed.moduleSpecifier); - return newEd as ts.Node as T; + return newEd as Node as T; } - return ts.visitEachChild(node, visitNode, context); + return visitEachChild(node, visitNode, context); } }; } @@ -195,58 +195,58 @@ namespace ts { // https://github.com/Microsoft/TypeScript/issues/19618 testBaseline("transformAddImportStar", () => { - return ts.transpileModule("", { + return transpileModule("", { transformers: { before: [transformAddImportStar], }, compilerOptions: { - target: ts.ScriptTarget.ES5, - module: ts.ModuleKind.System, + target: ScriptTarget.ES5, + module: ModuleKind.System, newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; - function transformAddImportStar(_context: ts.TransformationContext) { - return (sourceFile: ts.SourceFile): ts.SourceFile => { + function transformAddImportStar(_context: TransformationContext) { + return (sourceFile: SourceFile): SourceFile => { return visitNode(sourceFile); }; - function visitNode(sf: ts.SourceFile) { + function visitNode(sf: SourceFile) { // produce `import * as i0 from './comp'; - const importStar = ts.createImportDeclaration( + const importStar = createImportDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, - /*importClause*/ ts.createImportClause( + /*importClause*/ createImportClause( /*name*/ undefined, - ts.createNamespaceImport(ts.createIdentifier("i0")) + createNamespaceImport(createIdentifier("i0")) ), - /*moduleSpecifier*/ ts.createLiteral("./comp1")); - return ts.updateSourceFileNode(sf, [importStar]); + /*moduleSpecifier*/ createLiteral("./comp1")); + return updateSourceFileNode(sf, [importStar]); } } }); // https://github.com/Microsoft/TypeScript/issues/17384 testBaseline("transformAddDecoratedNode", () => { - return ts.transpileModule("", { + return transpileModule("", { transformers: { before: [transformAddDecoratedNode], }, compilerOptions: { - target: ts.ScriptTarget.ES5, + target: ScriptTarget.ES5, newLine: NewLineKind.CarriageReturnLineFeed, } }).outputText; - function transformAddDecoratedNode(_context: ts.TransformationContext) { - return (sourceFile: ts.SourceFile): ts.SourceFile => { + function transformAddDecoratedNode(_context: TransformationContext) { + return (sourceFile: SourceFile): SourceFile => { return visitNode(sourceFile); }; - function visitNode(sf: ts.SourceFile) { + function visitNode(sf: SourceFile) { // produce `class Foo { @Bar baz() {} }`; - const classDecl = ts.createClassDeclaration([], [], "Foo", /*typeParameters*/ undefined, /*heritageClauses*/ undefined, [ - ts.createMethod([ts.createDecorator(ts.createIdentifier("Bar"))], [], /**/ undefined, "baz", /**/ undefined, /**/ undefined, [], /**/ undefined, ts.createBlock([])) + const classDecl = createClassDeclaration([], [], "Foo", /*typeParameters*/ undefined, /*heritageClauses*/ undefined, [ + createMethod([createDecorator(createIdentifier("Bar"))], [], /**/ undefined, "baz", /**/ undefined, /**/ undefined, [], /**/ undefined, createBlock([])) ]); - return ts.updateSourceFileNode(sf, [classDecl]); + return updateSourceFileNode(sf, [classDecl]); } } }); diff --git a/src/harness/unittests/transpile.ts b/src/harness/unittests/transpile.ts index 7c4af8be167..7cf663bf06e 100644 --- a/src/harness/unittests/transpile.ts +++ b/src/harness/unittests/transpile.ts @@ -24,7 +24,7 @@ namespace ts { if (transpileOptions.compilerOptions.newLine === undefined) { // use \r\n as default new line - transpileOptions.compilerOptions.newLine = ts.NewLineKind.CarriageReturnLineFeed; + transpileOptions.compilerOptions.newLine = NewLineKind.CarriageReturnLineFeed; } transpileOptions.compilerOptions.sourceMap = true; @@ -85,7 +85,7 @@ namespace ts { } it("Correct output for " + justName, () => { - Harness.Baseline.runBaseline(justName.replace(/\.tsx?$/, ts.Extension.Js), () => { + Harness.Baseline.runBaseline(justName.replace(/\.tsx?$/, Extension.Js), () => { if (transpileResult.outputText) { return transpileResult.outputText; } diff --git a/src/harness/unittests/tscWatchMode.ts b/src/harness/unittests/tscWatchMode.ts index 5f5d871304f..1c23eb04ea4 100644 --- a/src/harness/unittests/tscWatchMode.ts +++ b/src/harness/unittests/tscWatchMode.ts @@ -4,15 +4,15 @@ namespace ts.tscWatch { - import WatchedSystem = ts.TestFSWithWatch.TestServerHost; - type FileOrFolder = ts.TestFSWithWatch.FileOrFolder; - import createWatchedSystem = ts.TestFSWithWatch.createWatchedSystem; - import checkFileNames = ts.TestFSWithWatch.checkFileNames; - import libFile = ts.TestFSWithWatch.libFile; - import checkWatchedFiles = ts.TestFSWithWatch.checkWatchedFiles; - import checkWatchedDirectories = ts.TestFSWithWatch.checkWatchedDirectories; - import checkOutputContains = ts.TestFSWithWatch.checkOutputContains; - import checkOutputDoesNotContain = ts.TestFSWithWatch.checkOutputDoesNotContain; + import WatchedSystem = TestFSWithWatch.TestServerHost; + type FileOrFolder = TestFSWithWatch.FileOrFolder; + import createWatchedSystem = TestFSWithWatch.createWatchedSystem; + import checkFileNames = TestFSWithWatch.checkFileNames; + import libFile = TestFSWithWatch.libFile; + import checkWatchedFiles = TestFSWithWatch.checkWatchedFiles; + import checkWatchedDirectories = TestFSWithWatch.checkWatchedDirectories; + import checkOutputContains = TestFSWithWatch.checkOutputContains; + import checkOutputDoesNotContain = TestFSWithWatch.checkOutputDoesNotContain; export function checkProgramActualFiles(program: Program, expectedFiles: string[]) { checkFileNames(`Program actual files`, program.getSourceFiles().map(file => file.fileName), expectedFiles); @@ -23,7 +23,7 @@ namespace ts.tscWatch { } function createWatchOfConfigFile(configFileName: string, host: WatchedSystem, maxNumberOfFilesToIterateForInvalidation?: number) { - const compilerHost = ts.createWatchCompilerHostOfConfigFile(configFileName, {}, host); + const compilerHost = createWatchCompilerHostOfConfigFile(configFileName, {}, host); compilerHost.maxNumberOfFilesToIterateForInvalidation = maxNumberOfFilesToIterateForInvalidation; const watch = createWatchProgram(compilerHost); return () => watch.getCurrentProgram().getProgram(); @@ -111,7 +111,7 @@ namespace ts.tscWatch { }); if (!skipWaiting) { if (errorsPosition === ExpectedOutputErrorsPosition.BeforeCompilationStarts) { - assertWatchDiagnosticAt(host, index, ts.Diagnostics.Starting_compilation_in_watch_mode); + assertWatchDiagnosticAt(host, index, Diagnostics.Starting_compilation_in_watch_mode); index += 1; } assertWatchDiagnosticAt(host, index, Diagnostics.Compilation_complete_Watching_for_file_changes); diff --git a/src/harness/unittests/tsconfigParsing.ts b/src/harness/unittests/tsconfigParsing.ts index 8d56360bba5..cf2ef33866b 100644 --- a/src/harness/unittests/tsconfigParsing.ts +++ b/src/harness/unittests/tsconfigParsing.ts @@ -4,41 +4,41 @@ namespace ts { describe("parseConfigFileTextToJson", () => { function assertParseResult(jsonText: string, expectedConfigObject: { config?: any; error?: Diagnostic[] }) { - const parsed = ts.parseConfigFileTextToJson("/apath/tsconfig.json", jsonText); + const parsed = parseConfigFileTextToJson("/apath/tsconfig.json", jsonText); assert.equal(JSON.stringify(parsed), JSON.stringify(expectedConfigObject)); } function assertParseError(jsonText: string) { - const parsed = ts.parseConfigFileTextToJson("/apath/tsconfig.json", jsonText); + const parsed = parseConfigFileTextToJson("/apath/tsconfig.json", jsonText); assert.deepEqual(parsed.config, {}); assert.isTrue(undefined !== parsed.error); } function assertParseErrorWithExcludesKeyword(jsonText: string) { { - const parsed = ts.parseConfigFileTextToJson("/apath/tsconfig.json", jsonText); - const parsedCommand = ts.parseJsonConfigFileContent(parsed.config, ts.sys, "tests/cases/unittests"); + const parsed = parseConfigFileTextToJson("/apath/tsconfig.json", jsonText); + const parsedCommand = parseJsonConfigFileContent(parsed.config, sys, "tests/cases/unittests"); assert.isTrue(parsedCommand.errors && parsedCommand.errors.length === 1 && - parsedCommand.errors[0].code === ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude.code); + parsedCommand.errors[0].code === Diagnostics.Unknown_option_excludes_Did_you_mean_exclude.code); } { - const parsed = ts.parseJsonText("/apath/tsconfig.json", jsonText); - const parsedCommand = ts.parseJsonSourceFileConfigFileContent(parsed, ts.sys, "tests/cases/unittests"); + const parsed = parseJsonText("/apath/tsconfig.json", jsonText); + const parsedCommand = parseJsonSourceFileConfigFileContent(parsed, sys, "tests/cases/unittests"); assert.isTrue(parsedCommand.errors && parsedCommand.errors.length === 1 && - parsedCommand.errors[0].code === ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude.code); + parsedCommand.errors[0].code === Diagnostics.Unknown_option_excludes_Did_you_mean_exclude.code); } } function getParsedCommandJson(jsonText: string, configFileName: string, basePath: string, allFileList: string[]) { - const parsed = ts.parseConfigFileTextToJson(configFileName, jsonText); + const parsed = parseConfigFileTextToJson(configFileName, jsonText); const host: ParseConfigHost = new Utils.MockParseConfigHost(basePath, true, allFileList); - return ts.parseJsonConfigFileContent(parsed.config, host, basePath, /*existingOptions*/ undefined, configFileName); + return parseJsonConfigFileContent(parsed.config, host, basePath, /*existingOptions*/ undefined, configFileName); } function getParsedCommandJsonNode(jsonText: string, configFileName: string, basePath: string, allFileList: string[]) { - const parsed = ts.parseJsonText(configFileName, jsonText); + const parsed = parseJsonText(configFileName, jsonText); const host: ParseConfigHost = new Utils.MockParseConfigHost(basePath, true, allFileList); - return ts.parseJsonSourceFileConfigFileContent(parsed, host, basePath, /*existingOptions*/ undefined, configFileName); + return parseJsonSourceFileConfigFileContent(parsed, host, basePath, /*existingOptions*/ undefined, configFileName); } function assertParseFileList(jsonText: string, configFileName: string, basePath: string, allFileList: string[], expectedFileList: string[]) { diff --git a/src/harness/unittests/tsserverProjectSystem.ts b/src/harness/unittests/tsserverProjectSystem.ts index f596896aacb..10f958ff800 100644 --- a/src/harness/unittests/tsserverProjectSystem.ts +++ b/src/harness/unittests/tsserverProjectSystem.ts @@ -7,14 +7,14 @@ namespace ts.projectSystem { import protocol = server.protocol; import CommandNames = server.CommandNames; - export import TestServerHost = ts.TestFSWithWatch.TestServerHost; - export type FileOrFolder = ts.TestFSWithWatch.FileOrFolder; - export import createServerHost = ts.TestFSWithWatch.createServerHost; - export import checkFileNames = ts.TestFSWithWatch.checkFileNames; - export import libFile = ts.TestFSWithWatch.libFile; - export import checkWatchedFiles = ts.TestFSWithWatch.checkWatchedFiles; - import checkWatchedDirectories = ts.TestFSWithWatch.checkWatchedDirectories; - import safeList = ts.TestFSWithWatch.safeList; + export import TestServerHost = TestFSWithWatch.TestServerHost; + export type FileOrFolder = TestFSWithWatch.FileOrFolder; + export import createServerHost = TestFSWithWatch.createServerHost; + export import checkFileNames = TestFSWithWatch.checkFileNames; + export import libFile = TestFSWithWatch.libFile; + export import checkWatchedFiles = TestFSWithWatch.checkWatchedFiles; + import checkWatchedDirectories = TestFSWithWatch.checkWatchedDirectories; + import safeList = TestFSWithWatch.safeList; export const customTypesMap = { path: "/typesMap.json", @@ -167,8 +167,8 @@ namespace ts.projectSystem { private events: server.ProjectServiceEvent[] = []; readonly session: TestSession; readonly service: server.ProjectService; - readonly host: projectSystem.TestServerHost; - constructor(files: projectSystem.FileOrFolder[]) { + readonly host: TestServerHost; + constructor(files: FileOrFolder[]) { this.host = createServerHost(files); this.session = createSession(this.host, { canUseEvents: true, @@ -210,7 +210,7 @@ namespace ts.projectSystem { } assertProjectInfoTelemetryEvent(partial: Partial, configFile?: string): void { - assert.deepEqual(this.getEvent(ts.server.ProjectInfoTelemetryEvent), { + assert.deepEqual(this.getEvent(server.ProjectInfoTelemetryEvent), { projectId: Harness.mockHash(configFile || "/tsconfig.json"), fileStats: fileStats({ ts: 1 }), compilerOptions: {}, @@ -227,7 +227,7 @@ namespace ts.projectSystem { configFileName: "tsconfig.json", projectType: "configured", languageServiceEnabled: true, - version: ts.version, + version, ...partial, }); } @@ -474,15 +474,15 @@ namespace ts.projectSystem { } function checkErrorMessage(session: TestSession, eventName: protocol.DiagnosticEventKind, diagnostics: protocol.DiagnosticEventBody, isMostRecent = false): void { - checkNthEvent(session, ts.server.toEvent(eventName, diagnostics), 0, isMostRecent); + checkNthEvent(session, server.toEvent(eventName, diagnostics), 0, isMostRecent); } function checkCompleteEvent(session: TestSession, numberOfCurrentEvents: number, expectedSequenceId: number, isMostRecent = true): void { - checkNthEvent(session, ts.server.toEvent("requestCompleted", { request_seq: expectedSequenceId }), numberOfCurrentEvents - 1, isMostRecent); + checkNthEvent(session, server.toEvent("requestCompleted", { request_seq: expectedSequenceId }), numberOfCurrentEvents - 1, isMostRecent); } function checkProjectUpdatedInBackgroundEvent(session: TestSession, openFiles: string[]) { - checkNthEvent(session, ts.server.toEvent("projectsUpdatedInBackground", { openFiles }), 0, /*isMostRecent*/ true); + checkNthEvent(session, server.toEvent("projectsUpdatedInBackground", { openFiles }), 0, /*isMostRecent*/ true); } function checkNthEvent(session: TestSession, expectedEvent: protocol.Event, index: number, isMostRecent: boolean) { @@ -4890,7 +4890,7 @@ namespace ts.projectSystem { command: server.CommandNames.CompilerOptionsDiagnosticsFull, seq: 2, arguments: { projectFileName } - }).response as ReadonlyArray; + }).response as ReadonlyArray; assert.isTrue(diags.length === 0); session.executeCommand({ @@ -4908,7 +4908,7 @@ namespace ts.projectSystem { command: server.CommandNames.CompilerOptionsDiagnosticsFull, seq: 4, arguments: { projectFileName } - }).response as ReadonlyArray; + }).response as ReadonlyArray; assert.isTrue(diagsAfterUpdate.length === 0); }); }); @@ -5072,7 +5072,7 @@ namespace ts.projectSystem { describe("tsserverProjectSystem cancellationToken", () => { // Disable sourcemap support for the duration of the test, as sourcemapping the errors generated during this test is slow and not something we care to test - let oldPrepare: ts.AnyFunction; + let oldPrepare: AnyFunction; before(() => { oldPrepare = (Error as any).prepareStackTrace; delete (Error as any).prepareStackTrace; @@ -5623,7 +5623,7 @@ namespace ts.projectSystem { function verifyCalledOnEachEntry(callback: CalledMaps, expectedKeys: Map) { const calledMap = calledMaps[callback]; - ts.TestFSWithWatch.verifyMapSize(callback, calledMap, arrayFrom(expectedKeys.keys())); + TestFSWithWatch.verifyMapSize(callback, calledMap, arrayFrom(expectedKeys.keys())); expectedKeys.forEach((called, name) => { assert.isTrue(calledMap.has(name), `${callback} is expected to contain ${name}, actual keys: ${arrayFrom(calledMap.keys())}`); assert.equal(calledMap.get(name).length, called, `${callback} is expected to be called ${called} times with ${name}. Actual entry: ${calledMap.get(name)}`); @@ -5674,7 +5674,7 @@ namespace ts.projectSystem { const host = createServerHost([root, imported]); const projectService = createProjectService(host); - projectService.setCompilerOptionsForInferredProjects({ module: ts.ModuleKind.AMD, noLib: true }); + projectService.setCompilerOptionsForInferredProjects({ module: ModuleKind.AMD, noLib: true }); projectService.openClientFile(root.path); checkNumberOfProjects(projectService, { inferredProjects: 1 }); const project = projectService.inferredProjects[0]; @@ -5720,7 +5720,7 @@ namespace ts.projectSystem { // setting compiler options discards module resolution cache callsTrackingHost.clear(); - projectService.setCompilerOptionsForInferredProjects({ module: ts.ModuleKind.AMD, noLib: true, target: ts.ScriptTarget.ES5 }); + projectService.setCompilerOptionsForInferredProjects({ module: ModuleKind.AMD, noLib: true, target: ScriptTarget.ES5 }); verifyImportedDiagnostics(); vertifyF1Lookups(); @@ -5790,7 +5790,7 @@ namespace ts.projectSystem { const host = createServerHost([root]); const projectService = createProjectService(host); - projectService.setCompilerOptionsForInferredProjects({ module: ts.ModuleKind.AMD, noLib: true }); + projectService.setCompilerOptionsForInferredProjects({ module: ModuleKind.AMD, noLib: true }); const callsTrackingHost = createCallsTrackingHost(host); projectService.openClientFile(root.path); checkNumberOfProjects(projectService, { inferredProjects: 1 }); @@ -6754,7 +6754,7 @@ namespace ts.projectSystem { const events: protocol.ProjectsUpdatedInBackgroundEvent[] = filter( map( host.getOutput(), s => convertToObject( - ts.parseJsonText("json.json", s.replace(outputEventRegex, "")), + parseJsonText("json.json", s.replace(outputEventRegex, "")), [] ) ), diff --git a/src/harness/unittests/typingsInstaller.ts b/src/harness/unittests/typingsInstaller.ts index b5265c5e5f2..0a27f860352 100644 --- a/src/harness/unittests/typingsInstaller.ts +++ b/src/harness/unittests/typingsInstaller.ts @@ -1387,7 +1387,7 @@ namespace ts.projectSystem { node: { typingLocation: node.path, version: Semver.parse("1.0.0") } }); const registry = createTypesRegistry("node"); - registry.delete(`ts${ts.versionMajorMinor}`); + registry.delete(`ts${versionMajorMinor}`); const logger = trackingLogger(); const result = JsTyping.discoverTypings(host, logger.log, [app.path], getDirectoryPath(app.path), emptySafeList, cache, { enable: true }, ["http"], registry); assert.deepEqual(logger.finish(), [ @@ -1419,7 +1419,7 @@ namespace ts.projectSystem { commander: { typingLocation: commander.path, version: Semver.parse("1.3.0-next.0") } }); const registry = createTypesRegistry("node", "commander"); - registry.get("node")[`ts${ts.versionMajorMinor}`] = "1.3.0-next.1"; + registry.get("node")[`ts${versionMajorMinor}`] = "1.3.0-next.1"; const logger = trackingLogger(); const result = JsTyping.discoverTypings(host, logger.log, [app.path], getDirectoryPath(app.path), emptySafeList, cache, { enable: true }, ["http", "commander"], registry); assert.deepEqual(logger.finish(), [ diff --git a/src/harness/unittests/versionCache.ts b/src/harness/unittests/versionCache.ts index 3062a55170c..f688a9e56bb 100644 --- a/src/harness/unittests/versionCache.ts +++ b/src/harness/unittests/versionCache.ts @@ -302,7 +302,7 @@ and grew 1cm per day`; it("Line/offset from pos", () => { for (let i = 0; i < iterationCount; i++) { const lp = lineIndex.positionToLineOffset(rsa[i]); - const lac = ts.computeLineAndCharacterOfPosition(lineMap, rsa[i]); + const lac = computeLineAndCharacterOfPosition(lineMap, rsa[i]); assert.equal(lac.line + 1, lp.line, "Line number mismatch " + (lac.line + 1) + " " + lp.line + " " + i); assert.equal(lac.character, lp.offset - 1, "Character offset mismatch " + lac.character + " " + (lp.offset - 1) + " " + i); } diff --git a/src/harness/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index 54a353a59c6..d518ce5e2c4 100644 --- a/src/harness/virtualFileSystemWithWatch.ts +++ b/src/harness/virtualFileSystemWithWatch.ts @@ -624,7 +624,7 @@ interface Array {}` } readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[] { - return ts.matchFiles(path, extensions, exclude, include, this.useCaseSensitiveFileNames, this.getCurrentDirectory(), depth, (dir) => { + return matchFiles(path, extensions, exclude, include, this.useCaseSensitiveFileNames, this.getCurrentDirectory(), depth, (dir) => { const directories: string[] = []; const files: string[] = []; const folder = this.getRealFolder(this.toPath(dir)); diff --git a/src/server/client.ts b/src/server/client.ts index 6f04f141957..f4e70cae59e 100644 --- a/src/server/client.ts +++ b/src/server/client.ts @@ -71,7 +71,7 @@ namespace ts.server { }; } - private convertCodeEditsToTextChange(fileName: string, codeEdit: protocol.CodeEdit): ts.TextChange { + private convertCodeEditsToTextChange(fileName: string, codeEdit: protocol.CodeEdit): TextChange { return { span: this.decodeSpan(codeEdit, fileName), newText: codeEdit.newText }; } @@ -229,7 +229,7 @@ namespace ts.server { })); } - getFormattingEditsForRange(file: string, start: number, end: number, _options: FormatCodeOptions): ts.TextChange[] { + getFormattingEditsForRange(file: string, start: number, end: number, _options: FormatCodeOptions): TextChange[] { const args: protocol.FormatRequestArgs = this.createFileLocationRequestArgsWithEndLineAndOffset(file, start, end); @@ -240,11 +240,11 @@ namespace ts.server { return response.body.map(entry => this.convertCodeEditsToTextChange(file, entry)); } - getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): ts.TextChange[] { + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[] { return this.getFormattingEditsForRange(fileName, 0, this.host.getScriptSnapshot(fileName).getLength(), options); } - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, _options: FormatCodeOptions): ts.TextChange[] { + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, _options: FormatCodeOptions): TextChange[] { const args: protocol.FormatOnKeyRequestArgs = { ...this.createFileLocationRequestArgs(fileName, position), key }; // TODO: handle FormatCodeOptions @@ -640,7 +640,7 @@ namespace ts.server { })); } - convertTextChangeToCodeEdit(change: protocol.CodeEdit, fileName: string): ts.TextChange { + convertTextChangeToCodeEdit(change: protocol.CodeEdit, fileName: string): TextChange { return { span: this.decodeSpan(change, fileName), newText: change.newText ? change.newText : "" diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index c525d5a3bc8..6c493bd35a1 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -448,19 +448,19 @@ namespace ts.server { this.documentRegistry = createDocumentRegistry(this.host.useCaseSensitiveFileNames, this.currentDirectory); if (this.logger.hasLevel(LogLevel.verbose)) { - this.watchFile = (host, file, cb, watchType, project) => ts.addFileWatcherWithLogging(host, file, cb, this.createWatcherLog(watchType, project)); - this.watchFilePath = (host, file, cb, path, watchType, project) => ts.addFilePathWatcherWithLogging(host, file, cb, path, this.createWatcherLog(watchType, project)); - this.watchDirectory = (host, dir, cb, flags, watchType, project) => ts.addDirectoryWatcherWithLogging(host, dir, cb, flags, this.createWatcherLog(watchType, project)); + this.watchFile = (host, file, cb, watchType, project) => addFileWatcherWithLogging(host, file, cb, this.createWatcherLog(watchType, project)); + this.watchFilePath = (host, file, cb, path, watchType, project) => addFilePathWatcherWithLogging(host, file, cb, path, this.createWatcherLog(watchType, project)); + this.watchDirectory = (host, dir, cb, flags, watchType, project) => addDirectoryWatcherWithLogging(host, dir, cb, flags, this.createWatcherLog(watchType, project)); } else if (this.logger.loggingEnabled()) { - this.watchFile = (host, file, cb, watchType, project) => ts.addFileWatcherWithOnlyTriggerLogging(host, file, cb, this.createWatcherLog(watchType, project)); - this.watchFilePath = (host, file, cb, path, watchType, project) => ts.addFilePathWatcherWithOnlyTriggerLogging(host, file, cb, path, this.createWatcherLog(watchType, project)); - this.watchDirectory = (host, dir, cb, flags, watchType, project) => ts.addDirectoryWatcherWithOnlyTriggerLogging(host, dir, cb, flags, this.createWatcherLog(watchType, project)); + this.watchFile = (host, file, cb, watchType, project) => addFileWatcherWithOnlyTriggerLogging(host, file, cb, this.createWatcherLog(watchType, project)); + this.watchFilePath = (host, file, cb, path, watchType, project) => addFilePathWatcherWithOnlyTriggerLogging(host, file, cb, path, this.createWatcherLog(watchType, project)); + this.watchDirectory = (host, dir, cb, flags, watchType, project) => addDirectoryWatcherWithOnlyTriggerLogging(host, dir, cb, flags, this.createWatcherLog(watchType, project)); } else { - this.watchFile = ts.addFileWatcher; - this.watchFilePath = ts.addFilePathWatcher; - this.watchDirectory = ts.addDirectoryWatcher; + this.watchFile = addFileWatcher; + this.watchFilePath = addFilePathWatcher; + this.watchDirectory = addDirectoryWatcher; } } @@ -1412,7 +1412,7 @@ namespace ts.server { return project; } - private sendProjectTelemetry(projectKey: string, project: server.ExternalProject | server.ConfiguredProject, projectOptions?: ProjectOptions): void { + private sendProjectTelemetry(projectKey: string, project: ExternalProject | ConfiguredProject, projectOptions?: ProjectOptions): void { if (this.seenProjects.has(projectKey)) { return; } @@ -1433,18 +1433,18 @@ namespace ts.server { exclude: projectOptions && projectOptions.configHasExcludeProperty, compileOnSave: project.compileOnSaveEnabled, configFileName: configFileName(), - projectType: project instanceof server.ExternalProject ? "external" : "configured", + projectType: project instanceof ExternalProject ? "external" : "configured", languageServiceEnabled: project.languageServiceEnabled, version, }; this.eventHandler({ eventName: ProjectInfoTelemetryEvent, data }); function configFileName(): ProjectInfoTelemetryEventData["configFileName"] { - if (!(project instanceof server.ConfiguredProject)) { + if (!(project instanceof ConfiguredProject)) { return "other"; } - const configFilePath = project instanceof server.ConfiguredProject && project.getConfigFilePath(); + const configFilePath = project instanceof ConfiguredProject && project.getConfigFilePath(); return getBaseConfigFileName(configFilePath) || "other"; } @@ -2256,7 +2256,7 @@ namespace ts.server { } const excludeRegexes = excludeRules.map(e => new RegExp(e, "i")); - const filesToKeep: ts.server.protocol.ExternalFile[] = []; + const filesToKeep: protocol.ExternalFile[] = []; for (let i = 0; i < proj.rootFiles.length; i++) { if (excludeRegexes.some(re => re.test(normalizedNames[i]))) { excludedFiles.push(normalizedNames[i]); diff --git a/src/server/project.ts b/src/server/project.ts index bfd039f26fb..e155466a10e 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -860,7 +860,7 @@ namespace ts.server { } protected removeExistingTypings(include: string[]): string[] { - const existing = ts.getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost); + const existing = getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost); return include.filter(i => existing.indexOf(i) < 0); } diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 40bee65e9f0..ea312196d0b 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -1,3 +1,5 @@ +// tslint:disable no-unnecessary-qualifier + /** * Declaration module describing the TypeScript Server protocol */ diff --git a/src/server/server.ts b/src/server/server.ts index 7f545ff3875..f70280c34a3 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -142,7 +142,7 @@ namespace ts.server { terminal: false, }); - class Logger implements server.Logger { + class Logger implements server.Logger { // tslint:disable-line no-unnecessary-qualifier private fd = -1; private seq = 0; private inGroup = false; @@ -266,7 +266,7 @@ namespace ts.server { constructor( private readonly telemetryEnabled: boolean, - private readonly logger: server.Logger, + private readonly logger: Logger, private readonly host: ServerHost, readonly globalTypingsCacheLocation: string, readonly typingSafeListLocation: string, @@ -391,7 +391,7 @@ namespace ts.server { switch (response.kind) { case EventTypesRegistry: - this.typesRegistryCache = ts.createMapFromTemplate(response.typesRegistry); + this.typesRegistryCache = createMapFromTemplate(response.typesRegistry); break; case ActionPackageInstalled: { const { success, message } = response; diff --git a/src/server/session.ts b/src/server/session.ts index 4f0981a3880..92b0c2ad02b 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -105,7 +105,7 @@ namespace ts.server { project: Project; } - function allEditsBeforePos(edits: ts.TextChange[], pos: number) { + function allEditsBeforePos(edits: TextChange[], pos: number) { for (const edit of edits) { if (textSpanEnd(edit.span) >= pos) { return false; @@ -122,7 +122,7 @@ namespace ts.server { export type CommandNames = protocol.CommandTypes; export const CommandNames = (protocol).CommandTypes; // tslint:disable-line variable-name - export function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string { + export function formatMessage(msg: T, logger: Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string { const verboseLogging = logger.hasLevel(LogLevel.verbose); const json = JSON.stringify(msg); @@ -1713,7 +1713,7 @@ namespace ts.server { }; } - private convertTextChangeToCodeEdit(change: ts.TextChange, scriptInfo: ScriptInfo): protocol.CodeEdit { + private convertTextChangeToCodeEdit(change: TextChange, scriptInfo: ScriptInfo): protocol.CodeEdit { return { start: scriptInfo.positionToLineOffset(change.span.start), end: scriptInfo.positionToLineOffset(change.span.start + change.span.length), diff --git a/src/server/typingsInstaller/nodeTypingsInstaller.ts b/src/server/typingsInstaller/nodeTypingsInstaller.ts index b0844b2369c..018dac7ec10 100644 --- a/src/server/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/server/typingsInstaller/nodeTypingsInstaller.ts @@ -221,11 +221,11 @@ namespace ts.server.typingsInstaller { }); } - const logFilePath = findArgument(server.Arguments.LogFile); - const globalTypingsCacheLocation = findArgument(server.Arguments.GlobalCacheLocation); - const typingSafeListLocation = findArgument(server.Arguments.TypingSafeListLocation); - const typesMapLocation = findArgument(server.Arguments.TypesMapLocation); - const npmLocation = findArgument(server.Arguments.NpmLocation); + const logFilePath = findArgument(Arguments.LogFile); + const globalTypingsCacheLocation = findArgument(Arguments.GlobalCacheLocation); + const typingSafeListLocation = findArgument(Arguments.TypingSafeListLocation); + const typesMapLocation = findArgument(Arguments.TypesMapLocation); + const npmLocation = findArgument(Arguments.NpmLocation); const log = new FileLog(logFilePath); if (log.isEnabled()) { diff --git a/src/server/typingsInstaller/typingsInstaller.ts b/src/server/typingsInstaller/typingsInstaller.ts index 059967ecb4d..80c1c7be6ea 100644 --- a/src/server/typingsInstaller/typingsInstaller.ts +++ b/src/server/typingsInstaller/typingsInstaller.ts @@ -277,7 +277,7 @@ namespace ts.server.typingsInstaller { this.sendResponse({ kind: EventBeginInstallTypes, eventId: requestId, - typingsInstallerVersion: ts.version, // qualified explicitly to prevent occasional shadowing + typingsInstallerVersion: ts.version, // tslint:disable-line no-unnecessary-qualifier (qualified explicitly to prevent occasional shadowing) projectName: req.projectName }); @@ -308,7 +308,7 @@ namespace ts.server.typingsInstaller { // packageName is guaranteed to exist in typesRegistry by filterTypings const distTags = this.typesRegistry.get(packageName); - const newVersion = Semver.parse(distTags[`ts${ts.versionMajorMinor}`] || distTags[latestDistTag]); + const newVersion = Semver.parse(distTags[`ts${versionMajorMinor}`] || distTags[latestDistTag]); const newTyping: JsTyping.CachedTyping = { typingLocation: typingFile, version: newVersion }; this.packageNameToTypingLocation.set(packageName, newTyping); installedTypingFiles.push(typingFile); @@ -326,7 +326,7 @@ namespace ts.server.typingsInstaller { projectName: req.projectName, packagesToInstall: scopedTypings, installSuccess: ok, - typingsInstallerVersion: ts.version // qualified explicitly to prevent occasional shadowing + typingsInstallerVersion: ts.version // tslint:disable-line no-unnecessary-qualifier (qualified explicitly to prevent occasional shadowing) }; this.sendResponse(response); } @@ -359,7 +359,7 @@ namespace ts.server.typingsInstaller { this.log.writeLine(`Got FS notification for ${f}, handler is already invoked '${isInvoked}'`); } if (!isInvoked) { - this.sendResponse({ projectName, kind: server.ActionInvalidate }); + this.sendResponse({ projectName, kind: ActionInvalidate }); isInvoked = true; } }, /*pollingInterval*/ 2000); diff --git a/src/services/classifier.ts b/src/services/classifier.ts index aff626ca9fe..4a8721154cb 100644 --- a/src/services/classifier.ts +++ b/src/services/classifier.ts @@ -178,7 +178,7 @@ namespace ts { /// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where /// we have a series of divide operator. this list allows us to be more accurate by ruling out /// locations where a regexp cannot exist. - const noRegexTable: true[] = ts.arrayToNumericMap([ + const noRegexTable: true[] = arrayToNumericMap([ SyntaxKind.Identifier, SyntaxKind.StringLiteral, SyntaxKind.NumericLiteral, diff --git a/src/services/codefixes/convertToEs6Module.ts b/src/services/codefixes/convertToEs6Module.ts index d494e5c907f..2ce8430e8b4 100644 --- a/src/services/codefixes/convertToEs6Module.ts +++ b/src/services/codefixes/convertToEs6Module.ts @@ -18,7 +18,7 @@ namespace ts.codefix { }, }); - function fixImportOfModuleExports(importingFile: ts.SourceFile, exportingFile: ts.SourceFile, changes: textChanges.ChangeTracker) { + function fixImportOfModuleExports(importingFile: SourceFile, exportingFile: SourceFile, changes: textChanges.ChangeTracker) { for (const moduleSpecifier of importingFile.imports) { const imported = getResolvedModule(importingFile, moduleSpecifier.text); if (!imported || imported.resolvedFileName !== exportingFile.fileName) { @@ -365,7 +365,7 @@ namespace ts.codefix { import x from "x"; const [a, b, c] = x; */ - const tmp = makeUniqueName(codefix.moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); + const tmp = makeUniqueName(moduleSpecifierToValidIdentifier(moduleSpecifier, target), identifiers); return [ makeImport(createIdentifier(tmp), /*namedImports*/ undefined, moduleSpecifier), makeConst(/*modifiers*/ undefined, getSynthesizedDeepClone(name), createIdentifier(tmp)), diff --git a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts index 551662210c1..9b775bef622 100644 --- a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts +++ b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts @@ -42,7 +42,7 @@ namespace ts.codefix { // (Trailing because leading might be indentation, which is more sensitive.) const text = sourceFile.text; let end = implementsToken.end; - while (end < text.length && ts.isWhiteSpaceSingleLine(text.charCodeAt(end))) { + while (end < text.length && isWhiteSpaceSingleLine(text.charCodeAt(end))) { end++; } diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 74a2aba76bb..4c43d323848 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -88,11 +88,11 @@ namespace ts.codefix { sourceFile: SourceFile, symbolName: string, host: LanguageServiceHost, - program: ts.Program, - checker: ts.TypeChecker, - compilerOptions: ts.CompilerOptions, - allSourceFiles: ReadonlyArray, - formatContext: ts.formatting.FormatContext, + program: Program, + checker: TypeChecker, + compilerOptions: CompilerOptions, + allSourceFiles: ReadonlyArray, + formatContext: formatting.FormatContext, getCanonicalFileName: GetCanonicalFileName, symbolToken: Node | undefined, ): { readonly moduleSpecifier: string, readonly codeAction: CodeAction } { diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index e17c5183611..dd47f96e62a 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -310,13 +310,13 @@ namespace ts.codefix { const callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; return callContexts && declaration.parameters.map((parameter, parameterIndex) => { const types: Type[] = []; - const isRestParameter = ts.isRestParameter(parameter); + const isRest = isRestParameter(parameter); for (const callContext of callContexts) { if (callContext.argumentTypes.length <= parameterIndex) { continue; } - if (isRestParameter) { + if (isRest) { for (let i = parameterIndex; i < callContext.argumentTypes.length; i++) { types.push(checker.getBaseTypeOfLiteralType(callContext.argumentTypes[i])); } @@ -329,7 +329,7 @@ namespace ts.codefix { return undefined; } const type = checker.getWidenedType(checker.getUnionType(types, UnionReduction.Subtype)); - return isRestParameter ? checker.createArrayType(type) : type; + return isRest ? checker.createArrayType(type) : type; }); } diff --git a/src/services/completions.ts b/src/services/completions.ts index 640cb5bedf3..9470381bd24 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -673,11 +673,11 @@ namespace ts.Completions { return getContextualTypeFromParent(currentToken as Identifier, checker); case SyntaxKind.EqualsToken: switch (parent.kind) { - case ts.SyntaxKind.VariableDeclaration: + case SyntaxKind.VariableDeclaration: return checker.getContextualType((parent as VariableDeclaration).initializer); - case ts.SyntaxKind.BinaryExpression: + case SyntaxKind.BinaryExpression: return checker.getTypeAtLocation((parent as BinaryExpression).left); - case ts.SyntaxKind.JsxAttribute: + case SyntaxKind.JsxAttribute: return checker.getContextualTypeForJsxAttribute(parent as JsxAttribute); default: return undefined; @@ -700,25 +700,25 @@ namespace ts.Completions { } } - function getContextualTypeFromParent(node: ts.Expression, checker: ts.TypeChecker): Type | undefined { + function getContextualTypeFromParent(node: Expression, checker: TypeChecker): Type | undefined { const { parent } = node; switch (parent.kind) { - case ts.SyntaxKind.NewExpression: - return checker.getContextualType(parent as ts.NewExpression); - case ts.SyntaxKind.BinaryExpression: { - const { left, operatorToken, right } = parent as ts.BinaryExpression; + case SyntaxKind.NewExpression: + return checker.getContextualType(parent as NewExpression); + case SyntaxKind.BinaryExpression: { + const { left, operatorToken, right } = parent as BinaryExpression; return isEqualityOperatorKind(operatorToken.kind) ? checker.getTypeAtLocation(node === right ? left : right) : checker.getContextualType(node); } - case ts.SyntaxKind.CaseClause: - return (parent as ts.CaseClause).expression === node ? getSwitchedType(parent as ts.CaseClause, checker) : undefined; + case SyntaxKind.CaseClause: + return (parent as CaseClause).expression === node ? getSwitchedType(parent as CaseClause, checker) : undefined; default: return checker.getContextualType(node); } } - function getSwitchedType(caseClause: ts.CaseClause, checker: ts.TypeChecker): ts.Type { + function getSwitchedType(caseClause: CaseClause, checker: TypeChecker): Type { return checker.getTypeAtLocation(caseClause.parent.parent.expression); } @@ -2140,7 +2140,7 @@ namespace ts.Completions { // A cache of completion entries for keywords, these do not change between sessions const _keywordCompletions: ReadonlyArray[] = []; - const allKeywordsCompletions: () => ReadonlyArray = ts.memoize(() => { + const allKeywordsCompletions: () => ReadonlyArray = memoize(() => { const res: CompletionEntry[] = []; for (let i = SyntaxKind.FirstKeyword; i <= SyntaxKind.LastKeyword; i++) { res.push({ @@ -2224,12 +2224,12 @@ namespace ts.Completions { return true; } - function isEqualityOperatorKind(kind: ts.SyntaxKind): kind is EqualityOperator { + function isEqualityOperatorKind(kind: SyntaxKind): kind is EqualityOperator { switch (kind) { - case ts.SyntaxKind.EqualsEqualsEqualsToken: - case ts.SyntaxKind.EqualsEqualsToken: - case ts.SyntaxKind.ExclamationEqualsEqualsToken: - case ts.SyntaxKind.ExclamationEqualsToken: + case SyntaxKind.EqualsEqualsEqualsToken: + case SyntaxKind.EqualsEqualsToken: + case SyntaxKind.ExclamationEqualsEqualsToken: + case SyntaxKind.ExclamationEqualsToken: return true; default: return false; diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index b917c426b7d..ee4f44d31db 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -10,9 +10,9 @@ namespace ts.FindAllReferences { export type Definition = | { type: "symbol"; symbol: Symbol } | { type: "label"; node: Identifier } - | { type: "keyword"; node: ts.Node } - | { type: "this"; node: ts.Node } - | { type: "string"; node: ts.StringLiteral }; + | { type: "keyword"; node: Node } + | { type: "this"; node: Node } + | { type: "string"; node: StringLiteral }; export type Entry = NodeEntry | SpanEntry; export interface NodeEntry { @@ -25,7 +25,7 @@ namespace ts.FindAllReferences { fileName: string; textSpan: TextSpan; } - export function nodeEntry(node: ts.Node, isInString?: true): NodeEntry { + export function nodeEntry(node: Node, isInString?: true): NodeEntry { return { type: "node", node, isInString }; } @@ -168,7 +168,7 @@ namespace ts.FindAllReferences { }; } - function toImplementationLocation(entry: Entry, checker: ts.TypeChecker): ImplementationLocation { + function toImplementationLocation(entry: Entry, checker: TypeChecker): ImplementationLocation { if (entry.type === "node") { const { node } = entry; return { textSpan: getTextSpan(node), fileName: node.getSourceFile().fileName, ...implementationKindDisplayParts(node, checker) }; @@ -179,7 +179,7 @@ namespace ts.FindAllReferences { } } - function implementationKindDisplayParts(node: ts.Node, checker: ts.TypeChecker): { kind: ScriptElementKind, displayParts: SymbolDisplayPart[] } { + function implementationKindDisplayParts(node: Node, checker: TypeChecker): { kind: ScriptElementKind, displayParts: SymbolDisplayPart[] } { const symbol = checker.getSymbolAtLocation(isDeclaration(node) && node.name ? node.name : node); if (symbol) { return getDefinitionKindAndDisplayParts(symbol, checker, node); @@ -201,7 +201,7 @@ namespace ts.FindAllReferences { } } - export function toHighlightSpan(entry: FindAllReferences.Entry): { fileName: string, span: HighlightSpan } { + export function toHighlightSpan(entry: Entry): { fileName: string, span: HighlightSpan } { if (entry.type === "span") { const { fileName, textSpan } = entry; return { fileName, span: { textSpan, kind: HighlightSpanKind.reference } }; @@ -267,7 +267,7 @@ namespace ts.FindAllReferences.Core { return getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options); } - function isModuleReferenceLocation(node: ts.Node): boolean { + function isModuleReferenceLocation(node: Node): boolean { if (!isStringLiteralLike(node)) { return false; } @@ -302,11 +302,11 @@ namespace ts.FindAllReferences.Core { for (const decl of symbol.declarations) { switch (decl.kind) { - case ts.SyntaxKind.SourceFile: + case SyntaxKind.SourceFile: // Don't include the source file itself. (This may not be ideal behavior, but awkward to include an entire file as a reference.) break; - case ts.SyntaxKind.ModuleDeclaration: - references.push({ type: "node", node: (decl as ts.ModuleDeclaration).name }); + case SyntaxKind.ModuleDeclaration: + references.push({ type: "node", node: (decl as ModuleDeclaration).name }); break; default: Debug.fail("Expected a module symbol to be declared by a SourceFile or ModuleDeclaration."); @@ -787,7 +787,7 @@ namespace ts.FindAllReferences.Core { } } - function getAllReferencesForKeyword(sourceFiles: ReadonlyArray, keywordKind: ts.SyntaxKind, cancellationToken: CancellationToken): SymbolAndEntries[] { + function getAllReferencesForKeyword(sourceFiles: ReadonlyArray, keywordKind: SyntaxKind, cancellationToken: CancellationToken): SymbolAndEntries[] { const references = flatMap(sourceFiles, sourceFile => { cancellationToken.throwIfCancellationRequested(); return mapDefined(getPossibleSymbolReferencePositions(sourceFile, tokenToString(keywordKind), sourceFile), position => { @@ -798,7 +798,7 @@ namespace ts.FindAllReferences.Core { return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references }] : undefined; } - function getReferencesInSourceFile(sourceFile: ts.SourceFile, search: Search, state: State): void { + function getReferencesInSourceFile(sourceFile: SourceFile, search: Search, state: State): void { state.cancellationToken.throwIfCancellationRequested(); return getReferencesInContainer(sourceFile, sourceFile, search, state); } @@ -808,7 +808,7 @@ namespace ts.FindAllReferences.Core { * tuple of(searchSymbol, searchText, searchLocation, and searchMeaning). * searchLocation: a node where the search value */ - function getReferencesInContainer(container: Node, sourceFile: ts.SourceFile, search: Search, state: State): void { + function getReferencesInContainer(container: Node, sourceFile: SourceFile, search: Search, state: State): void { if (!state.markSearchedSymbol(sourceFile, search.symbol)) { return; } @@ -910,7 +910,7 @@ namespace ts.FindAllReferences.Core { // For `export { foo as bar }`, rename `foo`, but not `bar`. if (!(referenceLocation === propertyName && state.options.isForRename)) { - const exportKind = referenceLocation.originalKeywordKind === ts.SyntaxKind.DefaultKeyword ? ExportKind.Default : ExportKind.Named; + const exportKind = referenceLocation.originalKeywordKind === SyntaxKind.DefaultKeyword ? ExportKind.Default : ExportKind.Named; const exportInfo = getExportInfo(referenceSymbol, exportKind, state.checker); Debug.assert(!!exportInfo); searchForImportsOfExport(referenceLocation, referenceSymbol, exportInfo, state); @@ -1043,7 +1043,7 @@ namespace ts.FindAllReferences.Core { */ function findOwnConstructorReferences(classSymbol: Symbol, sourceFile: SourceFile, addNode: (node: Node) => void): void { for (const decl of classSymbol.members.get(InternalSymbolName.Constructor).declarations) { - const ctrKeyword = findChildOfKind(decl, ts.SyntaxKind.ConstructorKeyword, sourceFile)!; + const ctrKeyword = findChildOfKind(decl, SyntaxKind.ConstructorKeyword, sourceFile)!; Debug.assert(decl.kind === SyntaxKind.Constructor && !!ctrKeyword); addNode(ctrKeyword); } diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index 3ed602d17fb..967015a88c1 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -6,8 +6,8 @@ /* @internal */ namespace ts.formatting { export interface FormatContext { - readonly options: ts.FormatCodeSettings; - readonly getRule: ts.formatting.RulesMap; + readonly options: FormatCodeSettings; + readonly getRule: RulesMap; } export interface TextRangeWithKind extends TextRange { diff --git a/src/services/formatting/formattingContext.ts b/src/services/formatting/formattingContext.ts index 2ba987e4af3..036cc64c98e 100644 --- a/src/services/formatting/formattingContext.ts +++ b/src/services/formatting/formattingContext.ts @@ -22,7 +22,7 @@ namespace ts.formatting { private contextNodeBlockIsOnOneLine: boolean; private nextNodeBlockIsOnOneLine: boolean; - constructor(public readonly sourceFile: SourceFileLike, public formattingRequestKind: FormattingRequestKind, public options: ts.FormatCodeSettings) { + constructor(public readonly sourceFile: SourceFileLike, public formattingRequestKind: FormattingRequestKind, public options: FormatCodeSettings) { } public updateContext(currentRange: TextRangeWithKind, currentTokenParent: Node, nextRange: TextRangeWithKind, nextTokenParent: Node, commonParent: Node) { diff --git a/src/services/formatting/rulesMap.ts b/src/services/formatting/rulesMap.ts index d44e47a763a..75cc68cb268 100644 --- a/src/services/formatting/rulesMap.ts +++ b/src/services/formatting/rulesMap.ts @@ -2,7 +2,7 @@ /* @internal */ namespace ts.formatting { - export function getFormatContext(options: FormatCodeSettings): formatting.FormatContext { + export function getFormatContext(options: FormatCodeSettings): FormatContext { return { options, getRule: getRulesMap() }; } diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index b8574ba89c1..7904db0969f 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -102,7 +102,7 @@ namespace ts.formatting { current--; } - const lineStart = ts.getLineStartPositionForPosition(current, sourceFile); + const lineStart = getLineStartPositionForPosition(current, sourceFile); return findFirstNonWhitespaceColumn(lineStart, current, sourceFile, options); } diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index cf51e8f93cd..08478344428 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -212,11 +212,11 @@ namespace ts.GoToDefinition { function isSignatureDeclaration(node: Node): boolean { switch (node.kind) { - case ts.SyntaxKind.Constructor: - case ts.SyntaxKind.ConstructSignature: - case ts.SyntaxKind.FunctionDeclaration: - case ts.SyntaxKind.MethodDeclaration: - case ts.SyntaxKind.MethodSignature: + case SyntaxKind.Constructor: + case SyntaxKind.ConstructSignature: + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.MethodSignature: return true; default: return false; diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index beecafe0e81..9f61b4ea69d 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -86,7 +86,7 @@ namespace ts.FindAllReferences { if (!isAvailableThroughGlobal) { const parent = direct.parent!; if (exportKind === ExportKind.ExportEquals && parent.kind === SyntaxKind.VariableDeclaration) { - const { name } = parent as ts.VariableDeclaration; + const { name } = parent as VariableDeclaration; if (name.kind === SyntaxKind.Identifier) { directImports.push(name); break; @@ -209,7 +209,7 @@ namespace ts.FindAllReferences { return; } - if (decl.kind === ts.SyntaxKind.Identifier) { + if (decl.kind === SyntaxKind.Identifier) { handleNamespaceImportLike(decl); return; } @@ -329,7 +329,7 @@ namespace ts.FindAllReferences { const checker = program.getTypeChecker(); for (const referencingFile of sourceFiles) { const searchSourceFile = searchModuleSymbol.valueDeclaration; - if (searchSourceFile.kind === ts.SyntaxKind.SourceFile) { + if (searchSourceFile.kind === SyntaxKind.SourceFile) { for (const ref of referencingFile.referencedFiles) { if (program.getSourceFileFromReference(referencingFile, ref) === searchSourceFile) { refs.push({ kind: "reference", referencingFile, ref }); @@ -337,7 +337,7 @@ namespace ts.FindAllReferences { } for (const ref of referencingFile.typeReferenceDirectives) { const referenced = program.getResolvedTypeReferenceDirectives().get(ref.fileName); - if (referenced !== undefined && referenced.resolvedFileName === (searchSourceFile as ts.SourceFile).fileName) { + if (referenced !== undefined && referenced.resolvedFileName === (searchSourceFile as SourceFile).fileName) { refs.push({ kind: "reference", referencingFile, ref }); } } @@ -503,7 +503,7 @@ namespace ts.FindAllReferences { return { kind: ImportExport.Export, symbol, exportInfo: { exportingModuleSymbol, exportKind } }; } - function getSpecialPropertyExport(node: ts.BinaryExpression, useLhsSymbol: boolean): ExportedSymbol | undefined { + function getSpecialPropertyExport(node: BinaryExpression, useLhsSymbol: boolean): ExportedSymbol | undefined { let kind: ExportKind; switch (getSpecialPropertyAssignmentKind(node)) { case SpecialPropertyAssignmentKind.ExportsProperty: @@ -579,9 +579,9 @@ namespace ts.FindAllReferences { // If a reference is a variable declaration, the exported node would be the variable statement. function getExportNode(parent: Node, node: Node): Node | undefined { if (parent.kind === SyntaxKind.VariableDeclaration) { - const p = parent as ts.VariableDeclaration; + const p = parent as VariableDeclaration; return p.name !== node ? undefined : - p.parent.kind === ts.SyntaxKind.CatchClause ? undefined : p.parent.parent.kind === SyntaxKind.VariableStatement ? p.parent.parent : undefined; + p.parent.kind === SyntaxKind.CatchClause ? undefined : p.parent.parent.kind === SyntaxKind.VariableStatement ? p.parent.parent : undefined; } else { return parent; diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index cf3c9606fb4..4033f40f76c 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -139,7 +139,7 @@ namespace ts.JsDoc { } export function getJSDocTagNameCompletions(): CompletionEntry[] { - return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, tagName => { + return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = map(jsDocTagNames, tagName => { return { name: tagName, kind: ScriptElementKind.keyword, @@ -152,7 +152,7 @@ namespace ts.JsDoc { export const getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails; export function getJSDocTagCompletions(): CompletionEntry[] { - return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, tagName => { + return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = map(jsDocTagNames, tagName => { return { name: `@${tagName}`, kind: ScriptElementKind.keyword, @@ -181,7 +181,7 @@ namespace ts.JsDoc { const nameThusFar = tag.name.text; const jsdoc = tag.parent; const fn = jsdoc.parent; - if (!ts.isFunctionLike(fn)) return []; + if (!isFunctionLike(fn)) return []; return mapDefined(fn.parameters, param => { if (!isIdentifier(param.name)) return undefined; @@ -338,7 +338,7 @@ namespace ts.JsDoc { case SyntaxKind.BinaryExpression: { const be = commentOwner as BinaryExpression; - if (getSpecialPropertyAssignmentKind(be) === ts.SpecialPropertyAssignmentKind.None) { + if (getSpecialPropertyAssignmentKind(be) === SpecialPropertyAssignmentKind.None) { return undefined; } const parameters = isFunctionLike(be.right) ? be.right.parameters : emptyArray; diff --git a/src/services/jsTyping.ts b/src/services/jsTyping.ts index bd6c2e5cb9f..0d78ed92fab 100644 --- a/src/services/jsTyping.ts +++ b/src/services/jsTyping.ts @@ -33,8 +33,8 @@ namespace ts.JsTyping { } /* @internal */ - export function isTypingUpToDate(cachedTyping: JsTyping.CachedTyping, availableTypingVersions: MapLike) { - const availableVersion = Semver.parse(getProperty(availableTypingVersions, `ts${ts.versionMajorMinor}`) || getProperty(availableTypingVersions, "latest")); + export function isTypingUpToDate(cachedTyping: CachedTyping, availableTypingVersions: MapLike) { + const availableVersion = Semver.parse(getProperty(availableTypingVersions, `ts${versionMajorMinor}`) || getProperty(availableTypingVersions, "latest")); return !availableVersion.greaterThan(cachedTyping.version); } diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index 21d8a792759..5165dcc6113 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -62,7 +62,7 @@ namespace ts.NavigateTo { } } - function shouldKeepItem(declaration: Declaration, checker: ts.TypeChecker): boolean { + function shouldKeepItem(declaration: Declaration, checker: TypeChecker): boolean { switch (declaration.kind) { case SyntaxKind.ImportClause: case SyntaxKind.ImportSpecifier: diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index cdc7b2b1864..5e9b07ab2d2 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -635,7 +635,7 @@ namespace ts.NavigationBar { return node.kind === SyntaxKind.SourceFile ? createTextSpanFromRange(node) : createTextSpanFromNode(node, curSourceFile); } - function getModifiers(node: ts.Node): string { + function getModifiers(node: Node): string { if (node.parent && node.parent.kind === SyntaxKind.VariableDeclaration) { node = node.parent; } diff --git a/src/services/pathCompletions.ts b/src/services/pathCompletions.ts index fd639aef817..cdf940cdc79 100644 --- a/src/services/pathCompletions.ts +++ b/src/services/pathCompletions.ts @@ -170,7 +170,7 @@ namespace ts.Completions.PathCompletions { } } - if (compilerOptions.moduleResolution === ts.ModuleResolutionKind.NodeJs) { + if (compilerOptions.moduleResolution === ModuleResolutionKind.NodeJs) { forEachAncestorDirectory(scriptPath, ancestor => { const nodeModules = combinePaths(ancestor, "node_modules"); if (host.directoryExists(nodeModules)) { diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 65c9fd6268c..1bec23a15d6 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -405,7 +405,7 @@ namespace ts.refactor.extractSymbol { switch (node.kind) { case SyntaxKind.FunctionDeclaration: case SyntaxKind.ClassDeclaration: - if (node.parent.kind === SyntaxKind.SourceFile && (node.parent as ts.SourceFile).externalModuleIndicator === undefined) { + if (isSourceFile(node.parent) && node.parent.externalModuleIndicator === undefined) { // You cannot extract global declarations (errors || (errors = [])).push(createDiagnosticForNode(node, Messages.functionWillNotBeVisibleInTheNewScope)); } @@ -1358,7 +1358,7 @@ namespace ts.refactor.extractSymbol { } function getPropertyAssignmentsForWritesAndVariableDeclarations( - exposedVariableDeclarations: ReadonlyArray, + exposedVariableDeclarations: ReadonlyArray, writes: ReadonlyArray) { const variableAssignments = map(exposedVariableDeclarations, v => createShorthandPropertyAssignment(v.symbol.name)); diff --git a/src/services/rename.ts b/src/services/rename.ts index eed2d120519..c40f7908776 100644 --- a/src/services/rename.ts +++ b/src/services/rename.ts @@ -1,7 +1,7 @@ /* @internal */ namespace ts.Rename { export function getRenameInfo(typeChecker: TypeChecker, defaultLibFileName: string, getCanonicalFileName: GetCanonicalFileName, sourceFile: SourceFile, position: number): RenameInfo { - const getCanonicalDefaultLibName = memoize(() => getCanonicalFileName(ts.normalizePath(defaultLibFileName))); + const getCanonicalDefaultLibName = memoize(() => getCanonicalFileName(normalizePath(defaultLibFileName))); const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); const renameInfo = node && nodeIsEligibleForRename(node) ? getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) @@ -14,7 +14,7 @@ namespace ts.Rename { } const sourceFile = declaration.getSourceFile(); - const canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile.fileName)); + const canonicalName = getCanonicalFileName(normalizePath(sourceFile.fileName)); return canonicalName === getCanonicalDefaultLibName(); } } diff --git a/src/services/services.ts b/src/services/services.ts index e29633a92e0..621cf6a9235 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -225,7 +225,7 @@ namespace ts { return undefined; } - const child = ts.find(children, kid => kid.kind < SyntaxKind.FirstJSDocNode || kid.kind > SyntaxKind.LastJSDocNode); + const child = find(children, kid => kid.kind < SyntaxKind.FirstJSDocNode || kid.kind > SyntaxKind.LastJSDocNode); return child.kind < SyntaxKind.FirstNode ? child : child.getFirstToken(sourceFile); @@ -377,7 +377,7 @@ namespace ts { const inheritedDocs = findInheritedJSDocComments(declaration, this.getName(), checker); if (inheritedDocs.length > 0) { if (this.documentationComment.length > 0) { - inheritedDocs.push(ts.lineBreakPart()); + inheritedDocs.push(lineBreakPart()); } this.documentationComment = concatenate(inheritedDocs, this.documentationComment); break; @@ -531,7 +531,7 @@ namespace ts { if (this.documentationComment.length === 0 || hasJSDocInheritDocTag(this.declaration)) { const inheritedDocs = findInheritedJSDocComments(this.declaration, this.declaration.symbol.getName(), this.checker); if (this.documentationComment.length > 0) { - inheritedDocs.push(ts.lineBreakPart()); + inheritedDocs.push(lineBreakPart()); } this.documentationComment = concatenate( inheritedDocs, @@ -562,7 +562,7 @@ namespace ts { * @returns `true` if `node` has a JSDoc "inheritDoc" tag on it, otherwise `false`. */ function hasJSDocInheritDocTag(node: Node) { - return ts.getJSDocTags(node).some(tag => tag.tagName.text === "inheritDoc"); + return getJSDocTags(node).some(tag => tag.tagName.text === "inheritDoc"); } /** @@ -665,7 +665,7 @@ namespace ts { } public getLineAndCharacterOfPosition(position: number): LineAndCharacter { - return ts.getLineAndCharacterOfPosition(this, position); + return getLineAndCharacterOfPosition(this, position); } public getLineStarts(): ReadonlyArray { @@ -673,7 +673,7 @@ namespace ts { } public getPositionOfLineAndCharacter(line: number, character: number): number { - return ts.getPositionOfLineAndCharacter(this, line, character); + return getPositionOfLineAndCharacter(this, line, character); } public getLineEndOfPosition(pos: number): number { @@ -848,7 +848,7 @@ namespace ts { constructor(public fileName: string, public text: string, public skipTrivia?: (pos: number) => number) { } public getLineAndCharacterOfPosition(pos: number): LineAndCharacter { - return ts.getLineAndCharacterOfPosition(this, pos); + return getLineAndCharacterOfPosition(this, pos); } } @@ -1617,7 +1617,7 @@ namespace ts { synchronizeHostData(); const sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); - return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); + return NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } function getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean) { @@ -1914,7 +1914,7 @@ namespace ts { function getSpanOfEnclosingComment(fileName: string, position: number, onlyMultiLine: boolean) { const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - const range = ts.formatting.getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine); + const range = formatting.getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine); return range && createTextSpanFromRange(range); } @@ -2189,7 +2189,7 @@ namespace ts { * then we want 'something' to be in the name table. Similarly, if we have * "a['propname']" then we want to store "propname" in the name table. */ - function literalIsName(node: ts.StringLiteral | ts.NumericLiteral): boolean { + function literalIsName(node: StringLiteral | NumericLiteral): boolean { return isDeclarationName(node) || node.parent.kind === SyntaxKind.ExternalModuleReference || isArgumentOfElementAccessExpression(node) || diff --git a/src/services/shims.ts b/src/services/shims.ts index 5d3f82eb966..1a43fbda146 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -663,7 +663,7 @@ namespace ts { private realizeDiagnostics(diagnostics: ReadonlyArray): { message: string; start: number; length: number; category: string; }[] { const newLine = getNewLineOrDefaultFromHost(this.host); - return ts.realizeDiagnostics(diagnostics, newLine); + return realizeDiagnostics(diagnostics, newLine); } public getSyntacticClassifications(fileName: string, start: number, length: number): string { @@ -925,7 +925,7 @@ namespace ts { return this.forwardJSONCall( `getCompletionEntryDetails('${fileName}', ${position}, '${entryName}')`, () => { - const localOptions: ts.FormatCodeOptions = options === undefined ? undefined : JSON.parse(options); + const localOptions: FormatCodeOptions = options === undefined ? undefined : JSON.parse(options); return this.languageService.getCompletionEntryDetails(fileName, position, entryName, localOptions, source); } ); @@ -935,7 +935,7 @@ namespace ts { return this.forwardJSONCall( `getFormattingEditsForRange('${fileName}', ${start}, ${end})`, () => { - const localOptions: ts.FormatCodeOptions = JSON.parse(options); + const localOptions: FormatCodeOptions = JSON.parse(options); return this.languageService.getFormattingEditsForRange(fileName, start, end, localOptions); }); } @@ -944,7 +944,7 @@ namespace ts { return this.forwardJSONCall( `getFormattingEditsForDocument('${fileName}')`, () => { - const localOptions: ts.FormatCodeOptions = JSON.parse(options); + const localOptions: FormatCodeOptions = JSON.parse(options); return this.languageService.getFormattingEditsForDocument(fileName, localOptions); }); } @@ -953,7 +953,7 @@ namespace ts { return this.forwardJSONCall( `getFormattingEditsAfterKeystroke('${fileName}', ${position}, '${key}')`, () => { - const localOptions: ts.FormatCodeOptions = JSON.parse(options); + const localOptions: FormatCodeOptions = JSON.parse(options); return this.languageService.getFormattingEditsAfterKeystroke(fileName, position, key, localOptions); }); } diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index 135e906143f..1b77f23fa33 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -117,7 +117,7 @@ namespace ts.SymbolDisplay { const displayParts: SymbolDisplayPart[] = []; let documentation: SymbolDisplayPart[]; let tags: JSDocTagInfo[]; - const symbolFlags = ts.getCombinedLocalAndExportSymbolFlags(symbol); + const symbolFlags = getCombinedLocalAndExportSymbolFlags(symbol); let symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); let hasAddedSymbolInfo: boolean; const isThisExpression = location.kind === SyntaxKind.ThisKeyword && isExpression(location); @@ -369,16 +369,16 @@ namespace ts.SymbolDisplay { const resolvedSymbol = typeChecker.getAliasedSymbol(symbol); if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { const resolvedNode = resolvedSymbol.declarations[0]; - const declarationName = ts.getNameOfDeclaration(resolvedNode); + const declarationName = getNameOfDeclaration(resolvedNode); if (declarationName) { const isExternalModuleDeclaration = - ts.isModuleWithStringLiteralName(resolvedNode) && - ts.hasModifier(resolvedNode, ModifierFlags.Ambient); + isModuleWithStringLiteralName(resolvedNode) && + hasModifier(resolvedNode, ModifierFlags.Ambient); const shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; const resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind( typeChecker, resolvedSymbol, - ts.getSourceFileOfNode(resolvedNode), + getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, @@ -406,7 +406,7 @@ namespace ts.SymbolDisplay { } displayParts.push(spacePart()); addFullSymbolName(symbol); - ts.forEach(symbol.declarations, declaration => { + forEach(symbol.declarations, declaration => { if (declaration.kind === SyntaxKind.ImportEqualsDeclaration) { const importEqualsDeclaration = declaration; if (isExternalModuleImportEqualsDeclaration(importEqualsDeclaration)) { @@ -607,7 +607,7 @@ namespace ts.SymbolDisplay { return false; // This is exported symbol } - return ts.forEach(symbol.declarations, declaration => { + return forEach(symbol.declarations, declaration => { // Function expressions are local if (declaration.kind === SyntaxKind.FunctionExpression) { return true; diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index bc70106e530..3ad3d6d57c6 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -192,7 +192,7 @@ namespace ts.textChanges { export interface TextChangesContext { host: LanguageServiceHost; - formatContext: ts.formatting.FormatContext; + formatContext: formatting.FormatContext; } export class ChangeTracker { @@ -212,7 +212,7 @@ namespace ts.textChanges { } /** Public for tests only. Other callers should use `ChangeTracker.with`. */ - constructor(private readonly newLineCharacter: string, private readonly formatContext: ts.formatting.FormatContext) {} + constructor(private readonly newLineCharacter: string, private readonly formatContext: formatting.FormatContext) {} public deleteRange(sourceFile: SourceFile, range: TextRange) { this.changes.push({ kind: ChangeKind.Remove, sourceFile, range }); diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 4fef3fc30d8..90ed78047e6 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -7181,7 +7181,7 @@ declare namespace ts.server { } type CommandNames = protocol.CommandTypes; const CommandNames: any; - function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string; + function formatMessage(msg: T, logger: Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string; type Event = (body: T, eventName: string) => void; interface EventSender { event: Event; diff --git a/tslint.json b/tslint.json index bd06724edb8..eaf76b52155 100644 --- a/tslint.json +++ b/tslint.json @@ -42,6 +42,7 @@ "no-switch-case-fall-through": true, "no-trailing-whitespace": [true, "ignore-template-strings"], "no-type-assertion-whitespace": true, + "no-unnecessary-qualifier": true, "no-var-keyword": true, "object-literal-shorthand": true, "object-literal-surrounding-space": true,