diff --git a/src/compiler/_namespaces/ts.moduleSpecifiers.ts b/src/compiler/_namespaces/ts.moduleSpecifiers.ts new file mode 100644 index 0000000000000..47a204d4a72b9 --- /dev/null +++ b/src/compiler/_namespaces/ts.moduleSpecifiers.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.moduleSpecifiers namespace. */ + +export * from "../moduleSpecifiers"; diff --git a/src/compiler/_namespaces/ts.performance.ts b/src/compiler/_namespaces/ts.performance.ts new file mode 100644 index 0000000000000..707f8f85ef697 --- /dev/null +++ b/src/compiler/_namespaces/ts.performance.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.performance namespace. */ + +export * from "../performance"; diff --git a/src/compiler/_namespaces/ts.ts b/src/compiler/_namespaces/ts.ts new file mode 100644 index 0000000000000..b31b19cae7cb5 --- /dev/null +++ b/src/compiler/_namespaces/ts.ts @@ -0,0 +1,74 @@ +/* Generated file to emulate the ts namespace. */ + +export * from "../corePublic"; +export * from "../core"; +export * from "../debug"; +export * from "../semver"; +export * from "../performanceCore"; +export * from "../perfLogger"; +export * from "../tracing"; +export * from "../types"; +export * from "../sys"; +export * from "../path"; +export * from "../diagnosticInformationMap.generated"; +export * from "../scanner"; +export * from "../utilitiesPublic"; +export * from "../utilities"; +export * from "../factory/baseNodeFactory"; +export * from "../factory/parenthesizerRules"; +export * from "../factory/nodeConverters"; +export * from "../factory/nodeFactory"; +export * from "../factory/emitNode"; +export * from "../factory/emitHelpers"; +export * from "../factory/nodeTests"; +export * from "../factory/utilities"; +export * from "../factory/utilitiesPublic"; +export * from "../parser"; +export * from "../commandLineParser"; +export * from "../moduleNameResolver"; +export * from "../binder"; +export * from "../symbolWalker"; +export * from "../checker"; +export * from "../visitorPublic"; +export * from "../sourcemap"; +export * from "../transformers/utilities"; +export * from "../transformers/destructuring"; +export * from "../transformers/taggedTemplate"; +export * from "../transformers/ts"; +export * from "../transformers/classFields"; +export * from "../transformers/typeSerializer"; +export * from "../transformers/legacyDecorators"; +export * from "../transformers/es2017"; +export * from "../transformers/es2018"; +export * from "../transformers/es2019"; +export * from "../transformers/es2020"; +export * from "../transformers/es2021"; +export * from "../transformers/esnext"; +export * from "../transformers/jsx"; +export * from "../transformers/es2016"; +export * from "../transformers/es2015"; +export * from "../transformers/es5"; +export * from "../transformers/generators"; +export * from "../transformers/module/module"; +export * from "../transformers/module/system"; +export * from "../transformers/module/esnextAnd2015"; +export * from "../transformers/module/node"; +export * from "../transformers/declarations/diagnostics"; +export * from "../transformers/declarations"; +export * from "../transformer"; +export * from "../emitter"; +export * from "../watchUtilities"; +export * from "../program"; +export * from "../builderStatePublic"; +export * from "../builderState"; +export * from "../builder"; +export * from "../builderPublic"; +export * from "../resolutionCache"; +export * from "../watch"; +export * from "../watchPublic"; +export * from "../tsbuild"; +export * from "../tsbuildPublic"; +import * as moduleSpecifiers from "./ts.moduleSpecifiers"; +export { moduleSpecifiers }; +import * as performance from "./ts.performance"; +export { performance }; diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index a1e1298927d16..591a81f61265e 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -1,6 +1,6 @@ +import * as ts from "./_namespaces/ts"; -/* @internal */ -namespace ts { +/** @internal */ export const enum ModuleInstanceState { NonInstantiated = 0, Instantiated = 1, @@ -15,6 +15,7 @@ interface ActiveLabel { referenced: boolean; } +/** @internal */ export function getModuleInstanceState(node: ts.ModuleDeclaration, visited?: ts.ESMap): ModuleInstanceState { if (node.body && !node.body.parent) { // getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already @@ -173,6 +174,7 @@ function initFlowNode(node: T) { const binder = createBinder(); +/** @internal */ export function bindSourceFile(file: ts.SourceFile, options: ts.CompilerOptions) { ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); @@ -3498,6 +3500,7 @@ function isPurelyTypeDeclaration(s: ts.Statement): boolean { } } +/** @internal */ export function isExportsOrModuleExportsOrAlias(sourceFile: ts.SourceFile, node: ts.Expression): boolean { let i = 0; const q = ts.createQueue(); @@ -3533,4 +3536,3 @@ function lookupSymbolForName(container: ts.Node, name: ts.__String): ts.Symbol | } return container.symbol && container.symbol.exports && container.symbol.exports.get(name); } -} diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts index 8463ef1ee663c..1fa1e1c71974d 100644 --- a/src/compiler/builder.ts +++ b/src/compiler/builder.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export interface ReusableDiagnostic extends ReusableDiagnosticRelatedInformation { /** May store more in future. For now, this will simply be `true` to indicate when a diagnostic is an unused-identifier diagnostic. */ reportsUnnecessary?: {}; @@ -9,6 +10,7 @@ export interface ReusableDiagnostic extends ReusableDiagnosticRelatedInformation skippedOn?: keyof ts.CompilerOptions; } +/** @internal */ export interface ReusableDiagnosticRelatedInformation { category: ts.DiagnosticCategory; code: number; @@ -18,11 +20,14 @@ export interface ReusableDiagnosticRelatedInformation { messageText: string | ReusableDiagnosticMessageChain; } +/** @internal */ export type ReusableDiagnosticMessageChain = ts.DiagnosticMessageChain; +/** @internal */ /** Signature (Hash of d.ts emitted), is string if it was emitted using same d.ts.map option as what compilerOptions indicate, otherwise tuple of string */ export type EmitSignature = string | [signature: string]; +/** @internal */ export interface ReusableBuilderProgramState extends ts.BuilderState { /** * Cache of bind and check diagnostics for files with their Path being the key @@ -70,6 +75,7 @@ export interface ReusableBuilderProgramState extends ts.BuilderState { bundle?: ts.BundleBuildInfo; } +/** @internal */ export const enum BuilderFileEmit { None = 0, Js = 1 << 0, // emit js file @@ -83,6 +89,7 @@ export const enum BuilderFileEmit { All = AllJs | AllDts, } +/** @internal */ /** * State to store the changed files, affected files and cache semantic diagnostics */ @@ -140,6 +147,7 @@ export interface BuilderProgramState extends ts.BuilderState, ReusableBuilderPro filesChangingSignature?: ts.Set; } +/** @internal */ export type SavedBuildProgramEmitState = Pick & { changedFilesSet: BuilderProgramState["changedFilesSet"] | undefined }; +/** @internal */ /** Get flags determining what all needs to be emitted */ export function getBuilderFileEmit(options: ts.CompilerOptions) { let result = BuilderFileEmit.Js; @@ -161,6 +170,7 @@ export function getBuilderFileEmit(options: ts.CompilerOptions) { return result; } +/** @internal */ /** Determing what all is pending to be emitted based on previous options or previous file emit flags */ export function getPendingEmitKind(optionsOrEmitKind: ts.CompilerOptions | BuilderFileEmit, oldOptionsOrEmitKind: ts.CompilerOptions | BuilderFileEmit | undefined): BuilderFileEmit { const oldEmitKind = oldOptionsOrEmitKind && (ts.isNumber(oldOptionsOrEmitKind) ? oldOptionsOrEmitKind : getBuilderFileEmit(oldOptionsOrEmitKind)); @@ -789,16 +799,22 @@ function getBinderAndCheckerDiagnosticsOfFile(state: BuilderProgramState, source return ts.filterSemanticDiagnostics(diagnostics, state.compilerOptions); } +/** @internal */ export type ProgramBuildInfoFileId = number & { __programBuildInfoFileIdBrand: any }; +/** @internal */ export type ProgramBuildInfoFileIdListId = number & { __programBuildInfoFileIdListIdBrand: any }; +/** @internal */ export type ProgramBuildInfoDiagnostic = ProgramBuildInfoFileId | [fileId: ProgramBuildInfoFileId, diagnostics: readonly ReusableDiagnostic[]]; +/** @internal */ /** * fileId if pending emit is same as what compilerOptions suggest * [fileId] if pending emit is only dts file emit * [fileId, emitKind] if any other type emit is pending */ export type ProgramBuilderInfoFilePendingEmit = ProgramBuildInfoFileId | [fileId: ProgramBuildInfoFileId] | [fileId: ProgramBuildInfoFileId, emitKind: BuilderFileEmit]; +/** @internal */ export type ProgramBuildInfoReferencedMap = [fileId: ProgramBuildInfoFileId, fileIdListId: ProgramBuildInfoFileIdListId][]; +/** @internal */ export type ProgramMultiFileEmitBuildInfoBuilderStateFileInfo = Omit & { /** * Signature is @@ -808,15 +824,18 @@ export type ProgramMultiFileEmitBuildInfoBuilderStateFileInfo = Omit { program?: ts.Program | undefined; compilerOptions: ts.CompilerOptions; }, configFileParsingDiagnostics: readonly ts.Diagnostic[]): ts.BuilderProgram { return { getState: ts.notImplemented, @@ -1705,4 +1743,3 @@ export function createRedirectedBuilderProgram(getState: () => { program?: ts.Pr return ts.Debug.checkDefined(getState().program); } } -} diff --git a/src/compiler/builderPublic.ts b/src/compiler/builderPublic.ts index 4f8d760af5041..fa87d96f333d8 100644 --- a/src/compiler/builderPublic.ts +++ b/src/compiler/builderPublic.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + export type AffectedFileResult = { result: T; affected: ts.SourceFile | ts.Program; } | undefined; export interface BuilderProgramHost { @@ -178,4 +179,3 @@ export function createAbstractBuilder(newProgramOrRootNames: ts.Program | readon const { newProgram, configFileParsingDiagnostics: newConfigFileParsingDiagnostics } = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences); return ts.createRedirectedBuilderProgram(() => ({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }), newConfigFileParsingDiagnostics); } -} diff --git a/src/compiler/builderState.ts b/src/compiler/builderState.ts index fbc9c9c148210..31ea38d87beb0 100644 --- a/src/compiler/builderState.ts +++ b/src/compiler/builderState.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export function getFileEmitOutput(program: ts.Program, sourceFile: ts.SourceFile, emitOnlyDtsFiles: boolean, cancellationToken?: ts.CancellationToken, customTransformers?: ts.CustomTransformers, forceDtsEmit?: boolean): ts.EmitOutput { const outputFiles: ts.OutputFile[] = []; @@ -10,6 +11,7 @@ export function getFileEmitOutput(program: ts.Program, sourceFile: ts.SourceFile outputFiles.push({ name: fileName, writeByteOrderMark, text }); } } +/** @internal */ export interface BuilderState { /** * Information of the file eg. its version, signature etc @@ -57,6 +59,7 @@ export interface BuilderState { */ allFileNames?: readonly string[]; } +/** @internal */ export namespace BuilderState { /** * Information about the source file: Its version and optional signature from last emit @@ -629,4 +632,3 @@ export namespace BuilderState { return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), value => value)); } } -} diff --git a/src/compiler/builderStatePublic.ts b/src/compiler/builderStatePublic.ts index 93e2fccf7a38d..b662d8c851891 100644 --- a/src/compiler/builderStatePublic.ts +++ b/src/compiler/builderStatePublic.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + export interface EmitOutput { outputFiles: OutputFile[]; emitSkipped: boolean; @@ -11,4 +12,3 @@ export interface OutputFile { text: string; /* @internal */ data?: ts.WriteFileCallbackData; } -} diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 3abcc33023d7f..06e90d0b1605f 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts { +import * as ts from "./_namespaces/ts"; + const ambientModuleSymbolRegex = /^".+"$/; const anon = "(anonymous)" as ts.__String & string; @@ -61,6 +61,7 @@ const enum WideningKind { GeneratorYield, } +/** @internal */ export const enum TypeFacts { None = 0, TypeofEQString = 1 << 0, // typeof x === "string" @@ -169,6 +170,7 @@ const enum TypeSystemPropertyName { WriteType, } +/** @internal */ export const enum CheckMode { Normal = 0, // Normal type checking Contextual = 1 << 0, // Explicitly assigned contextual type, therefore not cacheable @@ -182,6 +184,7 @@ export const enum CheckMode { // we need to preserve generic types instead of substituting them for constraints } +/** @internal */ export const enum SignatureCheckMode { BivariantCallback = 1 << 0, StrictCallback = 1 << 1, @@ -276,6 +279,7 @@ function NodeLinks(this: ts.NodeLinks) { this.flags = 0; } +/** @internal */ export function getNodeId(node: ts.Node): number { if (!node.id) { node.id = nextNodeId; @@ -284,6 +288,7 @@ export function getNodeId(node: ts.Node): number { return node.id; } +/** @internal */ export function getSymbolId(symbol: ts.Symbol): ts.SymbolId { if (!symbol.id) { symbol.id = nextSymbolId; @@ -293,12 +298,14 @@ export function getSymbolId(symbol: ts.Symbol): ts.SymbolId { return symbol.id; } +/** @internal */ export function isInstantiatedModule(node: ts.ModuleDeclaration, preserveConstEnums: boolean) { const moduleState = ts.getModuleInstanceState(node); return moduleState === ts.ModuleInstanceState.Instantiated || (preserveConstEnums && moduleState === ts.ModuleInstanceState.ConstEnumOnly); } +/** @internal */ export function createTypeChecker(host: ts.TypeCheckerHost): ts.TypeChecker { const getPackagesMap = ts.memoize(() => { // A package name maps to true when we detect it has .d.ts files. @@ -46175,11 +46182,12 @@ function getIterationTypesKeyFromIterationTypeKind(typeKind: IterationTypeKind) } } +/** @internal */ export function signatureHasRestParameter(s: ts.Signature) { return !!(s.flags & ts.SignatureFlags.HasRestParameter); } +/** @internal */ export function signatureHasLiteralTypes(s: ts.Signature) { return !!(s.flags & ts.SignatureFlags.HasLiteralTypes); } -} diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 8e9d93d34b7c3..c7a6e5e730cae 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + /* @internal */ export const compileOnSaveCommandLineOption: ts.CommandLineOption = { name: "compileOnSave", @@ -3764,4 +3765,3 @@ function getDefaultValueForOption(option: ts.CommandLineOption) { return ts.Debug.fail("Expected 'option.type' to have entries."); } } -} diff --git a/src/compiler/core.ts b/src/compiler/core.ts index d79fb7f05f8c2..ba8307d016a82 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1,15 +1,21 @@ -/* @internal */ -namespace ts { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export function getIterator | ts.ReadonlyESMap | undefined>(iterable: I): ts.Iterator< I extends ts.ReadonlyESMap ? [K, V] : I extends ts.ReadonlySet ? T : I extends readonly (infer T)[] ? T : I extends undefined ? undefined : never>; +/** @internal */ export function getIterator(iterable: ts.ReadonlyESMap): ts.Iterator<[K, V]>; +/** @internal */ export function getIterator(iterable: ts.ReadonlyESMap | undefined): ts.Iterator<[K, V]> | undefined; +/** @internal */ export function getIterator(iterable: readonly T[] | ts.ReadonlySet): ts.Iterator; +/** @internal */ export function getIterator(iterable: readonly T[] | ts.ReadonlySet | undefined): ts.Iterator | undefined; +/** @internal */ export function getIterator(iterable: readonly any[] | ts.ReadonlySet | ts.ReadonlyESMap | undefined): ts.Iterator | undefined { if (iterable) { if (isArray(iterable)) return arrayIterator(iterable); @@ -19,14 +25,19 @@ export function getIterator(iterable: readonly any[] | ts.ReadonlySet | ts. } } +/** @internal */ export const emptyArray: never[] = [] as never[]; +/** @internal */ export const emptyMap: ts.ReadonlyESMap = new ts.Map(); +/** @internal */ export const emptySet: ts.ReadonlySet = new ts.Set(); +/** @internal */ export function length(array: readonly any[] | undefined): number { return array ? array.length : 0; } +/** @internal */ /** * Iterates through 'array' by index and performs the callback on each element of array until the callback * returns a truthy value, then returns that value. @@ -44,6 +55,7 @@ export function forEach(array: readonly T[] | undefined, callback: (elemen return undefined; } +/** @internal */ /** * Like `forEach`, but iterates in reverse order. */ @@ -59,6 +71,7 @@ export function forEachRight(array: readonly T[] | undefined, callback: (e return undefined; } +/** @internal */ /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ export function firstDefined(array: readonly T[] | undefined, callback: (element: T, index: number) => U | undefined): U | undefined { if (array === undefined) { @@ -74,6 +87,7 @@ export function firstDefined(array: readonly T[] | undefined, callback: (e return undefined; } +/** @internal */ export function firstDefinedIterator(iter: ts.Iterator, callback: (element: T) => U | undefined): U | undefined { while (true) { const iterResult = iter.next(); @@ -87,6 +101,7 @@ export function firstDefinedIterator(iter: ts.Iterator, callback: (elem } } +/** @internal */ export function reduceLeftIterator(iterator: ts.Iterator | undefined, f: (memo: U, value: T, i: number) => U, initial: U): U { let result = initial; if (iterator) { @@ -97,6 +112,7 @@ export function reduceLeftIterator(iterator: ts.Iterator | undefined, f return result; } +/** @internal */ export function zipWith(arrayA: readonly T[], arrayB: readonly U[], callback: (a: T, b: U, index: number) => V): V[] { const result: V[] = []; ts.Debug.assertEqual(arrayA.length, arrayB.length); @@ -106,6 +122,7 @@ export function zipWith(arrayA: readonly T[], arrayB: readonly U[], cal return result; } +/** @internal */ export function zipToIterator(arrayA: readonly T[], arrayB: readonly U[]): ts.Iterator<[T, U]> { ts.Debug.assertEqual(arrayA.length, arrayB.length); let i = 0; @@ -120,6 +137,7 @@ export function zipToIterator(arrayA: readonly T[], arrayB: readonly U[]): }; } +/** @internal */ export function zipToMap(keys: readonly K[], values: readonly V[]): ts.ESMap { ts.Debug.assert(keys.length === values.length); const map = new ts.Map(); @@ -129,6 +147,7 @@ export function zipToMap(keys: readonly K[], values: readonly V[]): ts.ESM return map; } +/** @internal */ /** * Creates a new array with `element` interspersed in between each element of `input` * if there is more than 1 value in `input`. Otherwise, returns the existing array. @@ -145,6 +164,7 @@ export function intersperse(input: T[], element: T): T[] { return result; } +/** @internal */ /** * Iterates through `array` by index and performs the callback on each element of array until the callback * returns a falsey value, then returns false. @@ -162,9 +182,12 @@ export function every(array: readonly T[] | undefined, callback: (element: T, return true; } +/** @internal */ /** Works like Array.prototype.find, returning `undefined` if no element satisfying the predicate is found. */ export function find(array: readonly T[] | undefined, predicate: (element: T, index: number) => element is U, startIndex?: number): U | undefined; +/** @internal */ export function find(array: readonly T[] | undefined, predicate: (element: T, index: number) => boolean, startIndex?: number): T | undefined; +/** @internal */ export function find(array: readonly T[] | undefined, predicate: (element: T, index: number) => boolean, startIndex?: number): T | undefined { if (array === undefined) return undefined; for (let i = startIndex ?? 0; i < array.length; i++) { @@ -176,8 +199,11 @@ export function find(array: readonly T[] | undefined, predicate: (element: T, return undefined; } +/** @internal */ export function findLast(array: readonly T[] | undefined, predicate: (element: T, index: number) => element is U, startIndex?: number): U | undefined; +/** @internal */ export function findLast(array: readonly T[] | undefined, predicate: (element: T, index: number) => boolean, startIndex?: number): T | undefined; +/** @internal */ export function findLast(array: readonly T[] | undefined, predicate: (element: T, index: number) => boolean, startIndex?: number): T | undefined { if (array === undefined) return undefined; for (let i = startIndex ?? array.length - 1; i >= 0; i--) { @@ -189,6 +215,7 @@ export function findLast(array: readonly T[] | undefined, predicate: (element return undefined; } +/** @internal */ /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */ export function findIndex(array: readonly T[] | undefined, predicate: (element: T, index: number) => boolean, startIndex?: number): number { if (array === undefined) return -1; @@ -200,6 +227,7 @@ export function findIndex(array: readonly T[] | undefined, predicate: (elemen return -1; } +/** @internal */ export function findLastIndex(array: readonly T[] | undefined, predicate: (element: T, index: number) => boolean, startIndex?: number): number { if (array === undefined) return -1; for (let i = startIndex ?? array.length - 1; i >= 0; i--) { @@ -210,6 +238,7 @@ export function findLastIndex(array: readonly T[] | undefined, predicate: (el return -1; } +/** @internal */ /** * Returns the first truthy result of `callback`, or else fails. * This is like `forEach`, but never returns undefined. @@ -224,6 +253,7 @@ export function findMap(array: readonly T[], callback: (element: T, index: return ts.Debug.fail(); } +/** @internal */ export function contains(array: readonly T[] | undefined, value: T, equalityComparer: ts.EqualityComparer = equateValues): boolean { if (array) { for (const v of array) { @@ -235,10 +265,12 @@ export function contains(array: readonly T[] | undefined, value: T, equalityC return false; } +/** @internal */ export function arraysEqual(a: readonly T[], b: readonly T[], equalityComparer: ts.EqualityComparer = equateValues): boolean { return a.length === b.length && a.every((x, i) => equalityComparer(x, b[i])); } +/** @internal */ export function indexOfAnyCharCode(text: string, charCodes: readonly number[], start?: number): number { for (let i = start || 0; i < text.length; i++) { if (contains(charCodes, text.charCodeAt(i))) { @@ -248,6 +280,7 @@ export function indexOfAnyCharCode(text: string, charCodes: readonly number[], s return -1; } +/** @internal */ export function countWhere(array: readonly T[] | undefined, predicate: (x: T, i: number) => boolean): number { let count = 0; if (array) { @@ -261,18 +294,27 @@ export function countWhere(array: readonly T[] | undefined, predicate: (x: T, return count; } +/** @internal */ /** * Filters an array by a predicate function. Returns the same array instance if the predicate is * true for all elements, otherwise returns a new array instance containing the filtered subset. */ export function filter(array: T[], f: (x: T) => x is U): U[]; +/** @internal */ export function filter(array: T[], f: (x: T) => boolean): T[]; +/** @internal */ export function filter(array: readonly T[], f: (x: T) => x is U): readonly U[]; +/** @internal */ export function filter(array: readonly T[], f: (x: T) => boolean): readonly T[]; +/** @internal */ export function filter(array: T[] | undefined, f: (x: T) => x is U): U[] | undefined; +/** @internal */ export function filter(array: T[] | undefined, f: (x: T) => boolean): T[] | undefined; +/** @internal */ export function filter(array: readonly T[] | undefined, f: (x: T) => x is U): readonly U[] | undefined; +/** @internal */ export function filter(array: readonly T[] | undefined, f: (x: T) => boolean): readonly T[] | undefined; +/** @internal */ export function filter(array: readonly T[] | undefined, f: (x: T) => boolean): readonly T[] | undefined { if (array) { const len = array.length; @@ -294,6 +336,7 @@ export function filter(array: readonly T[] | undefined, f: (x: T) => boolean) return array; } +/** @internal */ export function filterMutate(array: T[], f: (x: T, i: number, array: T[]) => boolean): void { let outIndex = 0; for (let i = 0; i < array.length; i++) { @@ -305,12 +348,16 @@ export function filterMutate(array: T[], f: (x: T, i: number, array: T[]) => array.length = outIndex; } +/** @internal */ export function clear(array: unknown[]): void { array.length = 0; } +/** @internal */ export function map(array: readonly T[], f: (x: T, i: number) => U): U[]; +/** @internal */ export function map(array: readonly T[] | undefined, f: (x: T, i: number) => U): U[] | undefined; +/** @internal */ export function map(array: readonly T[] | undefined, f: (x: T, i: number) => U): U[] | undefined { let result: U[] | undefined; if (array) { @@ -323,6 +370,7 @@ export function map(array: readonly T[] | undefined, f: (x: T, i: number) } +/** @internal */ export function mapIterator(iter: ts.Iterator, mapFn: (x: T) => U): ts.Iterator { return { next() { @@ -333,10 +381,15 @@ export function mapIterator(iter: ts.Iterator, mapFn: (x: T) => U): ts. } // Maps from T to T and avoids allocation if all elements map to themselves +/** @internal */ export function sameMap(array: T[], f: (x: T, i: number) => T): T[]; +/** @internal */ export function sameMap(array: readonly T[], f: (x: T, i: number) => T): readonly T[]; +/** @internal */ export function sameMap(array: T[] | undefined, f: (x: T, i: number) => T): T[] | undefined; +/** @internal */ export function sameMap(array: readonly T[] | undefined, f: (x: T, i: number) => T): readonly T[] | undefined; +/** @internal */ export function sameMap(array: readonly T[] | undefined, f: (x: T, i: number) => T): readonly T[] | undefined { if (array) { for (let i = 0; i < array.length; i++) { @@ -355,6 +408,7 @@ export function sameMap(array: readonly T[] | undefined, f: (x: T, i: number) return array; } +/** @internal */ /** * Flattens an array containing a mix of array or non-array elements. * @@ -375,6 +429,7 @@ export function flatten(array: T[][] | readonly (T | readonly T[] | undefined return result; } +/** @internal */ /** * Maps an array. If the mapped value is an array, it is spread into the result. * @@ -399,6 +454,7 @@ export function flatMap(array: readonly T[] | undefined, mapfn: (x: T, i: return result || emptyArray; } +/** @internal */ export function flatMapToMutable(array: readonly T[] | undefined, mapfn: (x: T, i: number) => U | readonly U[] | undefined): U[] { const result: U[] = []; if (array) { @@ -417,6 +473,7 @@ export function flatMapToMutable(array: readonly T[] | undefined, mapfn: ( return result; } +/** @internal */ export function flatMapIterator(iter: ts.Iterator, mapfn: (x: T) => readonly U[] | ts.Iterator | undefined): ts.Iterator { const first = iter.next(); if (first.done) { @@ -445,6 +502,7 @@ export function flatMapIterator(iter: ts.Iterator, mapfn: (x: T) => rea } } +/** @internal */ /** * Maps an array. If the mapped value is an array, it is spread into the result. * Avoids allocation if all elements map to themselves. @@ -453,7 +511,9 @@ export function flatMapIterator(iter: ts.Iterator, mapfn: (x: T) => rea * @param mapfn The callback used to map the result into one or more values. */ export function sameFlatMap(array: T[], mapfn: (x: T, i: number) => T | readonly T[]): T[]; +/** @internal */ export function sameFlatMap(array: readonly T[], mapfn: (x: T, i: number) => T | readonly T[]): readonly T[]; +/** @internal */ export function sameFlatMap(array: T[], mapfn: (x: T, i: number) => T | T[]): T[] { let result: T[] | undefined; if (array) { @@ -476,6 +536,7 @@ export function sameFlatMap(array: T[], mapfn: (x: T, i: number) => T | T[]): return result || array; } +/** @internal */ export function mapAllOrFail(array: readonly T[], mapFn: (x: T, i: number) => U | undefined): U[] | undefined { const result: U[] = []; for (let i = 0; i < array.length; i++) { @@ -488,6 +549,7 @@ export function mapAllOrFail(array: readonly T[], mapFn: (x: T, i: number) return result; } +/** @internal */ export function mapDefined(array: readonly T[] | undefined, mapFn: (x: T, i: number) => U | undefined): U[] { const result: U[] = []; if (array) { @@ -501,6 +563,7 @@ export function mapDefined(array: readonly T[] | undefined, mapFn: (x: T, return result; } +/** @internal */ export function mapDefinedIterator(iter: ts.Iterator, mapFn: (x: T) => U | undefined): ts.Iterator { return { next() { @@ -518,8 +581,11 @@ export function mapDefinedIterator(iter: ts.Iterator, mapFn: (x: T) => }; } +/** @internal */ export function mapDefinedEntries(map: ts.ReadonlyESMap, f: (key: K1, value: V1) => readonly [K2, V2] | undefined): ts.ESMap; +/** @internal */ export function mapDefinedEntries(map: ts.ReadonlyESMap | undefined, f: (key: K1, value: V1) => readonly [K2 | undefined, V2 | undefined] | undefined): ts.ESMap | undefined; +/** @internal */ export function mapDefinedEntries(map: ts.ReadonlyESMap | undefined, f: (key: K1, value: V1) => readonly [K2 | undefined, V2 | undefined] | undefined): ts.ESMap | undefined { if (!map) { return undefined; @@ -539,8 +605,11 @@ export function mapDefinedEntries(map: ts.ReadonlyESMap return result; } +/** @internal */ export function mapDefinedValues(set: ts.ReadonlySet, f: (value: V1) => V2 | undefined): ts.Set; +/** @internal */ export function mapDefinedValues(set: ts.ReadonlySet | undefined, f: (value: V1) => V2 | undefined): ts.Set | undefined; +/** @internal */ export function mapDefinedValues(set: ts.ReadonlySet | undefined, f: (value: V1) => V2 | undefined): ts.Set | undefined { if (set) { const result = new ts.Set(); @@ -554,6 +623,7 @@ export function mapDefinedValues(set: ts.ReadonlySet | undefined, f: } } +/** @internal */ export function getOrUpdate(map: ts.ESMap, key: K, callback: () => V) { if (map.has(key)) { return map.get(key)!; @@ -563,6 +633,7 @@ export function getOrUpdate(map: ts.ESMap, key: K, callback: () => V return value; } +/** @internal */ export function tryAddToSet(set: ts.Set, value: T) { if (!set.has(value)) { set.add(value); @@ -571,8 +642,10 @@ export function tryAddToSet(set: ts.Set, value: T) { return false; } +/** @internal */ export const emptyIterator: ts.Iterator = { next: () => ({ value: undefined as never, done: true }) }; +/** @internal */ export function singleIterator(value: T): ts.Iterator { let done = false; return { @@ -584,6 +657,7 @@ export function singleIterator(value: T): ts.Iterator { }; } +/** @internal */ /** * Maps contiguous spans of values with the same key. * @@ -592,7 +666,9 @@ export function singleIterator(value: T): ts.Iterator { * @param mapfn A callback used to map a contiguous chunk of values to a single value. */ export function spanMap(array: readonly T[], keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[]; +/** @internal */ export function spanMap(array: readonly T[] | undefined, keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[] | undefined; +/** @internal */ export function spanMap(array: readonly T[] | undefined, keyfn: (x: T, i: number) => K, mapfn: (chunk: T[], key: K, start: number, end: number) => U): U[] | undefined { let result: U[] | undefined; if (array) { @@ -633,8 +709,11 @@ export function spanMap(array: readonly T[] | undefined, keyfn: (x: T, return result; } +/** @internal */ export function mapEntries(map: ts.ReadonlyESMap, f: (key: K1, value: V1) => readonly [K2, V2]): ts.ESMap; +/** @internal */ export function mapEntries(map: ts.ReadonlyESMap | undefined, f: (key: K1, value: V1) => readonly [K2, V2]): ts.ESMap | undefined; +/** @internal */ export function mapEntries(map: ts.ReadonlyESMap | undefined, f: (key: K1, value: V1) => readonly [K2, V2]): ts.ESMap | undefined { if (!map) { return undefined; @@ -648,8 +727,11 @@ export function mapEntries(map: ts.ReadonlyESMap | undef return result; } +/** @internal */ export function some(array: readonly T[] | undefined): array is readonly T[]; +/** @internal */ export function some(array: readonly T[] | undefined, predicate: (value: T) => boolean): boolean; +/** @internal */ export function some(array: readonly T[] | undefined, predicate?: (value: T) => boolean): boolean { if (array) { if (predicate) { @@ -666,6 +748,7 @@ export function some(array: readonly T[] | undefined, predicate?: (value: T) return false; } +/** @internal */ /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */ export function getRangesWhere(arr: readonly T[], pred: (t: T) => boolean, cb: (start: number, afterEnd: number) => void): void { let start: number | undefined; @@ -683,10 +766,15 @@ export function getRangesWhere(arr: readonly T[], pred: (t: T) => boolean, cb if (start !== undefined) cb(start, arr.length); } +/** @internal */ export function concatenate(array1: T[], array2: T[]): T[]; +/** @internal */ export function concatenate(array1: readonly T[], array2: readonly T[]): readonly T[]; +/** @internal */ export function concatenate(array1: T[] | undefined, array2: T[] | undefined): T[]; +/** @internal */ export function concatenate(array1: readonly T[] | undefined, array2: readonly T[] | undefined): readonly T[]; +/** @internal */ export function concatenate(array1: T[], array2: T[]): T[] { if (!some(array2)) return array1; if (!some(array1)) return array2; @@ -697,6 +785,7 @@ function selectIndex(_: unknown, i: number) { return i; } +/** @internal */ export function indicesOf(array: readonly unknown[]): number[] { return array.map(selectIndex); } @@ -731,6 +820,7 @@ function deduplicateEquality(array: readonly T[], equalityComparer: ts.Equali return result; } +/** @internal */ /** * Deduplicates an unsorted array. * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates. @@ -774,10 +864,12 @@ function deduplicateSorted(array: ts.SortedReadonlyArray, comparer: ts.Equ return deduplicated as any as ts.SortedReadonlyArray; } +/** @internal */ export function createSortedArray(): ts.SortedArray { return [] as any as ts.SortedArray; // TODO: GH#19873 } +/** @internal */ export function insertSorted(array: ts.SortedArray, insert: T, compare: ts.Comparer, allowDuplicates?: boolean): boolean { if (array.length === 0) { array.push(insert); @@ -798,12 +890,16 @@ export function insertSorted(array: ts.SortedArray, insert: T, compare: ts return false; } +/** @internal */ export function sortAndDeduplicate(array: readonly string[]): ts.SortedReadonlyArray; +/** @internal */ export function sortAndDeduplicate(array: readonly T[], comparer: ts.Comparer, equalityComparer?: ts.EqualityComparer): ts.SortedReadonlyArray; +/** @internal */ export function sortAndDeduplicate(array: readonly T[], comparer?: ts.Comparer, equalityComparer?: ts.EqualityComparer): ts.SortedReadonlyArray { return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive as any as ts.Comparer); } +/** @internal */ export function arrayIsSorted(array: readonly T[], comparer: ts.Comparer) { if (array.length < 2) return true; let prevElement = array[0]; @@ -816,6 +912,7 @@ export function arrayIsSorted(array: readonly T[], comparer: ts.Comparer) return true; } +/** @internal */ export function arrayIsEqualTo(array1: readonly T[] | undefined, array2: readonly T[] | undefined, equalityComparer: (a: T, b: T, index: number) => boolean = equateValues): boolean { if (!array1 || !array2) { return array1 === array2; @@ -834,14 +931,19 @@ export function arrayIsEqualTo(array1: readonly T[] | undefined, array2: read return true; } +/** @internal */ /** * Compacts an array, removing any falsey elements. */ export function compact(array: (T | undefined | null | false | 0 | "")[]): T[]; +/** @internal */ export function compact(array: readonly (T | undefined | null | false | 0 | "")[]): readonly T[]; // ESLint thinks these can be combined with the above - they cannot; they'd produce higher-priority inferences and prevent the falsey types from being stripped +/** @internal */ export function compact(array: T[]): T[]; // eslint-disable-line @typescript-eslint/unified-signatures +/** @internal */ export function compact(array: readonly T[]): readonly T[]; // eslint-disable-line @typescript-eslint/unified-signatures +/** @internal */ export function compact(array: T[]): T[] { let result: T[] | undefined; if (array) { @@ -860,6 +962,7 @@ export function compact(array: T[]): T[] { return result || array; } +/** @internal */ /** * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted @@ -903,6 +1006,7 @@ export function relativeComplement(arrayA: T[] | undefined, arrayB: T[] | und return result; } +/** @internal */ export function sum, K extends string>(array: readonly T[], prop: K): number { let result = 0; for (const v of array) { @@ -911,6 +1015,7 @@ export function sum, K extends string>(array: readon return result; } +/** @internal */ /** * Appends a value to an array, returning the array. * @@ -920,10 +1025,15 @@ export function sum, K extends string>(array: readon * appended. */ export function append[number] | undefined>(to: TArray, value: TValue): [undefined, undefined] extends [TArray, TValue] ? TArray : NonNullable[number][]; +/** @internal */ export function append(to: T[], value: T | undefined): T[]; +/** @internal */ export function append(to: T[] | undefined, value: T): T[]; +/** @internal */ export function append(to: T[] | undefined, value: T | undefined): T[] | undefined; +/** @internal */ export function append(to: ts.Push, value: T | undefined): void; +/** @internal */ export function append(to: T[], value: T | undefined): T[] | undefined { if (value === undefined) return to; if (to === undefined) return [value]; @@ -931,6 +1041,7 @@ export function append(to: T[], value: T | undefined): T[] | undefined { return to; } +/** @internal */ /** * Combines two arrays, values, or undefineds into the smallest container that can accommodate the resulting set: * @@ -944,7 +1055,9 @@ export function append(to: T[], value: T | undefined): T[] | undefined { * ``` */ export function combine(xs: T | readonly T[] | undefined, ys: T | readonly T[] | undefined): T | readonly T[] | undefined; +/** @internal */ export function combine(xs: T | T[] | undefined, ys: T | T[] | undefined): T | T[] | undefined; +/** @internal */ export function combine(xs: T | T[] | undefined, ys: T | T[] | undefined) { if (xs === undefined) return ys; if (ys === undefined) return xs; @@ -961,6 +1074,7 @@ function toOffset(array: readonly any[], offset: number) { return offset < 0 ? array.length + offset : offset; } +/** @internal */ /** * Appends a range of value to an array, returning the array. * @@ -972,7 +1086,9 @@ function toOffset(array: readonly any[], offset: number) { * @param end The offset in `from` at which to stop copying values (non-inclusive). */ export function addRange(to: T[], from: readonly T[] | undefined, start?: number, end?: number): T[]; +/** @internal */ export function addRange(to: T[] | undefined, from: readonly T[] | undefined, start?: number, end?: number): T[] | undefined; +/** @internal */ export function addRange(to: T[] | undefined, from: readonly T[] | undefined, start?: number, end?: number): T[] | undefined { if (from === undefined || from.length === 0) return to; if (to === undefined) return from.slice(start, end); @@ -986,6 +1102,7 @@ export function addRange(to: T[] | undefined, from: readonly T[] | undefined, return to; } +/** @internal */ /** * @return Whether the value was added. */ @@ -999,6 +1116,7 @@ export function pushIfUnique(array: T[], toAdd: T, equalityComparer?: ts.Equa } } +/** @internal */ /** * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array. */ @@ -1017,6 +1135,7 @@ function stableSortIndices(array: readonly T[], indices: number[], comparer: indices.sort((x, y) => comparer(array[x], array[y]) || compareValues(x, y)); } +/** @internal */ /** * Returns a new sorted array. */ @@ -1024,6 +1143,7 @@ export function sort(array: readonly T[], comparer?: ts.Comparer): ts.Sort return (array.length === 0 ? array : array.slice().sort(comparer)) as ts.SortedReadonlyArray; } +/** @internal */ export function arrayIterator(array: readonly T[]): ts.Iterator { let i = 0; return { next: () => { @@ -1037,6 +1157,7 @@ export function arrayIterator(array: readonly T[]): ts.Iterator { }}; } +/** @internal */ export function arrayReverseIterator(array: readonly T[]): ts.Iterator { let i = array.length; return { @@ -1052,6 +1173,7 @@ export function arrayReverseIterator(array: readonly T[]): ts.Iterator { }; } +/** @internal */ /** * Stable sort of an array. Elements equal to each other maintain their relative position in the array. */ @@ -1061,6 +1183,7 @@ export function stableSort(array: readonly T[], comparer: ts.Comparer): ts return indices.map(i => array[i]) as ts.SortedArray as ts.SortedReadonlyArray; } +/** @internal */ export function rangeEquals(array1: readonly T[], array2: readonly T[], pos: number, end: number) { while (pos < end) { if (array1[pos] !== array2[pos]) { @@ -1071,6 +1194,7 @@ export function rangeEquals(array1: readonly T[], array2: readonly T[], pos: return true; } +/** @internal */ /** * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise. * A negative offset indicates the element should be retrieved from the end of the array. @@ -1085,6 +1209,7 @@ export function elementAt(array: readonly T[] | undefined, offset: number): T return undefined; } +/** @internal */ /** * Returns the first element of an array if non-empty, `undefined` otherwise. */ @@ -1092,11 +1217,13 @@ export function firstOrUndefined(array: readonly T[] | undefined): T | undefi return array === undefined || array.length === 0 ? undefined : array[0]; } +/** @internal */ export function first(array: readonly T[]): T { ts.Debug.assert(array.length !== 0); return array[0]; } +/** @internal */ /** * Returns the last element of an array if non-empty, `undefined` otherwise. */ @@ -1104,11 +1231,13 @@ export function lastOrUndefined(array: readonly T[] | undefined): T | undefin return array === undefined || array.length === 0 ? undefined : array[array.length - 1]; } +/** @internal */ export function last(array: readonly T[]): T { ts.Debug.assert(array.length !== 0); return array[array.length - 1]; } +/** @internal */ /** * Returns the only element of an array if it contains only one element, `undefined` otherwise. */ @@ -1118,6 +1247,7 @@ export function singleOrUndefined(array: readonly T[] | undefined): T | undef : undefined; } +/** @internal */ /** * Returns the only element of an array if it contains only one element; throws otherwise. */ @@ -1125,26 +1255,33 @@ export function single(array: readonly T[]): T { return ts.Debug.checkDefined(singleOrUndefined(array)); } +/** @internal */ /** * Returns the only element of an array if it contains only one element; otherwise, returns the * array. */ export function singleOrMany(array: T[]): T | T[]; +/** @internal */ export function singleOrMany(array: readonly T[]): T | readonly T[]; +/** @internal */ export function singleOrMany(array: T[] | undefined): T | T[] | undefined; +/** @internal */ export function singleOrMany(array: readonly T[] | undefined): T | readonly T[] | undefined; +/** @internal */ export function singleOrMany(array: readonly T[] | undefined): T | readonly T[] | undefined { return array && array.length === 1 ? array[0] : array; } +/** @internal */ export function replaceElement(array: readonly T[], index: number, value: T): T[] { const result = array.slice(0); result[index] = value; return result; } +/** @internal */ /** * Performs a binary search, finding the index at which `value` occurs in `array`. * If no such index is found, returns the 2's-complement of first index at which @@ -1160,6 +1297,7 @@ export function binarySearch(array: readonly T[], value: T, keySelector: ( return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset); } +/** @internal */ /** * Performs a binary search, finding the index at which an object with `key` occurs in `array`. * If no such index is found, returns the 2's-complement of first index at which @@ -1195,8 +1333,11 @@ export function binarySearchKey(array: readonly T[], key: U, keySelector: return ~low; } +/** @internal */ export function reduceLeft(array: readonly T[] | undefined, f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U; +/** @internal */ export function reduceLeft(array: readonly T[], f: (memo: T, value: T, i: number) => T): T | undefined; +/** @internal */ export function reduceLeft(array: T[], f: (memo: T, value: T, i: number) => T, initial?: T, start?: number, count?: number): T | undefined { if (array && array.length > 0) { const size = array.length; @@ -1223,6 +1364,7 @@ export function reduceLeft(array: T[], f: (memo: T, value: T, i: number) => T const hasOwnProperty = Object.prototype.hasOwnProperty; +/** @internal */ /** * Indicates whether a map-like contains an own property with the specified key. * @@ -1233,6 +1375,7 @@ export function hasProperty(map: ts.MapLike, key: string): boolean { return hasOwnProperty.call(map, key); } +/** @internal */ /** * Gets the value of an owned property in a map-like. * @@ -1243,6 +1386,7 @@ export function getProperty(map: ts.MapLike, key: string): T | undefined { return hasOwnProperty.call(map, key) ? map[key] : undefined; } +/** @internal */ /** * Gets the owned, enumerable property keys of a map-like. */ @@ -1257,6 +1401,7 @@ export function getOwnKeys(map: ts.MapLike): string[] { return keys; } +/** @internal */ export function getAllKeys(obj: object): string[] { const result: string[] = []; do { @@ -1268,6 +1413,7 @@ export function getAllKeys(obj: object): string[] { return result; } +/** @internal */ export function getOwnValues(collection: ts.MapLike | T[]): T[] { const values: T[] = []; for (const key in collection) { @@ -1288,10 +1434,12 @@ const _entries = Object.entries || ((obj: ts.MapLike) => { return result; }); +/** @internal */ export function getEntries(obj: ts.MapLike): [string, T][] { return obj ? _entries(obj) : []; } +/** @internal */ export function arrayOf(count: number, f: (index: number) => T): T[] { const result = new Array(count); for (let i = 0; i < count; i++) { @@ -1300,9 +1448,12 @@ export function arrayOf(count: number, f: (index: number) => T): T[] { return result; } +/** @internal */ /** Shims `Array.from`. */ export function arrayFrom(iterator: ts.Iterator | IterableIterator, map: (t: T) => U): U[]; +/** @internal */ export function arrayFrom(iterator: ts.Iterator | IterableIterator): T[]; +/** @internal */ export function arrayFrom(iterator: ts.Iterator | IterableIterator, map?: (t: T) => U): (T | U)[] { const result: (T | U)[] = []; for (let iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) { @@ -1312,6 +1463,7 @@ export function arrayFrom(iterator: ts.Iterator | IterableIterator, } +/** @internal */ export function assign(t: T, ...args: (T | undefined)[]) { for (const arg of args) { if (arg === undefined) continue; @@ -1324,6 +1476,7 @@ export function assign(t: T, ...args: (T | undefined)[]) { return t; } +/** @internal */ /** * Performs a shallow equality comparison of the contents of two map-likes. * @@ -1349,6 +1502,7 @@ export function equalOwnProperties(left: ts.MapLike | undefined, right: ts return true; } +/** @internal */ /** * Creates a map from the elements of an array. * @@ -1360,9 +1514,13 @@ export function equalOwnProperties(left: ts.MapLike | undefined, right: ts * index in the array will be the one associated with the produced key. */ export function arrayToMap(array: readonly V[], makeKey: (value: V) => K | undefined): ts.ESMap; +/** @internal */ export function arrayToMap(array: readonly V1[], makeKey: (value: V1) => K | undefined, makeValue: (value: V1) => V2): ts.ESMap; +/** @internal */ export function arrayToMap(array: readonly T[], makeKey: (value: T) => string | undefined): ts.ESMap; +/** @internal */ export function arrayToMap(array: readonly T[], makeKey: (value: T) => string | undefined, makeValue: (value: T) => U): ts.ESMap; +/** @internal */ export function arrayToMap(array: readonly V1[], makeKey: (value: V1) => K | undefined, makeValue: (value: V1) => V1 | V2 = identity): ts.ESMap { const result = new ts.Map(); for (const value of array) { @@ -1372,8 +1530,11 @@ export function arrayToMap(array: readonly V1[], makeKey: (value: V1) return result; } +/** @internal */ export function arrayToNumericMap(array: readonly T[], makeKey: (value: T) => number): T[]; +/** @internal */ export function arrayToNumericMap(array: readonly T[], makeKey: (value: T) => number, makeValue: (value: T) => U): U[]; +/** @internal */ export function arrayToNumericMap(array: readonly T[], makeKey: (value: T) => number, makeValue: (value: T) => T | U = identity): (T | U)[] { const result: (T | U)[] = []; for (const value of array) { @@ -1382,8 +1543,11 @@ export function arrayToNumericMap(array: readonly T[], makeKey: (value: T) return result; } +/** @internal */ export function arrayToMultiMap(values: readonly V[], makeKey: (value: V) => K): MultiMap; +/** @internal */ export function arrayToMultiMap(values: readonly V[], makeKey: (value: V) => K, makeValue: (value: V) => U): MultiMap; +/** @internal */ export function arrayToMultiMap(values: readonly V[], makeKey: (value: V) => K, makeValue: (value: V) => V | U = identity): MultiMap { const result = createMultiMap(); for (const value of values) { @@ -1392,14 +1556,20 @@ export function arrayToMultiMap(values: readonly V[], makeKey: (value: return result; } +/** @internal */ export function group(values: readonly T[], getGroupId: (value: T) => K): readonly (readonly T[])[]; +/** @internal */ export function group(values: readonly T[], getGroupId: (value: T) => K, resultSelector: (values: readonly T[]) => R): R[]; +/** @internal */ export function group(values: readonly T[], getGroupId: (value: T) => string): readonly (readonly T[])[]; +/** @internal */ export function group(values: readonly T[], getGroupId: (value: T) => string, resultSelector: (values: readonly T[]) => R): R[]; +/** @internal */ export function group(values: readonly T[], getGroupId: (value: T) => K, resultSelector: (values: readonly T[]) => readonly T[] = identity): readonly (readonly T[])[] { return arrayFrom(arrayToMultiMap(values, getGroupId).values(), resultSelector); } +/** @internal */ export function clone(object: T): T { const result: any = {}; for (const id in object) { @@ -1410,6 +1580,7 @@ export function clone(object: T): T { return result; } +/** @internal */ /** * Creates a new object by adding the own properties of `second`, then the own properties of `first`. * @@ -1432,6 +1603,7 @@ export function extend(first: T1, second: T2): T1 & T2 { return result; } +/** @internal */ export function copyProperties(first: T1, second: T2) { for (const id in second) { if (hasOwnProperty.call(second, id)) { @@ -1440,10 +1612,12 @@ export function copyProperties(first: T1, second: T2) { } } +/** @internal */ export function maybeBind(obj: T, fn: ((this: T, ...args: A) => R) | undefined): ((...args: A) => R) | undefined { return fn ? fn.bind(obj) : undefined; } +/** @internal */ export interface MultiMap extends ts.ESMap { /** * Adds the value to an array of values associated with the key, and returns the array. @@ -1458,8 +1632,11 @@ export interface MultiMap extends ts.ESMap { remove(key: K, value: V): void; } +/** @internal */ export function createMultiMap(): MultiMap; +/** @internal */ export function createMultiMap(): MultiMap; +/** @internal */ export function createMultiMap(): MultiMap { const map = new ts.Map() as MultiMap; map.add = multiMapAdd; @@ -1486,6 +1663,7 @@ function multiMapRemove(this: MultiMap, key: K, value: V) { } } +/** @internal */ export interface UnderscoreEscapedMultiMap extends ts.UnderscoreEscapedMap { /** * Adds the value to an array of values associated with the key, and returns the array. @@ -1500,10 +1678,12 @@ export interface UnderscoreEscapedMultiMap extends ts.UnderscoreEscapedMap(): UnderscoreEscapedMultiMap { return createMultiMap() as UnderscoreEscapedMultiMap; } +/** @internal */ export function createQueue(items?: readonly T[]): ts.Queue { const elements: (T | undefined)[] = items?.slice() || []; let headIndex = 0; @@ -1545,6 +1725,7 @@ export function createQueue(items?: readonly T[]): ts.Queue { }; } +/** @internal */ /** * Creates a Set with custom equality and hash code functionality. This is useful when you * want to use something looser than object identity - e.g. "has the same span". @@ -1698,6 +1879,7 @@ export function createSet(getHashCode: (element: TElem return set; } +/** @internal */ /** * Tests whether a value is an array. */ @@ -1705,62 +1887,78 @@ export function isArray(value: any): value is readonly unknown[] { return Array.isArray ? Array.isArray(value) : value instanceof Array; } +/** @internal */ export function toArray(value: T | T[]): T[]; +/** @internal */ export function toArray(value: T | readonly T[]): readonly T[]; +/** @internal */ export function toArray(value: T | T[]): T[] { return isArray(value) ? value : [value]; } +/** @internal */ /** * Tests whether a value is string */ export function isString(text: unknown): text is string { return typeof text === "string"; } +/** @internal */ export function isNumber(x: unknown): x is number { return typeof x === "number"; } +/** @internal */ export function tryCast(value: TIn | undefined, test: (value: TIn) => value is TOut): TOut | undefined; +/** @internal */ export function tryCast(value: T, test: (value: T) => boolean): T | undefined; +/** @internal */ export function tryCast(value: T, test: (value: T) => boolean): T | undefined { return value !== undefined && test(value) ? value : undefined; } +/** @internal */ export function cast(value: TIn | undefined, test: (value: TIn) => value is TOut): TOut { if (value !== undefined && test(value)) return value; return ts.Debug.fail(`Invalid cast. The supplied value ${value} did not pass the test '${ts.Debug.getFunctionName(test)}'.`); } +/** @internal */ /** Does nothing. */ export function noop(_?: unknown): void { } +/** @internal */ export const noopPush: ts.Push = { push: noop, length: 0 }; +/** @internal */ /** Do nothing and return false */ export function returnFalse(): false { return false; } +/** @internal */ /** Do nothing and return true */ export function returnTrue(): true { return true; } +/** @internal */ /** Do nothing and return undefined */ export function returnUndefined(): undefined { return undefined; } +/** @internal */ /** Returns its argument. */ export function identity(x: T) { return x; } +/** @internal */ /** Returns lower case string */ export function toLowerCase(x: string) { return x.toLowerCase(); @@ -1789,6 +1987,7 @@ export function toLowerCase(x: string) { // But to avoid having to do string building for most common cases, also ignore // a-z, 0-9, \u0131, \u00DF, \, /, ., : and space const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g; +/** @internal */ /** * Case insensitive file systems have descripencies in how they handle some characters (eg. turkish Upper case I with dot on top - \u0130) * This function is used in places where we want to make file name as a key on these systems @@ -1806,11 +2005,13 @@ export function toFileNameLowerCase(x: string) { x; } +/** @internal */ /** Throws an error because a function is not implemented. */ export function notImplemented(): never { throw new Error("Not implemented"); } +/** @internal */ export function memoize(callback: () => T): () => T { let value: T; return () => { @@ -1822,6 +2023,7 @@ export function memoize(callback: () => T): () => T { }; } +/** @internal */ /** A version of `memoize` that supports a single primitive argument */ export function memoizeOne(callback: (arg: A) => T): (arg: A) => T { const map = new ts.Map(); @@ -1836,6 +2038,7 @@ export function memoizeOne(c }; } +/** @internal */ /** * High-order function, composes functions. Note that functions are composed inside-out; * for example, `compose(a, b)` is the equivalent of `x => b(a(x))`. @@ -1843,6 +2046,7 @@ export function memoizeOne(c * @param args The functions to compose. */ export function compose(...args: ((t: T) => T)[]): (t: T) => T; +/** @internal */ export function compose(a: (t: T) => T, b: (t: T) => T, c: (t: T) => T, d: (t: T) => T, e: (t: T) => T): (t: T) => T { if (!!e) { const args: ((t: T) => T)[] = []; @@ -1869,6 +2073,7 @@ export function compose(a: (t: T) => T, b: (t: T) => T, c: (t: T) => T, d: (t } } +/** @internal */ export const enum AssertionLevel { None = 0, Normal = 1, @@ -1876,17 +2081,21 @@ export const enum AssertionLevel { VeryAggressive = 3, } +/** @internal */ /** * Safer version of `Function` which should not be called. * Every function should be assignable to this, but this should not be assignable to every function. */ export type AnyFunction = (...args: never[]) => void; +/** @internal */ export type AnyConstructor = new (...args: unknown[]) => unknown; +/** @internal */ export function equateValues(a: T, b: T) { return a === b; } +/** @internal */ /** * Compare the equality of two strings using a case-sensitive ordinal comparison. * @@ -1902,6 +2111,7 @@ export function equateStringsCaseInsensitive(a: string, b: string) { && a.toUpperCase() === b.toUpperCase(); } +/** @internal */ /** * Compare the equality of two strings using a case-sensitive ordinal comparison. * @@ -1922,6 +2132,7 @@ function compareComparableValues(a: string | number | undefined, b: string | num ts.Comparison.GreaterThan; } +/** @internal */ /** * Compare two numeric values for their order relative to each other. * To compare strings, use any of the `compareStrings` functions. @@ -1930,6 +2141,7 @@ export function compareValues(a: number | undefined, b: number | undefined): ts. return compareComparableValues(a, b); } +/** @internal */ /** * Compare two TextSpans, first by `start`, then by `length`. */ @@ -1937,12 +2149,16 @@ export function compareTextSpans(a: Partial | undefined, b: Partial return compareValues(a?.start, b?.start) || compareValues(a?.length, b?.length); } +/** @internal */ export function min(items: readonly [T, ...T[]], compare: ts.Comparer): T; +/** @internal */ export function min(items: readonly T[], compare: ts.Comparer): T | undefined; +/** @internal */ export function min(items: readonly T[], compare: ts.Comparer): T | undefined { return reduceLeft(items, (x, y) => compare(x, y) === ts.Comparison.LessThan ? x : y); } +/** @internal */ /** * Compare two strings using a case-insensitive ordinal comparison. * @@ -1964,6 +2180,7 @@ export function compareStringsCaseInsensitive(a: string, b: string) { return a < b ? ts.Comparison.LessThan : a > b ? ts.Comparison.GreaterThan : ts.Comparison.EqualTo; } +/** @internal */ /** * Compare two strings using a case-sensitive ordinal comparison. * @@ -1978,6 +2195,7 @@ export function compareStringsCaseSensitive(a: string | undefined, b: string | u return compareComparableValues(a, b); } +/** @internal */ export function getStringComparer(ignoreCase?: boolean) { return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive; } @@ -2073,10 +2291,12 @@ const createUIStringComparer = (() => { let uiComparerCaseSensitive: ts.Comparer | undefined; let uiLocale: string | undefined; +/** @internal */ export function getUILocale() { return uiLocale; } +/** @internal */ export function setUILocale(value: string | undefined) { if (uiLocale !== value) { uiLocale = value; @@ -2084,6 +2304,7 @@ export function setUILocale(value: string | undefined) { } } +/** @internal */ /** * Compare two strings in a using the case-sensitive sort behavior of the UI locale. * @@ -2099,6 +2320,7 @@ export function compareStringsCaseSensitiveUI(a: string, b: string) { return comparer(a, b); } +/** @internal */ export function compareProperties(a: T | undefined, b: T | undefined, key: K, comparer: ts.Comparer): ts.Comparison { return a === b ? ts.Comparison.EqualTo : a === undefined ? ts.Comparison.LessThan : @@ -2106,11 +2328,13 @@ export function compareProperties(a: T | un comparer(a[key], b[key]); } +/** @internal */ /** True is greater than false. */ export function compareBooleans(a: boolean, b: boolean): ts.Comparison { return compareValues(a ? 1 : 0, b ? 1 : 0); } +/** @internal */ /** * Given a name and a list of names that are *not* equal to the name, return a spelling suggestion if there is one that is close enough. * Names less than length 3 only check for case-insensitive equality. @@ -2200,23 +2424,28 @@ function levenshteinWithMax(s1: string, s2: string, max: number): number | undef return res > max ? undefined : res; } +/** @internal */ export function endsWith(str: string, suffix: string): boolean { const expectedPos = str.length - suffix.length; return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos; } +/** @internal */ export function removeSuffix(str: string, suffix: string): string { return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str; } +/** @internal */ export function tryRemoveSuffix(str: string, suffix: string): string | undefined { return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined; } +/** @internal */ export function stringContains(str: string, substring: string): boolean { return str.indexOf(substring) !== -1; } +/** @internal */ /** * Takes a string like "jquery-min.4.2.3" and returns "jquery" */ @@ -2268,6 +2497,7 @@ export function removeMinAndVersionNumbers(fileName: string) { return end === fileName.length ? fileName : fileName.slice(0, end); } +/** @internal */ /** Remove an item from an array, moving everything to its right one space left. */ export function orderedRemoveItem(array: T[], item: T): boolean { for (let i = 0; i < array.length; i++) { @@ -2279,6 +2509,7 @@ export function orderedRemoveItem(array: T[], item: T): boolean { return false; } +/** @internal */ /** Remove an item by index from an array, moving everything to its right one space left. */ export function orderedRemoveItemAt(array: T[], index: number): void { // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. @@ -2288,12 +2519,14 @@ export function orderedRemoveItemAt(array: T[], index: number): void { array.pop(); } +/** @internal */ export function unorderedRemoveItemAt(array: T[], index: number): void { // Fill in the "hole" left at `index`. array[index] = array[array.length - 1]; array.pop(); } +/** @internal */ /** Remove the *first* occurrence of `item` from the array. */ export function unorderedRemoveItem(array: T[], item: T) { return unorderedRemoveFirstItemWhere(array, element => element === item); @@ -2310,21 +2543,26 @@ function unorderedRemoveFirstItemWhere(array: T[], predicate: (element: T) => return false; } +/** @internal */ export type GetCanonicalFileName = (fileName: string) => string; +/** @internal */ export function createGetCanonicalFileName(useCaseSensitiveFileNames: boolean): GetCanonicalFileName { return useCaseSensitiveFileNames ? identity : toFileNameLowerCase; } +/** @internal */ /** Represents a "prefix*suffix" pattern. */ export interface Pattern { prefix: string; suffix: string; } +/** @internal */ export function patternText({ prefix, suffix }: Pattern): string { return `${prefix}*${suffix}`; } +/** @internal */ /** * Given that candidate matches pattern, returns the text matching the '*'. * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" @@ -2334,6 +2572,7 @@ export function matchedText(pattern: Pattern, candidate: string): string { return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length); } +/** @internal */ /** Return the object corresponding to the best pattern to match `candidate`. */ export function findBestPatternMatch(values: readonly T[], getPattern: (value: T) => Pattern, candidate: string): T | undefined { let matchedValue: T | undefined; @@ -2351,31 +2590,40 @@ export function findBestPatternMatch(values: readonly T[], getPattern: (value return matchedValue; } +/** @internal */ export function startsWith(str: string, prefix: string): boolean { return str.lastIndexOf(prefix, 0) === 0; } +/** @internal */ export function removePrefix(str: string, prefix: string): string { return startsWith(str, prefix) ? str.substr(prefix.length) : str; } +/** @internal */ export function tryRemovePrefix(str: string, prefix: string, getCanonicalFileName: GetCanonicalFileName = identity): string | undefined { return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined; } +/** @internal */ export function isPatternMatch({ prefix, suffix }: Pattern, candidate: string) { return candidate.length >= prefix.length + suffix.length && startsWith(candidate, prefix) && endsWith(candidate, suffix); } +/** @internal */ export function and(f: (arg: T) => boolean, g: (arg: T) => boolean) { return (arg: T) => f(arg) && g(arg); } +/** @internal */ export function or(f1: (p1: P) => p1 is R1, f2: (p2: P) => p2 is R2): (p: P) => p is R1 | R2; +/** @internal */ export function or(f1: (p1: P) => p1 is R1, f2: (p2: P) => p2 is R2, f3: (p3: P) => p3 is R3): (p: P) => p is R1 | R2 | R3; +/** @internal */ export function or(...fs: ((...args: T) => U)[]): (...args: T) => U; +/** @internal */ export function or(...fs: ((...args: T) => U)[]): (...args: T) => U { return (...args) => { let lastResult: U; @@ -2389,16 +2637,20 @@ export function or(...fs: ((...args: T) => U)[]): (...ar }; } +/** @internal */ export function not(fn: (...args: T) => boolean): (...args: T) => boolean { return (...args) => !fn(...args); } +/** @internal */ export function assertType(_: T): void { } +/** @internal */ export function singleElementArray(t: T | undefined): T[] | undefined { return t === undefined ? undefined : [t]; } +/** @internal */ export function enumerateInsertsAndDeletes(newItems: readonly T[], oldItems: readonly U[], comparer: (a: T, b: U) => ts.Comparison, inserted: (newItem: T) => void, deleted: (oldItem: U) => void, unchanged?: (oldItem: U, newItem: T) => void) { unchanged = unchanged || noop; let newIndex = 0; @@ -2437,6 +2689,7 @@ export function enumerateInsertsAndDeletes(newItems: readonly T[], oldItem return hasChanges; } +/** @internal */ export function fill(length: number, cb: (index: number) => T): T[] { const result = Array(length); for (let i = 0; i < length; i++) { @@ -2445,6 +2698,7 @@ export function fill(length: number, cb: (index: number) => T): T[] { return result; } +/** @internal */ export function cartesianProduct(arrays: readonly T[][]) { const result: T[][] = []; cartesianProductWorker(arrays, result, /*outer*/ undefined, 0); @@ -2471,6 +2725,7 @@ function cartesianProductWorker(arrays: readonly (readonly T[])[], result: (r } +/** @internal */ /** * Returns string left-padded with spaces or zeros until it reaches the given length. * @@ -2482,6 +2737,7 @@ export function padLeft(s: string, length: number, padString: " " | "0" = " ") { return length <= s.length ? s : padString.repeat(length - s.length) + s; } +/** @internal */ /** * Returns string right-padded with spaces until it reaches the given length. * @@ -2493,7 +2749,9 @@ export function padRight(s: string, length: number, padString: " " = " ") { return length <= s.length ? s : s + padString.repeat(length - s.length); } +/** @internal */ export function takeWhile(array: readonly T[], predicate: (element: T) => element is U): U[]; +/** @internal */ export function takeWhile(array: readonly T[], predicate: (element: T) => boolean): T[] { const len = array.length; let index = 0; @@ -2503,16 +2761,19 @@ export function takeWhile(array: readonly T[], predicate: (element: T) => boo return array.slice(0, index); } +/** @internal */ /** * Removes the leading and trailing white space and line terminator characters from a string. */ export const trimString = !!String.prototype.trim ? ((s: string) => s.trim()) : (s: string) => trimStringEnd(trimStringStart(s)); +/** @internal */ /** * Returns a copy with trailing whitespace removed. */ export const trimStringEnd = !!String.prototype.trimEnd ? ((s: string) => s.trimEnd()) : trimEndImpl; +/** @internal */ /** * Returns a copy with leading whitespace removed. */ @@ -2532,4 +2793,3 @@ function trimEndImpl(s: string) { } return s.slice(0, end + 1); } -} diff --git a/src/compiler/corePublic.ts b/src/compiler/corePublic.ts index 74de07fd5d174..0727cf392e1c9 100644 --- a/src/compiler/corePublic.ts +++ b/src/compiler/corePublic.ts @@ -1,4 +1,3 @@ -namespace ts { // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values. // If changing the text in this section, be sure to test `configurePrerelease` too. export const versionMajorMinor = "5.0"; @@ -154,4 +153,3 @@ namespace NativeCollections { export const Map = NativeCollections.tryGetNativeMap(); /* @internal */ export const Set = NativeCollections.tryGetNativeSet(); -} diff --git a/src/compiler/debug.ts b/src/compiler/debug.ts index 73ed63caed9b3..5c6a44d83a95a 100644 --- a/src/compiler/debug.ts +++ b/src/compiler/debug.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export enum LogLevel { Off, Error, @@ -8,10 +9,12 @@ export enum LogLevel { Verbose } +/** @internal */ export interface LoggingHost { log(level: LogLevel, s: string): void; } +/** @internal */ export interface DeprecationOptions { message?: string; error?: boolean; @@ -22,6 +25,7 @@ export interface DeprecationOptions { name?: string; } +/** @internal */ export namespace Debug { let typeScriptVersion: ts.Version | undefined; @@ -814,4 +818,3 @@ m2: ${(this.mapper2 as unknown as DebugTypeMapper).__debugToString().split("\n") return mapper; } } -} diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 1be589d48f571..b704e6ebb3c8b 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + const brackets = createBracketsMap(); /*@internal*/ @@ -6050,4 +6051,3 @@ function getEmitListItem ts.setEmitFlags(factory.createTrue(), ts.EmitFlags.Immutable)); @@ -412,6 +414,7 @@ export function compareEmitHelpers(x: ts.EmitHelper, y: ts.EmitHelper) { return ts.compareValues(x.priority, y.priority); } +/** @internal */ /** * @param input Template string input strings * @param args Names which need to be made file-level unique @@ -430,6 +433,7 @@ export function helperString(input: TemplateStringsArray, ...args: string[]) { // TypeScript Helpers +/** @internal */ export const decorateHelper: ts.UnscopedEmitHelper = { name: "typescript:decorate", importName: "__decorate", @@ -444,6 +448,7 @@ export const decorateHelper: ts.UnscopedEmitHelper = { };` }; +/** @internal */ export const metadataHelper: ts.UnscopedEmitHelper = { name: "typescript:metadata", importName: "__metadata", @@ -455,6 +460,7 @@ export const metadataHelper: ts.UnscopedEmitHelper = { };` }; +/** @internal */ export const paramHelper: ts.UnscopedEmitHelper = { name: "typescript:param", importName: "__param", @@ -468,6 +474,7 @@ export const paramHelper: ts.UnscopedEmitHelper = { // ES2018 Helpers +/** @internal */ export const assignHelper: ts.UnscopedEmitHelper = { name: "typescript:assign", importName: "__assign", @@ -487,6 +494,7 @@ export const assignHelper: ts.UnscopedEmitHelper = { };` }; +/** @internal */ export const awaitHelper: ts.UnscopedEmitHelper = { name: "typescript:await", importName: "__await", @@ -495,6 +503,7 @@ export const awaitHelper: ts.UnscopedEmitHelper = { var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }` }; +/** @internal */ export const asyncGeneratorHelper: ts.UnscopedEmitHelper = { name: "typescript:asyncGenerator", importName: "__asyncGenerator", @@ -514,6 +523,7 @@ export const asyncGeneratorHelper: ts.UnscopedEmitHelper = { };` }; +/** @internal */ export const asyncDelegator: ts.UnscopedEmitHelper = { name: "typescript:asyncDelegator", importName: "__asyncDelegator", @@ -527,6 +537,7 @@ export const asyncDelegator: ts.UnscopedEmitHelper = { };` }; +/** @internal */ export const asyncValues: ts.UnscopedEmitHelper = { name: "typescript:asyncValues", importName: "__asyncValues", @@ -543,6 +554,7 @@ export const asyncValues: ts.UnscopedEmitHelper = { // ES2018 Destructuring Helpers +/** @internal */ export const restHelper: ts.UnscopedEmitHelper = { name: "typescript:rest", importName: "__rest", @@ -563,6 +575,7 @@ export const restHelper: ts.UnscopedEmitHelper = { // ES2017 Helpers +/** @internal */ export const awaiterHelper: ts.UnscopedEmitHelper = { name: "typescript:awaiter", importName: "__awaiter", @@ -582,6 +595,7 @@ export const awaiterHelper: ts.UnscopedEmitHelper = { // ES2015 Helpers +/** @internal */ export const extendsHelper: ts.UnscopedEmitHelper = { name: "typescript:extends", importName: "__extends", @@ -606,6 +620,7 @@ export const extendsHelper: ts.UnscopedEmitHelper = { })();` }; +/** @internal */ export const templateObjectHelper: ts.UnscopedEmitHelper = { name: "typescript:makeTemplateObject", importName: "__makeTemplateObject", @@ -618,6 +633,7 @@ export const templateObjectHelper: ts.UnscopedEmitHelper = { };` }; +/** @internal */ export const readHelper: ts.UnscopedEmitHelper = { name: "typescript:read", importName: "__read", @@ -641,6 +657,7 @@ export const readHelper: ts.UnscopedEmitHelper = { };` }; +/** @internal */ export const spreadArrayHelper: ts.UnscopedEmitHelper = { name: "typescript:spreadArray", importName: "__spreadArray", @@ -659,6 +676,7 @@ export const spreadArrayHelper: ts.UnscopedEmitHelper = { // ES2015 Destructuring Helpers +/** @internal */ export const valuesHelper: ts.UnscopedEmitHelper = { name: "typescript:values", importName: "__values", @@ -740,6 +758,7 @@ export const valuesHelper: ts.UnscopedEmitHelper = { // entering a finally block. // // For examples of how these are used, see the comments in ./transformers/generators.ts +/** @internal */ export const generatorHelper: ts.UnscopedEmitHelper = { name: "typescript:generator", importName: "__generator", @@ -777,6 +796,7 @@ export const generatorHelper: ts.UnscopedEmitHelper = { // ES Module Helpers +/** @internal */ export const createBindingHelper: ts.UnscopedEmitHelper = { name: "typescript:commonjscreatebinding", importName: "__createBinding", @@ -796,6 +816,7 @@ export const createBindingHelper: ts.UnscopedEmitHelper = { }));` }; +/** @internal */ export const setModuleDefaultHelper: ts.UnscopedEmitHelper = { name: "typescript:commonjscreatevalue", importName: "__setModuleDefault", @@ -810,6 +831,7 @@ export const setModuleDefaultHelper: ts.UnscopedEmitHelper = { }; // emit helper for `import * as Name from "foo"` +/** @internal */ export const importStarHelper: ts.UnscopedEmitHelper = { name: "typescript:commonjsimportstar", importName: "__importStar", @@ -827,6 +849,7 @@ export const importStarHelper: ts.UnscopedEmitHelper = { }; // emit helper for `import Name from "foo"` +/** @internal */ export const importDefaultHelper: ts.UnscopedEmitHelper = { name: "typescript:commonjsimportdefault", importName: "__importDefault", @@ -837,6 +860,7 @@ export const importDefaultHelper: ts.UnscopedEmitHelper = { };` }; +/** @internal */ export const exportStarHelper: ts.UnscopedEmitHelper = { name: "typescript:export-star", importName: "__exportStar", @@ -849,6 +873,7 @@ export const exportStarHelper: ts.UnscopedEmitHelper = { };` }; +/** @internal */ /** * Parameters: * @param receiver — The object from which the private member will be read. @@ -909,6 +934,7 @@ export const classPrivateFieldGetHelper: ts.UnscopedEmitHelper = { };` }; +/** @internal */ /** * Parameters: * @param receiver — The object on which the private member will be set. @@ -973,6 +999,7 @@ export const classPrivateFieldSetHelper: ts.UnscopedEmitHelper = { };` }; +/** @internal */ /** * Parameters: * @param state — One of the following: @@ -998,6 +1025,7 @@ export const classPrivateFieldInHelper: ts.UnscopedEmitHelper = { let allUnscopedEmitHelpers: ts.ReadonlyESMap | undefined; +/** @internal */ export function getAllUnscopedEmitHelpers() { return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([ decorateHelper, @@ -1027,6 +1055,7 @@ export function getAllUnscopedEmitHelpers() { ], helper => helper.name)); } +/** @internal */ export const asyncSuperHelper: ts.EmitHelper = { name: "typescript:async-super", scoped: true, @@ -1034,6 +1063,7 @@ export const asyncSuperHelper: ts.EmitHelper = { const ${"_superIndex"} = name => super[name];` }; +/** @internal */ export const advancedAsyncSuperHelper: ts.EmitHelper = { name: "typescript:advanced-async-super", scoped: true, @@ -1044,10 +1074,10 @@ export const advancedAsyncSuperHelper: ts.EmitHelper = { })(name => super[name], (name, value) => super[name] = value);` }; +/** @internal */ export function isCallToHelper(firstSegment: ts.Expression, helperName: ts.__String): boolean { return ts.isCallExpression(firstSegment) && ts.isIdentifier(firstSegment.expression) && (ts.getEmitFlags(firstSegment.expression) & ts.EmitFlags.HelperName) !== 0 && firstSegment.expression.escapedText === helperName; } -} diff --git a/src/compiler/factory/emitNode.ts b/src/compiler/factory/emitNode.ts index fe2329743cde1..2d34aa065be8f 100644 --- a/src/compiler/factory/emitNode.ts +++ b/src/compiler/factory/emitNode.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; + /** * Associates a node with the current transformation, initializing * various transient transformation properties. @@ -291,4 +292,3 @@ export function setTypeNode(node: T, type: ts.TypeNode): T { export function getTypeNode(node: T): ts.TypeNode | undefined { return node.emitNode?.typeNode; } -} diff --git a/src/compiler/factory/nodeConverters.ts b/src/compiler/factory/nodeConverters.ts index 2a7aef4a63364..3fa27aedbbd01 100644 --- a/src/compiler/factory/nodeConverters.ts +++ b/src/compiler/factory/nodeConverters.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export function createNodeConverters(factory: ts.NodeFactory): ts.NodeConverters { return { convertToFunctionBlock, @@ -124,6 +125,7 @@ export function createNodeConverters(factory: ts.NodeFactory): ts.NodeConverters } } +/** @internal */ export const nullNodeConverters: ts.NodeConverters = { convertToFunctionBlock: ts.notImplemented, convertToFunctionExpression: ts.notImplemented, @@ -133,5 +135,4 @@ export const nullNodeConverters: ts.NodeConverters = { convertToObjectAssignmentPattern: ts.notImplemented, convertToArrayAssignmentPattern: ts.notImplemented, convertToAssignmentElementTarget: ts.notImplemented, -}; -} \ No newline at end of file +}; \ No newline at end of file diff --git a/src/compiler/factory/nodeFactory.ts b/src/compiler/factory/nodeFactory.ts index 6c8fa8924c017..2350c5f68abbc 100644 --- a/src/compiler/factory/nodeFactory.ts +++ b/src/compiler/factory/nodeFactory.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; + let nextAutoGenerateId = 0; /* @internal */ @@ -6936,4 +6937,3 @@ function mergeTokenSourceMapRanges(sourceRanges: (ts.TextRange | undefined)[], d } return destRanges; } -} diff --git a/src/compiler/factory/nodeTests.ts b/src/compiler/factory/nodeTests.ts index 0db4e6e754df4..f13d8dd0b2790 100644 --- a/src/compiler/factory/nodeTests.ts +++ b/src/compiler/factory/nodeTests.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; + // Literals export function isNumericLiteral(node: ts.Node): node is ts.NumericLiteral { @@ -957,4 +958,3 @@ export function isJSDocImplementsTag(node: ts.Node): node is ts.JSDocImplementsT export function isSyntaxList(n: ts.Node): n is ts.SyntaxList { return n.kind === ts.SyntaxKind.SyntaxList; } -} diff --git a/src/compiler/factory/parenthesizerRules.ts b/src/compiler/factory/parenthesizerRules.ts index c256905d562f2..d261780fb571e 100644 --- a/src/compiler/factory/parenthesizerRules.ts +++ b/src/compiler/factory/parenthesizerRules.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export function createParenthesizerRules(factory: ts.NodeFactory): ts.ParenthesizerRules { interface BinaryPlusExpression extends ts.BinaryExpression { cachedLiteralKind: ts.SyntaxKind; @@ -602,6 +603,7 @@ export function createParenthesizerRules(factory: ts.NodeFactory): ts.Parenthesi } } +/** @internal */ export const nullParenthesizerRules: ts.ParenthesizerRules = { getParenthesizeLeftSideOfBinaryForOperator: _ => ts.identity, getParenthesizeRightSideOfBinaryForOperator: _ => ts.identity, @@ -634,4 +636,3 @@ export const nullParenthesizerRules: ts.ParenthesizerRules = { parenthesizeTypeArguments: nodes => nodes && ts.cast(nodes, ts.isNodeArray), parenthesizeLeadingTypeArgument: ts.identity, }; -} diff --git a/src/compiler/factory/utilities.ts b/src/compiler/factory/utilities.ts index fb0a2748e2dd5..18566ea39b608 100644 --- a/src/compiler/factory/utilities.ts +++ b/src/compiler/factory/utilities.ts @@ -1,12 +1,13 @@ -/* @internal */ -namespace ts { +import * as ts from "../_namespaces/ts"; // Compound nodes +/** @internal */ export function createEmptyExports(factory: ts.NodeFactory) { return factory.createExportDeclaration(/*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined); } +/** @internal */ export function createMemberAccessForPropertyName(factory: ts.NodeFactory, target: ts.Expression, memberName: ts.PropertyName, location?: ts.TextRange): ts.MemberExpression { if (ts.isComputedPropertyName(memberName)) { return ts.setTextRange(factory.createElementAccessExpression(target, memberName.expression), location); @@ -46,6 +47,7 @@ function createJsxFactoryExpressionFromEntityName(factory: ts.NodeFactory, jsxFa } } +/** @internal */ export function createJsxFactoryExpression(factory: ts.NodeFactory, jsxFactoryEntity: ts.EntityName | undefined, reactNamespace: string, parent: ts.JsxOpeningLikeElement | ts.JsxOpeningFragment): ts.Expression { return jsxFactoryEntity ? createJsxFactoryExpressionFromEntityName(factory, jsxFactoryEntity, parent) : @@ -64,6 +66,7 @@ function createJsxFragmentFactoryExpression(factory: ts.NodeFactory, jsxFragment ); } +/** @internal */ export function createExpressionForJsxElement(factory: ts.NodeFactory, callee: ts.Expression, tagName: ts.Expression, props: ts.Expression | undefined, children: readonly ts.Expression[] | undefined, location: ts.TextRange): ts.LeftHandSideExpression { const argumentsList = [tagName]; if (props) { @@ -96,6 +99,7 @@ export function createExpressionForJsxElement(factory: ts.NodeFactory, callee: t ); } +/** @internal */ export function createExpressionForJsxFragment(factory: ts.NodeFactory, jsxFactoryEntity: ts.EntityName | undefined, jsxFragmentFactoryEntity: ts.EntityName | undefined, reactNamespace: string, children: readonly ts.Expression[], parentElement: ts.JsxOpeningFragment, location: ts.TextRange): ts.LeftHandSideExpression { const tagName = createJsxFragmentFactoryExpression(factory, jsxFragmentFactoryEntity, reactNamespace, parentElement); const argumentsList = [tagName, factory.createNull()]; @@ -124,6 +128,7 @@ export function createExpressionForJsxFragment(factory: ts.NodeFactory, jsxFacto // Utilities +/** @internal */ export function createForOfBindingStatement(factory: ts.NodeFactory, node: ts.ForInitializer, boundValue: ts.Expression): ts.Statement { if (ts.isVariableDeclarationList(node)) { const firstDeclaration = ts.first(node.declarations); @@ -148,6 +153,7 @@ export function createForOfBindingStatement(factory: ts.NodeFactory, node: ts.Fo } } +/** @internal */ export function insertLeadingStatement(factory: ts.NodeFactory, dest: ts.Statement, source: ts.Statement) { if (ts.isBlock(dest)) { return factory.updateBlock(dest, ts.setTextRange(factory.createNodeArray([source, ...dest.statements]), dest.statements)); @@ -157,6 +163,7 @@ export function insertLeadingStatement(factory: ts.NodeFactory, dest: ts.Stateme } } +/** @internal */ export function createExpressionFromEntityName(factory: ts.NodeFactory, node: ts.EntityName | ts.Expression): ts.Expression { if (ts.isQualifiedName(node)) { const left = createExpressionFromEntityName(factory, node.left); @@ -170,6 +177,7 @@ export function createExpressionFromEntityName(factory: ts.NodeFactory, node: ts } } +/** @internal */ export function createExpressionForPropertyName(factory: ts.NodeFactory, memberName: Exclude): ts.Expression { if (ts.isIdentifier(memberName)) { return factory.createStringLiteralFromNode(memberName); @@ -286,6 +294,7 @@ function createExpressionForMethodDeclaration(factory: ts.NodeFactory, method: t ); } +/** @internal */ export function createExpressionForObjectLiteralElementLike(factory: ts.NodeFactory, node: ts.ObjectLiteralExpression, property: ts.ObjectLiteralElementLike, receiver: ts.Expression): ts.Expression | undefined { if (property.name && ts.isPrivateIdentifier(property.name)) { ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals."); @@ -303,6 +312,7 @@ export function createExpressionForObjectLiteralElementLike(factory: ts.NodeFact } } +/** @internal */ /** * Expand the read and increment/decrement operations a pre- or post-increment or pre- or post-decrement expression. * @@ -364,6 +374,7 @@ export function expandPreOrPostfixIncrementOrDecrementExpression(factory: ts.Nod return expression; } +/** @internal */ /** * Gets whether an identifier should only be referred to by its internal name. */ @@ -371,6 +382,7 @@ export function isInternalName(node: ts.Identifier) { return (ts.getEmitFlags(node) & ts.EmitFlags.InternalName) !== 0; } +/** @internal */ /** * Gets whether an identifier should only be referred to by its local name. */ @@ -378,6 +390,7 @@ export function isLocalName(node: ts.Identifier) { return (ts.getEmitFlags(node) & ts.EmitFlags.LocalName) !== 0; } +/** @internal */ /** * Gets whether an identifier should only be referred to by its export representation if the * name points to an exported symbol. @@ -390,6 +403,7 @@ function isUseStrictPrologue(node: ts.ExpressionStatement): boolean { return ts.isStringLiteral(node.expression) && node.expression.text === "use strict"; } +/** @internal */ export function findUseStrictPrologue(statements: readonly ts.Statement[]): ts.Statement | undefined { for (const statement of statements) { if (ts.isPrologueDirective(statement)) { @@ -404,6 +418,7 @@ export function findUseStrictPrologue(statements: readonly ts.Statement[]): ts.S return undefined; } +/** @internal */ export function startsWithUseStrict(statements: readonly ts.Statement[]) { const firstStatement = ts.firstOrUndefined(statements); return firstStatement !== undefined @@ -411,23 +426,27 @@ export function startsWithUseStrict(statements: readonly ts.Statement[]) { && isUseStrictPrologue(firstStatement); } +/** @internal */ export function isCommaSequence(node: ts.Expression): node is ts.BinaryExpression & {operatorToken: ts.Token} | ts.CommaListExpression { return node.kind === ts.SyntaxKind.BinaryExpression && (node as ts.BinaryExpression).operatorToken.kind === ts.SyntaxKind.CommaToken || node.kind === ts.SyntaxKind.CommaListExpression; } +/** @internal */ export function isJSDocTypeAssertion(node: ts.Node): node is ts.JSDocTypeAssertion { return ts.isParenthesizedExpression(node) && ts.isInJSFile(node) && !!ts.getJSDocTypeTag(node); } +/** @internal */ export function getJSDocTypeAssertionType(node: ts.JSDocTypeAssertion) { const type = ts.getJSDocType(node); ts.Debug.assertIsDefined(type); return type; } +/** @internal */ export function isOuterExpression(node: ts.Node, kinds = ts.OuterExpressionKinds.All): node is ts.OuterExpression { switch (node.kind) { case ts.SyntaxKind.ParenthesizedExpression: @@ -447,8 +466,11 @@ export function isOuterExpression(node: ts.Node, kinds = ts.OuterExpressionKinds return false; } +/** @internal */ export function skipOuterExpressions(node: ts.Expression, kinds?: ts.OuterExpressionKinds): ts.Expression; +/** @internal */ export function skipOuterExpressions(node: ts.Node, kinds?: ts.OuterExpressionKinds): ts.Node; +/** @internal */ export function skipOuterExpressions(node: ts.Node, kinds = ts.OuterExpressionKinds.All) { while (isOuterExpression(node, kinds)) { node = node.expression; @@ -456,28 +478,35 @@ export function skipOuterExpressions(node: ts.Node, kinds = ts.OuterExpressionKi return node; } +/** @internal */ export function skipAssertions(node: ts.Expression): ts.Expression; +/** @internal */ export function skipAssertions(node: ts.Node): ts.Node; +/** @internal */ export function skipAssertions(node: ts.Node): ts.Node { return skipOuterExpressions(node, ts.OuterExpressionKinds.Assertions); } +/** @internal */ export function startOnNewLine(node: T): T { return ts.setStartsOnNewLine(node, /*newLine*/ true); } +/** @internal */ export function getExternalHelpersModuleName(node: ts.SourceFile) { const parseNode = ts.getOriginalNode(node, ts.isSourceFile); const emitNode = parseNode && parseNode.emitNode; return emitNode && emitNode.externalHelpersModuleName; } +/** @internal */ export function hasRecordedExternalHelpers(sourceFile: ts.SourceFile) { const parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile); const emitNode = parseNode && parseNode.emitNode; return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers); } +/** @internal */ export function createExternalHelpersImportDeclarationIfNeeded(nodeFactory: ts.NodeFactory, helperFactory: ts.EmitHelperFactory, sourceFile: ts.SourceFile, compilerOptions: ts.CompilerOptions, hasExportStarsToExportValues?: boolean, hasImportStar?: boolean, hasImportDefault?: boolean) { if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(sourceFile, compilerOptions)) { let namedBindings: ts.NamedImportBindings | undefined; @@ -531,6 +560,7 @@ export function createExternalHelpersImportDeclarationIfNeeded(nodeFactory: ts.N } } +/** @internal */ export function getOrCreateExternalHelpersModuleNameIfNeeded(factory: ts.NodeFactory, node: ts.SourceFile, compilerOptions: ts.CompilerOptions, hasExportStarsToExportValues?: boolean, hasImportStarOrImportDefault?: boolean) { if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) { const externalHelpersModuleName = getExternalHelpersModuleName(node); @@ -562,6 +592,7 @@ export function getOrCreateExternalHelpersModuleNameIfNeeded(factory: ts.NodeFac } } +/** @internal */ /** * Get the name of that target module from an import or export declaration */ @@ -580,6 +611,7 @@ export function getLocalNameForExternalImport(factory: ts.NodeFactory, node: ts. return undefined; } +/** @internal */ /** * Get the name of a target module from an import/export declaration as should be written in the emitted output. * The emitted output name can be different from the input if: @@ -608,6 +640,7 @@ function tryRenameExternalModule(factory: ts.NodeFactory, moduleName: ts.Literal return rename ? factory.createStringLiteral(rename) : undefined; } +/** @internal */ /** * Get the name of a module as should be written in the emitted output. * The emitted output name can be different from the input if: @@ -632,6 +665,7 @@ function tryGetModuleNameFromDeclaration(declaration: ts.ImportEqualsDeclaration return tryGetModuleNameFromFile(factory, resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); } +/** @internal */ /** * Gets the initializer of an BindingOrAssignmentElement. */ @@ -675,6 +709,7 @@ export function getInitializerOfBindingOrAssignmentElement(bindingElement: ts.Bi } } +/** @internal */ /** * Gets the name of an BindingOrAssignmentElement. */ @@ -750,6 +785,7 @@ export function getTargetOfBindingOrAssignmentElement(bindingElement: ts.Binding return bindingElement; } +/** @internal */ /** * Determines whether an BindingOrAssignmentElement is a rest element. */ @@ -769,6 +805,7 @@ export function getRestIndicatorOfBindingOrAssignmentElement(bindingElement: ts. return undefined; } +/** @internal */ /** * Gets the property name of a BindingOrAssignmentElement */ @@ -778,6 +815,7 @@ export function getPropertyNameOfBindingOrAssignmentElement(bindingElement: ts.B return propertyName; } +/** @internal */ export function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement: ts.BindingOrAssignmentElement): Exclude | undefined { switch (bindingElement.kind) { case ts.SyntaxKind.BindingElement: @@ -834,6 +872,7 @@ function isStringOrNumericLiteral(node: ts.Node): node is ts.StringLiteral | ts. || kind === ts.SyntaxKind.NumericLiteral; } +/** @internal */ /** * Gets the elements of a BindingOrAssignmentPattern */ @@ -865,12 +904,14 @@ export function getJSDocTypeAliasName(fullName: ts.JSDocNamespaceBody | undefine } } +/** @internal */ export function canHaveIllegalType(node: ts.Node): node is ts.HasIllegalType { const kind = node.kind; return kind === ts.SyntaxKind.Constructor || kind === ts.SyntaxKind.SetAccessor; } +/** @internal */ export function canHaveIllegalTypeParameters(node: ts.Node): node is ts.HasIllegalTypeParameters { const kind = node.kind; return kind === ts.SyntaxKind.Constructor @@ -878,6 +919,7 @@ export function canHaveIllegalTypeParameters(node: ts.Node): node is ts.HasIlleg || kind === ts.SyntaxKind.SetAccessor; } +/** @internal */ export function canHaveIllegalDecorators(node: ts.Node): node is ts.HasIllegalDecorators { const kind = node.kind; return kind === ts.SyntaxKind.PropertyAssignment @@ -899,6 +941,7 @@ export function canHaveIllegalDecorators(node: ts.Node): node is ts.HasIllegalDe || kind === ts.SyntaxKind.ExportAssignment; } +/** @internal */ export function canHaveIllegalModifiers(node: ts.Node): node is ts.HasIllegalModifiers { const kind = node.kind; return kind === ts.SyntaxKind.ClassStaticBlockDeclaration @@ -909,13 +952,20 @@ export function canHaveIllegalModifiers(node: ts.Node): node is ts.HasIllegalMod || kind === ts.SyntaxKind.NamespaceExportDeclaration; } +/** @internal */ export const isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration) as (node: ts.Node) => node is ts.TypeNode | ts.TypeParameterDeclaration; +/** @internal */ export const isQuestionOrExclamationToken = ts.or(ts.isQuestionToken, ts.isExclamationToken) as (node: ts.Node) => node is ts.QuestionToken | ts.ExclamationToken; +/** @internal */ export const isIdentifierOrThisTypeNode = ts.or(ts.isIdentifier, ts.isThisTypeNode) as (node: ts.Node) => node is ts.Identifier | ts.ThisTypeNode; +/** @internal */ export const isReadonlyKeywordOrPlusOrMinusToken = ts.or(ts.isReadonlyKeyword, ts.isPlusToken, ts.isMinusToken) as (node: ts.Node) => node is ts.ReadonlyKeyword | ts.PlusToken | ts.MinusToken; +/** @internal */ export const isQuestionOrPlusOrMinusToken = ts.or(ts.isQuestionToken, ts.isPlusToken, ts.isMinusToken) as (node: ts.Node) => node is ts.QuestionToken | ts.PlusToken | ts.MinusToken; +/** @internal */ export const isModuleName = ts.or(ts.isIdentifier, ts.isStringLiteral) as (node: ts.Node) => node is ts.ModuleName; +/** @internal */ export function isLiteralTypeLikeExpression(node: ts.Node): node is ts.NullLiteral | ts.BooleanLiteral | ts.LiteralExpression | ts.PrefixUnaryExpression { const kind = node.kind; return kind === ts.SyntaxKind.NullKeyword @@ -1020,6 +1070,7 @@ function isBinaryOperator(kind: ts.SyntaxKind): kind is ts.BinaryOperator { || kind === ts.SyntaxKind.CommaToken; } +/** @internal */ export function isBinaryOperatorToken(node: ts.Node): node is ts.BinaryOperatorToken { return isBinaryOperator(node.kind); } @@ -1174,6 +1225,7 @@ class BinaryExpressionStateMachine { } } +/** @internal */ /** * Creates a state machine that walks a `BinaryExpression` using the heap to reduce call-stack depth on a large tree. * @param onEnter Callback evaluated when entering a `BinaryExpression`. Returns new user-defined state to associate with the node while walking. @@ -1191,6 +1243,7 @@ class BinaryExpressionStateMachine { onExit: (node: ts.BinaryExpression, userState: TState) => TResult, foldState: ((userState: TState, result: TResult, side: "left" | "right") => TState) | undefined, ): (node: ts.BinaryExpression) => TResult; +/** @internal */ /** * Creates a state machine that walks a `BinaryExpression` using the heap to reduce call-stack depth on a large tree. * @param onEnter Callback evaluated when entering a `BinaryExpression`. Returns new user-defined state to associate with the node while walking. @@ -1208,6 +1261,7 @@ export function createBinaryExpressionTrampoline( onExit: (node: ts.BinaryExpression, userState: TState) => TResult, foldState: ((userState: TState, result: TResult, side: "left" | "right") => TState) | undefined, ): (node: ts.BinaryExpression, outerState: TOuterState) => TResult; +/** @internal */ export function createBinaryExpressionTrampoline( onEnter: (node: ts.BinaryExpression, prev: TState | undefined, outerState: TOuterState) => TState, onLeft: ((left: ts.Expression, userState: TState, node: ts.BinaryExpression) => ts.BinaryExpression | void) | undefined, @@ -1238,13 +1292,16 @@ export function createBinaryExpressionTrampoline( * @internal */ export function elideNodes(factory: ts.NodeFactory, nodes: ts.NodeArray): ts.NodeArray; +/** @internal */ export function elideNodes(factory: ts.NodeFactory, nodes: ts.NodeArray | undefined): ts.NodeArray | undefined; +/** @internal */ export function elideNodes(factory: ts.NodeFactory, nodes: ts.NodeArray | undefined): ts.NodeArray | undefined { if (nodes === undefined) return undefined; if (nodes.length === 0) return nodes; return ts.setTextRange(factory.createNodeArray([], nodes.hasTrailingComma), nodes); } +/** @internal */ /** * Gets the node from which a name should be generated. */ @@ -1271,14 +1328,17 @@ export function getNodeForGeneratedName(name: ts.GeneratedIdentifier | ts.Genera return name; } +/** @internal */ /** * Formats a prefix or suffix of a generated name. */ export function formatGeneratedNamePart(part: string | undefined): string; +/** @internal */ /** * Formats a prefix or suffix of a generated name. If the part is a {@link GeneratedNamePart}, calls {@link generateName} to format the source node. */ export function formatGeneratedNamePart(part: string | ts.GeneratedNamePart | undefined, generateName: (name: ts.GeneratedIdentifier | ts.GeneratedPrivateIdentifier) => string): string; +/** @internal */ export function formatGeneratedNamePart(part: string | ts.GeneratedNamePart | undefined, generateName?: (name: ts.GeneratedIdentifier | ts.GeneratedPrivateIdentifier) => string): string { return typeof part === "object" ? formatGeneratedName(/*privateName*/ false, part.prefix, part.node, part.suffix, generateName!) : typeof part === "string" ? part.length > 0 && part.charCodeAt(0) === ts.CharacterCodes.hash ? part.slice(1) : part : @@ -1297,6 +1357,7 @@ function formatIdentifierWorker(node: ts.Identifier | ts.PrivateIdentifier, gene ts.idText(node); } +/** @internal */ /** * Formats a generated name. * @param privateName When `true`, inserts a `#` character at the start of the result. @@ -1305,6 +1366,7 @@ function formatIdentifierWorker(node: ts.Identifier | ts.PrivateIdentifier, gene * @param suffix The suffix (if any) to include after the base name. */ export function formatGeneratedName(privateName: boolean, prefix: string | undefined, baseName: string, suffix: string | undefined): string; +/** @internal */ /** * Formats a generated name. * @param privateName When `true`, inserts a `#` character at the start of the result. @@ -1314,6 +1376,7 @@ export function formatGeneratedName(privateName: boolean, prefix: string | undef * @param generateName Called to format the source node of {@link prefix} when it is a {@link GeneratedNamePart}. */ export function formatGeneratedName(privateName: boolean, prefix: string | ts.GeneratedNamePart | undefined, baseName: string | ts.Identifier | ts.PrivateIdentifier, suffix: string | ts.GeneratedNamePart | undefined, generateName: (name: ts.GeneratedIdentifier | ts.GeneratedPrivateIdentifier) => string): string; +/** @internal */ export function formatGeneratedName(privateName: boolean, prefix: string | ts.GeneratedNamePart | undefined, baseName: string | ts.Identifier | ts.PrivateIdentifier, suffix: string | ts.GeneratedNamePart | undefined, generateName?: (name: ts.GeneratedIdentifier | ts.GeneratedPrivateIdentifier) => string) { prefix = formatGeneratedNamePart(prefix, generateName!); suffix = formatGeneratedNamePart(suffix, generateName!); @@ -1322,6 +1385,7 @@ export function formatGeneratedName(privateName: boolean, prefix: string | ts.Ge } +/** @internal */ /** * Creates a private backing field for an `accessor` {@link PropertyDeclaration}. */ @@ -1336,6 +1400,7 @@ export function createAccessorPropertyBackingField(factory: ts.NodeFactory, node ); } +/** @internal */ /** * Creates a {@link GetAccessorDeclaration} that reads from a private backing field. */ @@ -1356,6 +1421,7 @@ export function createAccessorPropertyGetRedirector(factory: ts.NodeFactory, nod ); } +/** @internal */ /** * Creates a {@link SetAccessorDeclaration} that writes to a private backing field. */ @@ -1381,4 +1447,3 @@ export function createAccessorPropertySetRedirector(factory: ts.NodeFactory, nod ]) ); } -} diff --git a/src/compiler/factory/utilitiesPublic.ts b/src/compiler/factory/utilitiesPublic.ts index dd857d0b7b473..04668f4fa3896 100644 --- a/src/compiler/factory/utilitiesPublic.ts +++ b/src/compiler/factory/utilitiesPublic.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; + export function setTextRange(range: T, location: ts.TextRange | undefined): T { return location ? ts.setTextRangePosEnd(range, location.pos, location.end) : range; } @@ -41,5 +42,4 @@ export function canHaveDecorators(node: ts.Node): node is ts.HasDecorators { || kind === ts.SyntaxKind.SetAccessor || kind === ts.SyntaxKind.ClassExpression || kind === ts.SyntaxKind.ClassDeclaration; -} } \ No newline at end of file diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 1715278b2972c..8e6835a0bcf47 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + /* @internal */ export function trace(host: ts.ModuleResolutionHost, message: ts.DiagnosticMessage, ...args: any[]): void; export function trace(host: ts.ModuleResolutionHost): void { @@ -2718,4 +2719,3 @@ function traceIfEnabled(state: ModuleResolutionState, diagnostic: ts.DiagnosticM trace(state.host, diagnostic, ...args); } } -} diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts index e17923e3c9ffe..56d03a007fdfe 100644 --- a/src/compiler/moduleSpecifiers.ts +++ b/src/compiler/moduleSpecifiers.ts @@ -1,6 +1,7 @@ +import * as ts from "./_namespaces/ts"; + // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers. -/* @internal */ -namespace ts.moduleSpecifiers { + const enum RelativePreference { Relative, NonRelative, Shortest, ExternalNonRelative } // See UserPreferences#importPathEnding const enum Ending { Minimal, Index, JsExtension } @@ -63,6 +64,7 @@ function getModuleResolutionHost(host: ts.ModuleSpecifierResolutionHost): ts.Mod // Because when this is called by the file renamer, `importingSourceFile` is the file being renamed, // while `importingSourceFileName` its *new* name. We need a source file just to get its // `impliedNodeFormat` and to detect certain preferences from existing import module specifiers. +/** @internal */ export function updateModuleSpecifier( compilerOptions: ts.CompilerOptions, importingSourceFile: ts.SourceFile, @@ -83,6 +85,7 @@ export function updateModuleSpecifier( // one currently being produced; the latter to the one being imported). We need an implementation file // just to get its `impliedNodeFormat` and to detect certain preferences from existing import module // specifiers. +/** @internal */ export function getModuleSpecifier( compilerOptions: ts.CompilerOptions, importingSourceFile: ts.SourceFile, @@ -94,6 +97,7 @@ export function getModuleSpecifier( return getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, getPreferences(host, {}, compilerOptions, importingSourceFile), {}, options); } +/** @internal */ export function getNodeModulesPackageName( compilerOptions: ts.CompilerOptions, importingSourceFile: ts.SourceFile, @@ -124,6 +128,7 @@ function getModuleSpecifierWorker( getLocalModuleSpecifier(toFileName, info, compilerOptions, host, options.overrideImportMode || importingSourceFile.impliedNodeFormat, preferences); } +/** @internal */ export function tryGetModuleSpecifiersFromCache( moduleSymbol: ts.Symbol, importingSourceFile: ts.SourceFile, @@ -156,6 +161,7 @@ function tryGetModuleSpecifiersFromCacheWorker( return [cached?.moduleSpecifiers, moduleSourceFile, cached?.modulePaths, cache]; } +/** @internal */ /** Returns an import for each symlink and for the realpath. */ export function getModuleSpecifiers( moduleSymbol: ts.Symbol, @@ -177,6 +183,7 @@ export function getModuleSpecifiers( ).moduleSpecifiers; } +/** @internal */ export function getModuleSpecifiersWithCacheInfo( moduleSymbol: ts.Symbol, checker: ts.TypeChecker, @@ -361,6 +368,7 @@ function getLocalModuleSpecifier(moduleFileName: string, info: Info, compilerOpt return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative; } +/** @internal */ export function countPathComponents(path: string): number { let count = 0; for (let i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) { @@ -386,6 +394,7 @@ function getNearestAncestorDirectoryWithPackageJson(host: ts.ModuleSpecifierReso }); } +/** @internal */ export function forEachFileNameOfModule( importingFileName: string, importedFileName: string, @@ -923,6 +932,7 @@ function getJSExtensionForFile(fileName: string, options: ts.CompilerOptions): t return tryGetJSExtensionForFile(fileName, options) ?? ts.Debug.fail(`Extension ${ts.extensionFromPath(fileName)} is unsupported:: FileName:: ${fileName}`); } +/** @internal */ export function tryGetJSExtensionForFile(fileName: string, options: ts.CompilerOptions): ts.Extension | undefined { const ext = ts.tryGetExtensionFromPath(fileName); switch (ext) { @@ -956,4 +966,3 @@ function getRelativePathIfInDirectory(path: string, directoryPath: string, getCa function isPathRelativeToParent(path: string): boolean { return ts.startsWith(path, ".."); } -} diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 4bc176ce8bf80..327c6301fc4f7 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + const enum SignatureFlags { None = 0, Yield = 1 << 0, @@ -9962,4 +9963,3 @@ export function tagNamesAreEquivalent(lhs: ts.JsxTagNameExpression, rhs: ts.JsxT return (lhs as ts.PropertyAccessExpression).name.escapedText === (rhs as ts.PropertyAccessExpression).name.escapedText && tagNamesAreEquivalent((lhs as ts.PropertyAccessExpression).expression as ts.JsxTagNameExpression, (rhs as ts.PropertyAccessExpression).expression as ts.JsxTagNameExpression); } -} diff --git a/src/compiler/path.ts b/src/compiler/path.ts index 36c636aa1e0d5..8433e734053c2 100644 --- a/src/compiler/path.ts +++ b/src/compiler/path.ts @@ -1,17 +1,20 @@ -/* @internal */ -namespace ts { +import * as ts from "./_namespaces/ts"; + +/** @internal */ /** * Internally, we represent paths as strings with '/' as the directory separator. * When we make system calls (eg: LanguageServiceHost.getDirectory()), * we expect the host to correctly handle paths in our specified format. */ export const directorySeparator = "/"; +/** @internal */ export const altDirectorySeparator = "\\"; const urlSchemeSeparator = "://"; const backslashRegExp = /\\/g; //// Path Tests +/** @internal */ /** * Determines whether a charCode corresponds to `/` or `\`. */ @@ -19,6 +22,7 @@ export function isAnyDirectorySeparator(charCode: number): boolean { return charCode === ts.CharacterCodes.slash || charCode === ts.CharacterCodes.backslash; } +/** @internal */ /** * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.). */ @@ -26,6 +30,7 @@ export function isUrl(path: string) { return getEncodedRootLength(path) < 0; } +/** @internal */ /** * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path * like `c:`, `c:\` or `c:/`). @@ -34,6 +39,7 @@ export function isRootedDiskPath(path: string) { return getEncodedRootLength(path) > 0; } +/** @internal */ /** * Determines whether a path consists only of a path root. */ @@ -42,6 +48,7 @@ export function isDiskPathRoot(path: string) { return rootLength > 0 && rootLength === path.length; } +/** @internal */ /** * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.). * @@ -61,6 +68,7 @@ export function pathIsAbsolute(path: string): boolean { return getEncodedRootLength(path) !== 0; } +/** @internal */ /** * Determines whether a path starts with a relative path component (i.e. `.` or `..`). */ @@ -68,6 +76,7 @@ export function pathIsRelative(path: string): boolean { return /^\.\.?($|[\\/])/.test(path); } +/** @internal */ /** * Determines whether a path is neither relative nor absolute, e.g. "path/to/file". * Also known misleadingly as "non-relative". @@ -76,14 +85,17 @@ export function pathIsBareSpecifier(path: string): boolean { return !pathIsAbsolute(path) && !pathIsRelative(path); } +/** @internal */ export function hasExtension(fileName: string): boolean { return ts.stringContains(getBaseFileName(fileName), "."); } +/** @internal */ export function fileExtensionIs(path: string, extension: string): boolean { return path.length > extension.length && ts.endsWith(path, extension); } +/** @internal */ export function fileExtensionIsOneOf(path: string, extensions: readonly string[]): boolean { for (const extension of extensions) { if (fileExtensionIs(path, extension)) { @@ -94,6 +106,7 @@ export function fileExtensionIsOneOf(path: string, extensions: readonly string[] return false; } +/** @internal */ /** * Determines whether a path has a trailing separator (`/` or `\\`). */ @@ -178,6 +191,7 @@ function getEncodedRootLength(path: string): number { return 0; } +/** @internal */ /** * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). * @@ -208,6 +222,7 @@ export function getRootLength(path: string) { return rootLength < 0 ? ~rootLength : rootLength; } +/** @internal */ /** * Returns the path except for its basename. Semantics align with NodeJS's `path.dirname` * except that we support URLs as well. @@ -230,6 +245,7 @@ export function getRootLength(path: string) { * ``` */ export function getDirectoryPath(path: ts.Path): ts.Path; +/** @internal */ /** * Returns the path except for its basename. Semantics align with NodeJS's `path.dirname` * except that we support URLs as well. @@ -260,6 +276,7 @@ export function getDirectoryPath(path: ts.Path): ts.Path; * ``` */ export function getDirectoryPath(path: string): string; +/** @internal */ export function getDirectoryPath(path: string): string { path = normalizeSlashes(path); @@ -273,6 +290,7 @@ export function getDirectoryPath(path: string): string { return path.slice(0, Math.max(rootLength, path.lastIndexOf(directorySeparator))); } +/** @internal */ /** * Returns the path except for its containing directory name. * Semantics align with NodeJS's `path.basename` except that we support URL's as well. @@ -303,6 +321,7 @@ export function getDirectoryPath(path: string): string { * ``` */ export function getBaseFileName(path: string): string; +/** @internal */ /** * Gets the portion of a path following the last (non-terminal) separator (`/`). * Semantics align with NodeJS's `path.basename` except that we support URL's as well. @@ -316,6 +335,7 @@ export function getBaseFileName(path: string): string; * ``` */ export function getBaseFileName(path: string, extensions: string | readonly string[], ignoreCase: boolean): string; +/** @internal */ export function getBaseFileName(path: string, extensions?: string | readonly string[], ignoreCase?: boolean) { path = normalizeSlashes(path); @@ -352,6 +372,7 @@ function getAnyExtensionFromPathWorker(path: string, extensions: string | readon return ""; } +/** @internal */ /** * Gets the file extension for a path. * @@ -363,6 +384,7 @@ function getAnyExtensionFromPathWorker(path: string, extensions: string | readon * ``` */ export function getAnyExtensionFromPath(path: string): string; +/** @internal */ /** * Gets the file extension for a path, provided it is one of the provided extensions. * @@ -373,6 +395,7 @@ export function getAnyExtensionFromPath(path: string): string; * getAnyExtensionFromPath("/path/to/file.ext", ".EXT", false) === "" */ export function getAnyExtensionFromPath(path: string, extensions: string | readonly string[], ignoreCase: boolean): string; +/** @internal */ export function getAnyExtensionFromPath(path: string, extensions?: string | readonly string[], ignoreCase?: boolean): string { // Retrieves any string from the final "." onwards from a base file name. // Unlike extensionFromPath, which throws an exception on unrecognized extensions. @@ -394,6 +417,7 @@ function pathComponents(path: string, rootLength: number) { return [root, ...rest]; } +/** @internal */ /** * Parse a path into an array containing a root component (at index 0) and zero or more path * components (at indices > 0). The result is not normalized. @@ -431,6 +455,7 @@ export function getPathComponents(path: string, currentDirectory = "") { //// Path Formatting +/** @internal */ /** * Formats a parsed path consisting of a root component (at index 0) and zero or more path * segments (at indices > 0). @@ -448,6 +473,7 @@ export function getPathFromPathComponents(pathComponents: readonly string[]) { //// Path Normalization +/** @internal */ /** * Normalize path separators, converting `\` into `/`. */ @@ -457,6 +483,7 @@ export function normalizeSlashes(path: string): string { : path; } +/** @internal */ /** * Reduce an array of path components to a more simplified path by navigating any * `"."` or `".."` entries in the path. @@ -482,6 +509,7 @@ export function reducePathComponents(components: readonly string[]) { return reduced; } +/** @internal */ /** * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified. * @@ -515,6 +543,7 @@ export function combinePaths(path: string, ...paths: (string | undefined)[]): st return path; } +/** @internal */ /** * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any * `.` and `..` path components are resolved. Trailing directory separators are preserved. @@ -529,6 +558,7 @@ export function resolvePath(path: string, ...paths: (string | undefined)[]): str return normalizePath(ts.some(paths) ? combinePaths(path, ...paths) : normalizeSlashes(path)); } +/** @internal */ /** * Parse a path into an array containing a root component (at index 0) and zero or more path * components (at indices > 0). The result is normalized. @@ -543,10 +573,12 @@ export function getNormalizedPathComponents(path: string, currentDirectory: stri return reducePathComponents(getPathComponents(path, currentDirectory)); } +/** @internal */ export function getNormalizedAbsolutePath(fileName: string, currentDirectory: string | undefined) { return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); } +/** @internal */ export function normalizePath(path: string): string { path = normalizeSlashes(path); // Most paths don't require normalization @@ -571,10 +603,12 @@ function getPathWithoutRoot(pathComponents: readonly string[]) { return pathComponents.slice(1).join(directorySeparator); } +/** @internal */ export function getNormalizedAbsolutePathWithoutRoot(fileName: string, currentDirectory: string | undefined) { return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); } +/** @internal */ export function toPath(fileName: string, basePath: string | undefined, getCanonicalFileName: (path: string) => string): ts.Path { const nonCanonicalizedPath = isRootedDiskPath(fileName) ? normalizePath(fileName) @@ -584,6 +618,7 @@ export function toPath(fileName: string, basePath: string | undefined, getCanoni //// Path Mutation +/** @internal */ /** * Removes a trailing directory separator from a path, if it does not already have one. * @@ -593,7 +628,9 @@ export function toPath(fileName: string, basePath: string | undefined, getCanoni * ``` */ export function removeTrailingDirectorySeparator(path: ts.Path): ts.Path; +/** @internal */ export function removeTrailingDirectorySeparator(path: string): string; +/** @internal */ export function removeTrailingDirectorySeparator(path: string) { if (hasTrailingDirectorySeparator(path)) { return path.substr(0, path.length - 1); @@ -602,6 +639,7 @@ export function removeTrailingDirectorySeparator(path: string) { return path; } +/** @internal */ /** * Adds a trailing directory separator to a path, if it does not already have one. * @@ -611,7 +649,9 @@ export function removeTrailingDirectorySeparator(path: string) { * ``` */ export function ensureTrailingDirectorySeparator(path: ts.Path): ts.Path; +/** @internal */ export function ensureTrailingDirectorySeparator(path: string): string; +/** @internal */ export function ensureTrailingDirectorySeparator(path: string) { if (!hasTrailingDirectorySeparator(path)) { return path + directorySeparator; @@ -620,6 +660,7 @@ export function ensureTrailingDirectorySeparator(path: string) { return path; } +/** @internal */ /** * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed * with `./` or `../`) so as not to be confused with an unprefixed module name. @@ -635,6 +676,7 @@ export function ensurePathIsNonModuleName(path: string): string { return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; } +/** @internal */ /** * Changes the extension of a path to the provided extension. * @@ -643,6 +685,7 @@ export function ensurePathIsNonModuleName(path: string): string { * ``` */ export function changeAnyExtension(path: string, ext: string): string; +/** @internal */ /** * Changes the extension of a path to the provided extension if it has one of the provided extensions. * @@ -653,6 +696,7 @@ export function changeAnyExtension(path: string, ext: string): string; * ``` */ export function changeAnyExtension(path: string, ext: string, extensions: string | readonly string[], ignoreCase: boolean): string; +/** @internal */ export function changeAnyExtension(path: string, ext: string, extensions?: string | readonly string[], ignoreCase?: boolean) { const pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; @@ -699,6 +743,7 @@ function comparePathsWorker(a: string, b: string, componentComparer: (a: string, return ts.compareValues(aComponents.length, bComponents.length); } +/** @internal */ /** * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively. */ @@ -706,6 +751,7 @@ export function comparePathsCaseSensitive(a: string, b: string) { return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); } +/** @internal */ /** * Performs a case-insensitive comparison of two paths. */ @@ -713,11 +759,14 @@ export function comparePathsCaseInsensitive(a: string, b: string) { return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); } +/** @internal */ /** * Compare two paths using the provided case sensitivity. */ export function comparePaths(a: string, b: string, ignoreCase?: boolean): ts.Comparison; +/** @internal */ export function comparePaths(a: string, b: string, currentDirectory: string, ignoreCase?: boolean): ts.Comparison; +/** @internal */ export function comparePaths(a: string, b: string, currentDirectory?: string | boolean, ignoreCase?: boolean) { if (typeof currentDirectory === "string") { a = combinePaths(currentDirectory, a); @@ -729,11 +778,14 @@ export function comparePaths(a: string, b: string, currentDirectory?: string | b return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); } +/** @internal */ /** * Determines whether a `parent` path contains a `child` path using the provide case sensitivity. */ export function containsPath(parent: string, child: string, ignoreCase?: boolean): boolean; +/** @internal */ export function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean; +/** @internal */ export function containsPath(parent: string, child: string, currentDirectory?: string | boolean, ignoreCase?: boolean) { if (typeof currentDirectory === "string") { parent = combinePaths(currentDirectory, parent); @@ -761,6 +813,7 @@ export function containsPath(parent: string, child: string, currentDirectory?: s return true; } +/** @internal */ /** * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. * Comparison is case-sensitive between the canonical paths. @@ -775,6 +828,7 @@ export function startsWithDirectory(fileName: string, directoryName: string, get //// Relative Paths +/** @internal */ export function getPathComponentsRelativeTo(from: string, to: string, stringEqualityComparer: (a: string, b: string) => boolean, getCanonicalFileName: ts.GetCanonicalFileName) { const fromComponents = reducePathComponents(getPathComponents(from)); const toComponents = reducePathComponents(getPathComponents(to)); @@ -799,14 +853,17 @@ export function getPathComponentsRelativeTo(from: string, to: string, stringEqua return ["", ...relative, ...components]; } +/** @internal */ /** * Gets a relative path that can be used to traverse between `from` and `to`. */ export function getRelativePathFromDirectory(from: string, to: string, ignoreCase: boolean): string; +/** @internal */ /** * Gets a relative path that can be used to traverse between `from` and `to`. */ export function getRelativePathFromDirectory(fromDirectory: string, to: string, getCanonicalFileName: ts.GetCanonicalFileName): string; // eslint-disable-line @typescript-eslint/unified-signatures +/** @internal */ export function getRelativePathFromDirectory(fromDirectory: string, to: string, getCanonicalFileNameOrIgnoreCase: ts.GetCanonicalFileName | boolean) { ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); const getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; @@ -815,16 +872,19 @@ export function getRelativePathFromDirectory(fromDirectory: string, to: string, return getPathFromPathComponents(pathComponents); } +/** @internal */ export function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); } +/** @internal */ export function getRelativePathFromFile(from: string, to: string, getCanonicalFileName: ts.GetCanonicalFileName) { return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); } +/** @internal */ export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: ts.GetCanonicalFileName, isAbsolutePathAnUrl: boolean) { const pathComponents = getPathComponentsRelativeTo( resolvePath(currentDirectory, directoryPathOrUrl), @@ -844,11 +904,14 @@ export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, rela //// Path Traversal +/** @internal */ /** * Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ export function forEachAncestorDirectory(directory: ts.Path, callback: (directory: ts.Path) => T | undefined): T | undefined; +/** @internal */ export function forEachAncestorDirectory(directory: string, callback: (directory: string) => T | undefined): T | undefined; +/** @internal */ export function forEachAncestorDirectory(directory: ts.Path, callback: (directory: ts.Path) => T | undefined): T | undefined { while (true) { const result = callback(directory); @@ -865,7 +928,7 @@ export function forEachAncestorDirectory(directory: ts.Path, callback: (direc } } +/** @internal */ export function isNodeModulesDirectory(dirPath: ts.Path) { return ts.endsWith(dirPath, "/node_modules"); } -} diff --git a/src/compiler/perfLogger.ts b/src/compiler/perfLogger.ts index 8ef902ea3e636..6c0227e454192 100644 --- a/src/compiler/perfLogger.ts +++ b/src/compiler/perfLogger.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts { +import * as ts from "./_namespaces/ts"; + type PerfLogger = typeof import("@microsoft/typescript-etw"); const nullLogger: PerfLogger = { logEvent: ts.noop, @@ -38,6 +38,6 @@ catch (e) { etwModule = undefined; } +/** @internal */ /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ export const perfLogger: PerfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; -} diff --git a/src/compiler/performance.ts b/src/compiler/performance.ts index 071297b5334c7..4e2e52e6e34cd 100644 --- a/src/compiler/performance.ts +++ b/src/compiler/performance.ts @@ -1,20 +1,24 @@ -/*@internal*/ +import * as ts from "./_namespaces/ts"; + /** Performance measurements for the compiler. */ -namespace ts.performance { + let perfHooks: ts.PerformanceHooks | undefined; // when set, indicates the implementation of `Performance` to use for user timing. // when unset, indicates user timing is unavailable or disabled. let performanceImpl: ts.Performance | undefined; +/** @internal */ export interface Timer { enter(): void; exit(): void; } +/** @internal */ export function createTimerIf(condition: boolean, measureName: string, startMarkName: string, endMarkName: string) { return condition ? createTimer(measureName, startMarkName, endMarkName) : nullTimer; } +/** @internal */ export function createTimer(measureName: string, startMarkName: string, endMarkName: string): Timer { let enterCount = 0; return { @@ -39,6 +43,7 @@ export function createTimer(measureName: string, startMarkName: string, endMarkN } } +/** @internal */ export const nullTimer: Timer = { enter: ts.noop, exit: ts.noop }; let enabled = false; @@ -47,6 +52,7 @@ const marks = new ts.Map(); const counts = new ts.Map(); const durations = new ts.Map(); +/** @internal */ /** * Marks a performance event. * @@ -61,6 +67,7 @@ export function mark(markName: string) { } } +/** @internal */ /** * Adds a performance measurement with the specified name. * @@ -80,6 +87,7 @@ export function measure(measureName: string, startMarkName?: string, endMarkName } } +/** @internal */ /** * Gets the number of times a marker was encountered. * @@ -89,6 +97,7 @@ export function getCount(markName: string) { return counts.get(markName) || 0; } +/** @internal */ /** * Gets the total duration of all measurements with the supplied name. * @@ -98,6 +107,7 @@ export function getDuration(measureName: string) { return durations.get(measureName) || 0; } +/** @internal */ /** * Iterate over each measure, performing some action * @@ -107,16 +117,19 @@ export function forEachMeasure(cb: (measureName: string, duration: number) => vo durations.forEach((duration, measureName) => cb(measureName, duration)); } +/** @internal */ export function forEachMark(cb: (markName: string) => void) { marks.forEach((_time, markName) => cb(markName)); } +/** @internal */ export function clearMeasures(name?: string) { if (name !== undefined) durations.delete(name); else durations.clear(); performanceImpl?.clearMeasures(name); } +/** @internal */ export function clearMarks(name?: string) { if (name !== undefined) { counts.delete(name); @@ -129,6 +142,7 @@ export function clearMarks(name?: string) { performanceImpl?.clearMarks(name); } +/** @internal */ /** * Indicates whether the performance API is enabled. */ @@ -136,6 +150,7 @@ export function isEnabled() { return enabled; } +/** @internal */ /** Enables (and resets) performance measurements for the compiler. */ export function enable(system: ts.System = ts.sys) { if (!enabled) { @@ -155,6 +170,7 @@ export function enable(system: ts.System = ts.sys) { return true; } +/** @internal */ /** Disables performance measurements for the compiler. */ export function disable() { if (enabled) { @@ -165,4 +181,3 @@ export function disable() { enabled = false; } } -} diff --git a/src/compiler/performanceCore.ts b/src/compiler/performanceCore.ts index 7bc62a4e94f1e..4394c425204ed 100644 --- a/src/compiler/performanceCore.ts +++ b/src/compiler/performanceCore.ts @@ -1,8 +1,9 @@ -/*@internal*/ -namespace ts { +import * as ts from "./_namespaces/ts"; + // The following definitions provide the minimum compatible support for the Web Performance User Timings API // between browsers and NodeJS: +/** @internal */ export interface PerformanceHooks { /** Indicates whether we should write native performance events */ shouldWriteNativeEvents: boolean; @@ -10,6 +11,7 @@ export interface PerformanceHooks { PerformanceObserver: PerformanceObserverConstructor; } +/** @internal */ export interface Performance { mark(name: string): void; measure(name: string, startMark?: string, endMark?: string): void; @@ -19,6 +21,7 @@ export interface Performance { timeOrigin: number; } +/** @internal */ export interface PerformanceEntry { name: string; entryType: string; @@ -26,18 +29,22 @@ export interface PerformanceEntry { duration: number; } +/** @internal */ export interface PerformanceObserverEntryList { getEntries(): PerformanceEntryList; getEntriesByName(name: string, type?: string): PerformanceEntryList; getEntriesByType(type: string): PerformanceEntryList; } +/** @internal */ export interface PerformanceObserver { disconnect(): void; observe(options: { entryTypes: readonly ("mark" | "measure")[] }): void; } +/** @internal */ export type PerformanceObserverConstructor = new (callback: (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void) => PerformanceObserver; +/** @internal */ export type PerformanceEntryList = PerformanceEntry[]; // Browser globals for the Web Performance User Timings API @@ -123,13 +130,14 @@ function tryGetNodePerformanceHooks(): PerformanceHooks | undefined { const nativePerformanceHooks = tryGetWebPerformanceHooks() || tryGetNodePerformanceHooks(); const nativePerformance = nativePerformanceHooks?.performance; +/** @internal */ export function tryGetNativePerformanceHooks() { return nativePerformanceHooks; } +/** @internal */ /** Gets a timestamp with (at least) ms resolution */ export const timestamp = nativePerformance ? () => nativePerformance.now() : Date.now ? Date.now : - () => +(new Date()); -} \ No newline at end of file + () => +(new Date()); \ No newline at end of file diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 04cc4c05562f6..2764f517522be 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName = "tsconfig.json"): string | undefined { return ts.forEachAncestorDirectory(searchPath, ancestor => { const fileName = ts.combinePaths(ancestor, configName); @@ -4418,4 +4419,3 @@ export function getModuleNameStringLiteralAt({ imports, moduleAugmentations }: S } ts.Debug.fail("should never ask for module name at index higher than possible module name"); } -} diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index ee86afed50265..6e2d85fabbb8c 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "./_namespaces/ts"; + +/** @internal */ /** This is the cache of module/typedirectives resolution that can be retained across program */ export interface ResolutionCache { startRecordingFilesWithChangedResolutions(): void; @@ -57,6 +58,7 @@ interface CachedResolvedModuleWithFailedLookupLocations extends ts.ResolvedModul interface CachedResolvedTypeReferenceDirectiveWithFailedLookupLocations extends ts.ResolvedTypeReferenceDirectiveWithFailedLookupLocations, ResolutionWithFailedLookupLocations { } +/** @internal */ export interface ResolutionCacheHost extends ts.MinimalResolutionCacheHost { toPath(fileName: string): ts.Path; getCanonicalFileName: ts.GetCanonicalFileName; @@ -100,6 +102,7 @@ interface DirectoryOfFailedLookupWatch { nonRecursive?: boolean; } +/** @internal */ export function removeIgnoredPath(path: ts.Path): ts.Path | undefined { // Consider whole staging folder as if node_modules changed. if (ts.endsWith(path, "/node_modules/.staging")) { @@ -111,6 +114,7 @@ export function removeIgnoredPath(path: ts.Path): ts.Path | undefined { path; } +/** @internal */ /** * Filter out paths like * "/", "/user", "/user/username", "/user/username/folderAtRoot", @@ -163,6 +167,7 @@ export function canWatchDirectoryOrFile(dirPath: ts.Path) { type GetResolutionWithResolvedFileName = (resolution: T) => R | undefined; +/** @internal */ export function createResolutionCache(resolutionHost: ResolutionCacheHost, rootDirForResolution: string | undefined, logChangesWhenResolvingModule: boolean): ResolutionCache { let filesWithChangedSetOfUnresolvedImports: ts.Path[] | undefined; let filesWithInvalidatedResolutions: ts.Set | undefined; @@ -1157,4 +1162,3 @@ function resolutionIsSymlink(resolution: ResolutionWithFailedLookupLocations) { (resolution as ts.ResolvedTypeReferenceDirectiveWithFailedLookupLocations).resolvedTypeReferenceDirective?.originalPath ); } -} diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index 52cf3c12671ff..0552d246894f6 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + export type ErrorCallback = (message: ts.DiagnosticMessage, length: number) => void; /* @internal */ @@ -2659,4 +2660,3 @@ const utf16EncodeAsStringWorker: (codePoint: number) => string = (String as any) export function utf16EncodeAsString(codePoint: number) { return utf16EncodeAsStringWorker(codePoint); } -} diff --git a/src/compiler/semver.ts b/src/compiler/semver.ts index cc6b2f3c224af..d187fa4e0221c 100644 --- a/src/compiler/semver.ts +++ b/src/compiler/semver.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts { +import * as ts from "./_namespaces/ts"; + // https://semver.org/#spec-item-2 // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor @@ -28,6 +28,7 @@ const buildPartRegExp = /^[a-z0-9-]+$/i; // > Numeric identifiers MUST NOT include leading zeroes. const numericIdentifierRegExp = /^(0|[1-9]\d*)$/; +/** @internal */ /** * Describes a precise semantic version number, https://semver.org */ @@ -182,6 +183,7 @@ function comparePrereleaseIdentifiers(left: readonly string[], right: readonly s return ts.compareValues(left.length, right.length); } +/** @internal */ /** * Describes a semantic version range, per https://github.com/npm/node-semver#ranges */ @@ -412,5 +414,4 @@ function formatAlternative(comparators: readonly Comparator[]) { function formatComparator(comparator: Comparator) { return `${comparator.operator}${comparator.operand}`; -} } \ No newline at end of file diff --git a/src/compiler/sourcemap.ts b/src/compiler/sourcemap.ts index d7a7a5145eed6..0eb2cafd45ae4 100644 --- a/src/compiler/sourcemap.ts +++ b/src/compiler/sourcemap.ts @@ -1,9 +1,11 @@ -/* @internal */ -namespace ts { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export interface SourceMapGeneratorOptions { extendedDiagnostics?: boolean; } +/** @internal */ export function createSourceMapGenerator(host: ts.EmitHost, file: string, sourceRoot: string, sourcesDirectoryPath: string, generatorOptions: SourceMapGeneratorOptions): ts.SourceMapGenerator { const { enter, exit } = generatorOptions.extendedDiagnostics ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap") @@ -322,16 +324,21 @@ export function createSourceMapGenerator(host: ts.EmitHost, file: string, source } // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) +/** @internal */ export const sourceMapCommentRegExpDontCareLineStart = /\/\/[@#] source[M]appingURL=(.+)\r?\n?$/; +/** @internal */ export const sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\r?\n?$/; +/** @internal */ export const whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; +/** @internal */ export interface LineInfo { getLineCount(): number; getLineText(line: number): string; } +/** @internal */ export function getLineInfo(text: string, lineStarts: readonly number[]): LineInfo { return { getLineCount: () => lineStarts.length, @@ -339,6 +346,7 @@ export function getLineInfo(text: string, lineStarts: readonly number[]): LineIn }; } +/** @internal */ /** * Tries to find the sourceMappingURL comment at the end of a file. */ @@ -361,6 +369,7 @@ function isStringOrNull(x: any) { return typeof x === "string" || x === null; } +/** @internal */ export function isRawSourceMap(x: any): x is ts.RawSourceMap { return x !== null && typeof x === "object" @@ -374,6 +383,7 @@ export function isRawSourceMap(x: any): x is ts.RawSourceMap { } /* eslint-enable no-null/no-null */ +/** @internal */ export function tryParseRawSourceMap(text: string) { try { const parsed = JSON.parse(text); @@ -388,12 +398,14 @@ export function tryParseRawSourceMap(text: string) { return undefined; } +/** @internal */ export interface MappingsDecoder extends ts.Iterator { readonly pos: number; readonly error: string | undefined; readonly state: Required; } +/** @internal */ export interface Mapping { generatedLine: number; generatedCharacter: number; @@ -403,12 +415,14 @@ export interface Mapping { nameIndex?: number; } +/** @internal */ export interface SourceMapping extends Mapping { sourceIndex: number; sourceLine: number; sourceCharacter: number; } +/** @internal */ export function decodeMappings(mappings: string): MappingsDecoder { let done = false; let pos = 0; @@ -556,6 +570,7 @@ export function decodeMappings(mappings: string): MappingsDecoder { } } +/** @internal */ export function sameMapping(left: T, right: T) { return left === right || left.generatedLine === right.generatedLine @@ -566,6 +581,7 @@ export function sameMapping(left: T, right: T) { && left.nameIndex === right.nameIndex; } +/** @internal */ export function isSourceMapping(mapping: Mapping): mapping is SourceMapping { return mapping.sourceIndex !== undefined && mapping.sourceLine !== undefined @@ -634,6 +650,7 @@ function getGeneratedPositionOfMapping(value: MappedPosition) { return value.generatedPosition; } +/** @internal */ export function createDocumentPositionMapper(host: ts.DocumentPositionMapperHost, map: ts.RawSourceMap, mapPath: string): ts.DocumentPositionMapper { const mapDirectory = ts.getDirectoryPath(mapPath); const sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; @@ -754,8 +771,8 @@ export function createDocumentPositionMapper(host: ts.DocumentPositionMapperHost } } +/** @internal */ export const identitySourceMapConsumer: ts.DocumentPositionMapper = { getSourcePosition: ts.identity, getGeneratedPosition: ts.identity }; -} diff --git a/src/compiler/symbolWalker.ts b/src/compiler/symbolWalker.ts index b318c6a194bdd..b3e00e7bf4441 100644 --- a/src/compiler/symbolWalker.ts +++ b/src/compiler/symbolWalker.ts @@ -1,5 +1,8 @@ +import * as ts from "./_namespaces/ts"; + +/** @internal */ + /** @internal */ -namespace ts { export function createGetSymbolWalker( getRestTypeOfSignature: (sig: ts.Signature) => ts.Type, getTypePredicateOfSignature: (sig: ts.Signature) => ts.TypePredicate | undefined, @@ -186,5 +189,4 @@ export function createGetSymbolWalker( return false; } } -} } \ No newline at end of file diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 7857e091681fb..f96f3df585efb 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -1,7 +1,8 @@ +import * as ts from "./_namespaces/ts"; + declare function setTimeout(handler: (...args: any[]) => void, timeout: number): any; declare function clearTimeout(handle: any): void; -namespace ts { /** * djb2 hashing algorithm * http://www.cse.yorku.ca/~oz/hash.html @@ -1978,4 +1979,3 @@ if (sys && sys.getEnvironmentVariable) { if (sys && sys.debugMode) { ts.Debug.isDebugging = true; } -} diff --git a/src/compiler/tracing.ts b/src/compiler/tracing.ts index 73460ad187cd1..5e0a2302d5ebe 100644 --- a/src/compiler/tracing.ts +++ b/src/compiler/tracing.ts @@ -1,8 +1,10 @@ +import * as ts from "./_namespaces/ts"; + /* Tracing events for the compiler. */ -/*@internal*/ -namespace ts { // eslint-disable-line local/one-namespace-per-file +// eslint-disable-line local/one-namespace-per-file // should be used as tracing?.___ +/** @internal */ export let tracing: typeof tracingEnabled | undefined; // enable the above using startTracing() @@ -340,10 +342,12 @@ namespace tracingEnabled { // eslint-disable-line local/one-namespace-per-file } // define after tracingEnabled is initialized +/** @internal */ export const startTracing = tracingEnabled.startTracing; +/** @internal */ export const dumpTracingLegend = tracingEnabled.dumpLegend; +/** @internal */ export interface TracingNode { tracingPath?: ts.Path; } -} diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts index 04949ad698d70..42b2fb94ebf56 100644 --- a/src/compiler/transformer.ts +++ b/src/compiler/transformer.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts { +import * as ts from "./_namespaces/ts"; + function getModuleTransformer(moduleKind: ts.ModuleKind): ts.TransformerFactory { switch (moduleKind) { case ts.ModuleKind.ESNext: @@ -29,8 +29,10 @@ const enum SyntaxKindFeatureFlags { EmitNotifications = 1 << 1, } +/** @internal */ export const noTransformers: ts.EmitTransformers = { scriptTransformers: ts.emptyArray, declarationTransformers: ts.emptyArray }; +/** @internal */ export function getTransformers(compilerOptions: ts.CompilerOptions, customTransformers?: ts.CustomTransformers, emitOnly?: boolean | ts.EmitOnly): ts.EmitTransformers { return { scriptTransformers: getScriptTransformers(compilerOptions, customTransformers, emitOnly), @@ -134,14 +136,17 @@ function wrapDeclarationTransformerFactory(transformer: ts.TransformerFactory node); } +/** @internal */ export function noEmitSubstitution(_hint: ts.EmitHint, node: ts.Node) { return node; } +/** @internal */ export function noEmitNotification(hint: ts.EmitHint, node: ts.Node, callback: (hint: ts.EmitHint, node: ts.Node) => void) { callback(hint, node); } +/** @internal */ /** * Transforms an array of SourceFiles by passing them through each transformer. * @@ -566,6 +571,7 @@ export function transformNodes(resolver: ts.EmitResolver | un } } +/** @internal */ export const nullTransformationContext: ts.TransformationContext = { factory: ts.factory, // eslint-disable-line object-shorthand getCompilerOptions: () => ({}), @@ -594,4 +600,3 @@ export const nullTransformationContext: ts.TransformationContext = { onEmitNode: noEmitNotification, addDiagnostic: ts.noop, }; -} diff --git a/src/compiler/transformers/classFields.ts b/src/compiler/transformers/classFields.ts index 64f381a05bf9c..d3bf188e4c95b 100644 --- a/src/compiler/transformers/classFields.ts +++ b/src/compiler/transformers/classFields.ts @@ -1,5 +1,5 @@ -/*@internal*/ -namespace ts { +import * as ts from "../_namespaces/ts"; + const enum ClassPropertySubstitutionFlags { /** * Enables substitutions for class expressions with static fields @@ -13,6 +13,7 @@ const enum ClassPropertySubstitutionFlags { ClassStaticThisOrSuperReference = 1 << 1, } +/** @internal */ export const enum PrivateIdentifierKind { Field = "f", Method = "m", @@ -122,6 +123,7 @@ const enum ClassFacts { NeedsSubstitutionForThisInClassStaticField = 1 << 3, } +/** @internal */ /** * Transforms ECMAScript Class Syntax. * TypeScript parameter property syntax is transformed in the TypeScript transformer. @@ -2546,4 +2548,3 @@ function getPrivateIdentifierInfo(privateEnv: PrivateIdentifierEnvironment, key: function getGeneratedPrivateIdentifierInfo(privateEnv: PrivateIdentifierEnvironment, key: ts.Node) { return privateEnv.generatedIdentifiers?.get(key); } -} diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index f2973e217a9dc..beb23c5dbcc24 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export function getDeclarationDiagnostics(host: ts.EmitHost, resolver: ts.EmitResolver, file: ts.SourceFile | undefined): ts.DiagnosticWithLocation[] | undefined { const compilerOptions = host.getCompilerOptions(); const result = ts.transformNodes(resolver, host, ts.factory, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJson), [transformDeclarations], /*allowDtsFiles*/ false); @@ -11,6 +12,7 @@ function hasInternalAnnotation(range: ts.CommentRange, currentSourceFile: ts.Sou return ts.stringContains(comment, "@internal"); } +/** @internal */ export function isInternalDeclaration(node: ts.Node, currentSourceFile: ts.SourceFile) { const parseTreeNode = ts.getParseTreeNode(node); if (parseTreeNode && parseTreeNode.kind === ts.SyntaxKind.Parameter) { @@ -43,6 +45,7 @@ const declarationEmitNodeBuilderFlags = ts.NodeBuilderFlags.GenerateNamesForShadowedTypeParams | ts.NodeBuilderFlags.NoTruncation; +/** @internal */ /** * Transforms a ts file into a .d.ts file * This process requires type information, which is retrieved through the emit resolver. Because of this, @@ -1742,4 +1745,3 @@ function isProcessedComponent(node: ts.Node): node is ProcessedComponent { } return false; } -} diff --git a/src/compiler/transformers/declarations/diagnostics.ts b/src/compiler/transformers/declarations/diagnostics.ts index 3145f4ee2e41d..dba6a02b81346 100644 --- a/src/compiler/transformers/declarations/diagnostics.ts +++ b/src/compiler/transformers/declarations/diagnostics.ts @@ -1,13 +1,16 @@ -/* @internal */ -namespace ts { +import * as ts from "../../_namespaces/ts"; + +/** @internal */ export type GetSymbolAccessibilityDiagnostic = (symbolAccessibilityResult: ts.SymbolAccessibilityResult) => (SymbolAccessibilityDiagnostic | undefined); +/** @internal */ export interface SymbolAccessibilityDiagnostic { errorNode: ts.Node; diagnosticMessage: ts.DiagnosticMessage; typeName?: ts.DeclarationName | ts.QualifiedName; } +/** @internal */ export type DeclarationDiagnosticProducing = | ts.VariableDeclaration | ts.PropertyDeclaration @@ -32,6 +35,7 @@ export type DeclarationDiagnosticProducing = | ts.JSDocCallbackTag | ts.JSDocEnumTag; +/** @internal */ export function canProduceDiagnostics(node: ts.Node): node is DeclarationDiagnosticProducing { return ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || @@ -55,6 +59,7 @@ export function canProduceDiagnostics(node: ts.Node): node is DeclarationDiagnos ts.isJSDocTypeAlias(node); } +/** @internal */ export function createGetSymbolAccessibilityDiagnosticForNodeName(node: DeclarationDiagnosticProducing) { if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) { return getAccessorNameVisibilityError; @@ -128,6 +133,7 @@ export function createGetSymbolAccessibilityDiagnosticForNodeName(node: Declarat } } +/** @internal */ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationDiagnosticProducing): GetSymbolAccessibilityDiagnostic { if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) { return getVariableDeclarationTypeVisibilityError; @@ -488,4 +494,3 @@ export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationD }; } } -} diff --git a/src/compiler/transformers/destructuring.ts b/src/compiler/transformers/destructuring.ts index bd9ffea622efd..ef118aac232f8 100644 --- a/src/compiler/transformers/destructuring.ts +++ b/src/compiler/transformers/destructuring.ts @@ -1,5 +1,5 @@ -/*@internal*/ -namespace ts { +import * as ts from "../_namespaces/ts"; + interface FlattenContext { context: ts.TransformationContext; level: FlattenLevel; @@ -14,11 +14,13 @@ interface FlattenContext { visitor?: (node: ts.Node) => ts.VisitResult; } +/** @internal */ export const enum FlattenLevel { All, ObjectRest, } +/** @internal */ /** * Flattens a DestructuringAssignment or a VariableDeclaration to an expression. * @@ -158,6 +160,7 @@ function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern: ts.Bi return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName); } +/** @internal */ /** * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. * @@ -541,4 +544,3 @@ function makeBindingElement(factory: ts.NodeFactory, name: ts.Identifier) { function makeAssignmentElement(name: ts.Identifier) { return name; } -} diff --git a/src/compiler/transformers/es2015.ts b/src/compiler/transformers/es2015.ts index bb16c4d64d3e5..e1151aa7d0524 100644 --- a/src/compiler/transformers/es2015.ts +++ b/src/compiler/transformers/es2015.ts @@ -1,5 +1,5 @@ -/*@internal*/ -namespace ts { +import * as ts from "../_namespaces/ts"; + const enum ES2015SubstitutionFlags { /** Enables substitutions for captured `this` */ CapturedThis = 1 << 0, @@ -262,6 +262,7 @@ function createSpreadSegment(kind: SpreadSegmentKind, expression: ts.Expression) return { kind, expression }; } +/** @internal */ export function transformES2015(context: ts.TransformationContext) { const { factory, @@ -4417,4 +4418,3 @@ export function transformES2015(context: ts.TransformationContext) { return ts.isIdentifier(expression) && expression.escapedText === "arguments"; } } -} diff --git a/src/compiler/transformers/es2016.ts b/src/compiler/transformers/es2016.ts index 1ba6562bdd831..5dc010cd02b7f 100644 --- a/src/compiler/transformers/es2016.ts +++ b/src/compiler/transformers/es2016.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export function transformES2016(context: ts.TransformationContext) { const { factory, @@ -102,4 +103,3 @@ export function transformES2016(context: ts.TransformationContext) { return ts.setTextRange(factory.createGlobalMethodCall("Math", "pow", [left, right]), node); } } -} diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index 78dae43de33b5..36b0738a4932a 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -1,5 +1,5 @@ -/*@internal*/ -namespace ts { +import * as ts from "../_namespaces/ts"; + type SuperContainer = ts.ClassDeclaration | ts.MethodDeclaration | ts.GetAccessorDeclaration | ts.SetAccessorDeclaration | ts.ConstructorDeclaration; const enum ES2017SubstitutionFlags { @@ -12,6 +12,7 @@ const enum ContextFlags { HasLexicalThis = 1 << 1 } +/** @internal */ export function transformES2017(context: ts.TransformationContext) { const { factory, @@ -801,6 +802,7 @@ export function transformES2017(context: ts.TransformationContext) { } } +/** @internal */ /** Creates a variable named `_super` with accessor properties for the given property names. */ export function createSuperAccessVariableStatement(factory: ts.NodeFactory, resolver: ts.EmitResolver, node: ts.FunctionLikeDeclaration, names: ts.Set) { // Create a variable declaration with a getter/setter (if binding) definition for each name: @@ -896,4 +898,3 @@ export function createSuperAccessVariableStatement(factory: ts.NodeFactory, reso ], ts.NodeFlags.Const)); } -} diff --git a/src/compiler/transformers/es2018.ts b/src/compiler/transformers/es2018.ts index 061238cdfde6f..783f0b21abd7d 100644 --- a/src/compiler/transformers/es2018.ts +++ b/src/compiler/transformers/es2018.ts @@ -1,5 +1,5 @@ -/*@internal*/ -namespace ts { +import * as ts from "../_namespaces/ts"; + const enum ESNextSubstitutionFlags { /** Enables substitutions for async methods with `super` calls. */ AsyncMethodsWithSuper = 1 << 0 @@ -37,6 +37,7 @@ const enum HierarchyFacts { IterationStatementExcludes = None, } +/** @internal */ export function transformES2018(context: ts.TransformationContext) { const { factory, @@ -1337,4 +1338,3 @@ export function transformES2018(context: ts.TransformationContext) { } } } -} diff --git a/src/compiler/transformers/es2019.ts b/src/compiler/transformers/es2019.ts index 0c8985f5ca442..7a6c9d7f4bbc0 100644 --- a/src/compiler/transformers/es2019.ts +++ b/src/compiler/transformers/es2019.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export function transformES2019(context: ts.TransformationContext) { const factory = context.factory; return ts.chainBundle(context, transformSourceFile); @@ -35,4 +36,3 @@ export function transformES2019(context: ts.TransformationContext) { return ts.visitEachChild(node, visitor, context); } } -} diff --git a/src/compiler/transformers/es2020.ts b/src/compiler/transformers/es2020.ts index f0cb7a069b7e6..811833d2ecb53 100644 --- a/src/compiler/transformers/es2020.ts +++ b/src/compiler/transformers/es2020.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export function transformES2020(context: ts.TransformationContext) { const { factory, @@ -219,4 +220,3 @@ export function transformES2020(context: ts.TransformationContext) { : factory.updateDeleteExpression(node, ts.visitNode(node.expression, visitor, ts.isExpression)); } } -} diff --git a/src/compiler/transformers/es2021.ts b/src/compiler/transformers/es2021.ts index 991f0a0abeaf6..d5f4edfc993a4 100644 --- a/src/compiler/transformers/es2021.ts +++ b/src/compiler/transformers/es2021.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export function transformES2021(context: ts.TransformationContext) { const { hoistVariableDeclaration, @@ -88,4 +89,3 @@ export function transformES2021(context: ts.TransformationContext) { ); } } -} diff --git a/src/compiler/transformers/es5.ts b/src/compiler/transformers/es5.ts index ced2da564486b..e84c4fb96bf61 100644 --- a/src/compiler/transformers/es5.ts +++ b/src/compiler/transformers/es5.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "../_namespaces/ts"; + +/** @internal */ /** * Transforms ES5 syntax into ES3 syntax. * @@ -119,4 +120,3 @@ export function transformES5(context: ts.TransformationContext) { return undefined; } } -} diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index 9096a02e30fab..26f27ddbe47f2 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export function transformESNext(context: ts.TransformationContext) { return ts.chainBundle(context, transformSourceFile); @@ -21,4 +22,3 @@ export function transformESNext(context: ts.TransformationContext) { } } } -} diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts index 7b2f595b4fd78..6d461b27e2907 100644 --- a/src/compiler/transformers/generators.ts +++ b/src/compiler/transformers/generators.ts @@ -1,3 +1,5 @@ +import * as ts from "../_namespaces/ts"; + // Transforms generator functions into a compatible ES5 representation with similar runtime // semantics. This is accomplished by first transforming the body of each generator // function into an intermediate representation that is the compiled into a JavaScript @@ -117,8 +119,6 @@ // .endtry | // .mark END | case END: -/*@internal*/ -namespace ts { type Label = number; const enum OpCode { @@ -228,6 +228,7 @@ function getInstructionName(instruction: Instruction): string { } } +/** @internal */ export function transformGenerators(context: ts.TransformationContext) { const { factory, @@ -3186,4 +3187,3 @@ export function transformGenerators(context: ts.TransformationContext) { ); } } -} diff --git a/src/compiler/transformers/jsx.ts b/src/compiler/transformers/jsx.ts index 9d605ff331c8c..00a3b768bd6c6 100644 --- a/src/compiler/transformers/jsx.ts +++ b/src/compiler/transformers/jsx.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export function transformJsx(context: ts.TransformationContext) { interface PerFileState { importSpecifier?: string; @@ -812,4 +813,3 @@ const entities = new ts.Map(ts.getEntries({ hearts: 0x2665, diams: 0x2666 })); -} diff --git a/src/compiler/transformers/legacyDecorators.ts b/src/compiler/transformers/legacyDecorators.ts index 93c5c71666a6a..20d9a900c3c52 100644 --- a/src/compiler/transformers/legacyDecorators.ts +++ b/src/compiler/transformers/legacyDecorators.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export function transformLegacyDecorators(context: ts.TransformationContext) { const { factory, @@ -706,5 +707,4 @@ export function transformLegacyDecorators(context: ts.TransformationContext) { return undefined; } -} } \ No newline at end of file diff --git a/src/compiler/transformers/module/esnextAnd2015.ts b/src/compiler/transformers/module/esnextAnd2015.ts index e64471bbb1ff9..d43dde7a23110 100644 --- a/src/compiler/transformers/module/esnextAnd2015.ts +++ b/src/compiler/transformers/module/esnextAnd2015.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "../../_namespaces/ts"; + +/** @internal */ export function transformECMAScriptModule(context: ts.TransformationContext) { const { factory, @@ -275,4 +276,3 @@ export function transformECMAScriptModule(context: ts.TransformationContext) { return substitution; } } -} diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts index fd9e8e21c2d54..cc0ac32615115 100644 --- a/src/compiler/transformers/module/module.ts +++ b/src/compiler/transformers/module/module.ts @@ -1,6 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "../../_namespaces/ts"; +/** @internal */ export function transformModule(context: ts.TransformationContext) { interface AsynchronousDependencies { aliasedModuleNames: ts.Expression[]; @@ -2001,4 +2001,3 @@ const dynamicImportUMDHelper: ts.EmitHelper = { text: ` var __syncRequire = typeof module === "object" && typeof module.exports === "object";` }; -} diff --git a/src/compiler/transformers/module/node.ts b/src/compiler/transformers/module/node.ts index 3f20b7a37845f..b599004365159 100644 --- a/src/compiler/transformers/module/node.ts +++ b/src/compiler/transformers/module/node.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "../../_namespaces/ts"; + +/** @internal */ export function transformNodeModule(context: ts.TransformationContext) { const previousOnSubstituteNode = context.onSubstituteNode; const previousOnEmitNode = context.onEmitNode; @@ -81,4 +82,3 @@ export function transformNodeModule(context: ts.TransformationContext) { return context.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends); } } -} diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts index 58a9e61fe96ea..7fe59cfc2a1f2 100644 --- a/src/compiler/transformers/module/system.ts +++ b/src/compiler/transformers/module/system.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "../../_namespaces/ts"; + +/** @internal */ export function transformSystemModule(context: ts.TransformationContext) { interface DependencyGroup { name: ts.StringLiteral; @@ -1942,4 +1943,3 @@ export function transformSystemModule(context: ts.TransformationContext) { return noSubstitution && node.id && noSubstitution[node.id]; } } -} diff --git a/src/compiler/transformers/taggedTemplate.ts b/src/compiler/transformers/taggedTemplate.ts index f14b1d39cc827..23bc4fb636a24 100644 --- a/src/compiler/transformers/taggedTemplate.ts +++ b/src/compiler/transformers/taggedTemplate.ts @@ -1,10 +1,12 @@ -/*@internal*/ -namespace ts { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export enum ProcessLevel { LiftRestriction, All } +/** @internal */ export function processTaggedTemplateExpression( context: ts.TransformationContext, node: ts.TaggedTemplateExpression, @@ -99,4 +101,3 @@ function getRawLiteral(node: ts.TemplateLiteralLikeNode, currentSourceFile: ts.S text = text.replace(/\r\n?/g, "\n"); return ts.setTextRange(ts.factory.createStringLiteral(text), node); } -} diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index a5e7b0030a0af..488bce2090f55 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -1,5 +1,5 @@ -/*@internal*/ -namespace ts { +import * as ts from "../_namespaces/ts"; + /** * Indicates whether to emit type metadata in the new format. */ @@ -29,6 +29,7 @@ const enum ClassFacts { IsExported = IsExportOfNamespace | IsDefaultExternalExport | IsNamedExternalExport, } +/** @internal */ export function transformTypeScript(context: ts.TransformationContext) { const { factory, @@ -2469,4 +2470,3 @@ export function transformTypeScript(context: ts.TransformationContext) { : resolver.isReferencedAliasDeclaration(node)); } } -} diff --git a/src/compiler/transformers/typeSerializer.ts b/src/compiler/transformers/typeSerializer.ts index 86ac6a3f53875..7f6bbb5188db4 100644 --- a/src/compiler/transformers/typeSerializer.ts +++ b/src/compiler/transformers/typeSerializer.ts @@ -1,5 +1,5 @@ -/*@internal*/ -namespace ts { +import * as ts from "../_namespaces/ts"; + type SerializedEntityName = | ts.Identifier // Globals (i.e., `String`, `Number`, etc.) | ts.PropertyAccessEntityNameExpression // `A.B` @@ -11,6 +11,7 @@ type SerializedTypeNode = | ts.VoidExpression // `void 0` used for null/undefined/never ; +/** @internal */ export interface RuntimeTypeSerializerContext { /** Specifies the current lexical block scope */ currentLexicalScope: ts.SourceFile | ts.Block | ts.ModuleBlock | ts.CaseBlock; @@ -18,6 +19,7 @@ export interface RuntimeTypeSerializerContext { currentNameScope: ts.ClassLikeDeclaration | undefined; } +/** @internal */ export interface RuntimeTypeSerializer { /** * Serializes a type node for use with decorator type metadata. @@ -55,6 +57,7 @@ export interface RuntimeTypeSerializer { serializeReturnTypeOfNode(serializerContext: RuntimeTypeSerializerContext, node: ts.Node): SerializedTypeNode; } +/** @internal */ export function createRuntimeTypeSerializer(context: ts.TransformationContext): RuntimeTypeSerializer { const { hoistVariableDeclaration @@ -565,5 +568,4 @@ export function createRuntimeTypeSerializer(context: ts.TransformationContext): getGlobalConstructorWithFallback(name) : ts.factory.createIdentifier(name); } -} } \ No newline at end of file diff --git a/src/compiler/transformers/utilities.ts b/src/compiler/transformers/utilities.ts index 2a4406399e581..71b4441e012a3 100644 --- a/src/compiler/transformers/utilities.ts +++ b/src/compiler/transformers/utilities.ts @@ -1,10 +1,12 @@ -/* @internal */ -namespace ts { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export function getOriginalNodeId(node: ts.Node) { node = ts.getOriginalNode(node); return node ? ts.getNodeId(node) : 0; } +/** @internal */ export interface ExternalModuleInfo { externalImports: (ts.ImportDeclaration | ts.ImportEqualsDeclaration | ts.ExportDeclaration)[]; // imports of other external modules externalHelpersImportDeclaration: ts.ImportDeclaration | undefined; // import of external helpers @@ -25,6 +27,7 @@ function isNamedDefaultReference(e: ts.ImportSpecifier): boolean { return e.propertyName !== undefined && e.propertyName.escapedText === ts.InternalSymbolName.Default; } +/** @internal */ export function chainBundle(context: ts.CoreTransformationContext, transformSourceFile: (x: ts.SourceFile) => ts.SourceFile): (x: ts.SourceFile | ts.Bundle) => ts.SourceFile | ts.Bundle { return transformSourceFileOrBundle; @@ -37,10 +40,12 @@ export function chainBundle(context: ts.CoreTransformationContext, transformSour } } +/** @internal */ export function getExportNeedsImportStarHelper(node: ts.ExportDeclaration): boolean { return !!ts.getNamespaceDeclarationNode(node); } +/** @internal */ export function getImportNeedsImportStarHelper(node: ts.ImportDeclaration): boolean { if (!!ts.getNamespaceDeclarationNode(node)) { return true; @@ -60,11 +65,13 @@ export function getImportNeedsImportStarHelper(node: ts.ImportDeclaration): bool return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node)); } +/** @internal */ export function getImportNeedsImportDefaultHelper(node: ts.ImportDeclaration): boolean { // Import default is needed if there's a default import or a default ref and no other refs (meaning an import star helper wasn't requested) return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings!) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217 } +/** @internal */ export function collectExternalModuleInfo(context: ts.TransformationContext, sourceFile: ts.SourceFile, resolver: ts.EmitResolver, compilerOptions: ts.CompilerOptions): ExternalModuleInfo { const externalImports: (ts.ImportDeclaration | ts.ImportEqualsDeclaration | ts.ExportDeclaration)[] = []; const exportSpecifiers = ts.createMultiMap(); @@ -251,6 +258,7 @@ function multiMapSparseArrayAdd(map: V[][], key: number, value: V): V[] { return values; } +/** @internal */ /** * Used in the module transformer to check if an expression is reasonably without sideeffect, * and thus better to copy into multiple places rather than to cache in a temporary variable @@ -263,6 +271,7 @@ export function isSimpleCopiableExpression(expression: ts.Expression) { ts.isIdentifier(expression); } +/** @internal */ /** * A simple inlinable expression is an expression which can be copied into multiple locations * without risk of repeating any sideeffects and whose value could not possibly change between @@ -272,11 +281,13 @@ export function isSimpleInlineableExpression(expression: ts.Expression) { return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression); } +/** @internal */ export function isCompoundAssignment(kind: ts.BinaryOperator): kind is ts.CompoundAssignmentOperator { return kind >= ts.SyntaxKind.FirstCompoundAssignment && kind <= ts.SyntaxKind.LastCompoundAssignment; } +/** @internal */ export function getNonAssignmentOperatorForCompoundAssignment(kind: ts.CompoundAssignmentOperator): ts.LogicalOperatorOrHigher | ts.SyntaxKind.QuestionQuestionToken { switch (kind) { case ts.SyntaxKind.PlusEqualsToken: return ts.SyntaxKind.PlusToken; @@ -298,6 +309,7 @@ export function getNonAssignmentOperatorForCompoundAssignment(kind: ts.CompoundA } } +/** @internal */ /** * @returns Contained super() call from descending into the statement ignoring parentheses, if that call exists. */ @@ -312,6 +324,7 @@ export function getSuperCallFromStatement(statement: ts.Statement) { : undefined; } +/** @internal */ /** * @returns The index (after prologue statements) of a super call, or -1 if not found. */ @@ -327,6 +340,7 @@ export function findSuperStatementIndex(statements: ts.NodeArray, return -1; } +/** @internal */ /** * Gets all the static or all the instance property declarations of a class * @@ -334,7 +348,9 @@ export function findSuperStatementIndex(statements: ts.NodeArray, * @param isStatic A value indicating whether to get properties from the static or instance side of the class. */ export function getProperties(node: ts.ClassExpression | ts.ClassDeclaration, requireInitializer: true, isStatic: boolean): readonly ts.InitializedPropertyDeclaration[]; +/** @internal */ export function getProperties(node: ts.ClassExpression | ts.ClassDeclaration, requireInitializer: boolean, isStatic: boolean): readonly ts.PropertyDeclaration[]; +/** @internal */ export function getProperties(node: ts.ClassExpression | ts.ClassDeclaration, requireInitializer: boolean, isStatic: boolean): readonly ts.PropertyDeclaration[] { return ts.filter(node.members, m => isInitializedOrStaticProperty(m, requireInitializer, isStatic)) as ts.PropertyDeclaration[]; } @@ -343,8 +359,11 @@ function isStaticPropertyDeclarationOrClassStaticBlockDeclaration(element: ts.Cl return isStaticPropertyDeclaration(element) || ts.isClassStaticBlockDeclaration(element); } +/** @internal */ export function getStaticPropertiesAndClassStaticBlock(node: ts.ClassExpression | ts.ClassDeclaration): readonly (ts.PropertyDeclaration | ts.ClassStaticBlockDeclaration)[]; +/** @internal */ export function getStaticPropertiesAndClassStaticBlock(node: ts.ClassExpression | ts.ClassDeclaration): readonly (ts.PropertyDeclaration | ts.ClassStaticBlockDeclaration)[]; +/** @internal */ export function getStaticPropertiesAndClassStaticBlock(node: ts.ClassExpression | ts.ClassDeclaration): readonly (ts.PropertyDeclaration | ts.ClassStaticBlockDeclaration)[] { return ts.filter(node.members, isStaticPropertyDeclarationOrClassStaticBlockDeclaration); } @@ -365,6 +384,7 @@ function isStaticPropertyDeclaration(member: ts.ClassElement) { return ts.isPropertyDeclaration(member) && ts.hasStaticModifier(member); } +/** @internal */ /** * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer. * @@ -376,6 +396,7 @@ export function isInitializedProperty(member: ts.ClassElement): member is ts.Pro && (member as ts.PropertyDeclaration).initializer !== undefined; } +/** @internal */ /** * Gets a value indicating whether a class element is a private instance method or accessor. * @@ -413,6 +434,7 @@ function getDecoratorsOfParameters(node: ts.FunctionLikeDeclaration | undefined) return decorators; } +/** @internal */ /** * Gets an AllDecorators object containing the decorators for the class and the decorators for the * parameters of the constructor of the class. @@ -432,6 +454,7 @@ export function getAllDecoratorsOfClass(node: ts.ClassLikeDeclaration): ts.AllDe }; } +/** @internal */ /** * Gets an AllDecorators object containing the decorators for the member and its parameters. * @@ -523,5 +546,3 @@ function getAllDecoratorsOfProperty(property: ts.PropertyDeclaration): ts.AllDec return { decorators }; } - -} diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 0a6faebcae255..591607ecfcecd 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export enum UpToDateStatusType { Unbuildable, UpToDate, @@ -34,6 +35,7 @@ export enum UpToDateStatusType { ForceBuild, } +/** @internal */ export type UpToDateStatus = | Status.Unbuildable | Status.UpToDate @@ -50,6 +52,7 @@ export type UpToDateStatus = | Status.ContainerOnly | Status.ForceBuild; +/** @internal */ export namespace Status { /** * The project can't be built at all in its current state. For example, @@ -165,11 +168,11 @@ export namespace Status { } } +/** @internal */ export function resolveConfigFileProjectName(project: string): ts.ResolvedConfigFileName { if (ts.fileExtensionIs(project, ts.Extension.Json)) { return project as ts.ResolvedConfigFileName; } return ts.combinePaths(project, "tsconfig.json") as ts.ResolvedConfigFileName; -} } \ No newline at end of file diff --git a/src/compiler/tsbuildPublic.ts b/src/compiler/tsbuildPublic.ts index 5019be73b9f02..61fc055ebbdcc 100644 --- a/src/compiler/tsbuildPublic.ts +++ b/src/compiler/tsbuildPublic.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + const minimumDate = new Date(-8640000000000000); const maximumDate = new Date(8640000000000000); @@ -2504,4 +2505,3 @@ function verboseReportProjectStatus(state: SolutionBuilderState, configFileName: reportUpToDateStatus(state, configFileName, status); } } -} diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index cc5b4749835fd..df2979bb397c3 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -1,7 +1,7 @@ { "extends": "../tsconfig-base", "compilerOptions": { - "outFile": "../../built/local/compiler.js", + "outDir": "../../built/local", "types": ["node"] }, @@ -80,6 +80,9 @@ "watch.ts", "watchPublic.ts", "tsbuild.ts", - "tsbuildPublic.ts" + "tsbuildPublic.ts", + "_namespaces/ts.ts", + "_namespaces/ts.moduleSpecifiers.ts", + "_namespaces/ts.performance.ts" ] } diff --git a/src/compiler/tsconfig.release.json b/src/compiler/tsconfig.release.json index 570c9fd875727..ecbc53d780375 100644 --- a/src/compiler/tsconfig.release.json +++ b/src/compiler/tsconfig.release.json @@ -1,7 +1,7 @@ { "extends": "./tsconfig.json", "compilerOptions": { - "outFile": "../../built/local/compiler.release.js", + "outDir": "../../built/local/release", "removeComments": true, "preserveConstEnums": false }, diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 1deb880863364..23a3012ad90b9 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + // branded string type used to store absolute, normalized and canonicalized paths // arbitrary file name can be converted to Path via toPath function export type Path = string & { __pathBrand: any }; @@ -9286,4 +9287,3 @@ export interface Queue { dequeue(): T; isEmpty(): boolean; } -} diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index f27d6c7c610d1..47fb0cc3d01c8 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1,12 +1,17 @@ -/* @internal */ -namespace ts { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export const resolvingEmptyArray: never[] = []; +/** @internal */ export const externalHelpersModuleNameText = "tslib"; +/** @internal */ export const defaultMaximumTruncationLength = 160; +/** @internal */ export const noTruncationMaximumTruncationLength = 1_000_000; +/** @internal */ export function getDeclarationOfKind(symbol: ts.Symbol, kind: T["kind"]): T | undefined { const declarations = symbol.declarations; if (declarations) { @@ -20,10 +25,12 @@ export function getDeclarationOfKind(symbol: ts.Symbol return undefined; } +/** @internal */ export function getDeclarationsOfKind(symbol: ts.Symbol, kind: T["kind"]): T[] { return ts.filter(symbol.declarations || ts.emptyArray, d => d.kind === kind) as T[]; } +/** @internal */ export function createSymbolTable(symbols?: readonly ts.Symbol[]): ts.SymbolTable { const result = new ts.Map(); if (symbols) { @@ -34,6 +41,7 @@ export function createSymbolTable(symbols?: readonly ts.Symbol[]): ts.SymbolTabl return result; } +/** @internal */ export function isTransientSymbol(symbol: ts.Symbol): symbol is ts.TransientSymbol { return (symbol.flags & ts.SymbolFlags.Transient) !== 0; } @@ -79,24 +87,29 @@ function createSingleLineStringWriter(): ts.EmitTextWriter { }; } +/** @internal */ export function changesAffectModuleResolution(oldOptions: ts.CompilerOptions, newOptions: ts.CompilerOptions): boolean { return oldOptions.configFilePath !== newOptions.configFilePath || optionsHaveModuleResolutionChanges(oldOptions, newOptions); } +/** @internal */ export function optionsHaveModuleResolutionChanges(oldOptions: ts.CompilerOptions, newOptions: ts.CompilerOptions) { return optionsHaveChanges(oldOptions, newOptions, ts.moduleResolutionOptionDeclarations); } +/** @internal */ export function changesAffectingProgramStructure(oldOptions: ts.CompilerOptions, newOptions: ts.CompilerOptions) { return optionsHaveChanges(oldOptions, newOptions, ts.optionsAffectingProgramStructure); } +/** @internal */ export function optionsHaveChanges(oldOptions: ts.CompilerOptions, newOptions: ts.CompilerOptions, optionDeclarations: readonly ts.CommandLineOption[]) { return oldOptions !== newOptions && optionDeclarations.some(o => !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o))); } +/** @internal */ export function forEachAncestor(node: ts.Node, callback: (n: ts.Node) => T | undefined | "quit"): T | undefined { while (true) { const res = callback(node); @@ -107,6 +120,7 @@ export function forEachAncestor(node: ts.Node, callback: (n: ts.Node) => T | } } +/** @internal */ /** * Calls `callback` for each entry in the map, returning the first truthy result. * Use `map.forEach` instead for normal iteration. @@ -123,6 +137,7 @@ export function forEachEntry(map: ts.ReadonlyESMap, callback: (va return undefined; } +/** @internal */ /** `forEachEntry` for just keys. */ export function forEachKey(map: ts.ReadonlyCollection, callback: (key: K) => T | undefined): T | undefined { const iterator = map.keys(); @@ -135,6 +150,7 @@ export function forEachKey(map: ts.ReadonlyCollection, callback: (key: return undefined; } +/** @internal */ /** Copy entries from `source` to `target`. */ export function copyEntries(source: ts.ReadonlyESMap, target: ts.ESMap): void { source.forEach((value, key) => { @@ -142,6 +158,7 @@ export function copyEntries(source: ts.ReadonlyESMap, target: ts.ESM }); } +/** @internal */ export function usingSingleLineStringWriter(action: (writer: ts.EmitTextWriter) => void): string { const oldString = stringWriter.getText(); try { @@ -154,14 +171,17 @@ export function usingSingleLineStringWriter(action: (writer: ts.EmitTextWriter) } } +/** @internal */ export function getFullWidth(node: ts.Node) { return node.end - node.pos; } +/** @internal */ export function getResolvedModule(sourceFile: ts.SourceFile | undefined, moduleNameText: string, mode: ts.ModuleKind.CommonJS | ts.ModuleKind.ESNext | undefined): ts.ResolvedModuleFull | undefined { return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText, mode); } +/** @internal */ export function setResolvedModule(sourceFile: ts.SourceFile, moduleNameText: string, resolvedModule: ts.ResolvedModuleFull | undefined, mode: ts.ModuleKind.CommonJS | ts.ModuleKind.ESNext | undefined): void { if (!sourceFile.resolvedModules) { sourceFile.resolvedModules = ts.createModeAwareCache(); @@ -170,6 +190,7 @@ export function setResolvedModule(sourceFile: ts.SourceFile, moduleNameText: str sourceFile.resolvedModules.set(moduleNameText, mode, resolvedModule); } +/** @internal */ export function setResolvedTypeReferenceDirective(sourceFile: ts.SourceFile, typeReferenceDirectiveName: string, resolvedTypeReferenceDirective?: ts.ResolvedTypeReferenceDirective): void { if (!sourceFile.resolvedTypeReferenceDirectiveNames) { sourceFile.resolvedTypeReferenceDirectiveNames = ts.createModeAwareCache(); @@ -178,12 +199,14 @@ export function setResolvedTypeReferenceDirective(sourceFile: ts.SourceFile, typ sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, /*mode*/ undefined, resolvedTypeReferenceDirective); } +/** @internal */ export function projectReferenceIsEqualTo(oldRef: ts.ProjectReference, newRef: ts.ProjectReference) { return oldRef.path === newRef.path && !oldRef.prepend === !newRef.prepend && !oldRef.circular === !newRef.circular; } +/** @internal */ export function moduleResolutionIsEqualTo(oldResolution: ts.ResolvedModuleFull, newResolution: ts.ResolvedModuleFull): boolean { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && @@ -196,20 +219,24 @@ function packageIdIsEqual(a: ts.PackageId | undefined, b: ts.PackageId | undefin return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } +/** @internal */ export function packageIdToPackageName({ name, subModuleName }: ts.PackageId): string { return subModuleName ? `${name}/${subModuleName}` : name; } +/** @internal */ export function packageIdToString(packageId: ts.PackageId): string { return `${packageIdToPackageName(packageId)}@${packageId.version}`; } +/** @internal */ export function typeDirectiveIsEqualTo(oldResolution: ts.ResolvedTypeReferenceDirective, newResolution: ts.ResolvedTypeReferenceDirective): boolean { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary && oldResolution.originalPath === newResolution.originalPath; } +/** @internal */ export function hasChangesInResolutions( names: readonly ts.StringLiteralLike[] | readonly ts.FileReference[], newSourceFile: ts.SourceFile, @@ -236,6 +263,7 @@ export function hasChangesInResolutions( } // Returns true if this node contains a parse error anywhere underneath it. +/** @internal */ export function containsParseError(node: ts.Node): boolean { aggregateChildData(node); return (node.flags & ts.NodeFlags.ThisNodeOrAnySubNodesHasError) !== 0; @@ -261,8 +289,11 @@ function aggregateChildData(node: ts.Node): void { } } +/** @internal */ export function getSourceFileOfNode(node: ts.Node): ts.SourceFile; +/** @internal */ export function getSourceFileOfNode(node: ts.Node | undefined): ts.SourceFile | undefined; +/** @internal */ export function getSourceFileOfNode(node: ts.Node): ts.SourceFile { while (node && node.kind !== ts.SyntaxKind.SourceFile) { node = node.parent; @@ -270,14 +301,17 @@ export function getSourceFileOfNode(node: ts.Node): ts.SourceFile { return node as ts.SourceFile; } +/** @internal */ export function getSourceFileOfModule(module: ts.Symbol) { return getSourceFileOfNode(module.valueDeclaration || getNonAugmentationDeclaration(module)); } +/** @internal */ export function isPlainJsFile(file: ts.SourceFile | undefined, checkJs: boolean | undefined): boolean { return !!file && (file.scriptKind === ts.ScriptKind.JS || file.scriptKind === ts.ScriptKind.JSX) && !file.checkJsDirective && checkJs === undefined; } +/** @internal */ export function isStatementWithLocals(node: ts.Node) { switch (node.kind) { case ts.SyntaxKind.Block: @@ -290,18 +324,21 @@ export function isStatementWithLocals(node: ts.Node) { return false; } +/** @internal */ export function getStartPositionOfLine(line: number, sourceFile: ts.SourceFileLike): number { ts.Debug.assert(line >= 0); return ts.getLineStarts(sourceFile)[line]; } // This is a useful function for debugging purposes. +/** @internal */ export function nodePosToString(node: ts.Node): string { const file = getSourceFileOfNode(node); const loc = ts.getLineAndCharacterOfPosition(file, node.pos); return `${file.fileName}(${loc.line + 1},${loc.character + 1})`; } +/** @internal */ export function getEndLinePosition(line: number, sourceFile: ts.SourceFileLike): number { ts.Debug.assert(line >= 0); const lineStarts = ts.getLineStarts(sourceFile); @@ -329,6 +366,7 @@ export function getEndLinePosition(line: number, sourceFile: ts.SourceFileLike): } } +/** @internal */ /** * Returns a value indicating whether a name is unique globally or within the current file. * Note: This does not consider whether a name appears as a free identifier or not, so at the expression `x.y` this includes both `x` and `y`. @@ -349,6 +387,7 @@ export function isFileLevelUniqueName(sourceFile: ts.SourceFile, name: string, h // code). So the parser will attempt to parse out a type, and will create an actual node. // However, this node will be 'missing' in the sense that no actual source-code/tokens are // contained within it. +/** @internal */ export function nodeIsMissing(node: ts.Node | undefined): boolean { if (node === undefined) { return true; @@ -357,6 +396,7 @@ export function nodeIsMissing(node: ts.Node | undefined): boolean { return node.pos === node.end && node.pos >= 0 && node.kind !== ts.SyntaxKind.EndOfFileToken; } +/** @internal */ export function nodeIsPresent(node: ts.Node | undefined): boolean { return !nodeIsMissing(node); } @@ -392,6 +432,7 @@ function isAnyPrologueDirective(node: ts.Node) { return isPrologueDirective(node) || !!(getEmitFlags(node) & ts.EmitFlags.CustomPrologue); } +/** @internal */ /** * Prepends statements to an array while taking care of prologue directives. */ @@ -399,10 +440,12 @@ export function insertStatementsAfterStandardPrologue(to return insertStatementsAfterPrologue(to, from, isPrologueDirective); } +/** @internal */ export function insertStatementsAfterCustomPrologue(to: T[], from: readonly T[] | undefined): T[] { return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective); } +/** @internal */ /** * Prepends statements to an array while taking care of prologue directives. */ @@ -410,10 +453,12 @@ export function insertStatementAfterStandardPrologue(to: return insertStatementAfterPrologue(to, statement, isPrologueDirective); } +/** @internal */ export function insertStatementAfterCustomPrologue(to: T[], statement: T | undefined): T[] { return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective); } +/** @internal */ /** * Determine if the given comment is a triple-slash * @@ -435,11 +480,13 @@ export function isRecognizedTripleSlashComment(text: string, commentPos: number, return false; } +/** @internal */ export function isPinnedComment(text: string, start: number) { return text.charCodeAt(start + 1) === ts.CharacterCodes.asterisk && text.charCodeAt(start + 2) === ts.CharacterCodes.exclamation; } +/** @internal */ export function createCommentDirectivesMap(sourceFile: ts.SourceFile, commentDirectives: ts.CommentDirective[]): ts.CommentDirectivesMap { const directivesByLine = new ts.Map( commentDirectives.map(commentDirective => ([ @@ -468,6 +515,7 @@ export function createCommentDirectivesMap(sourceFile: ts.SourceFile, commentDir } } +/** @internal */ export function getTokenPosOfNode(node: ts.Node, sourceFile?: ts.SourceFileLike, includeJsDoc?: boolean): number { // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* // want to skip trivia because this will launch us forward to the next token. @@ -500,6 +548,7 @@ export function getTokenPosOfNode(node: ts.Node, sourceFile?: ts.SourceFileLike, isInJSDoc(node)); } +/** @internal */ export function getNonDecoratorTokenPosOfNode(node: ts.Node, sourceFile?: ts.SourceFileLike): number { const lastDecorator = !nodeIsMissing(node) && ts.canHaveModifiers(node) ? ts.findLast(node.modifiers, ts.isDecorator) : undefined; if (!lastDecorator) { @@ -509,6 +558,7 @@ export function getNonDecoratorTokenPosOfNode(node: ts.Node, sourceFile?: ts.Sou return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, lastDecorator.end); } +/** @internal */ export function getSourceTextOfNodeFromSourceFile(sourceFile: ts.SourceFile, node: ts.Node, includeTrivia = false): string { return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia); } @@ -517,10 +567,12 @@ function isJSDocTypeExpressionOrChild(node: ts.Node): boolean { return !!ts.findAncestor(node, ts.isJSDocTypeExpression); } +/** @internal */ export function isExportNamespaceAsDefaultDeclaration(node: ts.Node): boolean { return !!(ts.isExportDeclaration(node) && node.exportClause && ts.isNamespaceExport(node.exportClause) && node.exportClause.name.escapedText === "default"); } +/** @internal */ export function getTextOfNodeFromSourceText(sourceText: string, node: ts.Node, includeTrivia = false): string { if (nodeIsMissing(node)) { return ""; @@ -536,6 +588,7 @@ export function getTextOfNodeFromSourceText(sourceText: string, node: ts.Node, i return text; } +/** @internal */ export function getTextOfNode(node: ts.Node, includeTrivia = false): string { return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia); } @@ -544,6 +597,7 @@ function getPos(range: ts.Node) { return range.pos; } +/** @internal */ /** * Note: it is expected that the `nodeArray` and the `node` are within the same file. * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work. @@ -552,6 +606,7 @@ export function indexOfNode(nodeArray: readonly ts.Node[], node: ts.Node) { return ts.binarySearch(nodeArray, node, getPos, ts.compareValues); } +/** @internal */ /** * Gets flags that control emit behavior of a node. */ @@ -564,6 +619,7 @@ interface ScriptTargetFeatures { [key: string]: { [key: string]: string[] | undefined }; } +/** @internal */ export function getScriptTargetFeatures(): ScriptTargetFeatures { return { es2015: { @@ -648,6 +704,7 @@ export function getScriptTargetFeatures(): ScriptTargetFeatures { }; } +/** @internal */ export const enum GetLiteralTextFlags { None = 0, NeverAsciiEscape = 1 << 0, @@ -656,6 +713,7 @@ export const enum GetLiteralTextFlags { AllowNumericSeparator = 1 << 3 } +/** @internal */ export function getLiteralText(node: ts.LiteralLikeNode, sourceFile: ts.SourceFile | undefined, flags: GetLiteralTextFlags) { // If we don't need to downlevel and we can reach the original source text using // the node's parent reference, then simply get the text as it was originally written. @@ -724,38 +782,46 @@ function canUseOriginalText(node: ts.LiteralLikeNode, flags: GetLiteralTextFlags return !ts.isBigIntLiteral(node); } +/** @internal */ export function getTextOfConstantValue(value: string | number) { return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value; } // Make an identifier from an external module name by extracting the string after the last "/" and replacing // all non-alphanumeric characters with underscores +/** @internal */ export function makeIdentifierFromModuleName(moduleName: string): string { return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_"); } +/** @internal */ export function isBlockOrCatchScoped(declaration: ts.Declaration) { return (ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.BlockScoped) !== 0 || isCatchClauseVariableDeclarationOrBindingElement(declaration); } +/** @internal */ export function isCatchClauseVariableDeclarationOrBindingElement(declaration: ts.Declaration) { const node = getRootDeclaration(declaration); return node.kind === ts.SyntaxKind.VariableDeclaration && node.parent.kind === ts.SyntaxKind.CatchClause; } +/** @internal */ export function isAmbientModule(node: ts.Node): node is ts.AmbientModuleDeclaration { return ts.isModuleDeclaration(node) && (node.name.kind === ts.SyntaxKind.StringLiteral || isGlobalScopeAugmentation(node)); } +/** @internal */ export function isModuleWithStringLiteralName(node: ts.Node): node is ts.ModuleDeclaration { return ts.isModuleDeclaration(node) && node.name.kind === ts.SyntaxKind.StringLiteral; } +/** @internal */ export function isNonGlobalAmbientModule(node: ts.Node): node is ts.ModuleDeclaration & { name: ts.StringLiteral } { return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name); } +/** @internal */ /** * An effective module (namespace) declaration is either * 1. An actual declaration: namespace X { ... } @@ -766,6 +832,7 @@ export function isEffectiveModuleDeclaration(node: ts.Node) { return ts.isModuleDeclaration(node) || ts.isIdentifier(node); } +/** @internal */ /** Given a symbol for a module, checks that it is a shorthand ambient module. */ export function isShorthandAmbientModuleSymbol(moduleSymbol: ts.Symbol): boolean { return isShorthandAmbientModule(moduleSymbol.valueDeclaration); @@ -776,20 +843,24 @@ function isShorthandAmbientModule(node: ts.Node | undefined): boolean { return !!node && node.kind === ts.SyntaxKind.ModuleDeclaration && (!(node as ts.ModuleDeclaration).body); } +/** @internal */ export function isBlockScopedContainerTopLevel(node: ts.Node): boolean { return node.kind === ts.SyntaxKind.SourceFile || node.kind === ts.SyntaxKind.ModuleDeclaration || ts.isFunctionLikeOrClassStaticBlockDeclaration(node); } +/** @internal */ export function isGlobalScopeAugmentation(module: ts.ModuleDeclaration): boolean { return !!(module.flags & ts.NodeFlags.GlobalAugmentation); } +/** @internal */ export function isExternalModuleAugmentation(node: ts.Node): node is ts.AmbientModuleDeclaration { return isAmbientModule(node) && isModuleAugmentationExternal(node); } +/** @internal */ export function isModuleAugmentationExternal(node: ts.AmbientModuleDeclaration) { // external module augmentation is a ambient module declaration that is either: // - defined in the top level scope and source file is an external module @@ -803,6 +874,7 @@ export function isModuleAugmentationExternal(node: ts.AmbientModuleDeclaration) return false; } +/** @internal */ export function getNonAugmentationDeclaration(symbol: ts.Symbol) { return symbol.declarations?.find(d => !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d))); } @@ -811,10 +883,12 @@ function isCommonJSContainingModuleKind(kind: ts.ModuleKind) { return kind === ts.ModuleKind.CommonJS || kind === ts.ModuleKind.Node16 || kind === ts.ModuleKind.NodeNext; } +/** @internal */ export function isEffectiveExternalModule(node: ts.SourceFile, compilerOptions: ts.CompilerOptions) { return ts.isExternalModule(node) || compilerOptions.isolatedModules || (isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator); } +/** @internal */ /** * Returns whether the source file will be treated as if it were in strict mode at runtime. */ @@ -852,10 +926,12 @@ export function isEffectiveStrictModeSourceFile(node: ts.SourceFile, compilerOpt return false; } +/** @internal */ export function isAmbientPropertyDeclaration(node: ts.PropertyDeclaration) { return !!(node.flags & ts.NodeFlags.Ambient) || hasSyntacticModifier(node, ts.ModifierFlags.Ambient); } +/** @internal */ export function isBlockScope(node: ts.Node, parentNode: ts.Node | undefined): boolean { switch (node.kind) { case ts.SyntaxKind.SourceFile: @@ -885,7 +961,9 @@ export function isBlockScope(node: ts.Node, parentNode: ts.Node | undefined): bo return false; } +/** @internal */ export function isDeclarationWithTypeParameters(node: ts.Node): node is ts.DeclarationWithTypeParameters; +/** @internal */ export function isDeclarationWithTypeParameters(node: ts.DeclarationWithTypeParameters): node is ts.DeclarationWithTypeParameters { switch (node.kind) { case ts.SyntaxKind.JSDocCallbackTag: @@ -898,7 +976,9 @@ export function isDeclarationWithTypeParameters(node: ts.DeclarationWithTypePara } } +/** @internal */ export function isDeclarationWithTypeParameterChildren(node: ts.Node): node is ts.DeclarationWithTypeParameterChildren; +/** @internal */ export function isDeclarationWithTypeParameterChildren(node: ts.DeclarationWithTypeParameterChildren): node is ts.DeclarationWithTypeParameterChildren { switch (node.kind) { case ts.SyntaxKind.CallSignature: @@ -927,6 +1007,7 @@ export function isDeclarationWithTypeParameterChildren(node: ts.DeclarationWithT } } +/** @internal */ export function isAnyImportSyntax(node: ts.Node): node is ts.AnyImportSyntax { switch (node.kind) { case ts.SyntaxKind.ImportDeclaration: @@ -937,10 +1018,12 @@ export function isAnyImportSyntax(node: ts.Node): node is ts.AnyImportSyntax { } } +/** @internal */ export function isAnyImportOrBareOrAccessedRequire(node: ts.Node): node is ts.AnyImportOrBareOrAccessedRequire { return isAnyImportSyntax(node) || isVariableDeclarationInitializedToBareOrAccessedRequire(node); } +/** @internal */ export function isLateVisibilityPaintedStatement(node: ts.Node): node is ts.LateVisibilityPaintedStatement { switch (node.kind) { case ts.SyntaxKind.ImportDeclaration: @@ -958,20 +1041,24 @@ export function isLateVisibilityPaintedStatement(node: ts.Node): node is ts.Late } } +/** @internal */ export function hasPossibleExternalModuleReference(node: ts.Node): node is ts.AnyImportOrReExport | ts.ModuleDeclaration | ts.ImportTypeNode | ts.ImportCall { return isAnyImportOrReExport(node) || ts.isModuleDeclaration(node) || ts.isImportTypeNode(node) || isImportCall(node); } +/** @internal */ export function isAnyImportOrReExport(node: ts.Node): node is ts.AnyImportOrReExport { return isAnyImportSyntax(node) || ts.isExportDeclaration(node); } // Gets the nearest enclosing block scope container that has the provided node // as a descendant, that is not the provided node. +/** @internal */ export function getEnclosingBlockScopeContainer(node: ts.Node): ts.Node { return ts.findAncestor(node.parent, current => isBlockScope(current, current.parent))!; } +/** @internal */ export function forEachEnclosingBlockScopeContainer(node: ts.Node, cb: (container: ts.Node) => void): void { let container = getEnclosingBlockScopeContainer(node); while (container) { @@ -983,18 +1070,22 @@ export function forEachEnclosingBlockScopeContainer(node: ts.Node, cb: (containe // Return display name of an identifier // Computed property names will just be emitted as "[]", where is the source // text of the expression in the computed property. +/** @internal */ export function declarationNameToString(name: ts.DeclarationName | ts.QualifiedName | undefined) { return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name); } +/** @internal */ export function getNameFromIndexInfo(info: ts.IndexInfo): string | undefined { return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined; } +/** @internal */ export function isComputedNonLiteralName(name: ts.PropertyName): boolean { return name.kind === ts.SyntaxKind.ComputedPropertyName && !isStringOrNumericLiteralLike(name.expression); } +/** @internal */ export function tryGetTextOfPropertyName(name: ts.PropertyName | ts.NoSubstitutionTemplateLiteral): ts.__String | undefined { switch (name.kind) { case ts.SyntaxKind.Identifier: @@ -1012,10 +1103,12 @@ export function tryGetTextOfPropertyName(name: ts.PropertyName | ts.NoSubstituti } } +/** @internal */ export function getTextOfPropertyName(name: ts.PropertyName | ts.NoSubstitutionTemplateLiteral): ts.__String { return ts.Debug.checkDefined(tryGetTextOfPropertyName(name)); } +/** @internal */ export function entityNameToString(name: ts.EntityNameOrEntityNameExpression | ts.JSDocMemberName | ts.JsxTagNameExpression | ts.PrivateIdentifier): string { switch (name.kind) { case ts.SyntaxKind.ThisKeyword: @@ -1039,21 +1132,25 @@ export function entityNameToString(name: ts.EntityNameOrEntityNameExpression | t } } +/** @internal */ export function createDiagnosticForNode(node: ts.Node, message: ts.DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number, arg3?: string | number): ts.DiagnosticWithLocation { const sourceFile = getSourceFileOfNode(node); return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3); } +/** @internal */ export function createDiagnosticForNodeArray(sourceFile: ts.SourceFile, nodes: ts.NodeArray, message: ts.DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number, arg3?: string | number): ts.DiagnosticWithLocation { const start = ts.skipTrivia(sourceFile.text, nodes.pos); return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3); } +/** @internal */ export function createDiagnosticForNodeInSourceFile(sourceFile: ts.SourceFile, node: ts.Node, message: ts.DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number, arg3?: string | number): ts.DiagnosticWithLocation { const span = getErrorSpanForNode(sourceFile, node); return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3); } +/** @internal */ export function createDiagnosticForNodeFromMessageChain(node: ts.Node, messageChain: ts.DiagnosticMessageChain, relatedInformation?: ts.DiagnosticRelatedInformation[]): ts.DiagnosticWithLocation { const sourceFile = getSourceFileOfNode(node); const span = getErrorSpanForNode(sourceFile, node); @@ -1070,6 +1167,7 @@ function assertDiagnosticLocation(file: ts.SourceFile | undefined, start: number } } +/** @internal */ export function createFileDiagnosticFromMessageChain(file: ts.SourceFile, start: number, length: number, messageChain: ts.DiagnosticMessageChain, relatedInformation?: ts.DiagnosticRelatedInformation[]): ts.DiagnosticWithLocation { assertDiagnosticLocation(file, start, length); return { @@ -1083,6 +1181,7 @@ export function createFileDiagnosticFromMessageChain(file: ts.SourceFile, start: }; } +/** @internal */ export function createDiagnosticForFileFromMessageChain(sourceFile: ts.SourceFile, messageChain: ts.DiagnosticMessageChain, relatedInformation?: ts.DiagnosticRelatedInformation[]): ts.DiagnosticWithLocation { return { file: sourceFile, @@ -1095,6 +1194,7 @@ export function createDiagnosticForFileFromMessageChain(sourceFile: ts.SourceFil }; } +/** @internal */ export function createDiagnosticMessageChainFromDiagnostic(diagnostic: ts.DiagnosticRelatedInformation): ts.DiagnosticMessageChain { return typeof diagnostic.messageText === "string" ? { code: diagnostic.code, @@ -1104,6 +1204,7 @@ export function createDiagnosticMessageChainFromDiagnostic(diagnostic: ts.Diagno } : diagnostic.messageText; } +/** @internal */ export function createDiagnosticForRange(sourceFile: ts.SourceFile, range: ts.TextRange, message: ts.DiagnosticMessage): ts.DiagnosticWithLocation { return { file: sourceFile, @@ -1115,6 +1216,7 @@ export function createDiagnosticForRange(sourceFile: ts.SourceFile, range: ts.Te }; } +/** @internal */ export function getSpanOfTokenAtPosition(sourceFile: ts.SourceFile, pos: number): ts.TextSpan { const scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos); scanner.scan(); @@ -1136,6 +1238,7 @@ function getErrorSpanForArrowFunction(sourceFile: ts.SourceFile, node: ts.ArrowF return ts.createTextSpanFromBounds(pos, node.end); } +/** @internal */ export function getErrorSpanForNode(sourceFile: ts.SourceFile, node: ts.Node): ts.TextSpan { let errorNode: ts.Node | undefined = node; switch (node.kind) { @@ -1202,58 +1305,71 @@ export function getErrorSpanForNode(sourceFile: ts.SourceFile, node: ts.Node): t return ts.createTextSpanFromBounds(pos, errorNode.end); } +/** @internal */ export function isExternalOrCommonJsModule(file: ts.SourceFile): boolean { return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined; } +/** @internal */ export function isJsonSourceFile(file: ts.SourceFile): file is ts.JsonSourceFile { return file.scriptKind === ts.ScriptKind.JSON; } +/** @internal */ export function isEnumConst(node: ts.EnumDeclaration): boolean { return !!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Const); } +/** @internal */ export function isDeclarationReadonly(declaration: ts.Declaration): boolean { return !!(ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Readonly && !ts.isParameterPropertyDeclaration(declaration, declaration.parent)); } +/** @internal */ export function isVarConst(node: ts.VariableDeclaration | ts.VariableDeclarationList): boolean { return !!(ts.getCombinedNodeFlags(node) & ts.NodeFlags.Const); } +/** @internal */ export function isLet(node: ts.Node): boolean { return !!(ts.getCombinedNodeFlags(node) & ts.NodeFlags.Let); } +/** @internal */ export function isSuperCall(n: ts.Node): n is ts.SuperCall { return n.kind === ts.SyntaxKind.CallExpression && (n as ts.CallExpression).expression.kind === ts.SyntaxKind.SuperKeyword; } +/** @internal */ export function isImportCall(n: ts.Node): n is ts.ImportCall { return n.kind === ts.SyntaxKind.CallExpression && (n as ts.CallExpression).expression.kind === ts.SyntaxKind.ImportKeyword; } +/** @internal */ export function isImportMeta(n: ts.Node): n is ts.ImportMetaProperty { return ts.isMetaProperty(n) && n.keywordToken === ts.SyntaxKind.ImportKeyword && n.name.escapedText === "meta"; } +/** @internal */ export function isLiteralImportTypeNode(n: ts.Node): n is ts.LiteralImportTypeNode { return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal); } +/** @internal */ export function isPrologueDirective(node: ts.Node): node is ts.PrologueDirective { return node.kind === ts.SyntaxKind.ExpressionStatement && (node as ts.ExpressionStatement).expression.kind === ts.SyntaxKind.StringLiteral; } +/** @internal */ export function isCustomPrologue(node: ts.Statement) { return !!(getEmitFlags(node) & ts.EmitFlags.CustomPrologue); } +/** @internal */ export function isHoistedFunction(node: ts.Statement) { return isCustomPrologue(node) && ts.isFunctionDeclaration(node); @@ -1264,16 +1380,19 @@ function isHoistedVariable(node: ts.VariableDeclaration) { && !node.initializer; } +/** @internal */ export function isHoistedVariableStatement(node: ts.Statement) { return isCustomPrologue(node) && ts.isVariableStatement(node) && ts.every(node.declarationList.declarations, isHoistedVariable); } +/** @internal */ export function getLeadingCommentRangesOfNode(node: ts.Node, sourceFileOfNode: ts.SourceFile) { return node.kind !== ts.SyntaxKind.JsxText ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined; } +/** @internal */ export function getJSDocCommentRanges(node: ts.Node, text: string) { const commentRanges = (node.kind === ts.SyntaxKind.Parameter || node.kind === ts.SyntaxKind.TypeParameter || @@ -1291,11 +1410,14 @@ export function getJSDocCommentRanges(node: ts.Node, text: string) { text.charCodeAt(comment.pos + 3) !== ts.CharacterCodes.slash); } +/** @internal */ export const fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*/; const fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*/; +/** @internal */ export const fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*/; const defaultLibReferenceRegEx = /^(\/\/\/\s*/; +/** @internal */ export function isPartOfTypeNode(node: ts.Node): boolean { if (ts.SyntaxKind.FirstTypeNode <= node.kind && node.kind <= ts.SyntaxKind.LastTypeNode) { return true; @@ -1394,6 +1516,7 @@ export function isPartOfTypeNode(node: ts.Node): boolean { return false; } +/** @internal */ export function isChildOfNodeWithKind(node: ts.Node, kind: ts.SyntaxKind): boolean { while (node) { if (node.kind === kind) { @@ -1406,6 +1529,7 @@ export function isChildOfNodeWithKind(node: ts.Node, kind: ts.SyntaxKind): boole // Warning: This has the same semantics as the forEach family of functions, // in that traversal terminates in the event that 'visitor' supplies a truthy value. +/** @internal */ export function forEachReturnStatement(body: ts.Block | ts.Statement, visitor: (stmt: ts.ReturnStatement) => T): T | undefined { return traverse(body); @@ -1434,6 +1558,7 @@ export function forEachReturnStatement(body: ts.Block | ts.Statement, visitor } } +/** @internal */ export function forEachYieldExpression(body: ts.Block, visitor: (expr: ts.YieldExpression) => void): void { return traverse(body); @@ -1472,6 +1597,7 @@ export function forEachYieldExpression(body: ts.Block, visitor: (expr: ts.YieldE } } +/** @internal */ /** * Gets the most likely element type for a TypeNode. This is not an exhaustive test * as it assumes a rest argument can only be an array type (either T[], or Array). @@ -1490,6 +1616,7 @@ export function getRestParameterElementType(node: ts.TypeNode | undefined) { } } +/** @internal */ export function getMembersOfDeclaration(node: ts.Declaration): ts.NodeArray | undefined { switch (node.kind) { case ts.SyntaxKind.InterfaceDeclaration: @@ -1502,6 +1629,7 @@ export function getMembersOfDeclaration(node: ts.Declaration): ts.NodeArray void): ts.Statement { while (true) { if (beforeUnwrapLabelCallback) { @@ -1571,28 +1706,34 @@ export function unwrapInnermostStatementOfLabel(node: ts.LabeledStatement, befor } } +/** @internal */ export function isFunctionBlock(node: ts.Node): boolean { return node && node.kind === ts.SyntaxKind.Block && ts.isFunctionLike(node.parent); } +/** @internal */ export function isObjectLiteralMethod(node: ts.Node): node is ts.MethodDeclaration { return node && node.kind === ts.SyntaxKind.MethodDeclaration && node.parent.kind === ts.SyntaxKind.ObjectLiteralExpression; } +/** @internal */ export function isObjectLiteralOrClassExpressionMethodOrAccessor(node: ts.Node): node is ts.MethodDeclaration { return (node.kind === ts.SyntaxKind.MethodDeclaration || node.kind === ts.SyntaxKind.GetAccessor || node.kind === ts.SyntaxKind.SetAccessor) && (node.parent.kind === ts.SyntaxKind.ObjectLiteralExpression || node.parent.kind === ts.SyntaxKind.ClassExpression); } +/** @internal */ export function isIdentifierTypePredicate(predicate: ts.TypePredicate): predicate is ts.IdentifierTypePredicate { return predicate && predicate.kind === ts.TypePredicateKind.Identifier; } +/** @internal */ export function isThisTypePredicate(predicate: ts.TypePredicate): predicate is ts.ThisTypePredicate { return predicate && predicate.kind === ts.TypePredicateKind.This; } +/** @internal */ export function getPropertyAssignment(objectLiteral: ts.ObjectLiteralExpression, key: string, key2?: string): readonly ts.PropertyAssignment[] { return objectLiteral.properties.filter((property): property is ts.PropertyAssignment => { if (property.kind === ts.SyntaxKind.PropertyAssignment) { @@ -1603,6 +1744,7 @@ export function getPropertyAssignment(objectLiteral: ts.ObjectLiteralExpression, }); } +/** @internal */ export function getPropertyArrayElementValue(objectLiteral: ts.ObjectLiteralExpression, propKey: string, elementValue: string): ts.StringLiteral | undefined { return ts.firstDefined(getPropertyAssignment(objectLiteral, propKey), property => ts.isArrayLiteralExpression(property.initializer) ? @@ -1610,6 +1752,7 @@ export function getPropertyArrayElementValue(objectLiteral: ts.ObjectLiteralExpr undefined); } +/** @internal */ export function getTsConfigObjectLiteralExpression(tsConfigSourceFile: ts.TsConfigSourceFile | undefined): ts.ObjectLiteralExpression | undefined { if (tsConfigSourceFile && tsConfigSourceFile.statements.length) { const expression = tsConfigSourceFile.statements[0].expression; @@ -1617,6 +1760,7 @@ export function getTsConfigObjectLiteralExpression(tsConfigSourceFile: ts.TsConf } } +/** @internal */ export function getTsConfigPropArrayElementValue(tsConfigSourceFile: ts.TsConfigSourceFile | undefined, propKey: string, elementValue: string): ts.StringLiteral | undefined { return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), property => ts.isArrayLiteralExpression(property.initializer) ? @@ -1624,23 +1768,28 @@ export function getTsConfigPropArrayElementValue(tsConfigSourceFile: ts.TsConfig undefined); } +/** @internal */ export function getTsConfigPropArray(tsConfigSourceFile: ts.TsConfigSourceFile | undefined, propKey: string): readonly ts.PropertyAssignment[] { const jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile); return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray; } +/** @internal */ export function getContainingFunction(node: ts.Node): ts.SignatureDeclaration | undefined { return ts.findAncestor(node.parent, ts.isFunctionLike); } +/** @internal */ export function getContainingFunctionDeclaration(node: ts.Node): ts.FunctionLikeDeclaration | undefined { return ts.findAncestor(node.parent, ts.isFunctionLikeDeclaration); } +/** @internal */ export function getContainingClass(node: ts.Node): ts.ClassLikeDeclaration | undefined { return ts.findAncestor(node.parent, ts.isClassLike); } +/** @internal */ export function getContainingClassStaticBlock(node: ts.Node): ts.Node | undefined { return ts.findAncestor(node.parent, n => { if (ts.isClassLike(n) || ts.isFunctionLike(n)) { @@ -1650,10 +1799,12 @@ export function getContainingClassStaticBlock(node: ts.Node): ts.Node | undefine }); } +/** @internal */ export function getContainingFunctionOrClassStaticBlock(node: ts.Node): ts.SignatureDeclaration | ts.ClassStaticBlockDeclaration | undefined { return ts.findAncestor(node.parent, ts.isFunctionLikeOrClassStaticBlockDeclaration); } +/** @internal */ export function getThisContainer(node: ts.Node, includeArrowFunctions: boolean): ts.Node { ts.Debug.assert(node.kind !== ts.SyntaxKind.SourceFile); while (true) { @@ -1717,6 +1868,7 @@ export function getThisContainer(node: ts.Node, includeArrowFunctions: boolean): } } +/** @internal */ /** * @returns Whether the node creates a new 'this' scope for its children. */ @@ -1745,6 +1897,7 @@ export function isThisContainerOrFunctionBlock(node: ts.Node): boolean { } } +/** @internal */ export function isInTopLevelContext(node: ts.Node) { // The name of a class or function declaration is a BindingIdentifier in its surrounding scope. if (ts.isIdentifier(node) && (ts.isClassDeclaration(node.parent) || ts.isFunctionDeclaration(node.parent)) && node.parent.name === node) { @@ -1754,6 +1907,7 @@ export function isInTopLevelContext(node: ts.Node) { return ts.isSourceFile(container); } +/** @internal */ export function getNewTargetContainer(node: ts.Node) { const container = getThisContainer(node, /*includeArrowFunctions*/ false); if (container) { @@ -1768,6 +1922,7 @@ export function getNewTargetContainer(node: ts.Node) { return undefined; } +/** @internal */ /** * Given an super call/property node, returns the closest node where * - a super call/property access is legal in the node and not legal in the parent node the node. @@ -1820,6 +1975,7 @@ export function getSuperContainer(node: ts.Node, stopOnFunctions: boolean): ts.N } } +/** @internal */ export function getImmediatelyInvokedFunctionExpression(func: ts.Node): ts.CallExpression | undefined { if (func.kind === ts.SyntaxKind.FunctionExpression || func.kind === ts.SyntaxKind.ArrowFunction) { let prev = func; @@ -1834,11 +1990,13 @@ export function getImmediatelyInvokedFunctionExpression(func: ts.Node): ts.CallE } } +/** @internal */ export function isSuperOrSuperProperty(node: ts.Node): node is ts.SuperExpression | ts.SuperProperty { return node.kind === ts.SyntaxKind.SuperKeyword || isSuperProperty(node); } +/** @internal */ /** * Determines whether a node is a property or element access expression for `super`. */ @@ -1848,6 +2006,7 @@ export function isSuperProperty(node: ts.Node): node is ts.SuperProperty { && (node as ts.PropertyAccessExpression | ts.ElementAccessExpression).expression.kind === ts.SyntaxKind.SuperKeyword; } +/** @internal */ /** * Determines whether a node is a property or element access expression for `this`. */ @@ -1857,10 +2016,12 @@ export function isThisProperty(node: ts.Node): boolean { && (node as ts.PropertyAccessExpression | ts.ElementAccessExpression).expression.kind === ts.SyntaxKind.ThisKeyword; } +/** @internal */ export function isThisInitializedDeclaration(node: ts.Node | undefined): boolean { return !!node && ts.isVariableDeclaration(node) && node.initializer?.kind === ts.SyntaxKind.ThisKeyword; } +/** @internal */ export function isThisInitializedObjectBindingExpression(node: ts.Node | undefined): boolean { return !!node && (ts.isShorthandPropertyAssignment(node) || ts.isPropertyAssignment(node)) @@ -1869,6 +2030,7 @@ export function isThisInitializedObjectBindingExpression(node: ts.Node | undefin && node.parent.parent.right.kind === ts.SyntaxKind.ThisKeyword; } +/** @internal */ export function getEntityNameFromTypeNode(node: ts.TypeNode): ts.EntityNameOrEntityNameExpression | undefined { switch (node.kind) { case ts.SyntaxKind.TypeReference: @@ -1888,6 +2050,7 @@ export function getEntityNameFromTypeNode(node: ts.TypeNode): ts.EntityNameOrEnt return undefined; } +/** @internal */ export function getInvokedExpression(node: ts.CallLikeExpression): ts.Expression { switch (node.kind) { case ts.SyntaxKind.TaggedTemplateExpression: @@ -1900,9 +2063,13 @@ export function getInvokedExpression(node: ts.CallLikeExpression): ts.Expression } } +/** @internal */ export function nodeCanBeDecorated(node: ts.ClassDeclaration): true; +/** @internal */ export function nodeCanBeDecorated(node: ts.ClassElement, parent: ts.Node): boolean; +/** @internal */ export function nodeCanBeDecorated(node: ts.Node, parent: ts.Node, grandparent: ts.Node): boolean; +/** @internal */ export function nodeCanBeDecorated(node: ts.Node, parent?: ts.Node, grandparent?: ts.Node): boolean { // private names cannot be used with decorators yet if (ts.isNamedDeclaration(node) && ts.isPrivateIdentifier(node.name)) { @@ -1936,23 +2103,34 @@ export function nodeCanBeDecorated(node: ts.Node, parent?: ts.Node, grandparent? return false; } +/** @internal */ export function nodeIsDecorated(node: ts.ClassDeclaration): boolean; +/** @internal */ export function nodeIsDecorated(node: ts.ClassElement, parent: ts.Node): boolean; +/** @internal */ export function nodeIsDecorated(node: ts.Node, parent: ts.Node, grandparent: ts.Node): boolean; +/** @internal */ export function nodeIsDecorated(node: ts.Node, parent?: ts.Node, grandparent?: ts.Node): boolean { return hasDecorators(node) && nodeCanBeDecorated(node, parent!, grandparent!); // TODO: GH#18217 } +/** @internal */ export function nodeOrChildIsDecorated(node: ts.ClassDeclaration): boolean; +/** @internal */ export function nodeOrChildIsDecorated(node: ts.ClassElement, parent: ts.Node): boolean; +/** @internal */ export function nodeOrChildIsDecorated(node: ts.Node, parent: ts.Node, grandparent: ts.Node): boolean; +/** @internal */ export function nodeOrChildIsDecorated(node: ts.Node, parent?: ts.Node, grandparent?: ts.Node): boolean { return nodeIsDecorated(node, parent!, grandparent!) || childIsDecorated(node, parent!); // TODO: GH#18217 } +/** @internal */ export function childIsDecorated(node: ts.ClassDeclaration): boolean; +/** @internal */ export function childIsDecorated(node: ts.Node, parent: ts.Node): boolean; +/** @internal */ export function childIsDecorated(node: ts.Node, parent?: ts.Node): boolean { switch (node.kind) { case ts.SyntaxKind.ClassDeclaration: @@ -1966,12 +2144,14 @@ export function childIsDecorated(node: ts.Node, parent?: ts.Node): boolean { } } +/** @internal */ export function classOrConstructorParameterIsDecorated(node: ts.ClassDeclaration): boolean { if (nodeIsDecorated(node)) return true; const constructor = getFirstConstructorWithBody(node); return !!constructor && childIsDecorated(constructor, node); } +/** @internal */ export function isJSXTagName(node: ts.Node) { const { parent } = node; if (parent.kind === ts.SyntaxKind.JsxOpeningElement || @@ -1982,6 +2162,7 @@ export function isJSXTagName(node: ts.Node) { return false; } +/** @internal */ export function isExpressionNode(node: ts.Node): boolean { switch (node.kind) { case ts.SyntaxKind.SuperKeyword: @@ -2052,6 +2233,7 @@ export function isExpressionNode(node: ts.Node): boolean { } } +/** @internal */ export function isInExpressionContext(node: ts.Node): boolean { const { parent } = node; switch (parent.kind) { @@ -2106,6 +2288,7 @@ export function isInExpressionContext(node: ts.Node): boolean { } } +/** @internal */ export function isPartOfTypeQuery(node: ts.Node) { while (node.kind === ts.SyntaxKind.QualifiedName || node.kind === ts.SyntaxKind.Identifier) { node = node.parent; @@ -2113,51 +2296,63 @@ export function isPartOfTypeQuery(node: ts.Node) { return node.kind === ts.SyntaxKind.TypeQuery; } +/** @internal */ export function isNamespaceReexportDeclaration(node: ts.Node): boolean { return ts.isNamespaceExport(node) && !!node.parent.moduleSpecifier; } +/** @internal */ export function isExternalModuleImportEqualsDeclaration(node: ts.Node): node is ts.ImportEqualsDeclaration & { moduleReference: ts.ExternalModuleReference } { return node.kind === ts.SyntaxKind.ImportEqualsDeclaration && (node as ts.ImportEqualsDeclaration).moduleReference.kind === ts.SyntaxKind.ExternalModuleReference; } +/** @internal */ export function getExternalModuleImportEqualsDeclarationExpression(node: ts.Node) { ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node)); return ((node as ts.ImportEqualsDeclaration).moduleReference as ts.ExternalModuleReference).expression; } +/** @internal */ export function getExternalModuleRequireArgument(node: ts.Node) { return isVariableDeclarationInitializedToBareOrAccessedRequire(node) && (getLeftmostAccessExpression(node.initializer) as ts.CallExpression).arguments[0] as ts.StringLiteral; } +/** @internal */ export function isInternalModuleImportEqualsDeclaration(node: ts.Node): node is ts.ImportEqualsDeclaration { return node.kind === ts.SyntaxKind.ImportEqualsDeclaration && (node as ts.ImportEqualsDeclaration).moduleReference.kind !== ts.SyntaxKind.ExternalModuleReference; } +/** @internal */ export function isSourceFileJS(file: ts.SourceFile): boolean { return isInJSFile(file); } +/** @internal */ export function isSourceFileNotJS(file: ts.SourceFile): boolean { return !isInJSFile(file); } +/** @internal */ export function isInJSFile(node: ts.Node | undefined): boolean { return !!node && !!(node.flags & ts.NodeFlags.JavaScriptFile); } +/** @internal */ export function isInJsonFile(node: ts.Node | undefined): boolean { return !!node && !!(node.flags & ts.NodeFlags.JsonFile); } +/** @internal */ export function isSourceFileNotJson(file: ts.SourceFile) { return !isJsonSourceFile(file); } +/** @internal */ export function isInJSDoc(node: ts.Node | undefined): boolean { return !!node && !!(node.flags & ts.NodeFlags.JSDoc); } +/** @internal */ export function isJSDocIndexSignature(node: ts.TypeReferenceNode | ts.ExpressionWithTypeArguments) { return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && @@ -2166,13 +2361,16 @@ export function isJSDocIndexSignature(node: ts.TypeReferenceNode | ts.Expression (node.typeArguments[0].kind === ts.SyntaxKind.StringKeyword || node.typeArguments[0].kind === ts.SyntaxKind.NumberKeyword); } +/** @internal */ /** * Returns true if the node is a CallExpression to the identifier 'require' with * exactly one argument (of the form 'require("name")'). * This function does not test if the node is in a JavaScript file or not. */ export function isRequireCall(callExpression: ts.Node, requireStringLiteralLikeArgument: true): callExpression is ts.RequireOrImportCall & { expression: ts.Identifier, arguments: [ts.StringLiteralLike] }; +/** @internal */ export function isRequireCall(callExpression: ts.Node, requireStringLiteralLikeArgument: boolean): callExpression is ts.CallExpression; +/** @internal */ export function isRequireCall(callExpression: ts.Node, requireStringLiteralLikeArgument: boolean): callExpression is ts.CallExpression { if (callExpression.kind !== ts.SyntaxKind.CallExpression) { return false; @@ -2190,6 +2388,7 @@ export function isRequireCall(callExpression: ts.Node, requireStringLiteralLikeA return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } +/** @internal */ /** * Returns true if the node is a VariableDeclaration initialized to a require call (see `isRequireCall`). * This function does not test if the node is in a JavaScript file or not. @@ -2198,6 +2397,7 @@ export function isVariableDeclarationInitializedToRequire(node: ts.Node): node i return isVariableDeclarationInitializedWithRequireHelper(node, /*allowAccessedRequire*/ false); } +/** @internal */ /** * Like {@link isVariableDeclarationInitializedToRequire} but allows things like `require("...").foo.bar` or `require("...")["baz"]`. */ @@ -2211,24 +2411,29 @@ function isVariableDeclarationInitializedWithRequireHelper(node: ts.Node, allowA isRequireCall(allowAccessedRequire ? getLeftmostAccessExpression(node.initializer) : node.initializer, /*requireStringLiteralLikeArgument*/ true); } +/** @internal */ export function isRequireVariableStatement(node: ts.Node): node is ts.RequireVariableStatement { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && ts.every(node.declarationList.declarations, decl => isVariableDeclarationInitializedToRequire(decl)); } +/** @internal */ export function isSingleOrDoubleQuote(charCode: number) { return charCode === ts.CharacterCodes.singleQuote || charCode === ts.CharacterCodes.doubleQuote; } +/** @internal */ export function isStringDoubleQuoted(str: ts.StringLiteralLike, sourceFile: ts.SourceFile): boolean { return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === ts.CharacterCodes.doubleQuote; } +/** @internal */ export function isAssignmentDeclaration(decl: ts.Declaration) { return ts.isBinaryExpression(decl) || isAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl); } +/** @internal */ /** Get the initializer, taking into account defaulted Javascript initializers */ export function getEffectiveInitializer(node: ts.HasExpressionInitializer) { if (isInJSFile(node) && node.initializer && @@ -2240,6 +2445,7 @@ export function getEffectiveInitializer(node: ts.HasExpressionInitializer) { return node.initializer; } +/** @internal */ /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ export function getDeclaredExpandoInitializer(node: ts.HasExpressionInitializer) { const init = getEffectiveInitializer(node); @@ -2255,6 +2461,7 @@ function hasExpandoValueProperty(node: ts.ObjectLiteralExpression, isPrototypeAs getExpandoInitializer(p.initializer, isPrototypeAssignment)); } +/** @internal */ /** * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initializers as declarations. @@ -2273,6 +2480,7 @@ export function getAssignedExpandoInitializer(node: ts.Node | undefined): ts.Exp } } +/** @internal */ /** * Recognized expando initializers are: * 1. (function() {})() -- IIFEs @@ -2315,6 +2523,7 @@ function getDefaultedExpandoInitializer(name: ts.Expression, initializer: ts.Exp } } +/** @internal */ export function isDefaultedExpandoInitializer(node: ts.BinaryExpression) { const name = ts.isVariableDeclaration(node.parent) ? node.parent.name : ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken ? node.parent.left : @@ -2322,6 +2531,7 @@ export function isDefaultedExpandoInitializer(node: ts.BinaryExpression) { return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } +/** @internal */ /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ export function getNameOfExpando(node: ts.Declaration): ts.DeclarationName | undefined { if (ts.isBinaryExpression(node.parent)) { @@ -2335,6 +2545,7 @@ export function getNameOfExpando(node: ts.Declaration): ts.DeclarationName | und } } +/** @internal */ /** * Is the 'declared' name the same as the one in the initializer? * @return true for identical entity names, as well as ones where the initializer is prefixed with @@ -2363,6 +2574,7 @@ export function isSameEntityName(name: ts.Expression, initializer: ts.Expression return false; } +/** @internal */ export function getRightMostAssignedExpression(node: ts.Expression): ts.Expression { while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) { node = node.right; @@ -2370,14 +2582,17 @@ export function getRightMostAssignedExpression(node: ts.Expression): ts.Expressi return node; } +/** @internal */ export function isExportsIdentifier(node: ts.Node) { return ts.isIdentifier(node) && node.escapedText === "exports"; } +/** @internal */ export function isModuleIdentifier(node: ts.Node) { return ts.isIdentifier(node) && node.escapedText === "module"; } +/** @internal */ export function isModuleExportsAccessExpression(node: ts.Node): node is ts.LiteralLikeElementAccessExpression & { expression: ts.Identifier } { return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node)) && isModuleIdentifier(node.expression) @@ -2386,11 +2601,13 @@ export function isModuleExportsAccessExpression(node: ts.Node): node is ts.Liter /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder +/** @internal */ export function getAssignmentDeclarationKind(expr: ts.BinaryExpression | ts.CallExpression): ts.AssignmentDeclarationKind { const special = getAssignmentDeclarationKindWorker(expr); return special === ts.AssignmentDeclarationKind.Property || isInJSFile(expr) ? special : ts.AssignmentDeclarationKind.None; } +/** @internal */ export function isBindableObjectDefinePropertyCall(expr: ts.CallExpression): expr is ts.BindableObjectDefinePropertyCall { return ts.length(expr.arguments) === 3 && ts.isPropertyAccessExpression(expr.expression) && @@ -2401,22 +2618,26 @@ export function isBindableObjectDefinePropertyCall(expr: ts.CallExpression): exp isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true); } +/** @internal */ /** x.y OR x[0] */ export function isLiteralLikeAccess(node: ts.Node): node is ts.LiteralLikeElementAccessExpression | ts.PropertyAccessExpression { return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node); } +/** @internal */ /** x[0] OR x['a'] OR x[Symbol.y] */ export function isLiteralLikeElementAccess(node: ts.Node): node is ts.LiteralLikeElementAccessExpression { return ts.isElementAccessExpression(node) && isStringOrNumericLiteralLike(node.argumentExpression); } +/** @internal */ /** Any series of property and element accesses. */ export function isBindableStaticAccessExpression(node: ts.Node, excludeThisKeyword?: boolean): node is ts.BindableStaticAccessExpression { return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === ts.SyntaxKind.ThisKeyword || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true)) || isBindableStaticElementAccessExpression(node, excludeThisKeyword); } +/** @internal */ /** Any series of property and element accesses, ending in a literal element access */ export function isBindableStaticElementAccessExpression(node: ts.Node, excludeThisKeyword?: boolean): node is ts.BindableStaticElementAccessExpression { return isLiteralLikeElementAccess(node) @@ -2425,10 +2646,12 @@ export function isBindableStaticElementAccessExpression(node: ts.Node, excludeTh isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true)); } +/** @internal */ export function isBindableStaticNameExpression(node: ts.Node, excludeThisKeyword?: boolean): node is ts.BindableStaticNameExpression { return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword); } +/** @internal */ export function getNameOrArgument(expr: ts.PropertyAccessExpression | ts.LiteralLikeElementAccessExpression) { if (ts.isPropertyAccessExpression(expr)) { return expr.name; @@ -2482,7 +2705,9 @@ export function getElementOrPropertyAccessArgumentExpressionOrName(node: ts.Acce /* @internal */ export function getElementOrPropertyAccessName(node: ts.LiteralLikeElementAccessExpression | ts.PropertyAccessExpression): ts.__String; +/** @internal */ export function getElementOrPropertyAccessName(node: ts.AccessExpression): ts.__String | undefined; +/** @internal */ export function getElementOrPropertyAccessName(node: ts.AccessExpression): ts.__String | undefined { const name = getElementOrPropertyAccessArgumentExpressionOrName(node); if (name) { @@ -2496,6 +2721,7 @@ export function getElementOrPropertyAccessName(node: ts.AccessExpression): ts.__ return undefined; } +/** @internal */ export function getAssignmentDeclarationPropertyAccessKind(lhs: ts.AccessExpression): ts.AssignmentDeclarationKind { if (lhs.expression.kind === ts.SyntaxKind.ThisKeyword) { return ts.AssignmentDeclarationKind.ThisProperty; @@ -2531,6 +2757,7 @@ export function getAssignmentDeclarationPropertyAccessKind(lhs: ts.AccessExpress return ts.AssignmentDeclarationKind.None; } +/** @internal */ export function getInitializerOfBinaryExpression(expr: ts.BinaryExpression) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -2538,10 +2765,12 @@ export function getInitializerOfBinaryExpression(expr: ts.BinaryExpression) { return expr.right; } +/** @internal */ export function isPrototypePropertyAssignment(node: ts.Node): node is ts.BinaryExpression { return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === ts.AssignmentDeclarationKind.PrototypeProperty; } +/** @internal */ export function isSpecialPropertyDeclaration(expr: ts.PropertyAccessExpression | ts.ElementAccessExpression): expr is ts.PropertyAccessExpression | ts.LiteralLikeElementAccessExpression { return isInJSFile(expr) && expr.parent && expr.parent.kind === ts.SyntaxKind.ExpressionStatement && @@ -2549,6 +2778,7 @@ export function isSpecialPropertyDeclaration(expr: ts.PropertyAccessExpression | !!ts.getJSDocTypeTag(expr.parent); } +/** @internal */ export function setValueDeclaration(symbol: ts.Symbol, node: ts.Declaration): void { const { valueDeclaration } = symbol; if (!valueDeclaration || @@ -2560,6 +2790,7 @@ export function setValueDeclaration(symbol: ts.Symbol, node: ts.Declaration): vo } } +/** @internal */ export function isFunctionSymbol(symbol: ts.Symbol | undefined) { if (!symbol || !symbol.valueDeclaration) { return false; @@ -2568,6 +2799,7 @@ export function isFunctionSymbol(symbol: ts.Symbol | undefined) { return decl.kind === ts.SyntaxKind.FunctionDeclaration || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer); } +/** @internal */ export function tryGetModuleSpecifierFromDeclaration(node: ts.AnyImportOrBareOrAccessedRequire): ts.StringLiteralLike | undefined { switch (node.kind) { case ts.SyntaxKind.VariableDeclaration: @@ -2581,10 +2813,12 @@ export function tryGetModuleSpecifierFromDeclaration(node: ts.AnyImportOrBareOrA } } +/** @internal */ export function importFromModuleSpecifier(node: ts.StringLiteralLike): ts.AnyValidImportOrReExport { return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent); } +/** @internal */ export function tryGetImportFromModuleSpecifier(node: ts.StringLiteralLike): ts.AnyValidImportOrReExport | undefined { switch (node.parent.kind) { case ts.SyntaxKind.ImportDeclaration: @@ -2602,6 +2836,7 @@ export function tryGetImportFromModuleSpecifier(node: ts.StringLiteralLike): ts. } } +/** @internal */ export function getExternalModuleName(node: ts.AnyImportOrReExport | ts.ImportTypeNode | ts.ImportCall | ts.ModuleDeclaration): ts.Expression | undefined { switch (node.kind) { case ts.SyntaxKind.ImportDeclaration: @@ -2620,6 +2855,7 @@ export function getExternalModuleName(node: ts.AnyImportOrReExport | ts.ImportTy } } +/** @internal */ export function getNamespaceDeclarationNode(node: ts.ImportDeclaration | ts.ImportEqualsDeclaration | ts.ExportDeclaration): ts.ImportEqualsDeclaration | ts.NamespaceImport | ts.NamespaceExport | undefined { switch (node.kind) { case ts.SyntaxKind.ImportDeclaration: @@ -2633,10 +2869,12 @@ export function getNamespaceDeclarationNode(node: ts.ImportDeclaration | ts.Impo } } +/** @internal */ export function isDefaultImport(node: ts.ImportDeclaration | ts.ImportEqualsDeclaration | ts.ExportDeclaration): boolean { return node.kind === ts.SyntaxKind.ImportDeclaration && !!node.importClause && !!node.importClause.name; } +/** @internal */ export function forEachImportClauseDeclaration(node: ts.ImportClause, action: (declaration: ts.ImportClause | ts.NamespaceImport | ts.ImportSpecifier) => T | undefined): T | undefined { if (node.name) { const result = action(node); @@ -2650,6 +2888,7 @@ export function forEachImportClauseDeclaration(node: ts.ImportClause, action: } } +/** @internal */ export function hasQuestionToken(node: ts.Node) { if (node) { switch (node.kind) { @@ -2667,16 +2906,19 @@ export function hasQuestionToken(node: ts.Node) { return false; } +/** @internal */ export function isJSDocConstructSignature(node: ts.Node) { const param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined; const name = ts.tryCast(param && param.name, ts.isIdentifier); return !!name && name.escapedText === "new"; } +/** @internal */ export function isJSDocTypeAlias(node: ts.Node): node is ts.JSDocTypedefTag | ts.JSDocCallbackTag | ts.JSDocEnumTag { return node.kind === ts.SyntaxKind.JSDocTypedefTag || node.kind === ts.SyntaxKind.JSDocCallbackTag || node.kind === ts.SyntaxKind.JSDocEnumTag; } +/** @internal */ export function isTypeAlias(node: ts.Node): node is ts.JSDocTypedefTag | ts.JSDocCallbackTag | ts.JSDocEnumTag | ts.TypeAliasDeclaration { return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node); } @@ -2699,6 +2941,7 @@ function getSourceOfDefaultedAssignment(node: ts.Node): ts.Node | undefined { : undefined; } +/** @internal */ export function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node: ts.Node): ts.Expression | undefined { switch (node.kind) { case ts.SyntaxKind.VariableStatement: @@ -2711,6 +2954,7 @@ export function getSingleInitializerOfVariableStatementOrPropertyDeclaration(nod } } +/** @internal */ export function getSingleVariableOfVariableStatement(node: ts.Node): ts.VariableDeclaration | undefined { return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; } @@ -2723,6 +2967,7 @@ function getNestedModuleDeclaration(node: ts.Node): ts.Node | undefined { : undefined; } +/** @internal */ export function getJSDocCommentsAndTags(hostNode: ts.Node, noCache?: boolean): readonly (ts.JSDoc | ts.JSDocTag)[] { let result: (ts.JSDoc | ts.JSDocTag)[] | undefined; // Pull parameter comments from declaring function as well @@ -2769,6 +3014,7 @@ function ownsJSDocTag(hostNode: ts.Node, tag: ts.JSDocTag) { || tag.parent.parent === hostNode; } +/** @internal */ export function getNextJSDocCommentLocation(node: ts.Node) { const parent = node.parent; if (parent.kind === ts.SyntaxKind.PropertyAssignment || @@ -2799,6 +3045,7 @@ export function getNextJSDocCommentLocation(node: ts.Node) { } } +/** @internal */ /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */ export function getParameterSymbolFromJSDoc(node: ts.JSDocParameterTag): ts.Symbol | undefined { if (node.symbol) { @@ -2816,6 +3063,7 @@ export function getParameterSymbolFromJSDoc(node: ts.JSDocParameterTag): ts.Symb return parameter && parameter.symbol; } +/** @internal */ export function getEffectiveContainerForJSDocTemplateTag(node: ts.JSDocTemplateTag) { if (ts.isJSDoc(node.parent) && node.parent.tags) { // A @template tag belongs to any @typedef, @callback, or @enum tags in the same comment block, if they exist. @@ -2828,6 +3076,7 @@ export function getEffectiveContainerForJSDocTemplateTag(node: ts.JSDocTemplateT return getHostSignatureFromJSDoc(node); } +/** @internal */ export function getHostSignatureFromJSDoc(node: ts.Node): ts.SignatureDeclaration | undefined { const host = getEffectiveJSDocHost(node); if (host) { @@ -2837,6 +3086,7 @@ export function getHostSignatureFromJSDoc(node: ts.Node): ts.SignatureDeclaratio return undefined; } +/** @internal */ export function getEffectiveJSDocHost(node: ts.Node): ts.Node | undefined { const host = getJSDocHost(node); if (host) { @@ -2849,6 +3099,7 @@ export function getEffectiveJSDocHost(node: ts.Node): ts.Node | undefined { } } +/** @internal */ /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments. */ export function getJSDocHost(node: ts.Node): ts.HasJSDoc | undefined { const jsDoc = getJSDocRoot(node); @@ -2862,24 +3113,29 @@ export function getJSDocHost(node: ts.Node): ts.HasJSDoc | undefined { } } +/** @internal */ export function getJSDocRoot(node: ts.Node): ts.JSDoc | undefined { return ts.findAncestor(node.parent, ts.isJSDoc); } +/** @internal */ export function getTypeParameterFromJsDoc(node: ts.TypeParameterDeclaration & { parent: ts.JSDocTemplateTag }): ts.TypeParameterDeclaration | undefined { const name = node.name.escapedText; const { typeParameters } = (node.parent.parent.parent as ts.SignatureDeclaration | ts.InterfaceDeclaration | ts.ClassDeclaration); return typeParameters && ts.find(typeParameters, p => p.name.escapedText === name); } +/** @internal */ export function hasTypeArguments(node: ts.Node): node is ts.HasTypeArguments { return !!(node as ts.HasTypeArguments).typeArguments; } +/** @internal */ export const enum AssignmentKind { None, Definite, Compound } +/** @internal */ export function getAssignmentTargetKind(node: ts.Node): AssignmentKind { let parent = node.parent; while (true) { @@ -2928,10 +3184,12 @@ export function getAssignmentTargetKind(node: ts.Node): AssignmentKind { // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'. // (Note that `p` is not a target in the above examples, only `a`.) +/** @internal */ export function isAssignmentTarget(node: ts.Node): boolean { return getAssignmentTargetKind(node) !== AssignmentKind.None; } +/** @internal */ export type NodeWithPossibleHoistedDeclaration = | ts.Block | ts.VariableStatement @@ -2950,6 +3208,7 @@ export type NodeWithPossibleHoistedDeclaration = | ts.TryStatement | ts.CatchClause; +/** @internal */ /** * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to * the same `var` declaration scope as the node's parent. @@ -2977,6 +3236,7 @@ export function isNodeWithPossibleHoistedDeclaration(node: ts.Node): node is Nod return false; } +/** @internal */ export type ValueSignatureDeclaration = | ts.FunctionDeclaration | ts.MethodDeclaration @@ -2985,6 +3245,7 @@ export type ValueSignatureDeclaration = | ts.FunctionExpression | ts.ArrowFunction; +/** @internal */ export function isValueSignatureDeclaration(node: ts.Node): node is ValueSignatureDeclaration { return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node); } @@ -2996,14 +3257,17 @@ function walkUp(node: ts.Node, kind: ts.SyntaxKind) { return node; } +/** @internal */ export function walkUpParenthesizedTypes(node: ts.Node) { return walkUp(node, ts.SyntaxKind.ParenthesizedType); } +/** @internal */ export function walkUpParenthesizedExpressions(node: ts.Node) { return walkUp(node, ts.SyntaxKind.ParenthesizedExpression); } +/** @internal */ /** * Walks up parenthesized types. * It returns both the outermost parenthesized type and its parent. @@ -3018,13 +3282,17 @@ export function walkUpParenthesizedTypesAndGetParentAndChild(node: ts.Node): [ts return [child, node]; } +/** @internal */ export function skipTypeParentheses(node: ts.TypeNode): ts.TypeNode { while (ts.isParenthesizedTypeNode(node)) node = node.type; return node; } +/** @internal */ export function skipParentheses(node: ts.Expression, excludeJSDocTypeAssertions?: boolean): ts.Expression; +/** @internal */ export function skipParentheses(node: ts.Node, excludeJSDocTypeAssertions?: boolean): ts.Node; +/** @internal */ export function skipParentheses(node: ts.Node, excludeJSDocTypeAssertions?: boolean): ts.Node { const flags = excludeJSDocTypeAssertions ? ts.OuterExpressionKinds.Parentheses | ts.OuterExpressionKinds.ExcludeJSDocTypeAssertion : @@ -3033,6 +3301,7 @@ export function skipParentheses(node: ts.Node, excludeJSDocTypeAssertions?: bool } // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped +/** @internal */ export function isDeleteTarget(node: ts.Node): boolean { if (node.kind !== ts.SyntaxKind.PropertyAccessExpression && node.kind !== ts.SyntaxKind.ElementAccessExpression) { return false; @@ -3041,6 +3310,7 @@ export function isDeleteTarget(node: ts.Node): boolean { return node && node.kind === ts.SyntaxKind.DeleteExpression; } +/** @internal */ export function isNodeDescendantOf(node: ts.Node, ancestor: ts.Node | undefined): boolean { while (node) { if (node === ancestor) return true; @@ -3050,11 +3320,13 @@ export function isNodeDescendantOf(node: ts.Node, ancestor: ts.Node | undefined) } // True if `name` is the name of a declaration node +/** @internal */ export function isDeclarationName(name: ts.Node): boolean { return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name; } // See GH#16030 +/** @internal */ export function getDeclarationFromName(name: ts.Node): ts.Declaration | undefined { const parent = name.parent; switch (name.kind) { @@ -3087,6 +3359,7 @@ export function getDeclarationFromName(name: ts.Node): ts.Declaration | undefine } } +/** @internal */ export function isLiteralComputedPropertyDeclarationName(node: ts.Node) { return isStringOrNumericLiteralLike(node) && node.parent.kind === ts.SyntaxKind.ComputedPropertyName && @@ -3094,6 +3367,7 @@ export function isLiteralComputedPropertyDeclarationName(node: ts.Node) { } // Return true if the given identifier is classified as an IdentifierName +/** @internal */ export function isIdentifierName(node: ts.Identifier): boolean { const parent = node.parent; switch (parent.kind) { @@ -3141,6 +3415,7 @@ export function isIdentifierName(node: ts.Identifier): boolean { // const { x } = require("...") // const x = require("...").y // const { x } = require("...").y +/** @internal */ export function isAliasSymbolDeclaration(node: ts.Node): boolean { if (node.kind === ts.SyntaxKind.ImportEqualsDeclaration || node.kind === ts.SyntaxKind.NamespaceExportDeclaration || @@ -3163,6 +3438,7 @@ export function isAliasSymbolDeclaration(node: ts.Node): boolean { && isAliasableExpression(node.parent.right)); } +/** @internal */ export function getAliasDeclarationFromName(node: ts.EntityName): ts.Declaration | undefined { switch (node.parent.kind) { case ts.SyntaxKind.ImportClause: @@ -3181,24 +3457,29 @@ export function getAliasDeclarationFromName(node: ts.EntityName): ts.Declaration } } +/** @internal */ export function isAliasableExpression(e: ts.Expression) { return isEntityNameExpression(e) || ts.isClassExpression(e); } +/** @internal */ export function exportAssignmentIsAlias(node: ts.ExportAssignment | ts.BinaryExpression): boolean { const e = getExportAssignmentExpression(node); return isAliasableExpression(e); } +/** @internal */ export function getExportAssignmentExpression(node: ts.ExportAssignment | ts.BinaryExpression): ts.Expression { return ts.isExportAssignment(node) ? node.expression : node.right; } +/** @internal */ export function getPropertyAssignmentAliasLikeExpression(node: ts.PropertyAssignment | ts.ShorthandPropertyAssignment | ts.PropertyAccessExpression): ts.Expression { return node.kind === ts.SyntaxKind.ShorthandPropertyAssignment ? node.name : node.kind === ts.SyntaxKind.PropertyAssignment ? node.initializer : (node.parent as ts.BinaryExpression).right; } +/** @internal */ export function getEffectiveBaseTypeNode(node: ts.ClassLikeDeclaration | ts.InterfaceDeclaration) { const baseType = getClassExtendsHeritageElement(node); if (baseType && isInJSFile(node)) { @@ -3211,11 +3492,13 @@ export function getEffectiveBaseTypeNode(node: ts.ClassLikeDeclaration | ts.Inte return baseType; } +/** @internal */ export function getClassExtendsHeritageElement(node: ts.ClassLikeDeclaration | ts.InterfaceDeclaration) { const heritageClause = getHeritageClause(node.heritageClauses, ts.SyntaxKind.ExtendsKeyword); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } +/** @internal */ export function getEffectiveImplementsTypeNodes(node: ts.ClassLikeDeclaration): undefined | readonly ts.ExpressionWithTypeArguments[]{ if (isInJSFile(node)) { return ts.getJSDocImplementsTags(node).map(n => n.class); @@ -3226,6 +3509,7 @@ export function getEffectiveImplementsTypeNodes(node: ts.ClassLikeDeclaration): } } +/** @internal */ /** Returns the node in an `extends` or `implements` clause of a class or interface. */ export function getAllSuperTypeNodes(node: ts.Node): readonly ts.TypeNode[] { return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray : @@ -3233,11 +3517,13 @@ export function getAllSuperTypeNodes(node: ts.Node): readonly ts.TypeNode[] { ts.emptyArray; } +/** @internal */ export function getInterfaceBaseTypeNodes(node: ts.InterfaceDeclaration) { const heritageClause = getHeritageClause(node.heritageClauses, ts.SyntaxKind.ExtendsKeyword); return heritageClause ? heritageClause.types : undefined; } +/** @internal */ export function getHeritageClause(clauses: ts.NodeArray | undefined, kind: ts.SyntaxKind) { if (clauses) { for (const clause of clauses) { @@ -3250,6 +3536,7 @@ export function getHeritageClause(clauses: ts.NodeArray | und return undefined; } +/** @internal */ export function getAncestor(node: ts.Node | undefined, kind: ts.SyntaxKind): ts.Node | undefined { while (node) { if (node.kind === kind) { @@ -3260,40 +3547,49 @@ export function getAncestor(node: ts.Node | undefined, kind: ts.SyntaxKind): ts. return undefined; } +/** @internal */ export function isKeyword(token: ts.SyntaxKind): token is ts.KeywordSyntaxKind { return ts.SyntaxKind.FirstKeyword <= token && token <= ts.SyntaxKind.LastKeyword; } +/** @internal */ export function isContextualKeyword(token: ts.SyntaxKind): boolean { return ts.SyntaxKind.FirstContextualKeyword <= token && token <= ts.SyntaxKind.LastContextualKeyword; } +/** @internal */ export function isNonContextualKeyword(token: ts.SyntaxKind): boolean { return isKeyword(token) && !isContextualKeyword(token); } +/** @internal */ export function isFutureReservedKeyword(token: ts.SyntaxKind): boolean { return ts.SyntaxKind.FirstFutureReservedWord <= token && token <= ts.SyntaxKind.LastFutureReservedWord; } +/** @internal */ export function isStringANonContextualKeyword(name: string) { const token = ts.stringToToken(name); return token !== undefined && isNonContextualKeyword(token); } +/** @internal */ export function isStringAKeyword(name: string) { const token = ts.stringToToken(name); return token !== undefined && isKeyword(token); } +/** @internal */ export function isIdentifierANonContextualKeyword({ originalKeywordKind }: ts.Identifier): boolean { return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind); } +/** @internal */ export function isTrivia(token: ts.SyntaxKind): token is ts.TriviaSyntaxKind { return ts.SyntaxKind.FirstTriviaToken <= token && token <= ts.SyntaxKind.LastTriviaToken; } +/** @internal */ export const enum FunctionFlags { Normal = 0, // Function is a normal function Generator = 1 << 0, // Function is a generator function or async generator function @@ -3302,6 +3598,7 @@ export const enum FunctionFlags { AsyncGenerator = Async | Generator, // Function is an async generator function } +/** @internal */ export function getFunctionFlags(node: ts.SignatureDeclaration | undefined) { if (!node) { return FunctionFlags.Invalid; @@ -3331,6 +3628,7 @@ export function getFunctionFlags(node: ts.SignatureDeclaration | undefined) { return flags; } +/** @internal */ export function isAsyncFunction(node: ts.Node): boolean { switch (node.kind) { case ts.SyntaxKind.FunctionDeclaration: @@ -3344,14 +3642,17 @@ export function isAsyncFunction(node: ts.Node): boolean { return false; } +/** @internal */ export function isStringOrNumericLiteralLike(node: ts.Node): node is ts.StringLiteralLike | ts.NumericLiteral { return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node); } +/** @internal */ export function isSignedNumericLiteral(node: ts.Node): node is ts.PrefixUnaryExpression & { operand: ts.NumericLiteral } { return ts.isPrefixUnaryExpression(node) && (node.operator === ts.SyntaxKind.PlusToken || node.operator === ts.SyntaxKind.MinusToken) && ts.isNumericLiteral(node.operand); } +/** @internal */ /** * A declaration has a dynamic name if all of the following are true: * 1. The declaration has a computed property name. @@ -3365,6 +3666,7 @@ export function hasDynamicName(declaration: ts.Declaration): declaration is ts.D return !!name && isDynamicName(name); } +/** @internal */ export function isDynamicName(name: ts.DeclarationName): boolean { if (!(name.kind === ts.SyntaxKind.ComputedPropertyName || name.kind === ts.SyntaxKind.ElementAccessExpression)) { return false; @@ -3374,6 +3676,7 @@ export function isDynamicName(name: ts.DeclarationName): boolean { !isSignedNumericLiteral(expr); } +/** @internal */ export function getPropertyNameForPropertyNameNode(name: ts.PropertyName): ts.__String | undefined { switch (name.kind) { case ts.SyntaxKind.Identifier: @@ -3399,6 +3702,7 @@ export function getPropertyNameForPropertyNameNode(name: ts.PropertyName): ts.__ } } +/** @internal */ export function isPropertyNameLiteral(node: ts.Node): node is ts.PropertyNameLiteral { switch (node.kind) { case ts.SyntaxKind.Identifier: @@ -3410,30 +3714,37 @@ export function isPropertyNameLiteral(node: ts.Node): node is ts.PropertyNameLit return false; } } +/** @internal */ export function getTextOfIdentifierOrLiteral(node: ts.PropertyNameLiteral | ts.PrivateIdentifier): string { return ts.isMemberName(node) ? ts.idText(node) : node.text; } +/** @internal */ export function getEscapedTextOfIdentifierOrLiteral(node: ts.PropertyNameLiteral): ts.__String { return ts.isMemberName(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text); } +/** @internal */ export function getPropertyNameForUniqueESSymbol(symbol: ts.Symbol): ts.__String { return `__@${ts.getSymbolId(symbol)}@${symbol.escapedName}` as ts.__String; } +/** @internal */ export function getSymbolNameForPrivateIdentifier(containingClassSymbol: ts.Symbol, description: ts.__String): ts.__String { return `__#${ts.getSymbolId(containingClassSymbol)}@${description}` as ts.__String; } +/** @internal */ export function isKnownSymbol(symbol: ts.Symbol): boolean { return ts.startsWith(symbol.escapedName as string, "__@"); } +/** @internal */ export function isPrivateIdentifierSymbol(symbol: ts.Symbol): boolean { return ts.startsWith(symbol.escapedName as string, "__#"); } +/** @internal */ /** * Includes the word "Symbol" with unicode escapes */ @@ -3441,15 +3752,18 @@ export function isESSymbolIdentifier(node: ts.Node): boolean { return node.kind === ts.SyntaxKind.Identifier && (node as ts.Identifier).escapedText === "Symbol"; } +/** @internal */ export function isPushOrUnshiftIdentifier(node: ts.Identifier) { return node.escapedText === "push" || node.escapedText === "unshift"; } +/** @internal */ export function isParameterDeclaration(node: ts.VariableLikeDeclaration): boolean { const root = getRootDeclaration(node); return root.kind === ts.SyntaxKind.Parameter; } +/** @internal */ export function getRootDeclaration(node: ts.Node): ts.Node { while (node.kind === ts.SyntaxKind.BindingElement) { node = node.parent.parent; @@ -3457,6 +3771,7 @@ export function getRootDeclaration(node: ts.Node): ts.Node { return node; } +/** @internal */ export function nodeStartsNewLexicalEnvironment(node: ts.Node): boolean { const kind = node.kind; return kind === ts.SyntaxKind.Constructor @@ -3470,26 +3785,31 @@ export function nodeStartsNewLexicalEnvironment(node: ts.Node): boolean { || kind === ts.SyntaxKind.SourceFile; } +/** @internal */ export function nodeIsSynthesized(range: ts.TextRange): boolean { return positionIsSynthesized(range.pos) || positionIsSynthesized(range.end); } +/** @internal */ export function getOriginalSourceFile(sourceFile: ts.SourceFile) { return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile; } +/** @internal */ export const enum Associativity { Left, Right } +/** @internal */ export function getExpressionAssociativity(expression: ts.Expression) { const operator = getOperator(expression); const hasArguments = expression.kind === ts.SyntaxKind.NewExpression && (expression as ts.NewExpression).arguments !== undefined; return getOperatorAssociativity(expression.kind, operator, hasArguments); } +/** @internal */ export function getOperatorAssociativity(kind: ts.SyntaxKind, operator: ts.SyntaxKind, hasArguments?: boolean) { switch (kind) { case ts.SyntaxKind.NewExpression: @@ -3529,12 +3849,14 @@ export function getOperatorAssociativity(kind: ts.SyntaxKind, operator: ts.Synta return Associativity.Left; } +/** @internal */ export function getExpressionPrecedence(expression: ts.Expression) { const operator = getOperator(expression); const hasArguments = expression.kind === ts.SyntaxKind.NewExpression && (expression as ts.NewExpression).arguments !== undefined; return getOperatorPrecedence(expression.kind, operator, hasArguments); } +/** @internal */ export function getOperator(expression: ts.Expression): ts.SyntaxKind { if (expression.kind === ts.SyntaxKind.BinaryExpression) { return (expression as ts.BinaryExpression).operatorToken.kind; @@ -3547,6 +3869,7 @@ export function getOperator(expression: ts.Expression): ts.SyntaxKind { } } +/** @internal */ export const enum OperatorPrecedence { // Expression: // AssignmentExpression @@ -3740,6 +4063,7 @@ export const enum OperatorPrecedence { Invalid = -1, } +/** @internal */ export function getOperatorPrecedence(nodeKind: ts.SyntaxKind, operatorKind: ts.SyntaxKind, hasArguments?: boolean) { switch (nodeKind) { case ts.SyntaxKind.CommaListExpression: @@ -3840,6 +4164,7 @@ export function getOperatorPrecedence(nodeKind: ts.SyntaxKind, operatorKind: ts. } } +/** @internal */ export function getBinaryOperatorPrecedence(kind: ts.SyntaxKind): OperatorPrecedence { switch (kind) { case ts.SyntaxKind.QuestionQuestionToken: @@ -3888,6 +4213,7 @@ export function getBinaryOperatorPrecedence(kind: ts.SyntaxKind): OperatorPreced return -1; } +/** @internal */ export function getSemanticJsxChildren(children: readonly ts.JsxChild[]) { return ts.filter(children, i => { switch (i.kind) { @@ -3901,6 +4227,7 @@ export function getSemanticJsxChildren(children: readonly ts.JsxChild[]) { }); } +/** @internal */ export function createDiagnosticCollection(): ts.DiagnosticCollection { let nonFileDiagnostics = [] as ts.Diagnostic[] as ts.SortedArray; // See GH#19873 const filesWithDiagnostics = [] as string[] as ts.SortedArray; @@ -4033,6 +4360,7 @@ function getReplacement(c: string, offset: number, input: string) { return escapedCharsMap.get(c) || encodeUtf16EscapeSequence(c.charCodeAt(0)); } +/** @internal */ /** * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2), * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine) @@ -4047,6 +4375,7 @@ export function escapeString(s: string, quoteChar?: ts.CharacterCodes.doubleQuot } const nonAsciiCharacters = /[^\u0000-\u007F]/g; +/** @internal */ export function escapeNonAsciiString(s: string, quoteChar?: ts.CharacterCodes.doubleQuote | ts.CharacterCodes.singleQuote | ts.CharacterCodes.backtick): string { s = escapeString(s, quoteChar); // Replace non-ASCII characters with '\uNNNN' escapes if any exist. @@ -4079,6 +4408,7 @@ function getJsxAttributeStringReplacement(c: string) { return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0)); } +/** @internal */ export function escapeJsxAttributeString(s: string, quoteChar?: ts.CharacterCodes.doubleQuote | ts.CharacterCodes.singleQuote) { const escapedCharsRegExp = quoteChar === ts.CharacterCodes.singleQuote ? jsxSingleQuoteEscapedCharsRegExp : @@ -4086,6 +4416,7 @@ export function escapeJsxAttributeString(s: string, quoteChar?: ts.CharacterCode return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement); } +/** @internal */ /** * Strip off existed surrounding single quotes, double quotes, or backticks from a given string * @@ -4105,12 +4436,14 @@ function isQuoteOrBacktick(charCode: number) { charCode === ts.CharacterCodes.backtick; } +/** @internal */ export function isIntrinsicJsxName(name: ts.__String | string) { const ch = (name as string).charCodeAt(0); return (ch >= ts.CharacterCodes.a && ch <= ts.CharacterCodes.z) || ts.stringContains((name as string), "-") || ts.stringContains((name as string), ":"); } const indentStrings: string[] = ["", " "]; +/** @internal */ export function getIndentString(level: number) { // prepopulate cache const singleLevel = indentStrings[1]; @@ -4120,14 +4453,17 @@ export function getIndentString(level: number) { return indentStrings[level]; } +/** @internal */ export function getIndentSize() { return indentStrings[1].length; } +/** @internal */ export function isNightly() { return ts.stringContains(ts.version, "-dev") || ts.stringContains(ts.version, "-insiders"); } +/** @internal */ export function createTextWriter(newLine: string): ts.EmitTextWriter { let output: string; let indent: number; @@ -4242,6 +4578,7 @@ export function createTextWriter(newLine: string): ts.EmitTextWriter { }; } +/** @internal */ export function getTrailingSemicolonDeferringWriter(writer: ts.EmitTextWriter): ts.EmitTextWriter { let pendingTrailingSemicolon = false; @@ -4312,20 +4649,24 @@ export function getTrailingSemicolonDeferringWriter(writer: ts.EmitTextWriter): }; } +/** @internal */ export function hostUsesCaseSensitiveFileNames(host: { useCaseSensitiveFileNames?(): boolean; }): boolean { return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false; } +/** @internal */ export function hostGetCanonicalFileName(host: { useCaseSensitiveFileNames?(): boolean; }): ts.GetCanonicalFileName { return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host)); } +/** @internal */ export interface ResolveModuleNameResolutionHost { getCanonicalFileName(p: string): string; getCommonSourceDirectory(): string; getCurrentDirectory(): string; } +/** @internal */ export function getResolvedExternalModuleName(host: ResolveModuleNameResolutionHost, file: ts.SourceFile, referenceFile?: ts.SourceFile): string { return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName); } @@ -4334,6 +4675,7 @@ function getCanonicalAbsolutePath(host: ResolveModuleNameResolutionHost, path: s return host.getCanonicalFileName(ts.getNormalizedAbsolutePath(path, host.getCurrentDirectory())); } +/** @internal */ export function getExternalModuleNameFromDeclaration(host: ResolveModuleNameResolutionHost, resolver: ts.EmitResolver, declaration: ts.ImportEqualsDeclaration | ts.ImportDeclaration | ts.ExportDeclaration | ts.ModuleDeclaration | ts.ImportTypeNode): string | undefined { const file = resolver.getExternalModuleFileFromDeclaration(declaration); if (!file || file.isDeclarationFile) { @@ -4348,6 +4690,7 @@ export function getExternalModuleNameFromDeclaration(host: ResolveModuleNameReso return getResolvedExternalModuleName(host, file); } +/** @internal */ /** * Resolves a local path to a path which is absolute to the base of the emit */ @@ -4360,6 +4703,7 @@ export function getExternalModuleNameFromPath(host: ResolveModuleNameResolutionH return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless; } +/** @internal */ export function getOwnEmitOutputFilePath(fileName: string, host: ts.EmitHost, extension: string) { const compilerOptions = host.getCompilerOptions(); let emitOutputFilePathWithoutExtension: string; @@ -4373,10 +4717,12 @@ export function getOwnEmitOutputFilePath(fileName: string, host: ts.EmitHost, ex return emitOutputFilePathWithoutExtension + extension; } +/** @internal */ export function getDeclarationEmitOutputFilePath(fileName: string, host: ts.EmitHost) { return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), f => host.getCanonicalFileName(f)); } +/** @internal */ export function getDeclarationEmitOutputFilePathWorker(fileName: string, options: ts.CompilerOptions, currentDirectory: string, commonSourceDirectory: string, getCanonicalFileName: ts.GetCanonicalFileName): string { const outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified @@ -4387,6 +4733,7 @@ export function getDeclarationEmitOutputFilePathWorker(fileName: string, options return removeFileExtension(path) + declarationExtension; } +/** @internal */ export function getDeclarationEmitExtensionForPath(path: string) { return ts.fileExtensionIsOneOf(path, [ts.Extension.Mjs, ts.Extension.Mts]) ? ts.Extension.Dmts : ts.fileExtensionIsOneOf(path, [ts.Extension.Cjs, ts.Extension.Cts]) ? ts.Extension.Dcts : @@ -4394,6 +4741,7 @@ export function getDeclarationEmitExtensionForPath(path: string) { ts.Extension.Dts; } +/** @internal */ /** * This function is an inverse of `getDeclarationEmitExtensionForPath`. */ @@ -4404,16 +4752,19 @@ export function getPossibleOriginalInputExtensionForExtension(path: string) { [ts.Extension.Tsx, ts.Extension.Ts, ts.Extension.Jsx, ts.Extension.Js]; } +/** @internal */ export function outFile(options: ts.CompilerOptions) { return options.outFile || options.out; } +/** @internal */ /** Returns 'undefined' if and only if 'options.paths' is undefined. */ export function getPathsBasePath(options: ts.CompilerOptions, host: { getCurrentDirectory?(): string }) { if (!options.paths) return undefined; return options.baseUrl ?? ts.Debug.checkDefined(options.pathsBasePath || host.getCurrentDirectory?.(), "Encountered 'paths' without a 'baseUrl', config file, or host 'getCurrentDirectory'."); } +/** @internal */ export interface EmitFileNames { jsFilePath?: string | undefined; sourceMapFilePath?: string | undefined; @@ -4422,6 +4773,7 @@ export interface EmitFileNames { buildInfoPath?: string | undefined; } +/** @internal */ /** * Gets the source files that are expected to have an emit output. * @@ -4453,6 +4805,7 @@ export function getSourceFilesToEmit(host: ts.EmitHost, targetSourceFile?: ts.So } } +/** @internal */ /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ export function sourceFileMayBeEmitted(sourceFile: ts.SourceFile, host: ts.SourceFileMayBeEmittedHost, forceDtsEmit?: boolean) { const options = host.getCompilerOptions(); @@ -4465,10 +4818,12 @@ export function sourceFileMayBeEmitted(sourceFile: ts.SourceFile, host: ts.Sourc )); } +/** @internal */ export function getSourceFilePathInNewDir(fileName: string, host: ts.EmitHost, newDirPath: string): string { return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), f => host.getCanonicalFileName(f)); } +/** @internal */ export function getSourceFilePathInNewDirWorker(fileName: string, newDirPath: string, currentDirectory: string, commonSourceDirectory: string, getCanonicalFileName: ts.GetCanonicalFileName): string { let sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory); const isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0; @@ -4476,6 +4831,7 @@ export function getSourceFilePathInNewDirWorker(fileName: string, newDirPath: st return ts.combinePaths(newDirPath, sourceFilePath); } +/** @internal */ export function writeFile(host: { writeFile: ts.WriteFileCallback; }, diagnostics: ts.DiagnosticCollection, fileName: string, text: string, writeByteOrderMark: boolean, sourceFiles?: readonly ts.SourceFile[], data?: ts.WriteFileCallbackData) { host.writeFile(fileName, text, writeByteOrderMark, hostErrorMessage => { diagnostics.add(createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage)); @@ -4493,6 +4849,7 @@ function ensureDirectoriesExist( } } +/** @internal */ export function writeFileEnsuringDirectories( path: string, data: string, @@ -4512,19 +4869,23 @@ export function writeFileEnsuringDirectories( } } +/** @internal */ export function getLineOfLocalPosition(sourceFile: ts.SourceFile, pos: number) { const lineStarts = ts.getLineStarts(sourceFile); return ts.computeLineOfPosition(lineStarts, pos); } +/** @internal */ export function getLineOfLocalPositionFromLineMap(lineMap: readonly number[], pos: number) { return ts.computeLineOfPosition(lineMap, pos); } +/** @internal */ export function getFirstConstructorWithBody(node: ts.ClassLikeDeclaration): ts.ConstructorDeclaration & { body: ts.FunctionBody } | undefined { return ts.find(node.members, (member): member is ts.ConstructorDeclaration & { body: ts.FunctionBody } => ts.isConstructorDeclaration(member) && nodeIsPresent(member.body)); } +/** @internal */ export function getSetAccessorValueParameter(accessor: ts.SetAccessorDeclaration): ts.ParameterDeclaration | undefined { if (accessor && accessor.parameters.length > 0) { const hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); @@ -4532,12 +4893,14 @@ export function getSetAccessorValueParameter(accessor: ts.SetAccessorDeclaration } } +/** @internal */ /** Get the type annotation for the value parameter. */ export function getSetAccessorTypeAnnotationNode(accessor: ts.SetAccessorDeclaration): ts.TypeNode | undefined { const parameter = getSetAccessorValueParameter(accessor); return parameter && parameter.type; } +/** @internal */ export function getThisParameter(signature: ts.SignatureDeclaration | ts.JSDocSignature): ts.ParameterDeclaration | undefined { // callback tags do not currently support this parameters if (signature.parameters.length && !ts.isJSDocSignature(signature)) { @@ -4548,14 +4911,17 @@ export function getThisParameter(signature: ts.SignatureDeclaration | ts.JSDocSi } } +/** @internal */ export function parameterIsThisKeyword(parameter: ts.ParameterDeclaration): boolean { return isThisIdentifier(parameter.name); } +/** @internal */ export function isThisIdentifier(node: ts.Node | undefined): boolean { return !!node && node.kind === ts.SyntaxKind.Identifier && identifierIsThisKeyword(node as ts.Identifier); } +/** @internal */ export function isThisInTypeQuery(node: ts.Node): boolean { if (!isThisIdentifier(node)) { return false; @@ -4568,10 +4934,12 @@ export function isThisInTypeQuery(node: ts.Node): boolean { return node.parent.kind === ts.SyntaxKind.TypeQuery; } +/** @internal */ export function identifierIsThisKeyword(id: ts.Identifier): boolean { return id.originalKeywordKind === ts.SyntaxKind.ThisKeyword; } +/** @internal */ export function getAllAccessorDeclarations(declarations: readonly ts.Declaration[], accessor: ts.AccessorDeclaration): ts.AllAccessorDeclarations { // TODO: GH#18217 let firstAccessor!: ts.AccessorDeclaration; @@ -4623,6 +4991,7 @@ export function getAllAccessorDeclarations(declarations: readonly ts.Declaration }; } +/** @internal */ /** * Gets the effective type annotation of a variable, parameter, or property. If the node was * parsed in a JavaScript file, gets the type annotation from JSDoc. Also gets the type of @@ -4635,10 +5004,12 @@ export function getEffectiveTypeAnnotationNode(node: ts.Node): ts.TypeNode | und return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node); } +/** @internal */ export function getTypeAnnotationNode(node: ts.Node): ts.TypeNode | undefined { return (node as ts.HasType).type; } +/** @internal */ /** * Gets the effective return type annotation of a signature. If the node was parsed in a * JavaScript file, gets the return type annotation from JSDoc. @@ -4649,6 +5020,7 @@ export function getEffectiveReturnTypeNode(node: ts.SignatureDeclaration | ts.JS node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined); } +/** @internal */ export function getJSDocTypeParameterDeclarations(node: ts.DeclarationWithTypeParameters): readonly ts.TypeParameterDeclaration[] { return ts.flatMap(ts.getJSDocTags(node), tag => isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined); } @@ -4658,6 +5030,7 @@ function isNonTypeAliasTemplate(tag: ts.JSDocTag): tag is ts.JSDocTemplateTag { return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === ts.SyntaxKind.JSDoc && tag.parent.tags!.some(isJSDocTypeAlias)); } +/** @internal */ /** * Gets the effective type annotation of the value parameter of a set accessor. If the node * was parsed in a JavaScript file, gets the type annotation from JSDoc. @@ -4667,10 +5040,12 @@ export function getEffectiveSetAccessorTypeAnnotationNode(node: ts.SetAccessorDe return parameter && getEffectiveTypeAnnotationNode(parameter); } +/** @internal */ export function emitNewLineBeforeLeadingComments(lineMap: readonly number[], writer: ts.EmitTextWriter, node: ts.TextRange, leadingComments: readonly ts.CommentRange[] | undefined) { emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments); } +/** @internal */ export function emitNewLineBeforeLeadingCommentsOfPosition(lineMap: readonly number[], writer: ts.EmitTextWriter, pos: number, leadingComments: readonly ts.CommentRange[] | undefined) { // If the leading comments start on different line than the start of node, write new line if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos && @@ -4679,6 +5054,7 @@ export function emitNewLineBeforeLeadingCommentsOfPosition(lineMap: readonly num } } +/** @internal */ export function emitNewLineBeforeLeadingCommentOfPosition(lineMap: readonly number[], writer: ts.EmitTextWriter, pos: number, commentPos: number) { // If the leading comments start on different line than the start of node, write new line if (pos !== commentPos && @@ -4687,6 +5063,7 @@ export function emitNewLineBeforeLeadingCommentOfPosition(lineMap: readonly numb } } +/** @internal */ export function emitComments( text: string, lineMap: readonly number[], @@ -4723,6 +5100,7 @@ export function emitComments( } } +/** @internal */ /** * Detached comment is a comment at the top of file or function body that is separated from * the next statement by space. @@ -4791,6 +5169,7 @@ export function emitDetachedComments(text: string, lineMap: readonly number[], w } +/** @internal */ export function writeCommentRange(text: string, lineMap: readonly number[], writer: ts.EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) { if (text.charCodeAt(commentPos + 1) === ts.CharacterCodes.asterisk) { const firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos); @@ -4888,59 +5267,73 @@ function calculateIndent(text: string, pos: number, end: number) { return currentLineIndent; } +/** @internal */ export function hasEffectiveModifiers(node: ts.Node) { return getEffectiveModifierFlags(node) !== ts.ModifierFlags.None; } +/** @internal */ export function hasSyntacticModifiers(node: ts.Node) { return getSyntacticModifierFlags(node) !== ts.ModifierFlags.None; } +/** @internal */ export function hasEffectiveModifier(node: ts.Node, flags: ts.ModifierFlags): boolean { return !!getSelectedEffectiveModifierFlags(node, flags); } +/** @internal */ export function hasSyntacticModifier(node: ts.Node, flags: ts.ModifierFlags): boolean { return !!getSelectedSyntacticModifierFlags(node, flags); } +/** @internal */ export function isStatic(node: ts.Node) { // https://tc39.es/ecma262/#sec-static-semantics-isstatic return ts.isClassElement(node) && hasStaticModifier(node) || ts.isClassStaticBlockDeclaration(node); } +/** @internal */ export function hasStaticModifier(node: ts.Node): boolean { return hasSyntacticModifier(node, ts.ModifierFlags.Static); } +/** @internal */ export function hasOverrideModifier(node: ts.Node): boolean { return hasEffectiveModifier(node, ts.ModifierFlags.Override); } +/** @internal */ export function hasAbstractModifier(node: ts.Node): boolean { return hasSyntacticModifier(node, ts.ModifierFlags.Abstract); } +/** @internal */ export function hasAmbientModifier(node: ts.Node): boolean { return hasSyntacticModifier(node, ts.ModifierFlags.Ambient); } +/** @internal */ export function hasAccessorModifier(node: ts.Node): boolean { return hasSyntacticModifier(node, ts.ModifierFlags.Accessor); } +/** @internal */ export function hasEffectiveReadonlyModifier(node: ts.Node): boolean { return hasEffectiveModifier(node, ts.ModifierFlags.Readonly); } +/** @internal */ export function hasDecorators(node: ts.Node): boolean { return hasSyntacticModifier(node, ts.ModifierFlags.Decorator); } +/** @internal */ export function getSelectedEffectiveModifierFlags(node: ts.Node, flags: ts.ModifierFlags): ts.ModifierFlags { return getEffectiveModifierFlags(node) & flags; } +/** @internal */ export function getSelectedSyntacticModifierFlags(node: ts.Node, flags: ts.ModifierFlags): ts.ModifierFlags { return getSyntacticModifierFlags(node) & flags; } @@ -4961,6 +5354,7 @@ function getModifierFlagsWorker(node: ts.Node, includeJSDoc: boolean, alwaysIncl return node.modifierFlagsCache & ~(ts.ModifierFlags.HasComputedFlags | ts.ModifierFlags.HasComputedJSDocModifiers); } +/** @internal */ /** * Gets the effective ModifierFlags for the provided node, including JSDoc modifiers. The modifiers will be cached on the node to improve performance. * @@ -4970,10 +5364,12 @@ export function getEffectiveModifierFlags(node: ts.Node): ts.ModifierFlags { return getModifierFlagsWorker(node, /*includeJSDoc*/ true); } +/** @internal */ export function getEffectiveModifierFlagsAlwaysIncludeJSDoc(node: ts.Node): ts.ModifierFlags { return getModifierFlagsWorker(node, /*includeJSDOc*/ true, /*alwaysIncludeJSDOc*/ true); } +/** @internal */ /** * Gets the ModifierFlags for syntactic modifiers on the provided node. The modifiers will be cached on the node to improve performance. * @@ -4999,6 +5395,7 @@ function getJSDocModifierFlagsNoCache(node: ts.Node): ts.ModifierFlags { return flags; } +/** @internal */ /** * Gets the effective ModifierFlags for the provided node, including JSDoc modifiers. The modifier flags cache on the node is ignored. * @@ -5008,6 +5405,7 @@ export function getEffectiveModifierFlagsNoCache(node: ts.Node): ts.ModifierFlag return getSyntacticModifierFlagsNoCache(node) | getJSDocModifierFlagsNoCache(node); } +/** @internal */ /** * Gets the ModifierFlags for syntactic modifiers on the provided node. The modifier flags cache on the node is ignored. * @@ -5021,6 +5419,7 @@ export function getSyntacticModifierFlagsNoCache(node: ts.Node): ts.ModifierFlag return flags; } +/** @internal */ export function modifiersToFlags(modifiers: readonly ts.ModifierLike[] | undefined) { let flags = ts.ModifierFlags.None; if (modifiers) { @@ -5031,6 +5430,7 @@ export function modifiersToFlags(modifiers: readonly ts.ModifierLike[] | undefin return flags; } +/** @internal */ export function modifierToFlag(token: ts.SyntaxKind): ts.ModifierFlags { switch (token) { case ts.SyntaxKind.StaticKeyword: return ts.ModifierFlags.Static; @@ -5053,36 +5453,43 @@ export function modifierToFlag(token: ts.SyntaxKind): ts.ModifierFlags { return ts.ModifierFlags.None; } +/** @internal */ export function isLogicalOperator(token: ts.SyntaxKind): boolean { return token === ts.SyntaxKind.BarBarToken || token === ts.SyntaxKind.AmpersandAmpersandToken || token === ts.SyntaxKind.ExclamationToken; } +/** @internal */ export function isLogicalOrCoalescingAssignmentOperator(token: ts.SyntaxKind): token is ts.LogicalOrCoalescingAssignmentOperator { return token === ts.SyntaxKind.BarBarEqualsToken || token === ts.SyntaxKind.AmpersandAmpersandEqualsToken || token === ts.SyntaxKind.QuestionQuestionEqualsToken; } +/** @internal */ export function isLogicalOrCoalescingAssignmentExpression(expr: ts.BinaryExpression): expr is ts.AssignmentExpression> { return isLogicalOrCoalescingAssignmentOperator(expr.operatorToken.kind); } +/** @internal */ export function isAssignmentOperator(token: ts.SyntaxKind): boolean { return token >= ts.SyntaxKind.FirstAssignment && token <= ts.SyntaxKind.LastAssignment; } +/** @internal */ /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */ export function tryGetClassExtendingExpressionWithTypeArguments(node: ts.Node): ts.ClassLikeDeclaration | undefined { const cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node); return cls && !cls.isImplements ? cls.class : undefined; } +/** @internal */ export interface ClassImplementingOrExtendingExpressionWithTypeArguments { readonly class: ts.ClassLikeDeclaration; readonly isImplements: boolean; } +/** @internal */ export function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node: ts.Node): ClassImplementingOrExtendingExpressionWithTypeArguments | undefined { return ts.isExpressionWithTypeArguments(node) && ts.isHeritageClause(node.parent) @@ -5091,8 +5498,11 @@ export function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(no : undefined; } +/** @internal */ export function isAssignmentExpression(node: ts.Node, excludeCompoundAssignment: true): node is ts.AssignmentExpression; +/** @internal */ export function isAssignmentExpression(node: ts.Node, excludeCompoundAssignment?: false): node is ts.AssignmentExpression; +/** @internal */ export function isAssignmentExpression(node: ts.Node, excludeCompoundAssignment?: boolean): node is ts.AssignmentExpression { return ts.isBinaryExpression(node) && (excludeCompoundAssignment @@ -5101,9 +5511,11 @@ export function isAssignmentExpression(node: ts.Node, excludeCompoundAssignment? && ts.isLeftHandSideExpression(node.left); } +/** @internal */ export function isLeftHandSideOfAssignment(node: ts.Node) { return isAssignmentExpression(node.parent) && node.parent.left === node; } +/** @internal */ export function isDestructuringAssignment(node: ts.Node): node is ts.DestructuringAssignment { if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) { const kind = node.left.kind; @@ -5114,14 +5526,17 @@ export function isDestructuringAssignment(node: ts.Node): node is ts.Destructuri return false; } +/** @internal */ export function isExpressionWithTypeArgumentsInClassExtendsClause(node: ts.Node): node is ts.ExpressionWithTypeArguments { return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined; } +/** @internal */ export function isEntityNameExpression(node: ts.Node): node is ts.EntityNameExpression { return node.kind === ts.SyntaxKind.Identifier || isPropertyAccessEntityNameExpression(node); } +/** @internal */ export function getFirstIdentifier(node: ts.EntityNameOrEntityNameExpression): ts.Identifier { switch (node.kind) { case ts.SyntaxKind.Identifier: @@ -5139,6 +5554,7 @@ export function getFirstIdentifier(node: ts.EntityNameOrEntityNameExpression): t } } +/** @internal */ export function isDottedName(node: ts.Expression): boolean { return node.kind === ts.SyntaxKind.Identifier || node.kind === ts.SyntaxKind.ThisKeyword @@ -5148,10 +5564,12 @@ export function isDottedName(node: ts.Expression): boolean { || node.kind === ts.SyntaxKind.ParenthesizedExpression && isDottedName((node as ts.ParenthesizedExpression).expression); } +/** @internal */ export function isPropertyAccessEntityNameExpression(node: ts.Node): node is ts.PropertyAccessEntityNameExpression { return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression); } +/** @internal */ export function tryGetPropertyAccessOrIdentifierToString(expr: ts.Expression): string | undefined { if (ts.isPropertyAccessExpression(expr)) { const baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression); @@ -5171,36 +5589,43 @@ export function tryGetPropertyAccessOrIdentifierToString(expr: ts.Expression): s return undefined; } +/** @internal */ export function isPrototypeAccess(node: ts.Node): node is ts.BindableStaticAccessExpression { return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype"; } +/** @internal */ export function isRightSideOfQualifiedNameOrPropertyAccess(node: ts.Node) { return (node.parent.kind === ts.SyntaxKind.QualifiedName && (node.parent as ts.QualifiedName).right === node) || (node.parent.kind === ts.SyntaxKind.PropertyAccessExpression && (node.parent as ts.PropertyAccessExpression).name === node); } +/** @internal */ export function isRightSideOfAccessExpression(node: ts.Node) { return ts.isPropertyAccessExpression(node.parent) && node.parent.name === node || ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node; } +/** @internal */ export function isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName(node: ts.Node) { return ts.isQualifiedName(node.parent) && node.parent.right === node || ts.isPropertyAccessExpression(node.parent) && node.parent.name === node || ts.isJSDocMemberName(node.parent) && node.parent.right === node; } +/** @internal */ export function isEmptyObjectLiteral(expression: ts.Node): boolean { return expression.kind === ts.SyntaxKind.ObjectLiteralExpression && (expression as ts.ObjectLiteralExpression).properties.length === 0; } +/** @internal */ export function isEmptyArrayLiteral(expression: ts.Node): boolean { return expression.kind === ts.SyntaxKind.ArrayLiteralExpression && (expression as ts.ArrayLiteralExpression).elements.length === 0; } +/** @internal */ export function getLocalSymbolForExportDefault(symbol: ts.Symbol) { if (!isExportDefaultSymbol(symbol) || !symbol.declarations) return undefined; for (const decl of symbol.declarations) { @@ -5213,6 +5638,7 @@ function isExportDefaultSymbol(symbol: ts.Symbol): boolean { return symbol && ts.length(symbol.declarations) > 0 && hasSyntacticModifier(symbol.declarations![0], ts.ModifierFlags.Default); } +/** @internal */ /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ export function tryExtractTSExtension(fileName: string): string | undefined { return ts.find(supportedTSExtensionsForExtractExtension, extension => ts.fileExtensionIs(fileName, extension)); @@ -5257,6 +5683,7 @@ function getExpandedCharCodes(input: string): number[] { const base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; +/** @internal */ /** * Converts a string to a base-64 encoded ASCII string. */ @@ -5326,6 +5753,7 @@ function getStringFromExpandedCharCodes(codes: number[]): string { return output; } +/** @internal */ export function base64encode(host: { base64encode?(input: string): string } | undefined, input: string): string { if (host && host.base64encode) { return host.base64encode(input); @@ -5333,6 +5761,7 @@ export function base64encode(host: { base64encode?(input: string): string } | un return convertToBase64(input); } +/** @internal */ export function base64decode(host: { base64decode?(input: string): string } | undefined, input: string): string { if (host && host.base64decode) { return host.base64decode(input); @@ -5369,6 +5798,7 @@ export function base64decode(host: { base64decode?(input: string): string } | un return getStringFromExpandedCharCodes(expandedCharCodes); } +/** @internal */ export function readJsonOrUndefined(path: string, hostOrText: { readFile(fileName: string): string | undefined } | string): object | undefined { const jsonText = ts.isString(hostOrText) ? hostOrText : hostOrText.readFile(path); if (!jsonText) return undefined; @@ -5377,10 +5807,12 @@ export function readJsonOrUndefined(path: string, hostOrText: { readFile(fileNam return !result.error ? result.config : undefined; } +/** @internal */ export function readJson(path: string, host: { readFile(fileName: string): string | undefined }): object { return readJsonOrUndefined(path, host) || {}; } +/** @internal */ export function directoryProbablyExists(directoryName: string, host: { directoryExists?: (directoryName: string) => boolean }): boolean { // if host does not support 'directoryExists' assume that directory will exist return !host.directoryExists || host.directoryExists(directoryName); @@ -5388,6 +5820,7 @@ export function directoryProbablyExists(directoryName: string, host: { directory const carriageReturnLineFeed = "\r\n"; const lineFeed = "\n"; +/** @internal */ export function getNewLineCharacter(options: ts.CompilerOptions | ts.PrinterOptions, getNewLine?: () => string): string { switch (options.newLine) { case ts.NewLineKind.CarriageReturnLineFeed: @@ -5398,6 +5831,7 @@ export function getNewLineCharacter(options: ts.CompilerOptions | ts.PrinterOpti return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } +/** @internal */ /** * Creates a new TextRange from the provided pos and end. * @@ -5409,6 +5843,7 @@ export function createRange(pos: number, end: number = pos): ts.TextRange { return { pos, end }; } +/** @internal */ /** * Creates a new TextRange from a provided range with a new end position. * @@ -5419,6 +5854,7 @@ export function moveRangeEnd(range: ts.TextRange, end: number): ts.TextRange { return createRange(range.pos, end); } +/** @internal */ /** * Creates a new TextRange from a provided range with a new start position. * @@ -5429,6 +5865,7 @@ export function moveRangePos(range: ts.TextRange, pos: number): ts.TextRange { return createRange(pos, range.end); } +/** @internal */ /** * Moves the start position of a range past any decorators. */ @@ -5439,6 +5876,7 @@ export function moveRangePastDecorators(node: ts.Node): ts.TextRange { : node; } +/** @internal */ /** * Moves the start position of a range past any decorators or modifiers. */ @@ -5449,6 +5887,7 @@ export function moveRangePastModifiers(node: ts.Node): ts.TextRange { : moveRangePastDecorators(node); } +/** @internal */ /** * Determines whether a TextRange has the same start and end positions. * @@ -5458,6 +5897,7 @@ export function isCollapsedRange(range: ts.TextRange) { return range.pos === range.end; } +/** @internal */ /** * Creates a new TextRange for a token at the provides start position. * @@ -5468,10 +5908,12 @@ export function createTokenRange(pos: number, token: ts.SyntaxKind): ts.TextRang return createRange(pos, pos + ts.tokenToString(token)!.length); } +/** @internal */ export function rangeIsOnSingleLine(range: ts.TextRange, sourceFile: ts.SourceFile) { return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile); } +/** @internal */ export function rangeStartPositionsAreOnSameLine(range1: ts.TextRange, range2: ts.TextRange, sourceFile: ts.SourceFile) { return positionsAreOnSameLine( getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), @@ -5479,45 +5921,55 @@ export function rangeStartPositionsAreOnSameLine(range1: ts.TextRange, range2: t sourceFile); } +/** @internal */ export function rangeEndPositionsAreOnSameLine(range1: ts.TextRange, range2: ts.TextRange, sourceFile: ts.SourceFile) { return positionsAreOnSameLine(range1.end, range2.end, sourceFile); } +/** @internal */ export function rangeStartIsOnSameLineAsRangeEnd(range1: ts.TextRange, range2: ts.TextRange, sourceFile: ts.SourceFile) { return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), range2.end, sourceFile); } +/** @internal */ export function rangeEndIsOnSameLineAsRangeStart(range1: ts.TextRange, range2: ts.TextRange, sourceFile: ts.SourceFile) { return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile); } +/** @internal */ export function getLinesBetweenRangeEndAndRangeStart(range1: ts.TextRange, range2: ts.TextRange, sourceFile: ts.SourceFile, includeSecondRangeComments: boolean) { const range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments); return ts.getLinesBetweenPositions(sourceFile, range1.end, range2Start); } +/** @internal */ export function getLinesBetweenRangeEndPositions(range1: ts.TextRange, range2: ts.TextRange, sourceFile: ts.SourceFile) { return ts.getLinesBetweenPositions(sourceFile, range1.end, range2.end); } +/** @internal */ export function isNodeArrayMultiLine(list: ts.NodeArray, sourceFile: ts.SourceFile): boolean { return !positionsAreOnSameLine(list.pos, list.end, sourceFile); } +/** @internal */ export function positionsAreOnSameLine(pos1: number, pos2: number, sourceFile: ts.SourceFile) { return ts.getLinesBetweenPositions(sourceFile, pos1, pos2) === 0; } +/** @internal */ export function getStartPositionOfRange(range: ts.TextRange, sourceFile: ts.SourceFile, includeComments: boolean) { return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments); } +/** @internal */ export function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos: number, stopPos: number, sourceFile: ts.SourceFile, includeComments?: boolean) { const startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); const prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile); return ts.getLinesBetweenPositions(sourceFile, prevPos ?? stopPos, startPos); } +/** @internal */ export function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos: number, stopPos: number, sourceFile: ts.SourceFile, includeComments?: boolean) { const nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments); return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos)); @@ -5531,6 +5983,7 @@ function getPreviousNonWhitespacePosition(pos: number, stopPos = 0, sourceFile: } } +/** @internal */ /** * Determines whether a name was originally the declaration name of an enum or namespace * declaration. @@ -5547,6 +6000,7 @@ export function isDeclarationNameOfEnumOrNamespace(node: ts.Identifier) { return false; } +/** @internal */ export function getInitializedVariables(node: ts.VariableDeclarationList) { return ts.filter(node.declarations, isInitializedVariable); } @@ -5555,19 +6009,23 @@ function isInitializedVariable(node: ts.VariableDeclaration): node is ts.Initial return node.initializer !== undefined; } +/** @internal */ export function isWatchSet(options: ts.CompilerOptions) { // Firefox has Object.prototype.watch return options.watch && ts.hasProperty(options, "watch"); } +/** @internal */ export function closeFileWatcher(watcher: ts.FileWatcher) { watcher.close(); } +/** @internal */ export function getCheckFlags(symbol: ts.Symbol): ts.CheckFlags { return symbol.flags & ts.SymbolFlags.Transient ? (symbol as ts.TransientSymbol).checkFlags : 0; } +/** @internal */ export function getDeclarationModifierFlagsFromSymbol(s: ts.Symbol, isWrite = false): ts.ModifierFlags { if (s.valueDeclaration) { const declaration = (isWrite && s.declarations && ts.find(s.declarations, ts.isSetAccessorDeclaration)) @@ -5589,19 +6047,23 @@ export function getDeclarationModifierFlagsFromSymbol(s: ts.Symbol, isWrite = fa return 0; } +/** @internal */ export function skipAlias(symbol: ts.Symbol, checker: ts.TypeChecker) { return symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol; } +/** @internal */ /** See comment on `declareModuleMember` in `binder.ts`. */ export function getCombinedLocalAndExportSymbolFlags(symbol: ts.Symbol): ts.SymbolFlags { return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags; } +/** @internal */ export function isWriteOnlyAccess(node: ts.Node) { return accessKind(node) === AccessKind.Write; } +/** @internal */ export function isWriteAccess(node: ts.Node) { return accessKind(node) !== AccessKind.Read; } @@ -5664,6 +6126,7 @@ function reverseAccessKind(a: AccessKind): AccessKind { } } +/** @internal */ export function compareDataObjects(dst: any, src: any): boolean { if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) { return false; @@ -5684,6 +6147,7 @@ export function compareDataObjects(dst: any, src: any): boolean { return true; } +/** @internal */ /** * clears already present map by calling onDeleteExistingValue callback before deleting that key/value */ @@ -5693,6 +6157,7 @@ export function clearMap(map: { forEach: ts.ESMap["forEach"]; clear: map.clear(); } +/** @internal */ export interface MutateMapSkippingNewValuesOptions { onDeleteValue(existingValue: T, key: K): void; @@ -5705,6 +6170,7 @@ export interface MutateMapSkippingNewValuesOptions { onExistingValue?(existingValue: T, valueInNewMap: U, key: K): void; } +/** @internal */ /** * Mutates the map with newMap such that keys in map will be same as newMap. */ @@ -5729,10 +6195,12 @@ export function mutateMapSkippingNewValues( }); } +/** @internal */ export interface MutateMapOptions extends MutateMapSkippingNewValuesOptions { createNewValue(key: K, valueInNewMap: U): T; } +/** @internal */ /** * Mutates the map with newMap such that keys in map will be same as newMap. */ @@ -5750,6 +6218,7 @@ export function mutateMap(map: ts.ESMap, newMap: ts.ReadonlyESMap }); } +/** @internal */ export function isAbstractConstructorSymbol(symbol: ts.Symbol): boolean { if (symbol.flags & ts.SymbolFlags.Class) { const declaration = getClassLikeDeclarationOfSymbol(symbol); @@ -5758,30 +6227,37 @@ export function isAbstractConstructorSymbol(symbol: ts.Symbol): boolean { return false; } +/** @internal */ export function getClassLikeDeclarationOfSymbol(symbol: ts.Symbol): ts.ClassLikeDeclaration | undefined { return symbol.declarations?.find(ts.isClassLike); } +/** @internal */ export function getObjectFlags(type: ts.Type): ts.ObjectFlags { return type.flags & ts.TypeFlags.ObjectFlagsType ? (type as ts.ObjectFlagsType).objectFlags : 0; } +/** @internal */ export function typeHasCallOrConstructSignatures(type: ts.Type, checker: ts.TypeChecker) { return checker.getSignaturesOfType(type, ts.SignatureKind.Call).length !== 0 || checker.getSignaturesOfType(type, ts.SignatureKind.Construct).length !== 0; } +/** @internal */ export function forSomeAncestorDirectory(directory: string, callback: (directory: string) => boolean): boolean { return !!ts.forEachAncestorDirectory(directory, d => callback(d) ? true : undefined); } +/** @internal */ export function isUMDExportSymbol(symbol: ts.Symbol | undefined): boolean { return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]); } +/** @internal */ export function showModuleSpecifier({ moduleSpecifier }: ts.ImportDeclaration): string { return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier); } +/** @internal */ export function getLastChild(node: ts.Node): ts.Node | undefined { let lastChild: ts.Node | undefined; ts.forEachChild(node, @@ -5800,9 +6276,12 @@ export function getLastChild(node: ts.Node): ts.Node | undefined { return lastChild; } +/** @internal */ /** Add a value to a set, and return true if it wasn't already present. */ export function addToSeen(seen: ts.ESMap, key: K): boolean; +/** @internal */ export function addToSeen(seen: ts.ESMap, key: K, value: T): boolean; +/** @internal */ export function addToSeen(seen: ts.ESMap, key: K, value: T = true as any): boolean { if (seen.has(key)) { return false; @@ -5811,10 +6290,12 @@ export function addToSeen(seen: ts.ESMap, key: K, value: T = true as return true; } +/** @internal */ export function isObjectTypeDeclaration(node: ts.Node): node is ts.ObjectTypeDeclaration { return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node); } +/** @internal */ export function isTypeNodeKind(kind: ts.SyntaxKind): kind is ts.TypeNodeSyntaxKind { return (kind >= ts.SyntaxKind.FirstTypeNode && kind <= ts.SyntaxKind.LastTypeNode) || kind === ts.SyntaxKind.AnyKeyword @@ -5838,10 +6319,12 @@ export function isTypeNodeKind(kind: ts.SyntaxKind): kind is ts.TypeNodeSyntaxKi || kind === ts.SyntaxKind.JSDocVariadicType; } +/** @internal */ export function isAccessExpression(node: ts.Node): node is ts.AccessExpression { return node.kind === ts.SyntaxKind.PropertyAccessExpression || node.kind === ts.SyntaxKind.ElementAccessExpression; } +/** @internal */ export function getNameOfAccessExpression(node: ts.AccessExpression) { if (node.kind === ts.SyntaxKind.PropertyAccessExpression) { return node.name; @@ -5850,6 +6333,7 @@ export function getNameOfAccessExpression(node: ts.AccessExpression) { return node.argumentExpression; } +/** @internal */ export function isBundleFileTextLike(section: ts.BundleFileSection): section is ts.BundleFileTextLike { switch (section.kind) { case ts.BundleFileSectionKind.Text: @@ -5860,10 +6344,12 @@ export function isBundleFileTextLike(section: ts.BundleFileSection): section is } } +/** @internal */ export function isNamedImportsOrExports(node: ts.Node): node is ts.NamedImportsOrExports { return node.kind === ts.SyntaxKind.NamedImports || node.kind === ts.SyntaxKind.NamedExports; } +/** @internal */ export function getLeftmostAccessExpression(expr: ts.Expression): ts.Expression { while (isAccessExpression(expr)) { expr = expr.expression; @@ -5871,6 +6357,7 @@ export function getLeftmostAccessExpression(expr: ts.Expression): ts.Expression return expr; } +/** @internal */ export function forEachNameInAccessChainWalkingLeft(name: ts.MemberName | ts.StringLiteralLike, action: (name: ts.MemberName | ts.StringLiteralLike) => T | undefined): T | undefined { if (isAccessExpression(name.parent) && isRightSideOfAccessExpression(name)) { return walkAccessExpression(name.parent); @@ -5910,6 +6397,7 @@ export function forEachNameInAccessChainWalkingLeft(name: ts.MemberName | ts. +/** @internal */ export function getLeftmostExpression(node: ts.Expression, stopAtCallExpressions: boolean) { while (true) { switch (node.kind) { @@ -5948,6 +6436,7 @@ export function getLeftmostExpression(node: ts.Expression, stopAtCallExpressions } } +/** @internal */ export interface ObjectAllocator { getNodeConstructor(): new (kind: ts.SyntaxKind, pos?: number, end?: number) => ts.Node; getTokenConstructor(): new (kind: TKind, pos?: number, end?: number) => ts.Token; @@ -6025,6 +6514,7 @@ function SourceMapSource(this: ts.SourceMapSource, fileName: string, text: strin } // eslint-disable-next-line prefer-const +/** @internal */ export const objectAllocator: ObjectAllocator = { getNodeConstructor: () => Node as any, getTokenConstructor: () => Token as any, @@ -6037,10 +6527,12 @@ export const objectAllocator: ObjectAllocator = { getSourceMapSourceConstructor: () => SourceMapSource as any, }; +/** @internal */ export function setObjectAllocator(alloc: ObjectAllocator) { Object.assign(objectAllocator, alloc); } +/** @internal */ export function formatStringFromArgs(text: string, args: ArrayLike, baseIndex = 0): string { return text.replace(/{(\d+)}/g, (_match, index: string) => "" + ts.Debug.checkDefined(args[+index + baseIndex])); } @@ -6061,11 +6553,14 @@ export function maybeSetLocalizedDiagnosticMessages(getMessages: undefined | (() } } +/** @internal */ export function getLocaleSpecificMessage(message: ts.DiagnosticMessage) { return localizedDiagnosticMessages && localizedDiagnosticMessages[message.key] || message.message; } +/** @internal */ export function createDetachedDiagnostic(fileName: string, start: number, length: number, message: ts.DiagnosticMessage, ...args: (string | number | undefined)[]): ts.DiagnosticWithDetachedLocation; +/** @internal */ export function createDetachedDiagnostic(fileName: string, start: number, length: number, message: ts.DiagnosticMessage): ts.DiagnosticWithDetachedLocation { assertDiagnosticLocation(/*file*/ undefined, start, length); let text = getLocaleSpecificMessage(message); @@ -6125,6 +6620,7 @@ function attachFileToDiagnostic(diagnostic: ts.DiagnosticWithDetachedLocation, f return diagnosticWithLocation; } +/** @internal */ export function attachFileToDiagnostics(diagnostics: ts.DiagnosticWithDetachedLocation[], file: ts.SourceFile): ts.DiagnosticWithLocation[] { const diagnosticsWithLocation: ts.DiagnosticWithLocation[] = []; for (const diagnostic of diagnostics) { @@ -6133,7 +6629,9 @@ export function attachFileToDiagnostics(diagnostics: ts.DiagnosticWithDetachedLo return diagnosticsWithLocation; } +/** @internal */ export function createFileDiagnostic(file: ts.SourceFile, start: number, length: number, message: ts.DiagnosticMessage, ...args: (string | number | undefined)[]): ts.DiagnosticWithLocation; +/** @internal */ export function createFileDiagnostic(file: ts.SourceFile, start: number, length: number, message: ts.DiagnosticMessage): ts.DiagnosticWithLocation { assertDiagnosticLocation(file, start, length); @@ -6156,7 +6654,9 @@ export function createFileDiagnostic(file: ts.SourceFile, start: number, length: }; } +/** @internal */ export function formatMessage(_dummy: any, message: ts.DiagnosticMessage, ...args: (string | number | undefined)[]): string; +/** @internal */ export function formatMessage(_dummy: any, message: ts.DiagnosticMessage): string { let text = getLocaleSpecificMessage(message); @@ -6167,7 +6667,9 @@ export function formatMessage(_dummy: any, message: ts.DiagnosticMessage): strin return text; } +/** @internal */ export function createCompilerDiagnostic(message: ts.DiagnosticMessage, ...args: (string | number | undefined)[]): ts.Diagnostic; +/** @internal */ export function createCompilerDiagnostic(message: ts.DiagnosticMessage): ts.Diagnostic { let text = getLocaleSpecificMessage(message); @@ -6188,6 +6690,7 @@ export function createCompilerDiagnostic(message: ts.DiagnosticMessage): ts.Diag }; } +/** @internal */ export function createCompilerDiagnosticFromMessageChain(chain: ts.DiagnosticMessageChain, relatedInformation?: ts.DiagnosticRelatedInformation[]): ts.Diagnostic { return { file: undefined, @@ -6201,7 +6704,9 @@ export function createCompilerDiagnosticFromMessageChain(chain: ts.DiagnosticMes }; } +/** @internal */ export function chainDiagnosticMessages(details: ts.DiagnosticMessageChain | ts.DiagnosticMessageChain[] | undefined, message: ts.DiagnosticMessage, ...args: (string | number | undefined)[]): ts.DiagnosticMessageChain; +/** @internal */ export function chainDiagnosticMessages(details: ts.DiagnosticMessageChain | ts.DiagnosticMessageChain[] | undefined, message: ts.DiagnosticMessage): ts.DiagnosticMessageChain { let text = getLocaleSpecificMessage(message); @@ -6217,6 +6722,7 @@ export function chainDiagnosticMessages(details: ts.DiagnosticMessageChain | ts. }; } +/** @internal */ export function concatenateDiagnosticMessageChains(headChain: ts.DiagnosticMessageChain, tailChain: ts.DiagnosticMessageChain): void { let lastChain = headChain; while (lastChain.next) { @@ -6230,12 +6736,14 @@ function getDiagnosticFilePath(diagnostic: ts.Diagnostic): string | undefined { return diagnostic.file ? diagnostic.file.path : undefined; } +/** @internal */ export function compareDiagnostics(d1: ts.Diagnostic, d2: ts.Diagnostic): ts.Comparison { return compareDiagnosticsSkipRelatedInformation(d1, d2) || compareRelatedInformation(d1, d2) || ts.Comparison.EqualTo; } +/** @internal */ export function compareDiagnosticsSkipRelatedInformation(d1: ts.Diagnostic, d2: ts.Diagnostic): ts.Comparison { return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) || ts.compareValues(d1.start, d2.start) || @@ -6297,6 +6805,7 @@ function compareMessageText(t1: string | ts.DiagnosticMessageChain, t2: string | return ts.Comparison.EqualTo; } +/** @internal */ export function getLanguageVariant(scriptKind: ts.ScriptKind) { // .tsx and .jsx files are treated as jsx language variant. return scriptKind === ts.ScriptKind.TSX || scriptKind === ts.ScriptKind.JSX || scriptKind === ts.ScriptKind.JS || scriptKind === ts.ScriptKind.JSON ? ts.LanguageVariant.JSX : ts.LanguageVariant.Standard; @@ -6329,6 +6838,7 @@ function isFileForcedToBeModuleByFormat(file: ts.SourceFile): true | undefined { return (file.impliedNodeFormat === ts.ModuleKind.ESNext || (ts.fileExtensionIsOneOf(file.fileName, [ts.Extension.Cjs, ts.Extension.Cts, ts.Extension.Mjs, ts.Extension.Mts]))) && !file.isDeclarationFile ? true : undefined; } +/** @internal */ export function getSetExternalModuleIndicator(options: ts.CompilerOptions): (file: ts.SourceFile) => void { // TODO: Should this callback be cached? switch (getEmitModuleDetectionKind(options)) { @@ -6357,6 +6867,7 @@ export function getSetExternalModuleIndicator(options: ts.CompilerOptions): (fil } } +/** @internal */ export function getEmitScriptTarget(compilerOptions: {module?: ts.CompilerOptions["module"], target?: ts.CompilerOptions["target"]}) { return compilerOptions.target || (compilerOptions.module === ts.ModuleKind.Node16 && ts.ScriptTarget.ES2022) || @@ -6364,12 +6875,14 @@ export function getEmitScriptTarget(compilerOptions: {module?: ts.CompilerOption ts.ScriptTarget.ES3; } +/** @internal */ export function getEmitModuleKind(compilerOptions: {module?: ts.CompilerOptions["module"], target?: ts.CompilerOptions["target"]}) { return typeof compilerOptions.module === "number" ? compilerOptions.module : getEmitScriptTarget(compilerOptions) >= ts.ScriptTarget.ES2015 ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS; } +/** @internal */ export function getEmitModuleResolutionKind(compilerOptions: ts.CompilerOptions) { let moduleResolution = compilerOptions.moduleResolution; if (moduleResolution === undefined) { @@ -6391,11 +6904,13 @@ export function getEmitModuleResolutionKind(compilerOptions: ts.CompilerOptions) return moduleResolution; } +/** @internal */ export function getEmitModuleDetectionKind(options: ts.CompilerOptions) { return options.moduleDetection || (getEmitModuleKind(options) === ts.ModuleKind.Node16 || getEmitModuleKind(options) === ts.ModuleKind.NodeNext ? ts.ModuleDetectionKind.Force : ts.ModuleDetectionKind.Auto); } +/** @internal */ export function hasJsonModuleEmitEnabled(options: ts.CompilerOptions) { switch (getEmitModuleKind(options)) { case ts.ModuleKind.CommonJS: @@ -6412,18 +6927,22 @@ export function hasJsonModuleEmitEnabled(options: ts.CompilerOptions) { } } +/** @internal */ export function unreachableCodeIsError(options: ts.CompilerOptions): boolean { return options.allowUnreachableCode === false; } +/** @internal */ export function unusedLabelIsError(options: ts.CompilerOptions): boolean { return options.allowUnusedLabels === false; } +/** @internal */ export function getAreDeclarationMapsEnabled(options: ts.CompilerOptions) { return !!(getEmitDeclarations(options) && options.declarationMap); } +/** @internal */ export function getESModuleInterop(compilerOptions: ts.CompilerOptions) { if (compilerOptions.esModuleInterop !== undefined) { return compilerOptions.esModuleInterop; @@ -6436,6 +6955,7 @@ export function getESModuleInterop(compilerOptions: ts.CompilerOptions) { return undefined; } +/** @internal */ export function getAllowSyntheticDefaultImports(compilerOptions: ts.CompilerOptions) { const moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined @@ -6444,18 +6964,22 @@ export function getAllowSyntheticDefaultImports(compilerOptions: ts.CompilerOpti moduleKind === ts.ModuleKind.System; } +/** @internal */ export function getEmitDeclarations(compilerOptions: ts.CompilerOptions): boolean { return !!(compilerOptions.declaration || compilerOptions.composite); } +/** @internal */ export function shouldPreserveConstEnums(compilerOptions: ts.CompilerOptions): boolean { return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } +/** @internal */ export function isIncrementalCompilation(options: ts.CompilerOptions) { return !!(options.incremental || options.composite); } +/** @internal */ export type StrictOptionName = | "noImplicitAny" | "noImplicitThis" @@ -6467,39 +6991,48 @@ export type StrictOptionName = | "useUnknownInCatchVariables" ; +/** @internal */ export function getStrictOptionValue(compilerOptions: ts.CompilerOptions, flag: StrictOptionName): boolean { return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag]; } +/** @internal */ export function getAllowJSCompilerOption(compilerOptions: ts.CompilerOptions): boolean { return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs; } +/** @internal */ export function getUseDefineForClassFields(compilerOptions: ts.CompilerOptions): boolean { return compilerOptions.useDefineForClassFields === undefined ? getEmitScriptTarget(compilerOptions) >= ts.ScriptTarget.ES2022 : compilerOptions.useDefineForClassFields; } +/** @internal */ export function compilerOptionsAffectSemanticDiagnostics(newOptions: ts.CompilerOptions, oldOptions: ts.CompilerOptions): boolean { return optionsHaveChanges(oldOptions, newOptions, ts.semanticDiagnosticsOptionDeclarations); } +/** @internal */ export function compilerOptionsAffectEmit(newOptions: ts.CompilerOptions, oldOptions: ts.CompilerOptions): boolean { return optionsHaveChanges(oldOptions, newOptions, ts.affectsEmitOptionDeclarations); } +/** @internal */ export function compilerOptionsAffectDeclarationPath(newOptions: ts.CompilerOptions, oldOptions: ts.CompilerOptions): boolean { return optionsHaveChanges(oldOptions, newOptions, ts.affectsDeclarationPathOptionDeclarations); } +/** @internal */ export function getCompilerOptionValue(options: ts.CompilerOptions, option: ts.CommandLineOption): unknown { return option.strictFlag ? getStrictOptionValue(options, option.name as StrictOptionName) : options[option.name]; } +/** @internal */ export function getJSXTransformEnabled(options: ts.CompilerOptions): boolean { const jsx = options.jsx; return jsx === ts.JsxEmit.React || jsx === ts.JsxEmit.ReactJSX || jsx === ts.JsxEmit.ReactJSXDev; } +/** @internal */ export function getJSXImplicitImportBase(compilerOptions: ts.CompilerOptions, file?: ts.SourceFile): string | undefined { const jsxImportSourcePragmas = file?.pragmas.get("jsximportsource"); const jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[jsxImportSourcePragmas.length - 1] : jsxImportSourcePragmas; @@ -6511,10 +7044,12 @@ export function getJSXImplicitImportBase(compilerOptions: ts.CompilerOptions, fi undefined; } +/** @internal */ export function getJSXRuntimeImport(base: string | undefined, options: ts.CompilerOptions) { return base ? `${base}/${options.jsx === ts.JsxEmit.ReactJSXDev ? "jsx-dev-runtime" : "jsx-runtime"}` : undefined; } +/** @internal */ export function hasZeroOrOneAsteriskCharacter(str: string): boolean { let seenAsterisk = false; for (let i = 0; i < str.length; i++) { @@ -6531,6 +7066,7 @@ export function hasZeroOrOneAsteriskCharacter(str: string): boolean { return true; } +/** @internal */ export interface SymlinkedDirectory { /** Matches the casing returned by `realpath`. Used to compute the `realpath` of children. */ real: string; @@ -6538,6 +7074,7 @@ export interface SymlinkedDirectory { realPath: ts.Path; } +/** @internal */ export interface SymlinkCache { /** Gets a map from symlink to realpath. Keys have trailing directory separators. */ getSymlinkedDirectories(): ts.ReadonlyESMap | undefined; @@ -6561,6 +7098,7 @@ export interface SymlinkCache { hasProcessedResolutions(): boolean; } +/** @internal */ export function createSymlinkCache(cwd: string, getCanonicalFileName: ts.GetCanonicalFileName): SymlinkCache { let symlinkedDirectories: ts.ESMap | undefined; let symlinkedDirectoriesByRealpath: ts.MultiMap | undefined; @@ -6635,6 +7173,7 @@ function stripLeadingDirectorySeparator(s: string): string | undefined { return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; } +/** @internal */ export function tryRemoveDirectoryPrefix(path: string, dirPath: string, getCanonicalFileName: ts.GetCanonicalFileName): string | undefined { const withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix); @@ -6645,6 +7184,7 @@ export function tryRemoveDirectoryPrefix(path: string, dirPath: string, getCanon // proof. const reservedCharacterPattern = /[^\w\s\/]/g; +/** @internal */ export function regExpEscape(text: string) { return text.replace(reservedCharacterPattern, escapeRegExpCharacter); } @@ -6655,6 +7195,7 @@ function escapeRegExpCharacter(match: string) { const wildcardCharCodes = [ts.CharacterCodes.asterisk, ts.CharacterCodes.question]; +/** @internal */ export const commonPackageFolders: readonly string[] = ["node_modules", "bower_components", "jspm_packages"]; const implicitExcludePathRegexPattern = `(?!(${commonPackageFolders.join("|")})(/|$))`; @@ -6703,6 +7244,7 @@ const wildcardMatchers = { exclude: excludeMatcher }; +/** @internal */ export function getRegularExpressionForWildcard(specs: readonly string[] | undefined, basePath: string, usage: "files" | "directories" | "exclude"): string | undefined { const patterns = getRegularExpressionsForWildcards(specs, basePath, usage); if (!patterns || !patterns.length) { @@ -6715,6 +7257,7 @@ export function getRegularExpressionForWildcard(specs: readonly string[] | undef return `^(${pattern})${terminator}`; } +/** @internal */ export function getRegularExpressionsForWildcards(specs: readonly string[] | undefined, basePath: string, usage: "files" | "directories" | "exclude"): readonly string[] | undefined { if (specs === undefined || specs.length === 0) { return undefined; @@ -6724,6 +7267,7 @@ export function getRegularExpressionsForWildcards(specs: readonly string[] | und spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage])); } +/** @internal */ /** * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension, * and does not contain any glob characters itself. @@ -6732,6 +7276,7 @@ export function isImplicitGlob(lastPathComponent: string): boolean { return !/[.*?]/.test(lastPathComponent); } +/** @internal */ export function getPatternFromSpec(spec: string, basePath: string, usage: "files" | "directories" | "exclude") { const pattern = spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); return pattern && `^(${pattern})${usage === "exclude" ? "($|/)" : "$"}`; @@ -6817,11 +7362,13 @@ function replaceWildcardCharacter(match: string, singleAsteriskRegexFragment: st return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match; } +/** @internal */ export interface FileSystemEntries { readonly files: readonly string[]; readonly directories: readonly string[]; } +/** @internal */ export interface FileMatcherPatterns { /** One pattern for each "include" spec. */ includeFilePatterns: readonly string[] | undefined; @@ -6832,6 +7379,7 @@ export interface FileMatcherPatterns { basePaths: readonly string[]; } +/** @internal */ /** @param path directory of the tsconfig.json */ export function getFileMatcherPatterns(path: string, excludes: readonly string[] | undefined, includes: readonly string[] | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string): FileMatcherPatterns { path = ts.normalizePath(path); @@ -6847,10 +7395,12 @@ export function getFileMatcherPatterns(path: string, excludes: readonly string[] }; } +/** @internal */ export function getRegexFromPattern(pattern: string, useCaseSensitiveFileNames: boolean): RegExp { return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i"); } +/** @internal */ /** @param path directory of the tsconfig.json */ export function matchFiles(path: string, extensions: readonly string[] | undefined, excludes: readonly string[] | undefined, includes: readonly string[] | undefined, useCaseSensitiveFileNames: boolean, currentDirectory: string, depth: number | undefined, getFileSystemEntries: (path: string) => FileSystemEntries, realpath: (path: string) => string): string[] { path = ts.normalizePath(path); @@ -6957,6 +7507,7 @@ function getIncludeBasePath(absolute: string): string { return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } +/** @internal */ export function ensureScriptKind(fileName: string, scriptKind: ts.ScriptKind | undefined): ts.ScriptKind { // Using scriptKind as a condition handles both: // - 'scriptKind' is unspecified and thus it is `undefined` @@ -6967,6 +7518,7 @@ export function ensureScriptKind(fileName: string, scriptKind: ts.ScriptKind | u return scriptKind || getScriptKindFromFileName(fileName) || ts.ScriptKind.TS; } +/** @internal */ export function getScriptKindFromFileName(fileName: string): ts.ScriptKind { const ext = fileName.substr(fileName.lastIndexOf(".")); switch (ext.toLowerCase()) { @@ -6989,22 +7541,30 @@ export function getScriptKindFromFileName(fileName: string): ts.ScriptKind { } } +/** @internal */ /** * Groups of supported extensions in order of file resolution precedence. (eg, TS > TSX > DTS and seperately, CTS > DCTS) */ export const supportedTSExtensions: readonly ts.Extension[][] = [[ts.Extension.Ts, ts.Extension.Tsx, ts.Extension.Dts], [ts.Extension.Cts, ts.Extension.Dcts], [ts.Extension.Mts, ts.Extension.Dmts]]; +/** @internal */ export const supportedTSExtensionsFlat: readonly ts.Extension[] = ts.flatten(supportedTSExtensions); const supportedTSExtensionsWithJson: readonly ts.Extension[][] = [...supportedTSExtensions, [ts.Extension.Json]]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ const supportedTSExtensionsForExtractExtension: readonly ts.Extension[] = [ts.Extension.Dts, ts.Extension.Dcts, ts.Extension.Dmts, ts.Extension.Cts, ts.Extension.Mts, ts.Extension.Ts, ts.Extension.Tsx, ts.Extension.Cts, ts.Extension.Mts]; +/** @internal */ export const supportedJSExtensions: readonly ts.Extension[][] = [[ts.Extension.Js, ts.Extension.Jsx], [ts.Extension.Mjs], [ts.Extension.Cjs]]; +/** @internal */ export const supportedJSExtensionsFlat: readonly ts.Extension[] = ts.flatten(supportedJSExtensions); const allSupportedExtensions: readonly ts.Extension[][] = [[ts.Extension.Ts, ts.Extension.Tsx, ts.Extension.Dts, ts.Extension.Js, ts.Extension.Jsx], [ts.Extension.Cts, ts.Extension.Dcts, ts.Extension.Cjs], [ts.Extension.Mts, ts.Extension.Dmts, ts.Extension.Mjs]]; const allSupportedExtensionsWithJson: readonly ts.Extension[][] = [...allSupportedExtensions, [ts.Extension.Json]]; +/** @internal */ export const supportedDeclarationExtensions: readonly ts.Extension[] = [ts.Extension.Dts, ts.Extension.Dcts, ts.Extension.Dmts]; +/** @internal */ export function getSupportedExtensions(options?: ts.CompilerOptions): readonly ts.Extension[][]; +/** @internal */ export function getSupportedExtensions(options?: ts.CompilerOptions, extraFileExtensions?: readonly ts.FileExtensionInfo[]): readonly string[][]; +/** @internal */ export function getSupportedExtensions(options?: ts.CompilerOptions, extraFileExtensions?: readonly ts.FileExtensionInfo[]): readonly string[][] { const needJsExtensions = options && getAllowJSCompilerOption(options); @@ -7022,8 +7582,11 @@ export function getSupportedExtensions(options?: ts.CompilerOptions, extraFileEx return extensions; } +/** @internal */ export function getSupportedExtensionsWithJsonIfResolveJsonModule(options: ts.CompilerOptions | undefined, supportedExtensions: readonly ts.Extension[][]): readonly ts.Extension[][]; +/** @internal */ export function getSupportedExtensionsWithJsonIfResolveJsonModule(options: ts.CompilerOptions | undefined, supportedExtensions: readonly string[][]): readonly string[][]; +/** @internal */ export function getSupportedExtensionsWithJsonIfResolveJsonModule(options: ts.CompilerOptions | undefined, supportedExtensions: readonly string[][]): readonly string[][] { if (!options || !options.resolveJsonModule) return supportedExtensions; if (supportedExtensions === allSupportedExtensions) return allSupportedExtensionsWithJson; @@ -7035,14 +7598,17 @@ function isJSLike(scriptKind: ts.ScriptKind | undefined): boolean { return scriptKind === ts.ScriptKind.JS || scriptKind === ts.ScriptKind.JSX; } +/** @internal */ export function hasJSFileExtension(fileName: string): boolean { return ts.some(supportedJSExtensionsFlat, extension => ts.fileExtensionIs(fileName, extension)); } +/** @internal */ export function hasTSFileExtension(fileName: string): boolean { return ts.some(supportedTSExtensionsFlat, extension => ts.fileExtensionIs(fileName, extension)); } +/** @internal */ export function isSupportedSourceFileName(fileName: string, compilerOptions?: ts.CompilerOptions, extraFileExtensions?: readonly ts.FileExtensionInfo[]) { if (!fileName) return false; @@ -7060,6 +7626,7 @@ function numberOfDirectorySeparators(str: string) { return match ? match.length : 0; } +/** @internal */ export function compareNumberOfDirectorySeparators(path1: string, path2: string) { return ts.compareValues( numberOfDirectorySeparators(path1), @@ -7068,6 +7635,7 @@ export function compareNumberOfDirectorySeparators(path1: string, path2: string) } const extensionsToRemove = [ts.Extension.Dts, ts.Extension.Dmts, ts.Extension.Dcts, ts.Extension.Mjs, ts.Extension.Mts, ts.Extension.Cjs, ts.Extension.Cts, ts.Extension.Ts, ts.Extension.Js, ts.Extension.Tsx, ts.Extension.Jsx, ts.Extension.Json]; +/** @internal */ export function removeFileExtension(path: string): string { for (const ext of extensionsToRemove) { const extensionless = tryRemoveExtension(path, ext); @@ -7078,18 +7646,22 @@ export function removeFileExtension(path: string): string { return path; } +/** @internal */ export function tryRemoveExtension(path: string, extension: string): string | undefined { return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined; } +/** @internal */ export function removeExtension(path: string, extension: string): string { return path.substring(0, path.length - extension.length); } +/** @internal */ export function changeExtension(path: T, newExtension: string): T { return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false) as T; } +/** @internal */ /** * Returns the input if there are no stars, a pattern if there is exactly one, * and undefined if there are more. @@ -7107,25 +7679,30 @@ export function tryParsePattern(pattern: string): string | ts.Pattern | undefine }; } +/** @internal */ export function tryParsePatterns(paths: ts.MapLike): (string | ts.Pattern)[] { return ts.mapDefined(ts.getOwnKeys(paths), path => tryParsePattern(path)); } +/** @internal */ export function positionIsSynthesized(pos: number): boolean { // This is a fast way of testing the following conditions: // pos === undefined || pos === null || isNaN(pos) || pos < 0; return !(pos >= 0); } +/** @internal */ /** True if an extension is one of the supported TypeScript extensions. */ export function extensionIsTS(ext: ts.Extension): boolean { return ext === ts.Extension.Ts || ext === ts.Extension.Tsx || ext === ts.Extension.Dts || ext === ts.Extension.Cts || ext === ts.Extension.Mts || ext === ts.Extension.Dmts || ext === ts.Extension.Dcts; } +/** @internal */ export function resolutionExtensionIsTSOrJson(ext: ts.Extension) { return extensionIsTS(ext) || ext === ts.Extension.Json; } +/** @internal */ /** * Gets the extension from a path. * Path must have a valid extension. @@ -7135,24 +7712,29 @@ export function extensionFromPath(path: string): ts.Extension { return ext !== undefined ? ext : ts.Debug.fail(`File ${path} has unknown extension.`); } +/** @internal */ export function isAnySupportedFileExtension(path: string): boolean { return tryGetExtensionFromPath(path) !== undefined; } +/** @internal */ export function tryGetExtensionFromPath(path: string): ts.Extension | undefined { return ts.find(extensionsToRemove, e => ts.fileExtensionIs(path, e)); } +/** @internal */ export function isCheckJsEnabledForFile(sourceFile: ts.SourceFile, compilerOptions: ts.CompilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } +/** @internal */ export const emptyFileSystemEntries: FileSystemEntries = { files: ts.emptyArray, directories: ts.emptyArray }; +/** @internal */ /** * patternOrStrings contains both patterns (containing "*") and regular strings. * Return an exact match if possible, or a pattern match, or undefined. @@ -7173,14 +7755,17 @@ export function matchPatternOrExact(patternOrStrings: readonly (string | ts.Patt return ts.findBestPatternMatch(patterns, _ => _, candidate); } +/** @internal */ export type Mutable = { -readonly [K in keyof T]: T[K] }; +/** @internal */ export function sliceAfter(arr: readonly T[], value: T): readonly T[] { const index = arr.indexOf(value); ts.Debug.assert(index !== -1); return arr.slice(index); } +/** @internal */ export function addRelatedInfo(diagnostic: T, ...relatedInformation: ts.DiagnosticRelatedInformation[]): T { if (!relatedInformation.length) { return diagnostic; @@ -7193,6 +7778,7 @@ export function addRelatedInfo(diagnostic: T, ...relate return diagnostic; } +/** @internal */ export function minAndMax(arr: readonly T[], getValue: (value: T) => number): { readonly min: number, readonly max: number } { ts.Debug.assert(arr.length !== 0); let min = getValue(arr[0]); @@ -7209,10 +7795,12 @@ export function minAndMax(arr: readonly T[], getValue: (value: T) => number): return { min, max }; } +/** @internal */ export function rangeOfNode(node: ts.Node): ts.TextRange { return { pos: getTokenPosOfNode(node), end: node.end }; } +/** @internal */ export function rangeOfTypeParameters(sourceFile: ts.SourceFile, typeParameters: ts.NodeArray): ts.TextRange { // Include the `<>` const pos = typeParameters.pos - 1; @@ -7220,9 +7808,11 @@ export function rangeOfTypeParameters(sourceFile: ts.SourceFile, typeParameters: return { pos, end }; } +/** @internal */ export interface HostWithIsSourceOfProjectReferenceRedirect { isSourceOfProjectReferenceRedirect(fileName: string): boolean; } +/** @internal */ export function skipTypeChecking(sourceFile: ts.SourceFile, options: ts.CompilerOptions, host: HostWithIsSourceOfProjectReferenceRedirect) { // If skipLibCheck is enabled, skip reporting errors if file is a declaration file. // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a @@ -7232,11 +7822,13 @@ export function skipTypeChecking(sourceFile: ts.SourceFile, options: ts.Compiler host.isSourceOfProjectReferenceRedirect(sourceFile.fileName); } +/** @internal */ export function isJsonEqual(a: unknown, b: unknown): boolean { // eslint-disable-next-line no-null/no-null return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a as ts.MapLike, b as ts.MapLike, isJsonEqual); } +/** @internal */ /** * Converts a bigint literal string, e.g. `0x1234n`, * to its decimal string representation, e.g. `4660`. @@ -7308,10 +7900,12 @@ export function parsePseudoBigInt(stringValue: string): string { return base10Value; } +/** @internal */ export function pseudoBigIntToString({negative, base10Value}: ts.PseudoBigInt): string { return (negative && base10Value !== "0" ? "-" : "") + base10Value; } +/** @internal */ export function isValidTypeOnlyAliasUseSite(useSite: ts.Node): boolean { return !!(useSite.flags & ts.NodeFlags.Ambient) || isPartOfTypeQuery(useSite) @@ -7355,10 +7949,12 @@ function isIdentifierInNonEmittingHeritageClause(node: ts.Node): boolean { return heritageClause?.token === ts.SyntaxKind.ImplementsKeyword || heritageClause?.parent.kind === ts.SyntaxKind.InterfaceDeclaration; } +/** @internal */ export function isIdentifierTypeReference(node: ts.Node): node is ts.TypeReferenceNode & { typeName: ts.Identifier } { return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName); } +/** @internal */ export function arrayIsHomogeneous(array: readonly T[], comparer: ts.EqualityComparer = ts.equateValues) { if (array.length < 2) return true; const first = array[0]; @@ -7411,6 +8007,7 @@ export function setTextRangePosWidth(range: T, p export function setNodeFlags(node: T, newFlags: ts.NodeFlags): T; /* @internal */ export function setNodeFlags(node: T | undefined, newFlags: ts.NodeFlags): T | undefined; +/** @internal */ export function setNodeFlags(node: T | undefined, newFlags: ts.NodeFlags): T | undefined { if (node) { (node as Mutable).flags = newFlags; @@ -7425,6 +8022,7 @@ export function setNodeFlags(node: T | undefined, newFlags: t export function setParent(child: T, parent: T["parent"] | undefined): T; /* @internal */ export function setParent(child: T | undefined, parent: T["parent"] | undefined): T | undefined; +/** @internal */ export function setParent(child: T | undefined, parent: T["parent"] | undefined): T | undefined { if (child && parent) { (child as Mutable).parent = parent; @@ -7439,6 +8037,7 @@ export function setParent(child: T | undefined, parent: T["pa export function setEachParent(children: T, parent: T[number]["parent"]): T; /* @internal */ export function setEachParent(children: T | undefined, parent: T[number]["parent"]): T | undefined; +/** @internal */ export function setEachParent(children: T | undefined, parent: T[number]["parent"]): T | undefined { if (children) { for (const child of children) { @@ -7458,6 +8057,7 @@ export function setEachParent(children: T | undefi export function setParentRecursive(rootNode: T, incremental: boolean): T; /* @internal */ export function setParentRecursive(rootNode: T | undefined, incremental: boolean): T | undefined; +/** @internal */ export function setParentRecursive(rootNode: T | undefined, incremental: boolean): T | undefined { if (!rootNode) return rootNode; ts.forEachChildRecursively(rootNode, ts.isJSDocNode(rootNode) ? bindParentToChildIgnoringJSDoc : bindParentToChild); @@ -7488,6 +8088,7 @@ function isPackedElement(node: ts.Expression) { return !ts.isOmittedExpression(node); } +/** @internal */ /** * Determines whether the provided node is an ArrayLiteralExpression that contains no missing elements. */ @@ -7495,6 +8096,7 @@ export function isPackedArrayLiteral(node: ts.Expression) { return ts.isArrayLiteralExpression(node) && ts.every(node.elements, isPackedElement); } +/** @internal */ /** * Indicates whether the result of an `Expression` will be unused. * @@ -7533,10 +8135,12 @@ export function expressionResultIsUnused(node: ts.Expression): boolean { } } +/** @internal */ export function containsIgnoredPath(path: string) { return ts.some(ts.ignoredPaths, p => ts.stringContains(path, p)); } +/** @internal */ export function getContainingNodeArray(node: ts.Node): ts.NodeArray | undefined { if (!node.parent) return undefined; switch (node.kind) { @@ -7608,6 +8212,7 @@ export function getContainingNodeArray(node: ts.Node): ts.NodeArray | u } } +/** @internal */ export function hasContextSensitiveParameters(node: ts.FunctionLikeDeclaration) { // Functions with type parameters are not context sensitive. if (!node.typeParameters) { @@ -7632,23 +8237,28 @@ export function isInfinityOrNaNString(name: string | ts.__String): boolean { return name === "Infinity" || name === "-Infinity" || name === "NaN"; } +/** @internal */ export function isCatchClauseVariableDeclaration(node: ts.Node) { return node.kind === ts.SyntaxKind.VariableDeclaration && node.parent.kind === ts.SyntaxKind.CatchClause; } +/** @internal */ export function isParameterOrCatchClauseVariable(symbol: ts.Symbol) { const declaration = symbol.valueDeclaration && getRootDeclaration(symbol.valueDeclaration); return !!declaration && (ts.isParameter(declaration) || isCatchClauseVariableDeclaration(declaration)); } +/** @internal */ export function isFunctionExpressionOrArrowFunction(node: ts.Node): node is ts.FunctionExpression | ts.ArrowFunction { return node.kind === ts.SyntaxKind.FunctionExpression || node.kind === ts.SyntaxKind.ArrowFunction; } +/** @internal */ export function escapeSnippetText(text: string): string { return text.replace(/\$/gm, () => "\\$"); } +/** @internal */ export function isNumericLiteralName(name: string | ts.__String) { // The intent of numeric names is that // - they are names with text in a numeric form, and that @@ -7674,22 +8284,26 @@ export function isNumericLiteralName(name: string | ts.__String) { return (+name).toString() === name; } +/** @internal */ export function createPropertyNameNodeForIdentifierOrLiteral(name: string, target: ts.ScriptTarget, singleQuote?: boolean, stringNamed?: boolean) { return ts.isIdentifierText(name, target) ? ts.factory.createIdentifier(name) : !stringNamed && isNumericLiteralName(name) && +name >= 0 ? ts.factory.createNumericLiteral(+name) : ts.factory.createStringLiteral(name, !!singleQuote); } +/** @internal */ export function isThisTypeParameter(type: ts.Type): boolean { return !!(type.flags & ts.TypeFlags.TypeParameter && (type as ts.TypeParameter).isThisType); } +/** @internal */ export interface NodeModulePathParts { readonly topLevelNodeModulesIndex: number; readonly topLevelPackageNameIndex: number; readonly packageRootIndex: number; readonly fileNameIndex: number; } +/** @internal */ export function getNodeModulePathParts(fullPath: string): NodeModulePathParts | undefined { // If fullPath can't be valid module file within node_modules, returns undefined. // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js @@ -7748,10 +8362,12 @@ export function getNodeModulePathParts(fullPath: string): NodeModulePathParts | return state > States.NodeModules ? { topLevelNodeModulesIndex, topLevelPackageNameIndex, packageRootIndex, fileNameIndex } : undefined; } +/** @internal */ export function getParameterTypeNode(parameter: ts.ParameterDeclaration | ts.JSDocParameterTag) { return parameter.kind === ts.SyntaxKind.JSDocParameterTag ? parameter.typeExpression?.type : parameter.type; } +/** @internal */ export function isTypeDeclaration(node: ts.Node): node is ts.TypeParameterDeclaration | ts.ClassDeclaration | ts.InterfaceDeclaration | ts.TypeAliasDeclaration | ts.JSDocTypedefTag | ts.JSDocCallbackTag | ts.JSDocEnumTag | ts.EnumDeclaration | ts.ImportClause | ts.ImportSpecifier | ts.ExportSpecifier { switch (node.kind) { case ts.SyntaxKind.TypeParameter: @@ -7773,11 +8389,13 @@ export function isTypeDeclaration(node: ts.Node): node is ts.TypeParameterDeclar } } +/** @internal */ export function canHaveExportModifier(node: ts.Node): node is Extract { return ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node) || isTypeDeclaration(node) || (ts.isModuleDeclaration(node) && !isExternalModuleAugmentation(node) && !isGlobalScopeAugmentation(node)); } +/** @internal */ export function isOptionalJSDocPropertyLikeTag(node: ts.Node): node is ts.JSDocPropertyLikeTag { if (!ts.isJSDocPropertyLikeTag(node)) { return false; @@ -7785,4 +8403,3 @@ export function isOptionalJSDocPropertyLikeTag(node: ts.Node): node is ts.JSDocP const { isBracketed, typeExpression } = node; return isBracketed || !!typeExpression && typeExpression.type.kind === ts.SyntaxKind.JSDocOptionalType; } -} diff --git a/src/compiler/utilitiesPublic.ts b/src/compiler/utilitiesPublic.ts index 7f00b0d01a6aa..8051c26e6659c 100644 --- a/src/compiler/utilitiesPublic.ts +++ b/src/compiler/utilitiesPublic.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + export function isExternalModuleNameRelative(moduleName: string): boolean { // TypeScript 1.0 spec (April 2014): 11.2.1 // An external module name is "relative" if the first term is "." or "..". @@ -2089,6 +2090,3 @@ export function isRestParameter(node: ts.ParameterDeclaration | ts.JSDocParamete const type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type; return (node as ts.ParameterDeclaration).dotDotDotToken !== undefined || !!type && type.kind === ts.SyntaxKind.JSDocVariadicType; } - -// #endregion -} diff --git a/src/compiler/visitorPublic.ts b/src/compiler/visitorPublic.ts index 7b9c7209a2aec..f06eb5196f82e 100644 --- a/src/compiler/visitorPublic.ts +++ b/src/compiler/visitorPublic.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + /** * Visits a Node using the supplied visitor, possibly returning a new Node in its place. * @@ -1330,4 +1331,3 @@ function extractSingleNode(nodes: readonly ts.Node[]): ts.Node | undefined { ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output."); return ts.singleOrUndefined(nodes); } -} diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 2a34c338a1b74..8da89eefaa422 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -1,11 +1,12 @@ -/*@internal*/ -namespace ts { +import * as ts from "./_namespaces/ts"; + const sysFormatDiagnosticsHost: ts.FormatDiagnosticsHost | undefined = ts.sys ? { getCurrentDirectory: () => ts.sys.getCurrentDirectory(), getNewLine: () => ts.sys.newLine, getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) } : undefined; +/** @internal */ /** * Create a function that reports error by writing to the system and handles the formatting of the diagnostic */ @@ -43,6 +44,7 @@ function clearScreenIfNotWatchingForFileChanges(system: ts.System, diagnostic: t return false; } +/** @internal */ export const screenStartingMessageCodes: number[] = [ ts.Diagnostics.Starting_compilation_in_watch_mode.code, ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code, @@ -54,6 +56,7 @@ function getPlainDiagnosticFollowingNewLines(diagnostic: ts.Diagnostic, newLine: : newLine; } +/** @internal */ /** * Get locale specific time based on whether we are in test mode */ @@ -63,6 +66,7 @@ export function getLocaleTimeString(system: ts.System) { system.now().toLocaleTimeString("en-US", { timeZone: "UTC" }); } +/** @internal */ /** * Create a function that reports watch status by writing to the system and handles the formatting of the diagnostic */ @@ -88,6 +92,7 @@ export function createWatchStatusReporter(system: ts.System, pretty?: boolean): }; } +/** @internal */ /** Parses config file using System interface */ export function parseConfigFileWithSystem(configFileName: string, optionsToExtend: ts.CompilerOptions, extendedConfigCache: ts.Map | undefined, watchOptionsToExtend: ts.WatchOptions | undefined, system: ts.System, reportDiagnostic: ts.DiagnosticReporter) { const host: ts.ParseConfigFileHost = system as any; @@ -97,10 +102,12 @@ export function parseConfigFileWithSystem(configFileName: string, optionsToExten return result; } +/** @internal */ export function getErrorCountForSummary(diagnostics: readonly ts.Diagnostic[]) { return ts.countWhere(diagnostics, diagnostic => diagnostic.category === ts.DiagnosticCategory.Error); } +/** @internal */ export function getFilesInErrorForSummary(diagnostics: readonly ts.Diagnostic[]): (ts.ReportFileInError | undefined)[] { const filesInError = ts.filter(diagnostics, diagnostic => diagnostic.category === ts.DiagnosticCategory.Error) @@ -124,6 +131,7 @@ export function getFilesInErrorForSummary(diagnostics: readonly ts.Diagnostic[]) }); } +/** @internal */ export function getWatchErrorSummaryDiagnosticMessage(errorCount: number) { return errorCount === 1 ? ts.Diagnostics.Found_1_error_Watching_for_file_changes : @@ -139,6 +147,7 @@ function prettyPathForFileError(error: ts.ReportFileInError, cwd: string) { return error.fileName + line; } +/** @internal */ export function getErrorSummaryText( errorCount: number, filesInError: readonly (ts.ReportFileInError | undefined)[], @@ -201,10 +210,12 @@ function createTabularErrorsDisplay(filesInError: (ts.ReportFileInError | undefi return tabularData; } +/** @internal */ export function isBuilderProgram(program: ts.Program | ts.BuilderProgram): program is ts.BuilderProgram { return !!(program as ts.BuilderProgram).getState; } +/** @internal */ export function listFiles(program: ts.Program | T, write: (s: string) => void) { const options = program.getCompilerOptions(); if (options.explainFiles) { @@ -217,6 +228,7 @@ export function listFiles(program: ts.Program | T, } } +/** @internal */ export function explainFiles(program: ts.Program, write: (s: string) => void) { const reasons = program.getFileIncludeReasons(); const getCanonicalFileName = ts.createGetCanonicalFileName(program.useCaseSensitiveFileNames()); @@ -228,6 +240,7 @@ export function explainFiles(program: ts.Program, write: (s: string) => void) { } } +/** @internal */ export function explainIfFileIsRedirectAndImpliedFormat( file: ts.SourceFile, fileNameConvertor?: (fileName: string) => string, @@ -280,6 +293,7 @@ export function explainIfFileIsRedirectAndImpliedFormat( return result; } +/** @internal */ export function getMatchedFileSpec(program: ts.Program, fileName: string) { const configFile = program.getCompilerOptions().configFile; if (!configFile?.configFileSpecs?.validatedFilesSpec) return undefined; @@ -290,6 +304,7 @@ export function getMatchedFileSpec(program: ts.Program, fileName: string) { return ts.find(configFile.configFileSpecs.validatedFilesSpec, fileSpec => getCanonicalFileName(ts.getNormalizedAbsolutePath(fileSpec, basePath)) === filePath); } +/** @internal */ export function getMatchedIncludeSpec(program: ts.Program, fileName: string) { const configFile = program.getCompilerOptions().configFile; if (!configFile?.configFileSpecs?.validatedIncludeSpecs) return undefined; @@ -307,6 +322,7 @@ export function getMatchedIncludeSpec(program: ts.Program, fileName: string) { }); } +/** @internal */ export function fileIncludeReasonToDiagnostics(program: ts.Program, reason: ts.FileIncludeReason, fileNameConvertor?: (fileName: string) => string,): ts.DiagnosticMessageChain { const options = program.getCompilerOptions(); if (ts.isReferencedFile(reason)) { @@ -424,6 +440,7 @@ function toFileName(file: ts.SourceFile | string, fileNameConvertor?: (fileName: return fileNameConvertor ? fileNameConvertor(fileName) : fileName; } +/** @internal */ /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ @@ -486,6 +503,7 @@ export function emitFilesAndReportErrors( }; } +/** @internal */ export function emitFilesAndReportErrorsAndGetExitStatus( program: ts.Program | T, reportDiagnostic: ts.DiagnosticReporter, @@ -519,9 +537,12 @@ export function emitFilesAndReportErrorsAndGetExitStatus noopFileWatcher; +/** @internal */ export function createWatchHost(system = ts.sys, reportWatchStatus?: ts.WatchStatusReporter): ts.WatchHost { const onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); return { @@ -533,7 +554,9 @@ export function createWatchHost(system = ts.sys, reportWatchStatus?: ts.WatchSta }; } +/** @internal */ export type WatchType = WatchTypeRegistry[keyof WatchTypeRegistry]; +/** @internal */ export const WatchType: WatchTypeRegistry = { ConfigFile: "Config file", ExtendedConfigFile: "Extended config file", @@ -556,6 +579,7 @@ export const WatchType: WatchTypeRegistry = { NodeModulesForModuleSpecifierCache: "node_modules for module specifier cache invalidation", }; +/** @internal */ export interface WatchTypeRegistry { ConfigFile: "Config file", ExtendedConfigFile: "Extended config file", @@ -584,6 +608,7 @@ interface WatchFactory extends ts.WatchFactory { writeLog: (s: string) => void; } +/** @internal */ export function createWatchFactory(host: ts.WatchFactoryHost & { trace?(s: string): void; }, options: { extendedDiagnostics?: boolean; diagnostics?: boolean; }) { const watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; const writeLog: (s: string) => void = watchLogLevel !== ts.WatchLogLevel.None ? (s => host.trace!(s)) : ts.noop; @@ -592,6 +617,7 @@ export function createWatchFactory(host: ts.WatchFactoryHost & { return result; } +/** @internal */ export function createCompilerHostFromProgramHost(host: ts.ProgramHost, getCompilerOptions: () => ts.CompilerOptions, directoryStructureHost: ts.DirectoryStructureHost = host): ts.CompilerHost { const useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); const hostGetNewLine = ts.memoize(() => host.getNewLine()); @@ -626,6 +652,7 @@ export function createCompilerHostFromProgramHost(host: ts.ProgramHost, get }; } +/** @internal */ export function getSourceFileVersionAsHashFromText(host: Pick, text: string) { // If text can contain the sourceMapUrl ignore sourceMapUrl for calcualting hash if (text.match(ts.sourceMapCommentRegExpDontCareLineStart)) { @@ -664,6 +691,7 @@ export function getSourceFileVersionAsHashFromText(host: Pick { @@ -675,6 +703,7 @@ export function setGetSourceFileAsHashVersioned(compilerHost: ts.CompilerHost, h }; } +/** @internal */ /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ @@ -738,6 +767,7 @@ function reportUnrecoverableDiagnostic(system: ts.System, reportDiagnostic: ts.D system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } +/** @internal */ export interface CreateWatchCompilerHostInput { system: ts.System; createProgram?: ts.CreateProgram; @@ -745,12 +775,14 @@ export interface CreateWatchCompilerHostInput { reportWatchStatus?: ts.WatchStatusReporter; } +/** @internal */ export interface CreateWatchCompilerHostOfConfigFileInput extends CreateWatchCompilerHostInput { configFileName: string; optionsToExtend?: ts.CompilerOptions; watchOptionsToExtend?: ts.WatchOptions; extraFileExtensions?: readonly ts.FileExtensionInfo[]; } +/** @internal */ /** * Creates the watch compiler host from system for config file in watch mode */ @@ -768,12 +800,14 @@ export function createWatchCompilerHostOfConfigFile extends CreateWatchCompilerHostInput { rootFiles: string[]; options: ts.CompilerOptions; watchOptions: ts.WatchOptions | undefined; projectReferences?: readonly ts.ProjectReference[]; } +/** @internal */ /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ @@ -789,6 +823,7 @@ export function createWatchCompilerHostOfFilesAndCompilerOptions(host: WatchCompi ); } } -} diff --git a/src/compiler/watchUtilities.ts b/src/compiler/watchUtilities.ts index b3a39f4a19e8a..38c1880a98e81 100644 --- a/src/compiler/watchUtilities.ts +++ b/src/compiler/watchUtilities.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts { +import * as ts from "./_namespaces/ts"; + +/** @internal */ /** * Partial interface of the System thats needed to support the caching of directory structure */ @@ -22,6 +23,7 @@ interface FileAndDirectoryExistence { directoryExists: boolean; } +/** @internal */ export interface CachedDirectoryStructureHost extends DirectoryStructureHost { useCaseSensitiveFileNames: boolean; @@ -50,6 +52,7 @@ interface SortedAndCanonicalizedMutableFileSystemEntries { readonly sortedAndCanonicalizedDirectories: ts.SortedArray } +/** @internal */ export function createCachedDirectoryStructureHost(host: DirectoryStructureHost, currentDirectory: string, useCaseSensitiveFileNames: boolean): CachedDirectoryStructureHost | undefined { if (!host.getDirectories || !host.readDirectory) { return undefined; @@ -303,6 +306,7 @@ export function createCachedDirectoryStructureHost(host: DirectoryStructureHost, } } +/** @internal */ export enum ConfigFileProgramReloadLevel { None, /** Update the file name list from the disk */ @@ -311,11 +315,13 @@ export enum ConfigFileProgramReloadLevel { Full } +/** @internal */ export interface SharedExtendedConfigFileWatcher extends ts.FileWatcher { watcher: ts.FileWatcher; projects: ts.Set; } +/** @internal */ /** * Updates the map of shared extended config file watches with a new set of extended config files from a base config file of the project */ @@ -356,6 +362,7 @@ export function updateSharedExtendedConfigFileWatcher( }); } +/** @internal */ /** * Remove the project from the extended config file watchers and close not needed watches */ @@ -368,6 +375,7 @@ export function clearSharedExtendedConfigFileWatcher( }); } +/** @internal */ /** * Clean the extendsConfigCache when extended config file has changed */ @@ -384,6 +392,7 @@ export function cleanExtendedConfigCache( }); } +/** @internal */ /** * Updates watchers based on the package json files used in module resolution */ @@ -403,6 +412,7 @@ export function updatePackageJsonWatch( ); } +/** @internal */ /** * Updates the existing missing file watches with the new set of missing files after new program is created */ @@ -428,11 +438,13 @@ export function updateMissingFilePathsWatch( ); } +/** @internal */ export interface WildcardDirectoryWatcher { watcher: ts.FileWatcher; flags: ts.WatchDirectoryFlags; } +/** @internal */ /** * Updates the existing wild card directory watches with the new set of wild card directories from the config file * after new program is created because the config file was reloaded or program was created first time from the config file @@ -476,6 +488,7 @@ export function updateWatchingWildcardDirectories( } } +/** @internal */ export interface IsIgnoredFileFromWildCardWatchingInput { watchedDirPath: ts.Path; fileOrDirectory: string; @@ -556,6 +569,7 @@ function isBuilderProgram(program: ts.Program | T): return !!(program as T).getState; } +/** @internal */ export function isEmittedFileOfProgram(program: ts.Program | undefined, file: string) { if (!program) { return false; @@ -564,12 +578,14 @@ export function isEmittedFileOfProgram(program: ts.Program | undefined, file: st return program.isEmittedFile(file); } +/** @internal */ export enum WatchLogLevel { None, TriggerOnly, Verbose } +/** @internal */ export interface WatchFactoryHost { watchFile(path: string, callback: ts.FileWatcherCallback, pollingInterval?: number, options?: ts.WatchOptions): ts.FileWatcher; watchDirectory(path: string, callback: ts.DirectoryWatcherCallback, recursive?: boolean, options?: ts.WatchOptions): ts.FileWatcher; @@ -577,12 +593,15 @@ export interface WatchFactoryHost { useCaseSensitiveFileNames: boolean | (() => boolean); } +/** @internal */ export interface WatchFactory { watchFile: (file: string, callback: ts.FileWatcherCallback, pollingInterval: ts.PollingInterval, options: ts.WatchOptions | undefined, detailInfo1: X, detailInfo2?: Y) => ts.FileWatcher; watchDirectory: (directory: string, callback: ts.DirectoryWatcherCallback, flags: ts.WatchDirectoryFlags, options: ts.WatchOptions | undefined, detailInfo1: X, detailInfo2?: Y) => ts.FileWatcher; } +/** @internal */ export type GetDetailWatchInfo = (detailInfo1: X, detailInfo2: Y | undefined) => string; +/** @internal */ export function getWatchFactory(host: WatchFactoryHost, watchLogLevel: WatchLogLevel, log: (s: string) => void, getDetailWatchInfo?: GetDetailWatchInfo): WatchFactory { ts.setSysLog(watchLogLevel === WatchLogLevel.Verbose ? log : ts.noop); const plainInvokeFactory: WatchFactory = { @@ -709,6 +728,7 @@ export function getWatchFactory(host: WatchFactoryHost, watchL } } +/** @internal */ export function getFallbackOptions(options: ts.WatchOptions | undefined): ts.WatchOptions { const fallbackPolling = options?.fallbackPolling; return { @@ -718,7 +738,7 @@ export function getFallbackOptions(options: ts.WatchOptions | undefined): ts.Wat }; } +/** @internal */ export function closeFileWatcherOf(objWithWatcher: T) { objWithWatcher.watcher.close(); } -} diff --git a/src/debug/_namespaces/Debug.ts b/src/debug/_namespaces/Debug.ts new file mode 100644 index 0000000000000..449c31bdaefbe --- /dev/null +++ b/src/debug/_namespaces/Debug.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the Debug namespace. */ + +export * from "../dbg"; diff --git a/src/debug/dbg.ts b/src/debug/dbg.ts index c354e0b26a08c..c165c3e8725d8 100644 --- a/src/debug/dbg.ts +++ b/src/debug/dbg.ts @@ -1,7 +1,7 @@ +import * as Debug from "./_namespaces/Debug"; + /// -/* @internal */ -namespace Debug { interface Node { kind: number; } @@ -113,6 +113,7 @@ interface FlowArrayMutation extends FlowNodeBase { antecedent: FlowNode; } +/** @internal */ export interface FlowReduceLabel extends FlowNodeBase { target: FlowLabel; antecedents: FlowNode[]; @@ -125,6 +126,7 @@ let getSourceFileOfNode: TypeScriptModule["getSourceFileOfNode"]; let getSourceTextOfNodeFromSourceFile: TypeScriptModule["getSourceTextOfNodeFromSourceFile"]; let isDefaultClause: TypeScriptModule["isDefaultClause"]; +/** @internal */ export function init(ts: TypeScriptModule) { FlowFlags = ts.FlowFlags; getSourceFileOfNode = ts.getSourceFileOfNode; @@ -142,6 +144,7 @@ function getDebugFlowNodeId(f: FlowNode) { return f.id; } +/** @internal */ export function formatControlFlowGraph(flowNode: FlowNode) { const enum BoxCharacter { lr = "─", @@ -512,5 +515,4 @@ export function formatControlFlowGraph(flowNode: FlowNode) { declare const module: { exports: {} }; if (typeof module !== "undefined" && module.exports) { module.exports = Debug; -} } \ No newline at end of file diff --git a/src/debug/tsconfig.json b/src/debug/tsconfig.json index eae965391e3c7..45353e055756e 100644 --- a/src/debug/tsconfig.json +++ b/src/debug/tsconfig.json @@ -3,11 +3,12 @@ "compilerOptions": { "target": "es2019", "lib": ["es2019"], - "outFile": "../../built/local/compiler-debug.js", + "outDir": "../../built/local", "declaration": false, "sourceMap": true }, "files": [ - "dbg.ts" + "dbg.ts", + "_namespaces/Debug.ts" ] } diff --git a/src/deprecatedCompat/4.0/nodeFactoryTopLevelExports.ts b/src/deprecatedCompat/4.0/nodeFactoryTopLevelExports.ts index 8ed5643b98920..87f40bcf6b3de 100644 --- a/src/deprecatedCompat/4.0/nodeFactoryTopLevelExports.ts +++ b/src/deprecatedCompat/4.0/nodeFactoryTopLevelExports.ts @@ -1,10 +1,10 @@ +import * as ts from "../_namespaces/ts"; + // DEPRECATION: Node factory top-level exports // DEPRECATION PLAN: // - soft: 4.0 // - warn: 4.1 // - error: 5.0 -namespace ts { - // NOTE: These exports are deprecated in favor of using a `NodeFactory` instance and exist here purely for backwards compatibility reasons. const factoryDeprecation: ts.DeprecationOptions = { since: "4.0", warnAfter: "4.1", message: "Use the appropriate method on 'ts.factory' or the 'factory' supplied by your transformation context instead." }; @@ -1303,4 +1303,3 @@ export const getMutableClone = ts.Debug.deprecate(function getMutableClone` instead. - */ -export interface ReadonlyMap extends ts.ReadonlyESMap { +declare module "../../compiler/corePublic" { + // Module transform: converted from interface augmentation + /** + * @deprecated Use `ts.ReadonlyESMap` instead. + */ + export interface ReadonlyMap extends ts.ReadonlyESMap { + } } -/** - * @deprecated Use `ts.ESMap` instead. - */ -export interface Map extends ts.ESMap { -} +declare module "../../compiler/corePublic" { + // Module transform: converted from interface augmentation + /** + * @deprecated Use `ts.ESMap` instead. + */ + export interface Map extends ts.ESMap { + } } \ No newline at end of file diff --git a/src/deprecatedCompat/4.0/renamedNodeTests.ts b/src/deprecatedCompat/4.0/renamedNodeTests.ts index 04f07f0581446..dbf4f89c92c45 100644 --- a/src/deprecatedCompat/4.0/renamedNodeTests.ts +++ b/src/deprecatedCompat/4.0/renamedNodeTests.ts @@ -1,9 +1,10 @@ +import * as ts from "../_namespaces/ts"; + // DEPRECATION: Renamed node tests // DEPRECATION PLAN: // - soft: 4.0 // - warn: 4.1 // - error: TBD -namespace ts { /** @deprecated Use `isTypeAssertionExpression` instead. */ export const isTypeAssertion = ts.Debug.deprecate(function isTypeAssertion(node: ts.Node): node is ts.TypeAssertion { return node.kind === ts.SyntaxKind.TypeAssertionExpression; @@ -11,5 +12,4 @@ export const isTypeAssertion = ts.Debug.deprecate(function isTypeAssertion(node: since: "4.0", warnAfter: "4.1", message: "Use `isTypeAssertionExpression` instead." -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/deprecatedCompat/4.2/abstractConstructorTypes.ts b/src/deprecatedCompat/4.2/abstractConstructorTypes.ts index 04215a6784f99..a13f59d137221 100644 --- a/src/deprecatedCompat/4.2/abstractConstructorTypes.ts +++ b/src/deprecatedCompat/4.2/abstractConstructorTypes.ts @@ -1,15 +1,19 @@ +import * as ts from "../_namespaces/ts"; + // DEPRECATION: Overloads for createConstructorTypeNode/updateConstructorTypeNode that do not accept 'modifiers' // DEPRECATION PLAN: // - soft: 4.2 // - warn: 4.3 // - error: 5.0 -namespace ts { -export interface NodeFactory { - /** @deprecated Use the overload that accepts 'modifiers' */ - createConstructorTypeNode(typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode): ts.ConstructorTypeNode; +declare module "../../compiler/types" { + // Module transform: converted from interface augmentation + export interface NodeFactory { + /** @deprecated Use the overload that accepts 'modifiers' */ + createConstructorTypeNode(typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode): ts.ConstructorTypeNode; - /** @deprecated Use the overload that accepts 'modifiers' */ - updateConstructorTypeNode(node: ts.ConstructorTypeNode, typeParameters: ts.NodeArray | undefined, parameters: ts.NodeArray, type: ts.TypeNode): ts.ConstructorTypeNode; + /** @deprecated Use the overload that accepts 'modifiers' */ + updateConstructorTypeNode(node: ts.ConstructorTypeNode, typeParameters: ts.NodeArray | undefined, parameters: ts.NodeArray, type: ts.TypeNode): ts.ConstructorTypeNode; + } } function patchNodeFactory(factory: ts.NodeFactory) { @@ -63,4 +67,3 @@ ts.addNodeFactoryPatcher(patchNodeFactory); // Patch `ts.factory` because its public patchNodeFactory(ts.factory); -} diff --git a/src/deprecatedCompat/4.2/renamedNodeTests.ts b/src/deprecatedCompat/4.2/renamedNodeTests.ts index 69767fcfdcaff..8c30c6ac2f26a 100644 --- a/src/deprecatedCompat/4.2/renamedNodeTests.ts +++ b/src/deprecatedCompat/4.2/renamedNodeTests.ts @@ -1,9 +1,10 @@ +import * as ts from "../_namespaces/ts"; + // DEPRECATION: Renamed node tests // DEPRECATION PLAN: // - soft: 4.2 // - warn: 4.3 // - error: 5.0 -namespace ts { /** * @deprecated Use `isMemberName` instead. */ @@ -13,5 +14,4 @@ export const isIdentifierOrPrivateIdentifier = ts.Debug.deprecate(function isIde since: "4.2", warnAfter: "4.3", message: "Use `isMemberName` instead." -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/deprecatedCompat/4.6/importTypeAssertions.ts b/src/deprecatedCompat/4.6/importTypeAssertions.ts index fcd7c983e8089..04a0426e60591 100644 --- a/src/deprecatedCompat/4.6/importTypeAssertions.ts +++ b/src/deprecatedCompat/4.6/importTypeAssertions.ts @@ -1,18 +1,22 @@ +import * as ts from "../_namespaces/ts"; + // DEPRECATION: Overloads to createImportTypeNode/updateImportTypeNode that do not accept `assertions` // DEPRECATION PLAN: // - soft: 4.6 // - warn: 4.7 // - error: 5.0 -namespace ts { -export interface NodeFactory { - // NOTE: The following overload is not deprecated, but exists to ensure we don't mark `createImportTypeNode(argument)` as deprecated due to optional parameters. - createImportTypeNode(argument: ts.TypeNode, assertions?: ts.ImportTypeAssertionContainer, qualifier?: ts.EntityName, typeArguments?: readonly ts.TypeNode[], isTypeOf?: boolean): ts.ImportTypeNode; +declare module "../../compiler/types" { + // Module transform: converted from interface augmentation + export interface NodeFactory { + // NOTE: The following overload is not deprecated, but exists to ensure we don't mark `createImportTypeNode(argument)` as deprecated due to optional parameters. + createImportTypeNode(argument: ts.TypeNode, assertions?: ts.ImportTypeAssertionContainer, qualifier?: ts.EntityName, typeArguments?: readonly ts.TypeNode[], isTypeOf?: boolean): ts.ImportTypeNode; - /** @deprecated Use the overload that accepts 'assertions' */ - createImportTypeNode(argument: ts.TypeNode, qualifier?: ts.EntityName, typeArguments?: readonly ts.TypeNode[], isTypeOf?: boolean): ts.ImportTypeNode; + /** @deprecated Use the overload that accepts 'assertions' */ + createImportTypeNode(argument: ts.TypeNode, qualifier?: ts.EntityName, typeArguments?: readonly ts.TypeNode[], isTypeOf?: boolean): ts.ImportTypeNode; - /** @deprecated Use the overload that accepts 'assertions' */ - updateImportTypeNode(node: ts.ImportTypeNode, argument: ts.TypeNode, qualifier: ts.EntityName | undefined, typeArguments: readonly ts.TypeNode[] | undefined, isTypeOf?: boolean): ts.ImportTypeNode; + /** @deprecated Use the overload that accepts 'assertions' */ + updateImportTypeNode(node: ts.ImportTypeNode, argument: ts.TypeNode, qualifier: ts.EntityName | undefined, typeArguments: readonly ts.TypeNode[] | undefined, isTypeOf?: boolean): ts.ImportTypeNode; + } } function patchNodeFactory(factory: ts.NodeFactory) { @@ -84,4 +88,3 @@ ts.addNodeFactoryPatcher(patchNodeFactory); // Patch `ts.factory` because its public patchNodeFactory(ts.factory); -} diff --git a/src/deprecatedCompat/4.7/typeParameterModifiers.ts b/src/deprecatedCompat/4.7/typeParameterModifiers.ts index bb6998b741878..bdd1421b4c9c2 100644 --- a/src/deprecatedCompat/4.7/typeParameterModifiers.ts +++ b/src/deprecatedCompat/4.7/typeParameterModifiers.ts @@ -1,15 +1,19 @@ +import * as ts from "../_namespaces/ts"; + // DEPRECATION: Overloads to createTypeParameter/updateTypeParameter that does not accept `modifiers` // DEPRECATION PLAN: // - soft: 4.7 // - warn: 4.8 // - error: 5.0 -namespace ts { -export interface NodeFactory { - /** @deprecated Use the overload that accepts 'modifiers' */ - createTypeParameterDeclaration(name: string | ts.Identifier, constraint?: ts.TypeNode, defaultType?: ts.TypeNode): ts.TypeParameterDeclaration; +declare module "../../compiler/types" { + // Module transform: converted from interface augmentation + export interface NodeFactory { + /** @deprecated Use the overload that accepts 'modifiers' */ + createTypeParameterDeclaration(name: string | ts.Identifier, constraint?: ts.TypeNode, defaultType?: ts.TypeNode): ts.TypeParameterDeclaration; - /** @deprecated Use the overload that accepts 'modifiers' */ - updateTypeParameterDeclaration(node: ts.TypeParameterDeclaration, name: ts.Identifier, constraint: ts.TypeNode | undefined, defaultType: ts.TypeNode | undefined): ts.TypeParameterDeclaration; + /** @deprecated Use the overload that accepts 'modifiers' */ + updateTypeParameterDeclaration(node: ts.TypeParameterDeclaration, name: ts.Identifier, constraint: ts.TypeNode | undefined, defaultType: ts.TypeNode | undefined): ts.TypeParameterDeclaration; + } } function patchNodeFactory(factory: ts.NodeFactory) { @@ -69,4 +73,3 @@ ts.addNodeFactoryPatcher(patchNodeFactory); // Patch `ts.factory` because its public patchNodeFactory(ts.factory); -} diff --git a/src/deprecatedCompat/4.8/mergeDecoratorsAndModifiers.ts b/src/deprecatedCompat/4.8/mergeDecoratorsAndModifiers.ts index 36c1d6dcd665a..c35e0162ed005 100644 --- a/src/deprecatedCompat/4.8/mergeDecoratorsAndModifiers.ts +++ b/src/deprecatedCompat/4.8/mergeDecoratorsAndModifiers.ts @@ -1,217 +1,236 @@ +import * as ts from "../_namespaces/ts"; + // DEPRECATION: Deprecate passing `decorators` separate from `modifiers` // DEPRECATION PLAN: // - soft: 4.8 // - warn: 4.9 // - error: 5.0 -namespace ts { -export interface Node { - /** - * @deprecated `decorators` has been removed from `Node` and merged with `modifiers` on the `Node` subtypes that support them. - * Use `ts.canHaveDecorators()` to test whether a `Node` can have decorators. - * Use `ts.getDecorators()` to get the decorators of a `Node`. - * - * For example: - * ```ts - * const decorators = ts.canHaveDecorators(node) ? ts.getDecorators(node) : undefined; - * ``` - */ - readonly decorators?: undefined; - - /** - * @deprecated `modifiers` has been removed from `Node` and moved to the `Node` subtypes that support them. - * Use `ts.canHaveModifiers()` to test whether a `Node` can have modifiers. - * Use `ts.getModifiers()` to get the modifiers of a `Node`. - * - * For example: - * ```ts - * const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined; - * ``` - */ - readonly modifiers?: ts.NodeArray | undefined; +declare module "../../compiler/types" { + // Module transform: converted from interface augmentation + export interface Node { + /** + * @deprecated `decorators` has been removed from `Node` and merged with `modifiers` on the `Node` subtypes that support them. + * Use `ts.canHaveDecorators()` to test whether a `Node` can have decorators. + * Use `ts.getDecorators()` to get the decorators of a `Node`. + * + * For example: + * ```ts + * const decorators = ts.canHaveDecorators(node) ? ts.getDecorators(node) : undefined; + * ``` + */ + readonly decorators?: undefined; + + /** + * @deprecated `modifiers` has been removed from `Node` and moved to the `Node` subtypes that support them. + * Use `ts.canHaveModifiers()` to test whether a `Node` can have modifiers. + * Use `ts.getModifiers()` to get the modifiers of a `Node`. + * + * For example: + * ```ts + * const modifiers = ts.canHaveModifiers(node) ? ts.getModifiers(node) : undefined; + * ``` + */ + readonly modifiers?: ts.NodeArray | undefined; + } } -export interface PropertySignature { - /** @deprecated A property signature cannot have an initializer */ - readonly initializer?: ts.Expression | undefined; +declare module "../../compiler/types" { + // Module transform: converted from interface augmentation + export interface PropertySignature { + /** @deprecated A property signature cannot have an initializer */ + readonly initializer?: ts.Expression | undefined; + } } -export interface PropertyAssignment { - /** @deprecated A property assignment cannot have a question token */ - readonly questionToken?: ts.QuestionToken | undefined; +declare module "../../compiler/types" { + // Module transform: converted from interface augmentation + export interface PropertyAssignment { + /** @deprecated A property assignment cannot have a question token */ + readonly questionToken?: ts.QuestionToken | undefined; - /** @deprecated A property assignment cannot have an exclamation token */ - readonly exclamationToken?: ts.ExclamationToken | undefined; + /** @deprecated A property assignment cannot have an exclamation token */ + readonly exclamationToken?: ts.ExclamationToken | undefined; + } } -export interface ShorthandPropertyAssignment { - /** @deprecated A shorthand property assignment cannot have modifiers */ - readonly modifiers?: ts.NodeArray | undefined; +declare module "../../compiler/types" { + // Module transform: converted from interface augmentation + export interface ShorthandPropertyAssignment { + /** @deprecated A shorthand property assignment cannot have modifiers */ + readonly modifiers?: ts.NodeArray | undefined; - /** @deprecated A shorthand property assignment cannot have a question token */ - readonly questionToken?: ts.QuestionToken | undefined; + /** @deprecated A shorthand property assignment cannot have a question token */ + readonly questionToken?: ts.QuestionToken | undefined; - /** @deprecated A shorthand property assignment cannot have an exclamation token */ - readonly exclamationToken?: ts.ExclamationToken | undefined; + /** @deprecated A shorthand property assignment cannot have an exclamation token */ + readonly exclamationToken?: ts.ExclamationToken | undefined; + } } -export interface FunctionTypeNode { - /** @deprecated A function type cannot have modifiers */ - readonly modifiers?: ts.NodeArray | undefined; +declare module "../../compiler/types" { + // Module transform: converted from interface augmentation + export interface FunctionTypeNode { + /** @deprecated A function type cannot have modifiers */ + readonly modifiers?: ts.NodeArray | undefined; + } } -export interface NodeFactory { - /** - * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. - */ - createParameterDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, dotDotDotToken: ts.DotDotDotToken | undefined, name: string | ts.BindingName, questionToken?: ts.QuestionToken, type?: ts.TypeNode, initializer?: ts.Expression): ts.ParameterDeclaration; - /** - * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. - */ - updateParameterDeclaration(node: ts.ParameterDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, dotDotDotToken: ts.DotDotDotToken | undefined, name: string | ts.BindingName, questionToken: ts.QuestionToken | undefined, type: ts.TypeNode | undefined, initializer: ts.Expression | undefined): ts.ParameterDeclaration; - /** - * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. - */ - createPropertyDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.PropertyName, questionOrExclamationToken: ts.QuestionToken | ts.ExclamationToken | undefined, type: ts.TypeNode | undefined, initializer: ts.Expression | undefined): ts.PropertyDeclaration; - /** - * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. - */ - updatePropertyDeclaration(node: ts.PropertyDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.PropertyName, questionOrExclamationToken: ts.QuestionToken | ts.ExclamationToken | undefined, type: ts.TypeNode | undefined, initializer: ts.Expression | undefined): ts.PropertyDeclaration; - /** - * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. - */ - createMethodDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, asteriskToken: ts.AsteriskToken | undefined, name: string | ts.PropertyName, questionToken: ts.QuestionToken | undefined, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode | undefined, body: ts.Block | undefined): ts.MethodDeclaration; - /** - * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. - */ - updateMethodDeclaration(node: ts.MethodDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, asteriskToken: ts.AsteriskToken | undefined, name: ts.PropertyName, questionToken: ts.QuestionToken | undefined, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode | undefined, body: ts.Block | undefined): ts.MethodDeclaration; - /** - * @deprecated This node does not support Decorators. Callers should use an overload that does not accept a `decorators` parameter. - */ - createConstructorDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, parameters: readonly ts.ParameterDeclaration[], body: ts.Block | undefined): ts.ConstructorDeclaration; - /** - * @deprecated This node does not support Decorators. Callers should use an overload that does not accept a `decorators` parameter. - */ - updateConstructorDeclaration(node: ts.ConstructorDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, parameters: readonly ts.ParameterDeclaration[], body: ts.Block | undefined): ts.ConstructorDeclaration; - /** - * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. - */ - createGetAccessorDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.PropertyName, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode | undefined, body: ts.Block | undefined): ts.GetAccessorDeclaration; - /** - * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. - */ - updateGetAccessorDeclaration(node: ts.GetAccessorDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.PropertyName, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode | undefined, body: ts.Block | undefined): ts.GetAccessorDeclaration; - /** - * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. - */ - createSetAccessorDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.PropertyName, parameters: readonly ts.ParameterDeclaration[], body: ts.Block | undefined): ts.SetAccessorDeclaration; - /** - * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. - */ - updateSetAccessorDeclaration(node: ts.SetAccessorDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.PropertyName, parameters: readonly ts.ParameterDeclaration[], body: ts.Block | undefined): ts.SetAccessorDeclaration; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - createIndexSignature(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode): ts.IndexSignatureDeclaration; - /** - * @deprecated Decorators and modifiers are no longer supported for this function. Callers should use an overload that does not accept the `decorators` and `modifiers` parameters. - */ - updateIndexSignature(node: ts.IndexSignatureDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode): ts.IndexSignatureDeclaration; - /** - * @deprecated Decorators and modifiers are no longer supported for this function. Callers should use an overload that does not accept the `decorators` and `modifiers` parameters. - */ - createClassStaticBlockDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, body: ts.Block): ts.ClassStaticBlockDeclaration; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - updateClassStaticBlockDeclaration(node: ts.ClassStaticBlockDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, body: ts.Block): ts.ClassStaticBlockDeclaration; - /** - * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. - */ - createClassExpression(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.Identifier | undefined, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, heritageClauses: readonly ts.HeritageClause[] | undefined, members: readonly ts.ClassElement[]): ts.ClassExpression; - /** - * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. - */ - updateClassExpression(node: ts.ClassExpression, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.Identifier | undefined, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, heritageClauses: readonly ts.HeritageClause[] | undefined, members: readonly ts.ClassElement[]): ts.ClassExpression; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - createFunctionDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, asteriskToken: ts.AsteriskToken | undefined, name: string | ts.Identifier | undefined, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode | undefined, body: ts.Block | undefined): ts.FunctionDeclaration; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - updateFunctionDeclaration(node: ts.FunctionDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, asteriskToken: ts.AsteriskToken | undefined, name: ts.Identifier | undefined, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode | undefined, body: ts.Block | undefined): ts.FunctionDeclaration; - /** - * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. - */ - createClassDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.Identifier | undefined, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, heritageClauses: readonly ts.HeritageClause[] | undefined, members: readonly ts.ClassElement[]): ts.ClassDeclaration; - /** - * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. - */ - updateClassDeclaration(node: ts.ClassDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.Identifier | undefined, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, heritageClauses: readonly ts.HeritageClause[] | undefined, members: readonly ts.ClassElement[]): ts.ClassDeclaration; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - createInterfaceDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.Identifier, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, heritageClauses: readonly ts.HeritageClause[] | undefined, members: readonly ts.TypeElement[]): ts.InterfaceDeclaration; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - updateInterfaceDeclaration(node: ts.InterfaceDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.Identifier, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, heritageClauses: readonly ts.HeritageClause[] | undefined, members: readonly ts.TypeElement[]): ts.InterfaceDeclaration; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - createTypeAliasDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.Identifier, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, type: ts.TypeNode): ts.TypeAliasDeclaration; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - updateTypeAliasDeclaration(node: ts.TypeAliasDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.Identifier, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, type: ts.TypeNode): ts.TypeAliasDeclaration; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - createEnumDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.Identifier, members: readonly ts.EnumMember[]): ts.EnumDeclaration; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - updateEnumDeclaration(node: ts.EnumDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.Identifier, members: readonly ts.EnumMember[]): ts.EnumDeclaration; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - createModuleDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.ModuleName, body: ts.ModuleBody | undefined, flags?: ts.NodeFlags): ts.ModuleDeclaration; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - updateModuleDeclaration(node: ts.ModuleDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.ModuleName, body: ts.ModuleBody | undefined): ts.ModuleDeclaration; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - createImportEqualsDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, isTypeOnly: boolean, name: string | ts.Identifier, moduleReference: ts.ModuleReference): ts.ImportEqualsDeclaration; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - updateImportEqualsDeclaration(node: ts.ImportEqualsDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, isTypeOnly: boolean, name: ts.Identifier, moduleReference: ts.ModuleReference): ts.ImportEqualsDeclaration; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - createImportDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, importClause: ts.ImportClause | undefined, moduleSpecifier: ts.Expression, assertClause?: ts.AssertClause): ts.ImportDeclaration; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - updateImportDeclaration(node: ts.ImportDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, importClause: ts.ImportClause | undefined, moduleSpecifier: ts.Expression, assertClause: ts.AssertClause | undefined): ts.ImportDeclaration; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - createExportAssignment(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, isExportEquals: boolean | undefined, expression: ts.Expression): ts.ExportAssignment; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - updateExportAssignment(node: ts.ExportAssignment, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, expression: ts.Expression): ts.ExportAssignment; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - createExportDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, isTypeOnly: boolean, exportClause: ts.NamedExportBindings | undefined, moduleSpecifier?: ts.Expression, assertClause?: ts.AssertClause): ts.ExportDeclaration; - /** - * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. - */ - updateExportDeclaration(node: ts.ExportDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, isTypeOnly: boolean, exportClause: ts.NamedExportBindings | undefined, moduleSpecifier: ts.Expression | undefined, assertClause: ts.AssertClause | undefined): ts.ExportDeclaration; +declare module "../../compiler/types" { + // Module transform: converted from interface augmentation + export interface NodeFactory { + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createParameterDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, dotDotDotToken: ts.DotDotDotToken | undefined, name: string | ts.BindingName, questionToken?: ts.QuestionToken, type?: ts.TypeNode, initializer?: ts.Expression): ts.ParameterDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateParameterDeclaration(node: ts.ParameterDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, dotDotDotToken: ts.DotDotDotToken | undefined, name: string | ts.BindingName, questionToken: ts.QuestionToken | undefined, type: ts.TypeNode | undefined, initializer: ts.Expression | undefined): ts.ParameterDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createPropertyDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.PropertyName, questionOrExclamationToken: ts.QuestionToken | ts.ExclamationToken | undefined, type: ts.TypeNode | undefined, initializer: ts.Expression | undefined): ts.PropertyDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updatePropertyDeclaration(node: ts.PropertyDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.PropertyName, questionOrExclamationToken: ts.QuestionToken | ts.ExclamationToken | undefined, type: ts.TypeNode | undefined, initializer: ts.Expression | undefined): ts.PropertyDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createMethodDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, asteriskToken: ts.AsteriskToken | undefined, name: string | ts.PropertyName, questionToken: ts.QuestionToken | undefined, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode | undefined, body: ts.Block | undefined): ts.MethodDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateMethodDeclaration(node: ts.MethodDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, asteriskToken: ts.AsteriskToken | undefined, name: ts.PropertyName, questionToken: ts.QuestionToken | undefined, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode | undefined, body: ts.Block | undefined): ts.MethodDeclaration; + /** + * @deprecated This node does not support Decorators. Callers should use an overload that does not accept a `decorators` parameter. + */ + createConstructorDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, parameters: readonly ts.ParameterDeclaration[], body: ts.Block | undefined): ts.ConstructorDeclaration; + /** + * @deprecated This node does not support Decorators. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateConstructorDeclaration(node: ts.ConstructorDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, parameters: readonly ts.ParameterDeclaration[], body: ts.Block | undefined): ts.ConstructorDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createGetAccessorDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.PropertyName, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode | undefined, body: ts.Block | undefined): ts.GetAccessorDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateGetAccessorDeclaration(node: ts.GetAccessorDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.PropertyName, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode | undefined, body: ts.Block | undefined): ts.GetAccessorDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createSetAccessorDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.PropertyName, parameters: readonly ts.ParameterDeclaration[], body: ts.Block | undefined): ts.SetAccessorDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateSetAccessorDeclaration(node: ts.SetAccessorDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.PropertyName, parameters: readonly ts.ParameterDeclaration[], body: ts.Block | undefined): ts.SetAccessorDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createIndexSignature(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode): ts.IndexSignatureDeclaration; + /** + * @deprecated Decorators and modifiers are no longer supported for this function. Callers should use an overload that does not accept the `decorators` and `modifiers` parameters. + */ + updateIndexSignature(node: ts.IndexSignatureDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode): ts.IndexSignatureDeclaration; + /** + * @deprecated Decorators and modifiers are no longer supported for this function. Callers should use an overload that does not accept the `decorators` and `modifiers` parameters. + */ + createClassStaticBlockDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, body: ts.Block): ts.ClassStaticBlockDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateClassStaticBlockDeclaration(node: ts.ClassStaticBlockDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, body: ts.Block): ts.ClassStaticBlockDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createClassExpression(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.Identifier | undefined, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, heritageClauses: readonly ts.HeritageClause[] | undefined, members: readonly ts.ClassElement[]): ts.ClassExpression; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateClassExpression(node: ts.ClassExpression, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.Identifier | undefined, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, heritageClauses: readonly ts.HeritageClause[] | undefined, members: readonly ts.ClassElement[]): ts.ClassExpression; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createFunctionDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, asteriskToken: ts.AsteriskToken | undefined, name: string | ts.Identifier | undefined, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode | undefined, body: ts.Block | undefined): ts.FunctionDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateFunctionDeclaration(node: ts.FunctionDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, asteriskToken: ts.AsteriskToken | undefined, name: ts.Identifier | undefined, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, parameters: readonly ts.ParameterDeclaration[], type: ts.TypeNode | undefined, body: ts.Block | undefined): ts.FunctionDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + createClassDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.Identifier | undefined, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, heritageClauses: readonly ts.HeritageClause[] | undefined, members: readonly ts.ClassElement[]): ts.ClassDeclaration; + /** + * @deprecated Decorators have been combined with modifiers. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateClassDeclaration(node: ts.ClassDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.Identifier | undefined, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, heritageClauses: readonly ts.HeritageClause[] | undefined, members: readonly ts.ClassElement[]): ts.ClassDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createInterfaceDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.Identifier, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, heritageClauses: readonly ts.HeritageClause[] | undefined, members: readonly ts.TypeElement[]): ts.InterfaceDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateInterfaceDeclaration(node: ts.InterfaceDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.Identifier, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, heritageClauses: readonly ts.HeritageClause[] | undefined, members: readonly ts.TypeElement[]): ts.InterfaceDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createTypeAliasDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.Identifier, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, type: ts.TypeNode): ts.TypeAliasDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateTypeAliasDeclaration(node: ts.TypeAliasDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.Identifier, typeParameters: readonly ts.TypeParameterDeclaration[] | undefined, type: ts.TypeNode): ts.TypeAliasDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createEnumDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: string | ts.Identifier, members: readonly ts.EnumMember[]): ts.EnumDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateEnumDeclaration(node: ts.EnumDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.Identifier, members: readonly ts.EnumMember[]): ts.EnumDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createModuleDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.ModuleName, body: ts.ModuleBody | undefined, flags?: ts.NodeFlags): ts.ModuleDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateModuleDeclaration(node: ts.ModuleDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, name: ts.ModuleName, body: ts.ModuleBody | undefined): ts.ModuleDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createImportEqualsDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, isTypeOnly: boolean, name: string | ts.Identifier, moduleReference: ts.ModuleReference): ts.ImportEqualsDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateImportEqualsDeclaration(node: ts.ImportEqualsDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, isTypeOnly: boolean, name: ts.Identifier, moduleReference: ts.ModuleReference): ts.ImportEqualsDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createImportDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, importClause: ts.ImportClause | undefined, moduleSpecifier: ts.Expression, assertClause?: ts.AssertClause): ts.ImportDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateImportDeclaration(node: ts.ImportDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, importClause: ts.ImportClause | undefined, moduleSpecifier: ts.Expression, assertClause: ts.AssertClause | undefined): ts.ImportDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createExportAssignment(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, isExportEquals: boolean | undefined, expression: ts.Expression): ts.ExportAssignment; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateExportAssignment(node: ts.ExportAssignment, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, expression: ts.Expression): ts.ExportAssignment; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + createExportDeclaration(decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, isTypeOnly: boolean, exportClause: ts.NamedExportBindings | undefined, moduleSpecifier?: ts.Expression, assertClause?: ts.AssertClause): ts.ExportDeclaration; + /** + * @deprecated Decorators are no longer supported for this function. Callers should use an overload that does not accept a `decorators` parameter. + */ + updateExportDeclaration(node: ts.ExportDeclaration, decorators: readonly ts.Decorator[] | undefined, modifiers: readonly ts.Modifier[] | undefined, isTypeOnly: boolean, exportClause: ts.NamedExportBindings | undefined, moduleSpecifier: ts.Expression | undefined, assertClause: ts.AssertClause | undefined): ts.ExportDeclaration; + } } const MUST_MERGE: ts.DeprecationOptions = { since: "4.8", warnAfter: "4.9.0-0", message: "Decorators have been combined with modifiers. Callers should switch to an overload that does not accept a 'decorators' parameter." }; @@ -1401,4 +1420,3 @@ ts.addNodeFactoryPatcher(patchNodeFactory); // Patch `ts.factory` because its public patchNodeFactory(ts.factory); -} diff --git a/src/deprecatedCompat/_namespaces/ts.ts b/src/deprecatedCompat/_namespaces/ts.ts new file mode 100644 index 0000000000000..652fc18b2eef1 --- /dev/null +++ b/src/deprecatedCompat/_namespaces/ts.ts @@ -0,0 +1,12 @@ +/* Generated file to emulate the ts namespace. */ + +export * from "../../compiler/_namespaces/ts"; +export * from "../deprecations"; +export * from "../4.0/nodeFactoryTopLevelExports"; +export * from "../4.0/renamedNodeTests"; +export * from "../4.0/renamedMapInterfaces"; +export * from "../4.2/renamedNodeTests"; +export * from "../4.2/abstractConstructorTypes"; +export * from "../4.6/importTypeAssertions"; +export * from "../4.7/typeParameterModifiers"; +export * from "../4.8/mergeDecoratorsAndModifiers"; diff --git a/src/deprecatedCompat/deprecations.ts b/src/deprecatedCompat/deprecations.ts index 27e245d4b6450..fc5e1baed68a3 100644 --- a/src/deprecatedCompat/deprecations.ts +++ b/src/deprecatedCompat/deprecations.ts @@ -1,3 +1,5 @@ +import * as ts from "./_namespaces/ts"; + // The following are deprecations for the public API. Deprecated exports are removed from the compiler itself // and compatible implementations are added here, along with an appropriate deprecation warning using // the `@deprecated` JSDoc tag as well as the `Debug.deprecate` API. @@ -10,8 +12,6 @@ // // Once we have determined enough time has passed after a deprecation has been marked as `"warn"` or `"error"`, it will be removed from the public API. -/* @internal */ -namespace ts { /** Defines a list of overloads by ordinal */ type OverloadDefinitions = { readonly [P in number]: (...args: any[]) => any; }; @@ -38,6 +38,7 @@ type OverloadBinders = { [P in OverloadKeys]: /** Defines deprecations for specific overloads by ordinal. */ type OverloadDeprecations = { [P in OverloadKeys]?: ts.DeprecationOptions; }; +/** @internal */ export function createOverload(name: string, overloads: T, binder: OverloadBinders, deprecations?: OverloadDeprecations) { Object.defineProperty(call, "name", { ...Object.getOwnPropertyDescriptor(call, "name"), value: name }); @@ -93,6 +94,7 @@ interface BoundOverloadBuilder extends Finishable // NOTE: We only use this "builder" because we don't infer correctly when calling `createOverload` directly in < TS 4.7, // but lib is currently at TS 4.4. We can switch to directly calling `createOverload` when we update LKG in main. +/** @internal */ export function buildOverload(name: string): OverloadBuilder { return { overload: overloads => ({ @@ -104,5 +106,4 @@ export function buildOverload(name: string): OverloadBuilder { }) }) }; -} } \ No newline at end of file diff --git a/src/deprecatedCompat/tsconfig.json b/src/deprecatedCompat/tsconfig.json index 02ee1a79a8907..5eecec15a02dc 100644 --- a/src/deprecatedCompat/tsconfig.json +++ b/src/deprecatedCompat/tsconfig.json @@ -1,7 +1,7 @@ { "extends": "../tsconfig-base", "compilerOptions": { - "outFile": "../../built/local/deprecatedCompat.js", + "outDir": "../../built/local", "experimentalDecorators": true }, "references": [ @@ -16,6 +16,7 @@ "4.2/abstractConstructorTypes.ts", "4.6/importTypeAssertions.ts", "4.7/typeParameterModifiers.ts", - "4.8/mergeDecoratorsAndModifiers.ts" + "4.8/mergeDecoratorsAndModifiers.ts", + "_namespaces/ts.ts" ] } \ No newline at end of file diff --git a/src/dynamicImportCompat/_namespaces/ts.server.ts b/src/dynamicImportCompat/_namespaces/ts.server.ts new file mode 100644 index 0000000000000..729da9c24ef35 --- /dev/null +++ b/src/dynamicImportCompat/_namespaces/ts.server.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.server namespace. */ + +export * from "../dynamicImportCompat"; diff --git a/src/dynamicImportCompat/_namespaces/ts.ts b/src/dynamicImportCompat/_namespaces/ts.ts new file mode 100644 index 0000000000000..91d7693414440 --- /dev/null +++ b/src/dynamicImportCompat/_namespaces/ts.ts @@ -0,0 +1,4 @@ +/* Generated file to emulate the ts namespace. */ + +import * as server from "./ts.server"; +export { server }; diff --git a/src/dynamicImportCompat/dynamicImportCompat.ts b/src/dynamicImportCompat/dynamicImportCompat.ts index 21d9ab12bb9e5..5981d8c7e968e 100644 --- a/src/dynamicImportCompat/dynamicImportCompat.ts +++ b/src/dynamicImportCompat/dynamicImportCompat.ts @@ -1,3 +1 @@ -namespace ts.server { -export const dynamicImport = (id: string) => import(id); -} \ No newline at end of file +export const dynamicImport = (id: string) => import(id); \ No newline at end of file diff --git a/src/dynamicImportCompat/tsconfig.json b/src/dynamicImportCompat/tsconfig.json index 1ae167524208f..5ae4980fdaade 100644 --- a/src/dynamicImportCompat/tsconfig.json +++ b/src/dynamicImportCompat/tsconfig.json @@ -12,5 +12,7 @@ }, "files": [ "dynamicImportCompat.ts", + "_namespaces/ts.server.ts", + "_namespaces/ts.ts" ] } diff --git a/src/executeCommandLine/_namespaces/ts.ts b/src/executeCommandLine/_namespaces/ts.ts new file mode 100644 index 0000000000000..488d183df4a38 --- /dev/null +++ b/src/executeCommandLine/_namespaces/ts.ts @@ -0,0 +1,4 @@ +/* Generated file to emulate the ts namespace. */ + +export * from "../../compiler/_namespaces/ts"; +export * from "../executeCommandLine"; diff --git a/src/executeCommandLine/executeCommandLine.ts b/src/executeCommandLine/executeCommandLine.ts index 50fb1ea412a2d..e4ed65a428dcb 100644 --- a/src/executeCommandLine/executeCommandLine.ts +++ b/src/executeCommandLine/executeCommandLine.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + interface Statistic { name: string; value: number; @@ -1207,4 +1208,3 @@ function writeConfigFile( return; } -} diff --git a/src/executeCommandLine/tsconfig.json b/src/executeCommandLine/tsconfig.json index 7049d5ff90914..88eed2c43f87c 100644 --- a/src/executeCommandLine/tsconfig.json +++ b/src/executeCommandLine/tsconfig.json @@ -1,7 +1,7 @@ { "extends": "../tsconfig-base", "compilerOptions": { - "outFile": "../../built/local/executeCommandLine.js" + "outDir": "../../built/local" }, "references": [ @@ -9,6 +9,7 @@ ], "files": [ - "executeCommandLine.ts" + "executeCommandLine.ts", + "_namespaces/ts.ts" ] } diff --git a/src/executeCommandLine/tsconfig.release.json b/src/executeCommandLine/tsconfig.release.json index fee25efdd03f7..57ae0adbf56e3 100644 --- a/src/executeCommandLine/tsconfig.release.json +++ b/src/executeCommandLine/tsconfig.release.json @@ -1,7 +1,7 @@ { "extends": "./tsconfig.json", "compilerOptions": { - "outFile": "../../built/local/executeCommandLine.release.js", + "outDir": "../../built/local/release", "removeComments": true, "preserveConstEnums": false }, diff --git a/src/harness/_namespaces/FourSlash.ts b/src/harness/_namespaces/FourSlash.ts new file mode 100644 index 0000000000000..c069ebaf784de --- /dev/null +++ b/src/harness/_namespaces/FourSlash.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the FourSlash namespace. */ + +export * from "../fourslashImpl"; diff --git a/src/harness/_namespaces/FourSlashInterface.ts b/src/harness/_namespaces/FourSlashInterface.ts new file mode 100644 index 0000000000000..270be7300135f --- /dev/null +++ b/src/harness/_namespaces/FourSlashInterface.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the FourSlashInterface namespace. */ + +export * from "../fourslashInterfaceImpl"; diff --git a/src/harness/_namespaces/Harness.LanguageService.ts b/src/harness/_namespaces/Harness.LanguageService.ts new file mode 100644 index 0000000000000..53544477e279c --- /dev/null +++ b/src/harness/_namespaces/Harness.LanguageService.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the Harness.LanguageService namespace. */ + +export * from "../harnessLanguageService"; diff --git a/src/harness/_namespaces/Harness.SourceMapRecorder.ts b/src/harness/_namespaces/Harness.SourceMapRecorder.ts new file mode 100644 index 0000000000000..909654b08d165 --- /dev/null +++ b/src/harness/_namespaces/Harness.SourceMapRecorder.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the Harness.SourceMapRecorder namespace. */ + +export * from "../sourceMapRecorder"; diff --git a/src/harness/_namespaces/Harness.ts b/src/harness/_namespaces/Harness.ts new file mode 100644 index 0000000000000..3ff4b006555c1 --- /dev/null +++ b/src/harness/_namespaces/Harness.ts @@ -0,0 +1,9 @@ +/* Generated file to emulate the Harness namespace. */ + +export * from "../runnerbase"; +export * from "../harnessIO"; +export * from "../typeWriter"; +import * as LanguageService from "./Harness.LanguageService"; +export { LanguageService }; +import * as SourceMapRecorder from "./Harness.SourceMapRecorder"; +export { SourceMapRecorder }; diff --git a/src/harness/_namespaces/Utils.ts b/src/harness/_namespaces/Utils.ts new file mode 100644 index 0000000000000..3b958cd166789 --- /dev/null +++ b/src/harness/_namespaces/Utils.ts @@ -0,0 +1,5 @@ +/* Generated file to emulate the Utils namespace. */ + +export * from "../util"; +export * from "../findUpDir"; +export * from "../harnessUtils"; diff --git a/src/harness/_namespaces/collections.ts b/src/harness/_namespaces/collections.ts new file mode 100644 index 0000000000000..870e956769ebb --- /dev/null +++ b/src/harness/_namespaces/collections.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the collections namespace. */ + +export * from "../collectionsImpl"; diff --git a/src/harness/_namespaces/compiler.ts b/src/harness/_namespaces/compiler.ts new file mode 100644 index 0000000000000..3ff645eca59d2 --- /dev/null +++ b/src/harness/_namespaces/compiler.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the compiler namespace. */ + +export * from "../compilerImpl"; diff --git a/src/harness/_namespaces/documents.ts b/src/harness/_namespaces/documents.ts new file mode 100644 index 0000000000000..67dbd0e6c1c20 --- /dev/null +++ b/src/harness/_namespaces/documents.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the documents namespace. */ + +export * from "../documentsUtil"; diff --git a/src/harness/_namespaces/evaluator.ts b/src/harness/_namespaces/evaluator.ts new file mode 100644 index 0000000000000..e47f3eb0aeee2 --- /dev/null +++ b/src/harness/_namespaces/evaluator.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the evaluator namespace. */ + +export * from "../evaluatorImpl"; diff --git a/src/harness/_namespaces/fakes.ts b/src/harness/_namespaces/fakes.ts new file mode 100644 index 0000000000000..d2a68860bbb15 --- /dev/null +++ b/src/harness/_namespaces/fakes.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the fakes namespace. */ + +export * from "../fakesHosts"; diff --git a/src/harness/_namespaces/ts.TestFSWithWatch.ts b/src/harness/_namespaces/ts.TestFSWithWatch.ts new file mode 100644 index 0000000000000..d20826a03b03f --- /dev/null +++ b/src/harness/_namespaces/ts.TestFSWithWatch.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.TestFSWithWatch namespace. */ + +export * from "../virtualFileSystemWithWatch"; diff --git a/src/harness/_namespaces/ts.server.ts b/src/harness/_namespaces/ts.server.ts new file mode 100644 index 0000000000000..714986489e3d5 --- /dev/null +++ b/src/harness/_namespaces/ts.server.ts @@ -0,0 +1,6 @@ +/* Generated file to emulate the ts.server namespace. */ + +export * from "../../jsTyping/_namespaces/ts.server"; +export * from "../../server/_namespaces/ts.server"; +export * from "../../typingsInstallerCore/_namespaces/ts.server"; +export * from "../client"; diff --git a/src/harness/_namespaces/ts.ts b/src/harness/_namespaces/ts.ts new file mode 100644 index 0000000000000..9c29cb2905643 --- /dev/null +++ b/src/harness/_namespaces/ts.ts @@ -0,0 +1,13 @@ +/* Generated file to emulate the ts namespace. */ + +export * from "../../compiler/_namespaces/ts"; +export * from "../../services/_namespaces/ts"; +export * from "../../jsTyping/_namespaces/ts"; +export * from "../../server/_namespaces/ts"; +export * from "../../typingsInstallerCore/_namespaces/ts"; +export * from "../../deprecatedCompat/_namespaces/ts"; +export * from "../harnessGlobals"; +import * as server from "./ts.server"; +export { server }; +import * as TestFSWithWatch from "./ts.TestFSWithWatch"; +export { TestFSWithWatch }; diff --git a/src/harness/_namespaces/vfs.ts b/src/harness/_namespaces/vfs.ts new file mode 100644 index 0000000000000..1eb82cd822103 --- /dev/null +++ b/src/harness/_namespaces/vfs.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the vfs namespace. */ + +export * from "../vfsUtil"; diff --git a/src/harness/_namespaces/vpath.ts b/src/harness/_namespaces/vpath.ts new file mode 100644 index 0000000000000..7430c87d9b6ad --- /dev/null +++ b/src/harness/_namespaces/vpath.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the vpath namespace. */ + +export * from "../vpathUtil"; diff --git a/src/harness/client.ts b/src/harness/client.ts index cccc794eccd68..51e3eb0cc609b 100644 --- a/src/harness/client.ts +++ b/src/harness/client.ts @@ -1,4 +1,5 @@ -namespace ts.server { +import * as ts from "./_namespaces/ts"; + export interface SessionClientHost extends ts.LanguageServiceHost { writeMessage(message: string): void; } @@ -928,4 +929,3 @@ export class SessionClient implements ts.LanguageService { throw new Error("dispose is not available through the server layer."); } } -} diff --git a/src/harness/collectionsImpl.ts b/src/harness/collectionsImpl.ts index f06dd0aad667f..541358ac95862 100644 --- a/src/harness/collectionsImpl.ts +++ b/src/harness/collectionsImpl.ts @@ -1,4 +1,5 @@ -namespace collections { +import * as ts from "./_namespaces/ts"; + export interface SortOptions { comparer: (a: T, b: T) => number; sort: "insertion" | "comparison"; @@ -323,4 +324,3 @@ export class Metadata { return (text.length >= 3 && text.charAt(0) === "_" && text.charAt(1) === "_" && text.charAt(2) === "_" ? text.slice(1) : text); } } -} diff --git a/src/harness/compilerImpl.ts b/src/harness/compilerImpl.ts index 96bd494d377ac..dc694efa4415c 100644 --- a/src/harness/compilerImpl.ts +++ b/src/harness/compilerImpl.ts @@ -1,7 +1,15 @@ +import * as ts from "./_namespaces/ts"; +import * as fakes from "./_namespaces/fakes"; +import * as vpath from "./_namespaces/vpath"; +import * as documents from "./_namespaces/documents"; +import * as vfs from "./_namespaces/vfs"; +import * as collections from "./_namespaces/collections"; +import * as Harness from "./_namespaces/Harness"; + /** * Test harness compiler functionality. */ -namespace compiler { + export interface Project { file: string; config?: ts.ParsedCommandLine; @@ -285,4 +293,3 @@ export function compileFiles(host: fakes.CompilerHost, rootFiles: string[] | und ] : postErrors; return new CompilationResult(host, compilerOptions, program, emitResult, errors); } -} diff --git a/src/harness/documentsUtil.ts b/src/harness/documentsUtil.ts index e06726fb9141b..dd012f4477263 100644 --- a/src/harness/documentsUtil.ts +++ b/src/harness/documentsUtil.ts @@ -1,7 +1,9 @@ +import * as Harness from "./_namespaces/Harness"; +import * as ts from "./_namespaces/ts"; + // NOTE: The contents of this file are all exported from the namespace 'documents'. This is to // support the eventual conversion of harness into a modular system. -namespace documents { export class TextDocument { public readonly meta: Map; public readonly file: string; @@ -183,5 +185,4 @@ export class SourceMap { } return vlq; } -} } \ No newline at end of file diff --git a/src/harness/evaluatorImpl.ts b/src/harness/evaluatorImpl.ts index 20b303c5537e9..3f51831308e78 100644 --- a/src/harness/evaluatorImpl.ts +++ b/src/harness/evaluatorImpl.ts @@ -1,4 +1,10 @@ -namespace evaluator { +import * as vpath from "./_namespaces/vpath"; +import * as vfs from "./_namespaces/vfs"; +import * as ts from "./_namespaces/ts"; +import * as Harness from "./_namespaces/Harness"; +import * as fakes from "./_namespaces/fakes"; +import * as compiler from "./_namespaces/compiler"; + declare let Symbol: SymbolConstructor; const sourceFile = vpath.combine(vfs.srcFolder, "source.ts"); @@ -456,4 +462,3 @@ class SystemLoader extends Loader { } } } -} diff --git a/src/harness/fakesHosts.ts b/src/harness/fakesHosts.ts index 85914a08df03f..8bafb0a902934 100644 --- a/src/harness/fakesHosts.ts +++ b/src/harness/fakesHosts.ts @@ -1,7 +1,15 @@ +import * as ts from "./_namespaces/ts"; +import * as vfs from "./_namespaces/vfs"; +import * as Utils from "./_namespaces/Utils"; +import * as vpath from "./_namespaces/vpath"; +import * as documents from "./_namespaces/documents"; +import * as collections from "./_namespaces/collections"; +import * as Harness from "./_namespaces/Harness"; + /** * Fake implementations of various compiler dependencies. */ -namespace fakes { + const processExitSentinel = new Error("System exit"); export interface SystemOptions { @@ -594,5 +602,4 @@ Actual All:: ${JSON.stringify(this.diagnostics.slice().map(diagnosticToText), /* return this.sys.now(); } } -} diff --git a/src/harness/findUpDir.ts b/src/harness/findUpDir.ts index c729ac407ea48..6fd1b51b0719d 100644 --- a/src/harness/findUpDir.ts +++ b/src/harness/findUpDir.ts @@ -1,4 +1,3 @@ -namespace Utils { const { join, resolve, dirname } = require("path") as typeof import("path"); const { existsSync } = require("fs") as typeof import("fs"); @@ -18,4 +17,3 @@ export function findUpFile(name: string): string { export const findUpRoot: { (): string; cached?: string; } = () => findUpRoot.cached ||= dirname(findUpFile("Gulpfile.mjs")); -} diff --git a/src/harness/fourslashImpl.ts b/src/harness/fourslashImpl.ts index 32f06316bc2a3..ff8de94c2ef9c 100644 --- a/src/harness/fourslashImpl.ts +++ b/src/harness/fourslashImpl.ts @@ -1,4 +1,11 @@ -namespace FourSlash { +import * as FourSlashInterface from "./_namespaces/FourSlashInterface"; +import * as Harness from "./_namespaces/Harness"; +import * as vfs from "./_namespaces/vfs"; +import * as ts from "./_namespaces/ts"; +import * as fakes from "./_namespaces/fakes"; +import * as vpath from "./_namespaces/vpath"; +import * as Utils from "./_namespaces/Utils"; + import ArrayOrSingle = FourSlashInterface.ArrayOrSingle; export const enum FourSlashTestType { @@ -4627,4 +4634,3 @@ function rangesOfDiffBetweenTwoStrings(source: string, target: string) { }); return emTarget; } -} diff --git a/src/harness/fourslashInterfaceImpl.ts b/src/harness/fourslashInterfaceImpl.ts index 46bcea992958c..25889e77f4002 100644 --- a/src/harness/fourslashInterfaceImpl.ts +++ b/src/harness/fourslashInterfaceImpl.ts @@ -1,4 +1,6 @@ -namespace FourSlashInterface { +import * as FourSlash from "./_namespaces/FourSlash"; +import * as ts from "./_namespaces/ts"; + export class Test { constructor(private state: FourSlash.TestState) { } @@ -1907,4 +1909,3 @@ export interface RenameOptions { readonly findInComments?: boolean; readonly providePrefixAndSuffixTextForRename?: boolean; } -} diff --git a/src/harness/harnessGlobals.ts b/src/harness/harnessGlobals.ts index 79acccf26cedc..97c363e95f413 100644 --- a/src/harness/harnessGlobals.ts +++ b/src/harness/harnessGlobals.ts @@ -1,9 +1,17 @@ +import * as ts from "./_namespaces/ts"; + // Block scoped definitions work poorly for global variables, temporarily enable var /* eslint-disable no-var */ // this will work in the browser via browserify -declare var assert: typeof _chai.assert; -declare var expect: typeof _chai.expect; +declare global { + // Module transform: converted from ambient declaration + var assert: typeof _chai.assert; +} +declare global { + // Module transform: converted from ambient declaration + var expect: typeof _chai.expect; +} var _chai: typeof import("chai") = require("chai"); globalThis.assert = _chai.assert; { @@ -34,5 +42,4 @@ globalThis.assert = _chai.assert; globalThis.expect = _chai.expect; /* eslint-enable no-var */ // empty ts namespace so this file is included in the `ts.ts` namespace file generated by the module swapover -// This way, everything that ends up importing `ts` downstream also imports this file and picks up its augmentation -namespace ts {} \ No newline at end of file +// This way, everything that ends up importing `ts` downstream also imports this file and picks up its augmentation \ No newline at end of file diff --git a/src/harness/harnessIO.ts b/src/harness/harnessIO.ts index 99ba5c83eb4a3..a962d24d5caa2 100644 --- a/src/harness/harnessIO.ts +++ b/src/harness/harnessIO.ts @@ -1,4 +1,12 @@ -namespace Harness { +import * as Harness from "./_namespaces/Harness"; +import * as ts from "./_namespaces/ts"; +import * as Utils from "./_namespaces/Utils"; +import * as vpath from "./_namespaces/vpath"; +import * as vfs from "./_namespaces/vfs"; +import * as compiler from "./_namespaces/compiler"; +import * as documents from "./_namespaces/documents"; +import * as fakes from "./_namespaces/fakes"; + export interface IO { newLine(): string; getCurrentDirectory(): string; @@ -1491,4 +1499,3 @@ export function getConfigNameFromFileName(filename: string): "tsconfig.json" | " } if (Error) (Error as any).stackTraceLimit = 100; -} diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index 29e147bae1530..b69ee930af1e7 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -1,4 +1,10 @@ -namespace Harness.LanguageService { +import * as Harness from "./_namespaces/Harness"; +import * as ts from "./_namespaces/ts"; +import * as fakes from "./_namespaces/fakes"; +import * as vfs from "./_namespaces/vfs"; +import * as collections from "./_namespaces/collections"; +import * as vpath from "./_namespaces/vpath"; +import * as Utils from "./_namespaces/Utils"; export function makeDefaultProxy(info: ts.server.PluginCreateInfo): ts.LanguageService { const proxy = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null @@ -1041,4 +1047,3 @@ export class ServerLanguageServiceAdapter implements LanguageServiceAdapter { ].join(ts.sys.newLine)); } } -} diff --git a/src/harness/harnessUtils.ts b/src/harness/harnessUtils.ts index 64bcd9228276c..7251afc719c7e 100644 --- a/src/harness/harnessUtils.ts +++ b/src/harness/harnessUtils.ts @@ -1,4 +1,6 @@ -namespace Utils { +import * as ts from "./_namespaces/ts"; +import * as Harness from "./_namespaces/Harness"; + export function encodeString(s: string): string { return ts.sys.bufferFrom!(s).toString("utf8"); } @@ -375,4 +377,3 @@ function isNode(line: string) { function isHarness(line: string) { return /[\\/]src[\\/]harness[\\/]|[\\/]run\.js/.test(line); } -} diff --git a/src/harness/runnerbase.ts b/src/harness/runnerbase.ts index b7658c24ea3f0..e35332a537ba7 100644 --- a/src/harness/runnerbase.ts +++ b/src/harness/runnerbase.ts @@ -1,4 +1,6 @@ -namespace Harness { +import * as Harness from "./_namespaces/Harness"; +import * as ts from "./_namespaces/ts"; + export type TestRunnerKind = CompilerTestKind | FourslashTestKind | "project" | "rwc" | "test262" | "user" | "dt" | "docker"; export type CompilerTestKind = "conformance" | "compiler"; export type FourslashTestKind = "fourslash" | "fourslash-shims" | "fourslash-shims-pp" | "fourslash-server"; @@ -59,5 +61,4 @@ export abstract class RunnerBase { fixedPath = fixedPath.replace(localHost, ""); return fixedPath; } -} } \ No newline at end of file diff --git a/src/harness/sourceMapRecorder.ts b/src/harness/sourceMapRecorder.ts index 3a844b3e6bda8..4955560cf15e9 100644 --- a/src/harness/sourceMapRecorder.ts +++ b/src/harness/sourceMapRecorder.ts @@ -1,4 +1,7 @@ -namespace Harness.SourceMapRecorder { +import * as Harness from "./_namespaces/Harness"; +import * as ts from "./_namespaces/ts"; +import * as documents from "./_namespaces/documents"; +import * as Utils from "./_namespaces/Utils"; interface SourceMapSpanWithDecodeErrors { sourceMapSpan: ts.Mapping; @@ -364,4 +367,3 @@ export function getSourceMapRecordWithSystem(sys: ts.System, sourceMapFile: stri return value; } } -} diff --git a/src/harness/tsconfig.json b/src/harness/tsconfig.json index 533ac9c4d3952..55091a17fbe52 100644 --- a/src/harness/tsconfig.json +++ b/src/harness/tsconfig.json @@ -1,7 +1,7 @@ { "extends": "../tsconfig-base", "compilerOptions": { - "outFile": "../../built/local/harness.js", + "outDir": "../../built/local", "types": [ "node", "mocha", "chai" ], @@ -40,6 +40,22 @@ "virtualFileSystemWithWatch.ts", "fourslashImpl.ts", "fourslashInterfaceImpl.ts", - "typeWriter.ts" + "typeWriter.ts", + "_namespaces/ts.server.ts", + "_namespaces/ts.ts", + "_namespaces/collections.ts", + "_namespaces/compiler.ts", + "_namespaces/documents.ts", + "_namespaces/evaluator.ts", + "_namespaces/fakes.ts", + "_namespaces/Utils.ts", + "_namespaces/FourSlash.ts", + "_namespaces/FourSlashInterface.ts", + "_namespaces/Harness.ts", + "_namespaces/Harness.LanguageService.ts", + "_namespaces/Harness.SourceMapRecorder.ts", + "_namespaces/vfs.ts", + "_namespaces/ts.TestFSWithWatch.ts", + "_namespaces/vpath.ts" ] } diff --git a/src/harness/typeWriter.ts b/src/harness/typeWriter.ts index 7efba33459721..6593623c4d71f 100644 --- a/src/harness/typeWriter.ts +++ b/src/harness/typeWriter.ts @@ -1,4 +1,5 @@ -namespace Harness { +import * as ts from "./_namespaces/ts"; + export interface TypeWriterTypeResult { line: number; syntaxKind: number; @@ -190,5 +191,4 @@ export class TypeWriterWalker { symbol: symbolString }; } -} } \ No newline at end of file diff --git a/src/harness/util.ts b/src/harness/util.ts index cf6317c47ec63..2dac1835f1293 100644 --- a/src/harness/util.ts +++ b/src/harness/util.ts @@ -1,7 +1,9 @@ +import * as ts from "./_namespaces/ts"; + /** * Common utilities */ -namespace Utils { + const testPathPrefixRegExp = /(?:(file:\/{3})|\/)\.(ts|lib|src)\//g; export function removeTestPathPrefixes(text: string, retainTrailingDirectorySeparator?: boolean): string { return text !== undefined ? text.replace(testPathPrefixRegExp, (_, scheme) => scheme || (retainTrailingDirectorySeparator ? "/" : "")) : undefined!; // TODO: GH#18217 @@ -124,5 +126,4 @@ export function defer(): Deferred { reject = _reject; }); return { resolve, reject, promise }; -} } \ No newline at end of file diff --git a/src/harness/vfsUtil.ts b/src/harness/vfsUtil.ts index 5cd3c2f033683..b52f712e768fd 100644 --- a/src/harness/vfsUtil.ts +++ b/src/harness/vfsUtil.ts @@ -1,4 +1,9 @@ -namespace vfs { +import * as collections from "./_namespaces/collections"; +import * as ts from "./_namespaces/ts"; +import * as vpath from "./_namespaces/vpath"; +import * as documents from "./_namespaces/documents"; +import * as Harness from "./_namespaces/Harness"; + /** * Posix-style path to the TypeScript compiler build outputs (including tsc.js, lib.d.ts, etc.) */ @@ -1627,4 +1632,3 @@ function* iteratePatchWorker(dirname: string, container: FileSet): IterableItera } } } -} diff --git a/src/harness/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index 46ca4e615ebaf..0c938d323958a 100644 --- a/src/harness/virtualFileSystemWithWatch.ts +++ b/src/harness/virtualFileSystemWithWatch.ts @@ -1,4 +1,6 @@ -namespace ts.TestFSWithWatch { +import * as ts from "./_namespaces/ts"; +import * as Harness from "./_namespaces/Harness"; + export const libFile: File = { path: "/a/lib/lib.d.ts", content: `/// @@ -1190,4 +1192,3 @@ export function getTsBuildProjectFile(project: string, file: string): File { content: Harness.IO.readFile(`${Harness.IO.getWorkspaceRoot()}/tests/projects/${project}/${file}`)! }; } -} diff --git a/src/harness/vpathUtil.ts b/src/harness/vpathUtil.ts index 88dd6d752fe25..0e84144cf0958 100644 --- a/src/harness/vpathUtil.ts +++ b/src/harness/vpathUtil.ts @@ -1,4 +1,6 @@ -namespace vpath { +import * as ts from "./_namespaces/ts"; +import * as vfs from "./_namespaces/vfs"; + export import sep = ts.directorySeparator; export import normalizeSeparators = ts.normalizeSlashes; export import isAbsolute = ts.isRootedDiskPath; @@ -133,4 +135,3 @@ export function isDefaultLibrary(path: string) { export function isTsConfigFile(path: string): boolean { return path.indexOf("tsconfig") !== -1 && path.indexOf("json") !== -1; } -} diff --git a/src/jsTyping/_namespaces/ts.JsTyping.ts b/src/jsTyping/_namespaces/ts.JsTyping.ts new file mode 100644 index 0000000000000..6b010af980713 --- /dev/null +++ b/src/jsTyping/_namespaces/ts.JsTyping.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.JsTyping namespace. */ + +export * from "../jsTyping"; diff --git a/src/jsTyping/_namespaces/ts.server.ts b/src/jsTyping/_namespaces/ts.server.ts new file mode 100644 index 0000000000000..fe67648d42d98 --- /dev/null +++ b/src/jsTyping/_namespaces/ts.server.ts @@ -0,0 +1,4 @@ +/* Generated file to emulate the ts.server namespace. */ + +export * from "../shared"; +export * from "../types"; diff --git a/src/jsTyping/_namespaces/ts.ts b/src/jsTyping/_namespaces/ts.ts new file mode 100644 index 0000000000000..adf9791f4d2b5 --- /dev/null +++ b/src/jsTyping/_namespaces/ts.ts @@ -0,0 +1,7 @@ +/* Generated file to emulate the ts namespace. */ + +export * from "../../compiler/_namespaces/ts"; +import * as JsTyping from "./ts.JsTyping"; +export { JsTyping }; +import * as server from "./ts.server"; +export { server }; diff --git a/src/jsTyping/jsTyping.ts b/src/jsTyping/jsTyping.ts index 281cb36389836..20e467e72d3bd 100644 --- a/src/jsTyping/jsTyping.ts +++ b/src/jsTyping/jsTyping.ts @@ -1,6 +1,6 @@ -/* @internal */ -namespace ts.JsTyping { +import * as ts from "./_namespaces/ts"; +/** @internal */ export interface TypingResolutionHost { directoryExists(path: string): boolean; fileExists(fileName: string): boolean; @@ -18,11 +18,13 @@ interface PackageJson { typings?: string; } +/** @internal */ export interface CachedTyping { typingLocation: string; version: ts.Version; } +/** @internal */ export function isTypingUpToDate(cachedTyping: CachedTyping, availableTypingVersions: ts.MapLike) { const availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, `ts${ts.versionMajorMinor}`) || ts.getProperty(availableTypingVersions, "latest")!); return availableVersion.compareTo(cachedTyping.version) <= 0; @@ -78,26 +80,33 @@ const unprefixedNodeCoreModuleList = [ "zlib" ]; +/** @internal */ export const prefixedNodeCoreModuleList = unprefixedNodeCoreModuleList.map(name => `node:${name}`); +/** @internal */ export const nodeCoreModuleList: readonly string[] = [...unprefixedNodeCoreModuleList, ...prefixedNodeCoreModuleList]; +/** @internal */ export const nodeCoreModules = new ts.Set(nodeCoreModuleList); +/** @internal */ export function nonRelativeModuleNameForTypingCache(moduleName: string) { return nodeCoreModules.has(moduleName) ? "node" : moduleName; } +/** @internal */ /** * A map of loose file names to library names that we are confident require typings */ export type SafeList = ts.ReadonlyESMap; +/** @internal */ export function loadSafeList(host: TypingResolutionHost, safeListPath: ts.Path): SafeList { const result = ts.readConfigFile(safeListPath, path => host.readFile(path)); return new ts.Map(ts.getEntries(result.config)); } +/** @internal */ export function loadTypesMap(host: TypingResolutionHost, typesMapPath: ts.Path): SafeList | undefined { const result = ts.readConfigFile(typesMapPath, path => host.readFile(path)); if (result.config) { @@ -106,6 +115,7 @@ export function loadTypesMap(host: TypingResolutionHost, typesMapPath: ts.Path): return undefined; } +/** @internal */ /** * @param host is the object providing I/O related operations. * @param fileNames are the file names that belong to the same project @@ -334,6 +344,7 @@ export function discoverTypings( } } +/** @internal */ export const enum NameValidationResult { Ok, EmptyName, @@ -345,13 +356,16 @@ export const enum NameValidationResult { const maxPackageNameLength = 214; +/** @internal */ export interface ScopedPackageNameValidationResult { name: string; isScopeName: boolean; result: NameValidationResult; } +/** @internal */ export type PackageNameValidationResult = NameValidationResult | ScopedPackageNameValidationResult; +/** @internal */ /** * Validates package name using rules defined at https://docs.npmjs.com/files/package.json */ @@ -396,6 +410,7 @@ function validatePackageNameWorker(packageName: string, supportScopedPackage: bo return NameValidationResult.Ok; } +/** @internal */ export function renderPackageNameValidationFailure(result: PackageNameValidationResult, typing: string): string { return typeof result === "object" ? renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) : @@ -421,4 +436,3 @@ function renderPackageNameValidationFailureWorker(typing: string, result: NameVa throw ts.Debug.assertNever(result); } } -} diff --git a/src/jsTyping/shared.ts b/src/jsTyping/shared.ts index 75cec1fce1f44..f7e40c00b1368 100644 --- a/src/jsTyping/shared.ts +++ b/src/jsTyping/shared.ts @@ -1,4 +1,5 @@ -namespace ts.server { +import * as ts from "./_namespaces/ts"; + export type ActionSet = "action::set"; export type ActionInvalidate = "action::invalidate"; export type ActionPackageInstalled = "action::packageInstalled"; @@ -59,4 +60,3 @@ export function nowString() { const d = new Date(); return `${ts.padLeft(d.getHours().toString(), 2, "0")}:${ts.padLeft(d.getMinutes().toString(), 2, "0")}:${ts.padLeft(d.getSeconds().toString(), 2, "0")}.${ts.padLeft(d.getMilliseconds().toString(), 3, "0")}`; } -} diff --git a/src/jsTyping/tsconfig.json b/src/jsTyping/tsconfig.json index ac5b8b19c2920..9d360f086afae 100644 --- a/src/jsTyping/tsconfig.json +++ b/src/jsTyping/tsconfig.json @@ -1,7 +1,7 @@ { "extends": "../tsconfig-base", "compilerOptions": { - "outFile": "../../built/local/jsTyping.js", + "outDir": "../../built/local", "types": [ "node" ], @@ -16,6 +16,9 @@ "files": [ "shared.ts", "types.ts", - "jsTyping.ts" + "jsTyping.ts", + "_namespaces/ts.JsTyping.ts", + "_namespaces/ts.ts", + "_namespaces/ts.server.ts" ] } diff --git a/src/jsTyping/types.ts b/src/jsTyping/types.ts index 6a697e9407701..9a0ca8dd09639 100644 --- a/src/jsTyping/types.ts +++ b/src/jsTyping/types.ts @@ -1,4 +1,5 @@ -declare namespace ts.server { +import * as ts from "./_namespaces/ts"; + export interface TypingInstallerResponse { readonly kind: ts.server.ActionSet | ts.server.ActionInvalidate | ts.server.EventTypesRegistry | ts.server.ActionPackageInstalled | ts.server.EventBeginInstallTypes | ts.server.EventEndInstallTypes | ts.server.EventInitializationFailed; } @@ -98,4 +99,3 @@ export interface SetTypings extends ProjectResponse { /* @internal */ export type TypingInstallerResponseUnion = SetTypings | InvalidateCachedTypings | TypesRegistryResponse | PackageInstalledResponse | InstallTypes | InitializationFailedResponse; -} diff --git a/src/loggedIO/_namespaces/Harness.ts b/src/loggedIO/_namespaces/Harness.ts new file mode 100644 index 0000000000000..bcd2ed640ddec --- /dev/null +++ b/src/loggedIO/_namespaces/Harness.ts @@ -0,0 +1,4 @@ +/* Generated file to emulate the Harness namespace. */ + +export * from "../../harness/_namespaces/Harness"; +export * from "../loggedIO"; diff --git a/src/loggedIO/_namespaces/Playback.ts b/src/loggedIO/_namespaces/Playback.ts new file mode 100644 index 0000000000000..a2e238e856aab --- /dev/null +++ b/src/loggedIO/_namespaces/Playback.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the Playback namespace. */ + +export * from "../loggedIO"; diff --git a/src/loggedIO/_namespaces/ts.server.ts b/src/loggedIO/_namespaces/ts.server.ts new file mode 100644 index 0000000000000..b4a44f9d78c5e --- /dev/null +++ b/src/loggedIO/_namespaces/ts.server.ts @@ -0,0 +1,7 @@ +/* Generated file to emulate the ts.server namespace. */ + +export * from "../../jsTyping/_namespaces/ts.server"; +export * from "../../server/_namespaces/ts.server"; +export * from "../../typingsInstallerCore/_namespaces/ts.server"; +export * from "../../harness/_namespaces/ts.server"; +export * from "../loggedIO"; diff --git a/src/loggedIO/_namespaces/ts.ts b/src/loggedIO/_namespaces/ts.ts new file mode 100644 index 0000000000000..2f90a4b4fb34f --- /dev/null +++ b/src/loggedIO/_namespaces/ts.ts @@ -0,0 +1,10 @@ +/* Generated file to emulate the ts namespace. */ + +export * from "../../compiler/_namespaces/ts"; +export * from "../../services/_namespaces/ts"; +export * from "../../jsTyping/_namespaces/ts"; +export * from "../../server/_namespaces/ts"; +export * from "../../typingsInstallerCore/_namespaces/ts"; +export * from "../../harness/_namespaces/ts"; +import * as server from "./ts.server"; +export { server }; diff --git a/src/loggedIO/loggedIO.ts b/src/loggedIO/loggedIO.ts index 3cb8cd05f0624..5333de43710de 100644 --- a/src/loggedIO/loggedIO.ts +++ b/src/loggedIO/loggedIO.ts @@ -1,4 +1,7 @@ -namespace Playback { // eslint-disable-line local/one-namespace-per-file +import * as ts from "./_namespaces/ts"; +import * as Harness from "./_namespaces/Harness"; + +// eslint-disable-line local/one-namespace-per-file interface FileInformation { contents?: string; contentsPath?: string; @@ -444,8 +447,5 @@ export function wrapSystem(underlying: ts.System): PlaybackSystem { initWrapper(wrapper, underlying); return wrapper; } -} // empty modules for the module migration script -namespace ts.server { } // eslint-disable-line local/one-namespace-per-file -namespace Harness { } // eslint-disable-line local/one-namespace-per-file diff --git a/src/loggedIO/tsconfig.json b/src/loggedIO/tsconfig.json index 900997bc6c9aa..78c7a1ae483c1 100644 --- a/src/loggedIO/tsconfig.json +++ b/src/loggedIO/tsconfig.json @@ -1,7 +1,7 @@ { "extends": "../tsconfig-base", "compilerOptions": { - "outFile": "../../built/local/loggedIO.js", + "outDir": "../../built/local", "types": [ ], "lib": [ @@ -19,6 +19,10 @@ ], "files": [ - "loggedIO.ts" + "loggedIO.ts", + "_namespaces/Playback.ts", + "_namespaces/ts.server.ts", + "_namespaces/ts.ts", + "_namespaces/Harness.ts" ] } diff --git a/src/server/_namespaces/ts.server.protocol.ts b/src/server/_namespaces/ts.server.protocol.ts new file mode 100644 index 0000000000000..781f82d050732 --- /dev/null +++ b/src/server/_namespaces/ts.server.protocol.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.server.protocol namespace. */ + +export * from "../protocol"; diff --git a/src/server/_namespaces/ts.server.ts b/src/server/_namespaces/ts.server.ts new file mode 100644 index 0000000000000..66e9ce997b7f3 --- /dev/null +++ b/src/server/_namespaces/ts.server.ts @@ -0,0 +1,16 @@ +/* Generated file to emulate the ts.server namespace. */ + +export * from "../../jsTyping/_namespaces/ts.server"; +export * from "../types"; +export * from "../utilitiesPublic"; +export * from "../utilities"; +export * from "../scriptInfo"; +export * from "../typingsCache"; +export * from "../project"; +export * from "../editorServices"; +export * from "../moduleSpecifierCache"; +export * from "../packageJsonCache"; +export * from "../session"; +export * from "../scriptVersionCache"; +import * as protocol from "./ts.server.protocol"; +export { protocol }; diff --git a/src/server/_namespaces/ts.ts b/src/server/_namespaces/ts.ts new file mode 100644 index 0000000000000..0751d694916c5 --- /dev/null +++ b/src/server/_namespaces/ts.ts @@ -0,0 +1,7 @@ +/* Generated file to emulate the ts namespace. */ + +export * from "../../compiler/_namespaces/ts"; +export * from "../../jsTyping/_namespaces/ts"; +export * from "../../services/_namespaces/ts"; +import * as server from "./ts.server"; +export { server }; diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 7a72b0d019890..ae57fdec43d2f 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -1,4 +1,5 @@ -namespace ts.server { +import * as ts from "./_namespaces/ts"; + export const maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; /*@internal*/ export const maxFileSize = 4 * 1024 * 1024; @@ -4319,4 +4320,3 @@ export function isConfigFile(config: ScriptInfoOrConfig): config is ts.TsConfigS function printProjectWithoutFileNames(project: ts.server.Project) { project.print(/*writeProjectFileNames*/ false); } -} diff --git a/src/server/moduleSpecifierCache.ts b/src/server/moduleSpecifierCache.ts index 86adb1d48e4e9..85c49fbfd91de 100644 --- a/src/server/moduleSpecifierCache.ts +++ b/src/server/moduleSpecifierCache.ts @@ -1,9 +1,11 @@ -/*@internal*/ -namespace ts.server { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export interface ModuleSpecifierResolutionCacheHost { watchNodeModulesForPackageJsonChanges(directoryPath: string): ts.FileWatcher; } +/** @internal */ export function createModuleSpecifierCache(host: ModuleSpecifierResolutionCacheHost): ts.ModuleSpecifierCache { let containedNodeModulesWatchers: ts.ESMap | undefined; let cache: ts.ESMap | undefined; @@ -92,4 +94,3 @@ export function createModuleSpecifierCache(host: ModuleSpecifierResolutionCacheH return { modulePaths, moduleSpecifiers, isBlockedByPackageJsonDependencies }; } } -} diff --git a/src/server/packageJsonCache.ts b/src/server/packageJsonCache.ts index 3a91356515660..a1fbacb50ec06 100644 --- a/src/server/packageJsonCache.ts +++ b/src/server/packageJsonCache.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts.server { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export interface PackageJsonCache { addOrUpdate(fileName: ts.Path): void; forEach(action: (info: ts.ProjectPackageJsonInfo, fileName: ts.Path) => void): void; @@ -10,6 +11,7 @@ export interface PackageJsonCache { searchDirectoryAndAncestors(directory: ts.Path): void; } +/** @internal */ export function createPackageJsonCache(host: ts.server.ProjectService): PackageJsonCache { const packageJsons = new ts.Map(); const directoriesWithoutPackageJson = new ts.Map(); @@ -53,4 +55,3 @@ export function createPackageJsonCache(host: ts.server.ProjectService): PackageJ ts.Ternary.Maybe; } } -} diff --git a/src/server/project.ts b/src/server/project.ts index 8ef2530b8788f..68d3b06160cd3 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -1,4 +1,4 @@ -namespace ts.server { +import * as ts from "./_namespaces/ts"; export enum ProjectKind { Inferred, @@ -2715,4 +2715,3 @@ export function isConfiguredProject(project: Project): project is ConfiguredProj export function isExternalProject(project: Project): project is ExternalProject { return project.projectKind === ProjectKind.External; } -} diff --git a/src/server/protocol.ts b/src/server/protocol.ts index f056c2a3e5e7d..63717a363b114 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -1,9 +1,11 @@ +import * as ts from "./_namespaces/ts"; + /* eslint-disable @typescript-eslint/no-unnecessary-qualifier */ /** * Declaration module describing the TypeScript Server protocol */ -namespace ts.server.protocol { + // NOTE: If updating this, be sure to also update `allCommandNames` in `testRunner/unittests/tsserver/session.ts`. export const enum CommandTypes { JsxClosingTag = "jsxClosingTag", @@ -3630,4 +3632,3 @@ export const enum ClassificationType { jsxAttributeStringLiteralValue = 24, bigintLiteral = 25, } -} diff --git a/src/server/scriptInfo.ts b/src/server/scriptInfo.ts index 6af0ced0a4e86..aadde721b2df0 100644 --- a/src/server/scriptInfo.ts +++ b/src/server/scriptInfo.ts @@ -1,4 +1,5 @@ -namespace ts.server { +import * as ts from "./_namespaces/ts"; + export interface ScriptInfoVersion { svc: number; text: number; @@ -695,4 +696,3 @@ function failIfInvalidLocation(location: ts.server.protocol.Location) { ts.Debug.assert(location.line > 0, `Expected line to be non-${location.line === 0 ? "zero" : "negative"}`); ts.Debug.assert(location.offset > 0, `Expected offset to be non-${location.offset === 0 ? "zero" : "negative"}`); } -} diff --git a/src/server/scriptVersionCache.ts b/src/server/scriptVersionCache.ts index ee2447ec6c8e2..83e549e014dc3 100644 --- a/src/server/scriptVersionCache.ts +++ b/src/server/scriptVersionCache.ts @@ -1,5 +1,5 @@ -/*@internal*/ -namespace ts.server { +import * as ts from "./_namespaces/ts"; + const lineCollectionCapacity = 4; interface LineCollection { @@ -9,6 +9,7 @@ interface LineCollection { walk(rangeStart: number, rangeLength: number, walkFns: LineIndexWalker): void; } +/** @internal */ export interface AbsolutePositionAndLineText { absolutePosition: number; lineText: string | undefined; @@ -248,6 +249,7 @@ class TextChange { } } +/** @internal */ export class ScriptVersionCache { private changes: TextChange[] = []; private readonly versions: LineIndexSnapshot[] = new Array(ScriptVersionCache.maxVersions); @@ -384,6 +386,7 @@ class LineIndexSnapshot implements ts.IScriptSnapshot { } } +/** @internal */ export class LineIndex { root!: LineNode; // set this to true to check each edit for accuracy @@ -832,4 +835,3 @@ class LineLeaf implements LineCollection { return 1; } } -} diff --git a/src/server/session.ts b/src/server/session.ts index 1bac61b311cbf..d9d97c5b77335 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -1,4 +1,5 @@ -namespace ts.server { +import * as ts from "./_namespaces/ts"; + interface StackTraceError extends Error { stack?: string; } @@ -3543,4 +3544,3 @@ function isCompletionEntryData(data: any): data is ts.CompletionEntryData { && (data.ambientModuleName === undefined || typeof data.ambientModuleName === "string" && (data.isPackageJsonImport === undefined || typeof data.isPackageJsonImport === "boolean")); } -} diff --git a/src/server/tsconfig.json b/src/server/tsconfig.json index 4e8dd18dcdb55..8fac9006b09f0 100644 --- a/src/server/tsconfig.json +++ b/src/server/tsconfig.json @@ -2,7 +2,7 @@ "extends": "../tsconfig-base", "compilerOptions": { "removeComments": false, - "outFile": "../../built/local/server.js", + "outDir": "../../built/local", "preserveConstEnums": true, "types": [ "node" @@ -25,6 +25,9 @@ "moduleSpecifierCache.ts", "packageJsonCache.ts", "session.ts", - "scriptVersionCache.ts" + "scriptVersionCache.ts", + "_namespaces/ts.server.ts", + "_namespaces/ts.ts", + "_namespaces/ts.server.protocol.ts" ] } diff --git a/src/server/types.ts b/src/server/types.ts index 99e0d304ed1a3..51aee4bd55eef 100644 --- a/src/server/types.ts +++ b/src/server/types.ts @@ -1,4 +1,5 @@ -declare namespace ts.server { +import * as ts from "./_namespaces/ts"; + export interface CompressedData { length: number; compressionKind: string; @@ -23,4 +24,3 @@ export interface ServerHost extends ts.System { /*@internal*/ importPlugin?(root: string, moduleName: string): Promise; } -} diff --git a/src/server/typingsCache.ts b/src/server/typingsCache.ts index dcbd505853712..6061e8a8f0482 100644 --- a/src/server/typingsCache.ts +++ b/src/server/typingsCache.ts @@ -1,4 +1,5 @@ -namespace ts.server { +import * as ts from "./_namespaces/ts"; + export interface InstallPackageOptionsWithProject extends ts.InstallPackageOptions { projectName: string; projectRootPath: ts.Path; @@ -140,4 +141,3 @@ export class TypingsCache { this.installer.onProjectClosed(project); } } -} diff --git a/src/server/utilities.ts b/src/server/utilities.ts index 94b77fb6437a8..3bbcec9996e15 100644 --- a/src/server/utilities.ts +++ b/src/server/utilities.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts.server { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export class ThrottledOperations { private readonly pendingTimeouts = new ts.Map(); private readonly logger?: ts.server.Logger | undefined; @@ -44,6 +45,7 @@ export class ThrottledOperations { } } +/** @internal */ export class GcTimer { private timerId: any; constructor(private readonly host: ts.server.ServerHost, private readonly delay: number, private readonly logger: ts.server.Logger) { @@ -73,11 +75,13 @@ export class GcTimer { } } +/** @internal */ export function getBaseConfigFileName(configFilePath: ts.server.NormalizedPath): "tsconfig.json" | "jsconfig.json" | undefined { const base = ts.getBaseFileName(configFilePath); return base === "tsconfig.json" || base === "jsconfig.json" ? base : undefined; } +/** @internal */ export function removeSorted(array: ts.SortedArray, remove: T, compare: ts.Comparer): void { if (!array || array.length === 0) { return; @@ -96,12 +100,13 @@ export function removeSorted(array: ts.SortedArray, remove: T, compare: ts const indentStr = "\n "; +/** @internal */ export function indent(str: string): string { return indentStr + str.replace(/\n/g, indentStr); } +/** @internal */ /** Put stringified JSON on the next line, indented. */ export function stringifyIndented(json: {}): string { return indentStr + JSON.stringify(json); } -} diff --git a/src/server/utilitiesPublic.ts b/src/server/utilitiesPublic.ts index 21bdfd88fc48f..6a15bc65beaf7 100644 --- a/src/server/utilitiesPublic.ts +++ b/src/server/utilitiesPublic.ts @@ -1,4 +1,5 @@ -namespace ts.server { +import * as ts from "./_namespaces/ts"; + export enum LogLevel { terse, normal, @@ -130,4 +131,3 @@ export function makeAuxiliaryProjectName(counter: number): string { export function createSortedArray(): ts.SortedArray { return [] as any as ts.SortedArray; // TODO: GH#19873 } -} diff --git a/src/services/_namespaces/ts.BreakpointResolver.ts b/src/services/_namespaces/ts.BreakpointResolver.ts new file mode 100644 index 0000000000000..25d68e38408d2 --- /dev/null +++ b/src/services/_namespaces/ts.BreakpointResolver.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.BreakpointResolver namespace. */ + +export * from "../breakpoints"; diff --git a/src/services/_namespaces/ts.CallHierarchy.ts b/src/services/_namespaces/ts.CallHierarchy.ts new file mode 100644 index 0000000000000..412260c0935f4 --- /dev/null +++ b/src/services/_namespaces/ts.CallHierarchy.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.CallHierarchy namespace. */ + +export * from "../callHierarchy"; diff --git a/src/services/_namespaces/ts.Completions.StringCompletions.ts b/src/services/_namespaces/ts.Completions.StringCompletions.ts new file mode 100644 index 0000000000000..23e0c06c32ffd --- /dev/null +++ b/src/services/_namespaces/ts.Completions.StringCompletions.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.Completions.StringCompletions namespace. */ + +export * from "../stringCompletions"; diff --git a/src/services/_namespaces/ts.Completions.ts b/src/services/_namespaces/ts.Completions.ts new file mode 100644 index 0000000000000..bd0d6a8522511 --- /dev/null +++ b/src/services/_namespaces/ts.Completions.ts @@ -0,0 +1,5 @@ +/* Generated file to emulate the ts.Completions namespace. */ + +export * from "../completions"; +import * as StringCompletions from "./ts.Completions.StringCompletions"; +export { StringCompletions }; diff --git a/src/services/_namespaces/ts.FindAllReferences.ts b/src/services/_namespaces/ts.FindAllReferences.ts new file mode 100644 index 0000000000000..a5325a82f0cc4 --- /dev/null +++ b/src/services/_namespaces/ts.FindAllReferences.ts @@ -0,0 +1,4 @@ +/* Generated file to emulate the ts.FindAllReferences namespace. */ + +export * from "../importTracker"; +export * from "../findAllReferences"; diff --git a/src/services/_namespaces/ts.GoToDefinition.ts b/src/services/_namespaces/ts.GoToDefinition.ts new file mode 100644 index 0000000000000..41c12c0d1f1dc --- /dev/null +++ b/src/services/_namespaces/ts.GoToDefinition.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.GoToDefinition namespace. */ + +export * from "../goToDefinition"; diff --git a/src/services/_namespaces/ts.InlayHints.ts b/src/services/_namespaces/ts.InlayHints.ts new file mode 100644 index 0000000000000..fd189d5732578 --- /dev/null +++ b/src/services/_namespaces/ts.InlayHints.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.InlayHints namespace. */ + +export * from "../inlayHints"; diff --git a/src/services/_namespaces/ts.JsDoc.ts b/src/services/_namespaces/ts.JsDoc.ts new file mode 100644 index 0000000000000..1572df70c3b20 --- /dev/null +++ b/src/services/_namespaces/ts.JsDoc.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.JsDoc namespace. */ + +export * from "../jsDoc"; diff --git a/src/services/_namespaces/ts.NavigateTo.ts b/src/services/_namespaces/ts.NavigateTo.ts new file mode 100644 index 0000000000000..cf0e35ad1cf1c --- /dev/null +++ b/src/services/_namespaces/ts.NavigateTo.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.NavigateTo namespace. */ + +export * from "../navigateTo"; diff --git a/src/services/_namespaces/ts.NavigationBar.ts b/src/services/_namespaces/ts.NavigationBar.ts new file mode 100644 index 0000000000000..ad1c32d373d63 --- /dev/null +++ b/src/services/_namespaces/ts.NavigationBar.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.NavigationBar namespace. */ + +export * from "../navigationBar"; diff --git a/src/services/_namespaces/ts.OrganizeImports.ts b/src/services/_namespaces/ts.OrganizeImports.ts new file mode 100644 index 0000000000000..1a338fc8e12b1 --- /dev/null +++ b/src/services/_namespaces/ts.OrganizeImports.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.OrganizeImports namespace. */ + +export * from "../organizeImports"; diff --git a/src/services/_namespaces/ts.OutliningElementsCollector.ts b/src/services/_namespaces/ts.OutliningElementsCollector.ts new file mode 100644 index 0000000000000..b6b05f8f6772e --- /dev/null +++ b/src/services/_namespaces/ts.OutliningElementsCollector.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.OutliningElementsCollector namespace. */ + +export * from "../outliningElementsCollector"; diff --git a/src/services/_namespaces/ts.Rename.ts b/src/services/_namespaces/ts.Rename.ts new file mode 100644 index 0000000000000..e587684f8e689 --- /dev/null +++ b/src/services/_namespaces/ts.Rename.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.Rename namespace. */ + +export * from "../rename"; diff --git a/src/services/_namespaces/ts.SignatureHelp.ts b/src/services/_namespaces/ts.SignatureHelp.ts new file mode 100644 index 0000000000000..c87bf5c7e8d14 --- /dev/null +++ b/src/services/_namespaces/ts.SignatureHelp.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.SignatureHelp namespace. */ + +export * from "../signatureHelp"; diff --git a/src/services/_namespaces/ts.SmartSelectionRange.ts b/src/services/_namespaces/ts.SmartSelectionRange.ts new file mode 100644 index 0000000000000..f90161430d9b0 --- /dev/null +++ b/src/services/_namespaces/ts.SmartSelectionRange.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.SmartSelectionRange namespace. */ + +export * from "../smartSelection"; diff --git a/src/services/_namespaces/ts.SymbolDisplay.ts b/src/services/_namespaces/ts.SymbolDisplay.ts new file mode 100644 index 0000000000000..fcb8050c44372 --- /dev/null +++ b/src/services/_namespaces/ts.SymbolDisplay.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.SymbolDisplay namespace. */ + +export * from "../symbolDisplay"; diff --git a/src/services/_namespaces/ts.classifier.ts b/src/services/_namespaces/ts.classifier.ts new file mode 100644 index 0000000000000..34bc4e52196cc --- /dev/null +++ b/src/services/_namespaces/ts.classifier.ts @@ -0,0 +1,4 @@ +/* Generated file to emulate the ts.classifier namespace. */ + +import * as v2020 from "./ts.classifier.v2020"; +export { v2020 }; diff --git a/src/services/_namespaces/ts.classifier.v2020.ts b/src/services/_namespaces/ts.classifier.v2020.ts new file mode 100644 index 0000000000000..361c15f82351b --- /dev/null +++ b/src/services/_namespaces/ts.classifier.v2020.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.classifier.v2020 namespace. */ + +export * from "../classifier2020"; diff --git a/src/services/_namespaces/ts.codefix.ts b/src/services/_namespaces/ts.codefix.ts new file mode 100644 index 0000000000000..23e971449be17 --- /dev/null +++ b/src/services/_namespaces/ts.codefix.ts @@ -0,0 +1,72 @@ +/* Generated file to emulate the ts.codefix namespace. */ + +export * from "../codeFixProvider"; +export * from "../codefixes/addConvertToUnknownForNonOverlappingTypes"; +export * from "../codefixes/addEmptyExportDeclaration"; +export * from "../codefixes/addMissingAsync"; +export * from "../codefixes/addMissingAwait"; +export * from "../codefixes/addMissingConst"; +export * from "../codefixes/addMissingDeclareProperty"; +export * from "../codefixes/addMissingInvocationForDecorator"; +export * from "../codefixes/addNameToNamelessParameter"; +export * from "../codefixes/addOptionalPropertyUndefined"; +export * from "../codefixes/annotateWithTypeFromJSDoc"; +export * from "../codefixes/convertFunctionToEs6Class"; +export * from "../codefixes/convertToAsyncFunction"; +export * from "../codefixes/convertToEsModule"; +export * from "../codefixes/correctQualifiedNameToIndexedAccessType"; +export * from "../codefixes/convertToTypeOnlyExport"; +export * from "../codefixes/convertToTypeOnlyImport"; +export * from "../codefixes/convertLiteralTypeToMappedType"; +export * from "../codefixes/fixClassIncorrectlyImplementsInterface"; +export * from "../codefixes/importFixes"; +export * from "../codefixes/fixAddMissingConstraint"; +export * from "../codefixes/fixOverrideModifier"; +export * from "../codefixes/fixNoPropertyAccessFromIndexSignature"; +export * from "../codefixes/fixImplicitThis"; +export * from "../codefixes/fixImportNonExportedMember"; +export * from "../codefixes/fixIncorrectNamedTupleSyntax"; +export * from "../codefixes/fixSpelling"; +export * from "../codefixes/returnValueCorrect"; +export * from "../codefixes/fixAddMissingMember"; +export * from "../codefixes/fixAddMissingNewOperator"; +export * from "../codefixes/fixCannotFindModule"; +export * from "../codefixes/fixClassDoesntImplementInheritedAbstractMember"; +export * from "../codefixes/fixClassSuperMustPrecedeThisAccess"; +export * from "../codefixes/fixConstructorForDerivedNeedSuperCall"; +export * from "../codefixes/fixEnableExperimentalDecorators"; +export * from "../codefixes/fixEnableJsxFlag"; +export * from "../codefixes/fixNaNEquality"; +export * from "../codefixes/fixModuleAndTargetOptions"; +export * from "../codefixes/fixPropertyAssignment"; +export * from "../codefixes/fixExtendsInterfaceBecomesImplements"; +export * from "../codefixes/fixForgottenThisPropertyAccess"; +export * from "../codefixes/fixInvalidJsxCharacters"; +export * from "../codefixes/fixUnmatchedParameter"; +export * from "../codefixes/fixUnreferenceableDecoratorMetadata"; +export * from "../codefixes/fixUnusedIdentifier"; +export * from "../codefixes/fixUnreachableCode"; +export * from "../codefixes/fixUnusedLabel"; +export * from "../codefixes/fixJSDocTypes"; +export * from "../codefixes/fixMissingCallParentheses"; +export * from "../codefixes/fixAwaitInSyncFunction"; +export * from "../codefixes/fixPropertyOverrideAccessor"; +export * from "../codefixes/inferFromUsage"; +export * from "../codefixes/fixReturnTypeInAsyncFunction"; +export * from "../codefixes/disableJsDiagnostics"; +export * from "../codefixes/helpers"; +export * from "../codefixes/generateAccessors"; +export * from "../codefixes/fixInvalidImportSyntax"; +export * from "../codefixes/fixStrictClassInitialization"; +export * from "../codefixes/requireInTs"; +export * from "../codefixes/useDefaultImport"; +export * from "../codefixes/useBigintLiteral"; +export * from "../codefixes/fixAddModuleReferTypeMissingTypeof"; +export * from "../codefixes/wrapJsxInFragment"; +export * from "../codefixes/convertToMappedObjectType"; +export * from "../codefixes/removeAccidentalCallParentheses"; +export * from "../codefixes/removeUnnecessaryAwait"; +export * from "../codefixes/splitTypeOnlyImport"; +export * from "../codefixes/convertConstToLet"; +export * from "../codefixes/fixExpectedComma"; +export * from "../codefixes/fixAddVoidToPromise"; diff --git a/src/services/_namespaces/ts.formatting.ts b/src/services/_namespaces/ts.formatting.ts new file mode 100644 index 0000000000000..72e03b2f7e915 --- /dev/null +++ b/src/services/_namespaces/ts.formatting.ts @@ -0,0 +1,9 @@ +/* Generated file to emulate the ts.formatting namespace. */ + +export * from "../formatting/formattingContext"; +export * from "../formatting/formattingScanner"; +export * from "../formatting/rule"; +export * from "../formatting/rules"; +export * from "../formatting/rulesMap"; +export * from "../formatting/formatting"; +export * from "../formatting/smartIndenter"; diff --git a/src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts b/src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts new file mode 100644 index 0000000000000..5dd00f2f63b86 --- /dev/null +++ b/src/services/_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts @@ -0,0 +1,4 @@ +/* Generated file to emulate the ts.refactor.addOrRemoveBracesToArrowFunction namespace. */ + +export * from "../refactors/convertOverloadListToSingleSignature"; +export * from "../refactors/addOrRemoveBracesToArrowFunction"; diff --git a/src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts b/src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts new file mode 100644 index 0000000000000..48fb788058cd4 --- /dev/null +++ b/src/services/_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.refactor.convertArrowFunctionOrFunctionExpression namespace. */ + +export * from "../refactors/convertArrowFunctionOrFunctionExpression"; diff --git a/src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts b/src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts new file mode 100644 index 0000000000000..3cc94f5e9f048 --- /dev/null +++ b/src/services/_namespaces/ts.refactor.convertParamsToDestructuredObject.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.refactor.convertParamsToDestructuredObject namespace. */ + +export * from "../refactors/convertParamsToDestructuredObject"; diff --git a/src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts b/src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts new file mode 100644 index 0000000000000..e084befebaafc --- /dev/null +++ b/src/services/_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.refactor.convertStringOrTemplateLiteral namespace. */ + +export * from "../refactors/convertStringOrTemplateLiteral"; diff --git a/src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts b/src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts new file mode 100644 index 0000000000000..d8b0ab31eabaa --- /dev/null +++ b/src/services/_namespaces/ts.refactor.convertToOptionalChainExpression.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.refactor.convertToOptionalChainExpression namespace. */ + +export * from "../refactors/convertToOptionalChainExpression"; diff --git a/src/services/_namespaces/ts.refactor.extractSymbol.ts b/src/services/_namespaces/ts.refactor.extractSymbol.ts new file mode 100644 index 0000000000000..c71cacd346c4d --- /dev/null +++ b/src/services/_namespaces/ts.refactor.extractSymbol.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.refactor.extractSymbol namespace. */ + +export * from "../refactors/extractSymbol"; diff --git a/src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts b/src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts new file mode 100644 index 0000000000000..8128f0cb6cb0e --- /dev/null +++ b/src/services/_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.refactor.generateGetAccessorAndSetAccessor namespace. */ + +export * from "../refactors/generateGetAccessorAndSetAccessor"; diff --git a/src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts b/src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts new file mode 100644 index 0000000000000..3dd2e0a9b04ad --- /dev/null +++ b/src/services/_namespaces/ts.refactor.inferFunctionReturnType.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.refactor.inferFunctionReturnType namespace. */ + +export * from "../refactors/inferFunctionReturnType"; diff --git a/src/services/_namespaces/ts.refactor.ts b/src/services/_namespaces/ts.refactor.ts new file mode 100644 index 0000000000000..19159057c6da6 --- /dev/null +++ b/src/services/_namespaces/ts.refactor.ts @@ -0,0 +1,24 @@ +/* Generated file to emulate the ts.refactor namespace. */ + +export * from "../refactorProvider"; +export * from "../refactors/convertExport"; +export * from "../refactors/convertImport"; +export * from "../refactors/extractType"; +export * from "../refactors/helpers"; +export * from "../refactors/moveToNewFile"; +import * as addOrRemoveBracesToArrowFunction from "./ts.refactor.addOrRemoveBracesToArrowFunction"; +export { addOrRemoveBracesToArrowFunction }; +import * as convertArrowFunctionOrFunctionExpression from "./ts.refactor.convertArrowFunctionOrFunctionExpression"; +export { convertArrowFunctionOrFunctionExpression }; +import * as convertParamsToDestructuredObject from "./ts.refactor.convertParamsToDestructuredObject"; +export { convertParamsToDestructuredObject }; +import * as convertStringOrTemplateLiteral from "./ts.refactor.convertStringOrTemplateLiteral"; +export { convertStringOrTemplateLiteral }; +import * as convertToOptionalChainExpression from "./ts.refactor.convertToOptionalChainExpression"; +export { convertToOptionalChainExpression }; +import * as extractSymbol from "./ts.refactor.extractSymbol"; +export { extractSymbol }; +import * as generateGetAccessorAndSetAccessor from "./ts.refactor.generateGetAccessorAndSetAccessor"; +export { generateGetAccessorAndSetAccessor }; +import * as inferFunctionReturnType from "./ts.refactor.inferFunctionReturnType"; +export { inferFunctionReturnType }; diff --git a/src/services/_namespaces/ts.textChanges.ts b/src/services/_namespaces/ts.textChanges.ts new file mode 100644 index 0000000000000..12a272788fd09 --- /dev/null +++ b/src/services/_namespaces/ts.textChanges.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.textChanges namespace. */ + +export * from "../textChanges"; diff --git a/src/services/_namespaces/ts.ts b/src/services/_namespaces/ts.ts new file mode 100644 index 0000000000000..eae114fd2e834 --- /dev/null +++ b/src/services/_namespaces/ts.ts @@ -0,0 +1,59 @@ +/* Generated file to emulate the ts namespace. */ + +export * from "../../compiler/_namespaces/ts"; +export * from "../../jsTyping/_namespaces/ts"; +export * from "../types"; +export * from "../utilities"; +export * from "../exportInfoMap"; +export * from "../classifier"; +export * from "../documentHighlights"; +export * from "../documentRegistry"; +export * from "../getEditsForFileRename"; +export * from "../patternMatcher"; +export * from "../preProcess"; +export * from "../sourcemaps"; +export * from "../suggestionDiagnostics"; +export * from "../transpile"; +export * from "../services"; +export * from "../transform"; +export * from "../shims"; +import * as BreakpointResolver from "./ts.BreakpointResolver"; +export { BreakpointResolver }; +import * as CallHierarchy from "./ts.CallHierarchy"; +export { CallHierarchy }; +import * as classifier from "./ts.classifier"; +export { classifier }; +import * as codefix from "./ts.codefix"; +export { codefix }; +import * as Completions from "./ts.Completions"; +export { Completions }; +import * as FindAllReferences from "./ts.FindAllReferences"; +export { FindAllReferences }; +import * as GoToDefinition from "./ts.GoToDefinition"; +export { GoToDefinition }; +import * as InlayHints from "./ts.InlayHints"; +export { InlayHints }; +import * as JsDoc from "./ts.JsDoc"; +export { JsDoc }; +import * as NavigateTo from "./ts.NavigateTo"; +export { NavigateTo }; +import * as NavigationBar from "./ts.NavigationBar"; +export { NavigationBar }; +import * as OrganizeImports from "./ts.OrganizeImports"; +export { OrganizeImports }; +import * as OutliningElementsCollector from "./ts.OutliningElementsCollector"; +export { OutliningElementsCollector }; +import * as refactor from "./ts.refactor"; +export { refactor }; +import * as Rename from "./ts.Rename"; +export { Rename }; +import * as SignatureHelp from "./ts.SignatureHelp"; +export { SignatureHelp }; +import * as SmartSelectionRange from "./ts.SmartSelectionRange"; +export { SmartSelectionRange }; +import * as SymbolDisplay from "./ts.SymbolDisplay"; +export { SymbolDisplay }; +import * as textChanges from "./ts.textChanges"; +export { textChanges }; +import * as formatting from "./ts.formatting"; +export { formatting }; diff --git a/src/services/breakpoints.ts b/src/services/breakpoints.ts index c552d61d93101..f9b5e94bd0254 100644 --- a/src/services/breakpoints.ts +++ b/src/services/breakpoints.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts.BreakpointResolver { +import * as ts from "./_namespaces/ts"; + +/** @internal */ /** * Get the breakpoint span in given sourceFile */ @@ -731,4 +732,3 @@ export function spanInSourceFileAtLocation(sourceFile: ts.SourceFile, position: } } } -} diff --git a/src/services/callHierarchy.ts b/src/services/callHierarchy.ts index 4af0228aebcd0..774b415325124 100644 --- a/src/services/callHierarchy.ts +++ b/src/services/callHierarchy.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts.CallHierarchy { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export type NamedExpression = | ts.ClassExpression & { name: ts.Identifier } | ts.FunctionExpression & { name: ts.Identifier } @@ -10,6 +11,7 @@ function isNamedExpression(node: ts.Node): node is NamedExpression { return (ts.isFunctionExpression(node) || ts.isClassExpression(node)) && ts.isNamedDeclaration(node); } +/** @internal */ export type ConstNamedExpression = | ts.ClassExpression & { name: undefined, parent: ts.VariableDeclaration & { name: ts.Identifier } } | ts.FunctionExpression & { name: undefined, parent: ts.VariableDeclaration & { name: ts.Identifier } } @@ -25,6 +27,7 @@ function isConstNamedExpression(node: ts.Node): node is ConstNamedExpression { && !!(ts.getCombinedNodeFlags(node.parent) & ts.NodeFlags.Const); } +/** @internal */ export type CallHierarchyDeclaration = | ts.SourceFile | ts.ModuleDeclaration & { name: ts.Identifier } @@ -221,6 +224,7 @@ function findImplementationOrAllInitialDeclarations(typeChecker: ts.TypeChecker, return findAllInitialDeclarations(typeChecker, node) ?? node; } +/** @internal */ /** Resolves the call hierarchy declaration for a node. */ export function resolveCallHierarchyDeclaration(program: ts.Program, location: ts.Node): CallHierarchyDeclaration | CallHierarchyDeclaration[] | undefined { // A call hierarchy item must refer to either a SourceFile, Module Declaration, Class Static Block, or something intrinsically callable that has a name: @@ -291,6 +295,7 @@ export function resolveCallHierarchyDeclaration(program: ts.Program, location: t } } +/** @internal */ /** Creates a `CallHierarchyItem` for a call hierarchy declaration. */ export function createCallHierarchyItem(program: ts.Program, node: CallHierarchyDeclaration): ts.CallHierarchyItem { const sourceFile = node.getSourceFile(); @@ -340,6 +345,7 @@ function convertCallSiteGroupToIncomingCall(program: ts.Program, entries: readon return createCallHierarchyIncomingCall(createCallHierarchyItem(program, entries[0].declaration), ts.map(entries, entry => ts.createTextSpanFromRange(entry.range))); } +/** @internal */ /** Gets the call sites that call into the provided call hierarchy declaration. */ export function getIncomingCalls(program: ts.Program, declaration: CallHierarchyDeclaration, cancellationToken: ts.CancellationToken): ts.CallHierarchyIncomingCall[] { // Source files and modules have no incoming calls. @@ -549,6 +555,7 @@ function convertCallSiteGroupToOutgoingCall(program: ts.Program, entries: readon return createCallHierarchyOutgoingCall(createCallHierarchyItem(program, entries[0].declaration), ts.map(entries, entry => ts.createTextSpanFromRange(entry.range))); } +/** @internal */ /** Gets the call sites that call out of the provided call hierarchy declaration. */ export function getOutgoingCalls(program: ts.Program, declaration: CallHierarchyDeclaration): ts.CallHierarchyOutgoingCall[] { if (declaration.flags & ts.NodeFlags.Ambient || ts.isMethodSignature(declaration)) { @@ -556,4 +563,3 @@ export function getOutgoingCalls(program: ts.Program, declaration: CallHierarchy } return ts.group(collectCallSites(program, declaration), getCallSiteGroupKey, entries => convertCallSiteGroupToOutgoingCall(program, entries)); } -} diff --git a/src/services/classifier.ts b/src/services/classifier.ts index 50b555b4a04be..0603706a08733 100644 --- a/src/services/classifier.ts +++ b/src/services/classifier.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + /** The classifier is used for syntactic highlighting in editors via the TSServer */ export function createClassifier(): ts.Classifier { const scanner = ts.createScanner(ts.ScriptTarget.Latest, /*skipTrivia*/ false); @@ -1104,4 +1105,3 @@ export function getEncodedSyntacticClassifications(cancellationToken: ts.Cancell } } } -} diff --git a/src/services/classifier2020.ts b/src/services/classifier2020.ts index c229b4e4c4f0a..22d09402aaa9f 100644 --- a/src/services/classifier2020.ts +++ b/src/services/classifier2020.ts @@ -1,19 +1,24 @@ +import * as ts from "./_namespaces/ts"; + /** @internal */ -namespace ts.classifier.v2020 { +/** @internal */ export const enum TokenEncodingConsts { typeOffset = 8, modifierMask = (1 << typeOffset) - 1 } +/** @internal */ export const enum TokenType { class, enum, interface, namespace, typeParameter, type, parameter, variable, enumMember, property, function, member } +/** @internal */ export const enum TokenModifier { declaration, static, async, readonly, defaultLibrary, local } +/** @internal */ /** This is mainly used internally for testing */ export function getSemanticClassifications(program: ts.Program, cancellationToken: ts.CancellationToken, sourceFile: ts.SourceFile, span: ts.TextSpan): ts.ClassifiedSpan2020[] { const classifications = getEncodedSemanticClassifications(program, cancellationToken, sourceFile, span); @@ -31,6 +36,7 @@ export function getSemanticClassifications(program: ts.Program, cancellationToke return result; } +/** @internal */ export function getEncodedSemanticClassifications(program: ts.Program, cancellationToken: ts.CancellationToken, sourceFile: ts.SourceFile, span: ts.TextSpan): ts.Classifications { return { spans: getSemanticTokens(program, sourceFile, span, cancellationToken), @@ -246,4 +252,3 @@ const tokenFromDeclarationMapping = new ts.Map([ [ts.SyntaxKind.PropertyAssignment, TokenType.property], [ts.SyntaxKind.ShorthandPropertyAssignment, TokenType.property] ]); -} diff --git a/src/services/codeFixProvider.ts b/src/services/codeFixProvider.ts index 2a29613172074..90903f98d918a 100644 --- a/src/services/codeFixProvider.ts +++ b/src/services/codeFixProvider.ts @@ -1,16 +1,19 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "./_namespaces/ts"; + const errorCodeToFixes = ts.createMultiMap(); const fixIdToRegistration = new ts.Map(); +/** @internal */ export function createCodeFixActionWithoutFixAll(fixName: string, changes: ts.FileTextChanges[], description: ts.DiagnosticAndArguments) { return createCodeFixActionWorker(fixName, ts.diagnosticToString(description), changes, /*fixId*/ undefined, /*fixAllDescription*/ undefined); } +/** @internal */ export function createCodeFixAction(fixName: string, changes: ts.FileTextChanges[], description: ts.DiagnosticAndArguments, fixId: {}, fixAllDescription: ts.DiagnosticAndArguments, command?: ts.CodeActionCommand): ts.CodeFixAction { return createCodeFixActionWorker(fixName, ts.diagnosticToString(description), changes, fixId, ts.diagnosticToString(fixAllDescription), command); } +/** @internal */ export function createCodeFixActionMaybeFixAll(fixName: string, changes: ts.FileTextChanges[], description: ts.DiagnosticAndArguments, fixId?: {}, fixAllDescription?: ts.DiagnosticAndArguments, command?: ts.CodeActionCommand) { return createCodeFixActionWorker(fixName, ts.diagnosticToString(description), changes, fixId, fixAllDescription && ts.diagnosticToString(fixAllDescription), command); } @@ -19,6 +22,7 @@ function createCodeFixActionWorker(fixName: string, description: string, changes return { fixName, description, changes, fixId, fixAllDescription, commands: command ? [command] : undefined }; } +/** @internal */ export function registerCodeFix(reg: ts.CodeFixRegistration) { for (const error of reg.errorCodes) { errorCodeToFixes.add(String(error), reg); @@ -31,6 +35,7 @@ export function registerCodeFix(reg: ts.CodeFixRegistration) { } } +/** @internal */ export function getSupportedErrorCodes(): string[] { return ts.arrayFrom(errorCodeToFixes.keys()); } @@ -49,25 +54,30 @@ function removeFixIdIfFixAllUnavailable(registration: ts.CodeFixRegistration, di }; } +/** @internal */ export function getFixes(context: ts.CodeFixContext): readonly ts.CodeFixAction[] { const diagnostics = getDiagnostics(context); const registrations = errorCodeToFixes.get(String(context.errorCode)); return ts.flatMap(registrations, f => ts.map(f.getCodeActions(context), removeFixIdIfFixAllUnavailable(f, diagnostics))); } +/** @internal */ export function getAllFixes(context: ts.CodeFixAllContext): ts.CombinedCodeActions { // Currently fixId is always a string. return fixIdToRegistration.get(ts.cast(context.fixId, ts.isString))!.getAllCodeActions!(context); } +/** @internal */ export function createCombinedCodeActions(changes: ts.FileTextChanges[], commands?: ts.CodeActionCommand[]): ts.CombinedCodeActions { return { changes, commands }; } +/** @internal */ export function createFileTextChanges(fileName: string, textChanges: ts.TextChange[]): ts.FileTextChanges { return { fileName, textChanges }; } +/** @internal */ export function codeFixAll( context: ts.CodeFixAllContext, errorCodes: number[], @@ -78,6 +88,7 @@ export function codeFixAll( return createCombinedCodeActions(changes, commands.length === 0 ? undefined : commands); } +/** @internal */ export function eachDiagnostic(context: ts.CodeFixAllContext, errorCodes: readonly number[], cb: (diag: ts.DiagnosticWithLocation) => void): void { for (const diag of getDiagnostics(context)) { if (ts.contains(errorCodes, diag.code)) { @@ -93,4 +104,3 @@ function getDiagnostics({ program, sourceFile, cancellationToken }: ts.CodeFixCo ...ts.computeSuggestionDiagnostics(sourceFile, program, cancellationToken) ]; } -} diff --git a/src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts b/src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts index b79130c656bfd..e94a2f348fff3 100644 --- a/src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts +++ b/src/services/codefixes/addConvertToUnknownForNonOverlappingTypes.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "addConvertToUnknownForNonOverlappingTypes"; const errorCodes = [ts.Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first.code]; ts.codefix.registerCodeFix({ @@ -30,4 +30,3 @@ function getAssertion(sourceFile: ts.SourceFile, pos: number): ts.AsExpression | if (ts.isInJSFile(sourceFile)) return undefined; return ts.findAncestor(ts.getTokenAtPosition(sourceFile, pos), (n): n is ts.AsExpression | ts.TypeAssertion => ts.isAsExpression(n) || ts.isTypeAssertionExpression(n)); } -} diff --git a/src/services/codefixes/addEmptyExportDeclaration.ts b/src/services/codefixes/addEmptyExportDeclaration.ts index 7b3856cf77247..7708f5661ca32 100644 --- a/src/services/codefixes/addEmptyExportDeclaration.ts +++ b/src/services/codefixes/addEmptyExportDeclaration.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + ts.codefix.registerCodeFix({ errorCodes: [ ts.Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module.code, @@ -18,5 +18,4 @@ ts.codefix.registerCodeFix({ }); return [ts.codefix.createCodeFixActionWithoutFixAll("addEmptyExportDeclaration", changes, ts.Diagnostics.Add_export_to_make_this_file_into_a_module)]; }, -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/services/codefixes/addMissingAsync.ts b/src/services/codefixes/addMissingAsync.ts index 44bba89fe43a3..cf475bce3e64d 100644 --- a/src/services/codefixes/addMissingAsync.ts +++ b/src/services/codefixes/addMissingAsync.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + type ContextualTrackChangesFunction = (cb: (changeTracker: ts.textChanges.ChangeTracker) => void) => ts.FileTextChanges[]; const fixId = "addMissingAsync"; const errorCodes = [ @@ -84,4 +84,3 @@ function getIsMatchingAsyncError(span: ts.TextSpan, errorCode: number) { !!relatedInformation && ts.some(relatedInformation, related => related.code === ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async.code); } -} diff --git a/src/services/codefixes/addMissingAwait.ts b/src/services/codefixes/addMissingAwait.ts index adf7128c7d037..c8d5cc3bd8839 100644 --- a/src/services/codefixes/addMissingAwait.ts +++ b/src/services/codefixes/addMissingAwait.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + type ContextualTrackChangesFunction = (cb: (changeTracker: ts.textChanges.ChangeTracker) => void) => ts.FileTextChanges[]; const fixId = "addMissingAwait"; const propertyAccessCode = ts.Diagnostics.Property_0_does_not_exist_on_type_1.code; @@ -288,4 +288,3 @@ function insertLeadingSemicolonIfNeeded(changeTracker: ts.textChanges.ChangeTrac changeTracker.insertText(sourceFile, beforeNode.getStart(sourceFile), ";"); } } -} diff --git a/src/services/codefixes/addMissingConst.ts b/src/services/codefixes/addMissingConst.ts index ea72f07f2d834..05bad2a67be7b 100644 --- a/src/services/codefixes/addMissingConst.ts +++ b/src/services/codefixes/addMissingConst.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "addMissingConst"; const errorCodes = [ ts.Diagnostics.Cannot_find_name_0.code, @@ -108,4 +108,3 @@ function expressionCouldBeVariableDeclaration(expression: ts.Node, checker: ts.T && ts.isIdentifier(expression.left) && !checker.getSymbolAtLocation(expression.left); } -} diff --git a/src/services/codefixes/addMissingDeclareProperty.ts b/src/services/codefixes/addMissingDeclareProperty.ts index d4a018b934fd6..15498acc93cd7 100644 --- a/src/services/codefixes/addMissingDeclareProperty.ts +++ b/src/services/codefixes/addMissingDeclareProperty.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "addMissingDeclareProperty"; const errorCodes = [ ts.Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration.code, @@ -31,4 +31,3 @@ function makeChange(changeTracker: ts.textChanges.ChangeTracker, sourceFile: ts. changeTracker.insertModifierBefore(sourceFile, ts.SyntaxKind.DeclareKeyword, declaration); } } -} diff --git a/src/services/codefixes/addMissingInvocationForDecorator.ts b/src/services/codefixes/addMissingInvocationForDecorator.ts index 7647b53717786..00103d9525a72 100644 --- a/src/services/codefixes/addMissingInvocationForDecorator.ts +++ b/src/services/codefixes/addMissingInvocationForDecorator.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "addMissingInvocationForDecorator"; const errorCodes = [ts.Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0.code]; ts.codefix.registerCodeFix({ @@ -19,4 +19,3 @@ function makeChange(changeTracker: ts.textChanges.ChangeTracker, sourceFile: ts. const replacement = ts.factory.createCallExpression(decorator.expression, /*typeArguments*/ undefined, /*argumentsArray*/ undefined); changeTracker.replaceNode(sourceFile, decorator.expression, replacement); } -} diff --git a/src/services/codefixes/addNameToNamelessParameter.ts b/src/services/codefixes/addNameToNamelessParameter.ts index d252b4a2775b5..57b5cf061f5f8 100644 --- a/src/services/codefixes/addNameToNamelessParameter.ts +++ b/src/services/codefixes/addNameToNamelessParameter.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "addNameToNamelessParameter"; const errorCodes = [ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code]; ts.codefix.registerCodeFix({ @@ -33,4 +33,3 @@ function makeChange(changeTracker: ts.textChanges.ChangeTracker, sourceFile: ts. param.initializer); changeTracker.replaceNode(sourceFile, param, replacement); } -} diff --git a/src/services/codefixes/addOptionalPropertyUndefined.ts b/src/services/codefixes/addOptionalPropertyUndefined.ts index 3405d13d7c59b..9867c889ed766 100644 --- a/src/services/codefixes/addOptionalPropertyUndefined.ts +++ b/src/services/codefixes/addOptionalPropertyUndefined.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const addOptionalPropertyUndefined = "addOptionalPropertyUndefined"; const errorCodes = [ @@ -93,4 +93,3 @@ function addUndefinedToOptionalProperty(changes: ts.textChanges.ChangeTracker, t } } } -} diff --git a/src/services/codefixes/annotateWithTypeFromJSDoc.ts b/src/services/codefixes/annotateWithTypeFromJSDoc.ts index 692a14ecfb698..bc1a8d5835507 100644 --- a/src/services/codefixes/annotateWithTypeFromJSDoc.ts +++ b/src/services/codefixes/annotateWithTypeFromJSDoc.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "annotateWithTypeFromJSDoc"; const errorCodes = [ts.Diagnostics.JSDoc_types_may_be_moved_to_TypeScript_types.code]; ts.codefix.registerCodeFix({ @@ -29,6 +29,7 @@ type DeclarationWithType = | ts.PropertySignature | ts.PropertyDeclaration; +/** @internal */ export function parameterShouldGetTypeFromJSDoc(node: ts.Node): node is DeclarationWithType { return isDeclarationWithType(node) && hasUsableJSDoc(node); } @@ -180,4 +181,3 @@ function transformJSDocIndexSignature(node: ts.TypeReferenceNode) { ts.setEmitFlags(indexSignature, ts.EmitFlags.SingleLine); return indexSignature; } -} diff --git a/src/services/codefixes/convertConstToLet.ts b/src/services/codefixes/convertConstToLet.ts index 202995ac13099..8173c6c5c1da7 100644 --- a/src/services/codefixes/convertConstToLet.ts +++ b/src/services/codefixes/convertConstToLet.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "fixConvertConstToLet"; const errorCodes = [ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant.code]; @@ -54,4 +54,3 @@ function getInfo(sourceFile: ts.SourceFile, pos: number, program: ts.Program): I function doChange(changes: ts.textChanges.ChangeTracker, sourceFile: ts.SourceFile, token: ts.Token) { changes.replaceNode(sourceFile, token, ts.factory.createToken(ts.SyntaxKind.LetKeyword)); } -} diff --git a/src/services/codefixes/convertFunctionToEs6Class.ts b/src/services/codefixes/convertFunctionToEs6Class.ts index 19ea4c69ce6b8..39d402b9f3869 100644 --- a/src/services/codefixes/convertFunctionToEs6Class.ts +++ b/src/services/codefixes/convertFunctionToEs6Class.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "convertFunctionToEs6Class"; const errorCodes = [ts.Diagnostics.This_constructor_function_may_be_converted_to_a_class_declaration.code]; ts.codefix.registerCodeFix({ @@ -275,4 +275,3 @@ function tryGetPropertyName(node: ts.AccessExpression, compilerOptions: ts.Compi return undefined; } -} diff --git a/src/services/codefixes/convertLiteralTypeToMappedType.ts b/src/services/codefixes/convertLiteralTypeToMappedType.ts index 6e5de3405f3dd..600590c210510 100644 --- a/src/services/codefixes/convertLiteralTypeToMappedType.ts +++ b/src/services/codefixes/convertLiteralTypeToMappedType.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "convertLiteralTypeToMappedType"; const errorCodes = [ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0.code]; @@ -55,4 +55,3 @@ function doChange(changes: ts.textChanges.ChangeTracker, sourceFile: ts.SourceFi typeNode, /*members*/ undefined)); } -} diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index 2eb7d29245c23..9b315217e8851 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "convertToAsyncFunction"; const errorCodes = [ts.Diagnostics.This_may_be_converted_to_an_async_function.code]; let codeActionSucceeded = true; @@ -842,4 +842,3 @@ function isSynthBindingPattern(bindingName: SynthBindingName): bindingName is Sy function shouldReturn(expression: ts.Expression, transformer: Transformer): boolean { return !!expression.original && transformer.setOfExpressionsToReturn.has(ts.getNodeId(expression.original)); } -} diff --git a/src/services/codefixes/convertToEsModule.ts b/src/services/codefixes/convertToEsModule.ts index 33d4c1149090b..f8c71646f5192 100644 --- a/src/services/codefixes/convertToEsModule.ts +++ b/src/services/codefixes/convertToEsModule.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + ts.codefix.registerCodeFix({ errorCodes: [ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES_module.code], getCodeActions(context) { @@ -599,4 +599,3 @@ function convertedImports(newImports: readonly ts.Node[], useSitesToUnqualify?: useSitesToUnqualify }; } -} diff --git a/src/services/codefixes/convertToMappedObjectType.ts b/src/services/codefixes/convertToMappedObjectType.ts index 5fbf88d6d417f..e43db82789db3 100644 --- a/src/services/codefixes/convertToMappedObjectType.ts +++ b/src/services/codefixes/convertToMappedObjectType.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "fixConvertToMappedObjectType"; const errorCodes = [ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_literal_type_or_generic_type_Consider_using_a_mapped_object_type_instead.code]; @@ -57,4 +57,3 @@ function doChange(changes: ts.textChanges.ChangeTracker, sourceFile: ts.SourceFi ]); changes.replaceNode(sourceFile, container, createTypeAliasFromInterface(container, intersectionType)); } -} diff --git a/src/services/codefixes/convertToTypeOnlyExport.ts b/src/services/codefixes/convertToTypeOnlyExport.ts index eaa300ba2eab6..179edb9af8c8e 100644 --- a/src/services/codefixes/convertToTypeOnlyExport.ts +++ b/src/services/codefixes/convertToTypeOnlyExport.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const errorCodes = [ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type.code]; const fixId = "convertToTypeOnlyExport"; ts.codefix.registerCodeFix({ @@ -76,4 +76,3 @@ function getTypeExportSpecifiers(originExportSpecifier: ts.ExportSpecifier, cont return element === originExportSpecifier || ts.findDiagnosticForNode(element, diagnostics)?.code === errorCodes[0]; }); } -} diff --git a/src/services/codefixes/convertToTypeOnlyImport.ts b/src/services/codefixes/convertToTypeOnlyImport.ts index 1e43f240278de..4df5c35a8ba61 100644 --- a/src/services/codefixes/convertToTypeOnlyImport.ts +++ b/src/services/codefixes/convertToTypeOnlyImport.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const errorCodes = [ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error.code]; const fixId = "convertToTypeOnlyImport"; ts.codefix.registerCodeFix({ @@ -49,4 +49,3 @@ function fixSingleImportDeclaration(changes: ts.textChanges.ChangeTracker, impor /*assertClause*/ undefined)); } } -} diff --git a/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts b/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts index f1e81049bddf8..6892b6def718f 100644 --- a/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts +++ b/src/services/codefixes/correctQualifiedNameToIndexedAccessType.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "correctQualifiedNameToIndexedAccessType"; const errorCodes = [ts.Diagnostics.Cannot_access_0_1_because_0_is_a_type_but_not_a_namespace_Did_you_mean_to_retrieve_the_type_of_the_property_1_in_0_with_0_1.code]; ts.codefix.registerCodeFix({ @@ -33,4 +33,3 @@ function doChange(changeTracker: ts.textChanges.ChangeTracker, sourceFile: ts.So ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(rightText))); changeTracker.replaceNode(sourceFile, qualifiedName, replacement); } -} diff --git a/src/services/codefixes/disableJsDiagnostics.ts b/src/services/codefixes/disableJsDiagnostics.ts index c5fe119eaccc5..fb429684cb901 100644 --- a/src/services/codefixes/disableJsDiagnostics.ts +++ b/src/services/codefixes/disableJsDiagnostics.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixName = "disableJsDiagnostics"; const fixId = "disableJsDiagnostics"; const errorCodes = ts.mapDefined(Object.keys(ts.Diagnostics) as readonly (keyof typeof ts.Diagnostics)[], key => { @@ -53,4 +53,3 @@ function makeChange(changes: ts.textChanges.ChangeTracker, sourceFile: ts.Source changes.insertCommentBeforeLine(sourceFile, lineNumber, position, " @ts-ignore"); } } -} diff --git a/src/services/codefixes/fixAddMissingConstraint.ts b/src/services/codefixes/fixAddMissingConstraint.ts index a62cb9c468de4..c15bd6de230b0 100644 --- a/src/services/codefixes/fixAddMissingConstraint.ts +++ b/src/services/codefixes/fixAddMissingConstraint.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "addMissingConstraint"; const errorCodes = [ // We want errors this could be attached to: @@ -106,4 +106,3 @@ function tryGetConstraintType(checker: ts.TypeChecker, node: ts.Node) { const contextualType = ts.isExpression(node) ? checker.getContextualType(node) : undefined; return contextualType || checker.getTypeAtLocation(node); } -} diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index 73c9a12895d09..d166a85d79257 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixMissingMember = "fixMissingMember"; const fixMissingProperties = "fixMissingProperties"; const fixMissingAttributes = "fixMissingAttributes"; @@ -652,4 +652,3 @@ function findScope(node: ts.Node) { } return ts.getSourceFileOfNode(node); } -} diff --git a/src/services/codefixes/fixAddMissingNewOperator.ts b/src/services/codefixes/fixAddMissingNewOperator.ts index 23ba4012e8ba4..c256238aa9881 100644 --- a/src/services/codefixes/fixAddMissingNewOperator.ts +++ b/src/services/codefixes/fixAddMissingNewOperator.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "addMissingNewOperator"; const errorCodes = [ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code]; ts.codefix.registerCodeFix({ @@ -29,4 +29,3 @@ function findAncestorMatchingSpan(sourceFile: ts.SourceFile, span: ts.TextSpan): } return token; } -} diff --git a/src/services/codefixes/fixAddModuleReferTypeMissingTypeof.ts b/src/services/codefixes/fixAddModuleReferTypeMissingTypeof.ts index 1ee63440b8775..f699c34947bce 100644 --- a/src/services/codefixes/fixAddModuleReferTypeMissingTypeof.ts +++ b/src/services/codefixes/fixAddModuleReferTypeMissingTypeof.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixIdAddMissingTypeof = "fixAddModuleReferTypeMissingTypeof"; const fixId = fixIdAddMissingTypeof; const errorCodes = [ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0.code]; @@ -28,4 +28,3 @@ function doChange(changes: ts.textChanges.ChangeTracker, sourceFile: ts.SourceFi const newTypeNode = ts.factory.updateImportTypeNode(importType, importType.argument, importType.assertions, importType.qualifier, importType.typeArguments, /* isTypeOf */ true); changes.replaceNode(sourceFile, importType, newTypeNode); } -} diff --git a/src/services/codefixes/fixAddVoidToPromise.ts b/src/services/codefixes/fixAddVoidToPromise.ts index c086dfe873a84..ebf1f5d08c11a 100644 --- a/src/services/codefixes/fixAddVoidToPromise.ts +++ b/src/services/codefixes/fixAddVoidToPromise.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixName = "addVoidToPromise"; const fixId = "addVoidToPromise"; const errorCodes = [ @@ -79,5 +79,4 @@ function getEffectiveTypeArguments(node: ts.NewExpression) { else { return node.typeArguments; } -} } \ No newline at end of file diff --git a/src/services/codefixes/fixAwaitInSyncFunction.ts b/src/services/codefixes/fixAwaitInSyncFunction.ts index 97a45a5ef3734..e3563e5727873 100644 --- a/src/services/codefixes/fixAwaitInSyncFunction.ts +++ b/src/services/codefixes/fixAwaitInSyncFunction.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "fixAwaitInSyncFunction"; const errorCodes = [ ts.Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code, @@ -80,4 +80,3 @@ function doChange( } changes.insertModifierBefore(sourceFile, ts.SyntaxKind.AsyncKeyword, insertBefore); } -} diff --git a/src/services/codefixes/fixCannotFindModule.ts b/src/services/codefixes/fixCannotFindModule.ts index 5261f57fcb514..c3d85897e62fe 100644 --- a/src/services/codefixes/fixCannotFindModule.ts +++ b/src/services/codefixes/fixCannotFindModule.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixName = "fixCannotFindModule"; const fixIdInstallTypesPackage = "installTypesPackage"; @@ -56,4 +56,3 @@ function getTypesPackageNameToInstall(packageName: string, host: ts.LanguageServ ? (ts.JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName?.(packageName) ? ts.getTypesPackageName(packageName) : undefined); } -} diff --git a/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts b/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts index 12c994a3794e6..82f88679c8ffa 100644 --- a/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts +++ b/src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const errorCodes = [ ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code, @@ -52,4 +52,3 @@ function symbolPointsToNonPrivateAndAbstractMember(symbol: ts.Symbol): boolean { const flags = ts.getSyntacticModifierFlags(ts.first(symbol.getDeclarations()!)); return !(flags & ts.ModifierFlags.Private) && !!(flags & ts.ModifierFlags.Abstract); } -} diff --git a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts index 5148a08622e21..d01e8a5caf0c8 100644 --- a/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts +++ b/src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const errorCodes = [ ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code, ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code @@ -92,4 +92,3 @@ function getHeritageClauseSymbolTable(classDeclaration: ts.ClassLikeDeclaration, const heritageClauseTypeSymbols = checker.getPropertiesOfType(heritageClauseType); return ts.createSymbolTable(heritageClauseTypeSymbols.filter(symbolPointsToNonPrivateMember)); } -} diff --git a/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts b/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts index 99365213dcd1e..6febd4d1604f4 100644 --- a/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts +++ b/src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "classSuperMustPrecedeThisAccess"; const errorCodes = [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code]; ts.codefix.registerCodeFix({ @@ -49,4 +49,3 @@ function findSuperCall(n: ts.Node): ts.ExpressionStatement & { expression: ts.Ca ? undefined : ts.forEachChild(n, findSuperCall); } -} diff --git a/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts b/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts index f66d2dc8f173b..3665cdc95f814 100644 --- a/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts +++ b/src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "constructorForDerivedNeedSuperCall"; const errorCodes = [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code]; ts.codefix.registerCodeFix({ @@ -25,4 +25,3 @@ function doChange(changes: ts.textChanges.ChangeTracker, sourceFile: ts.SourceFi const superCall = ts.factory.createExpressionStatement(ts.factory.createCallExpression(ts.factory.createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ ts.emptyArray)); changes.insertNodeAtConstructorStart(sourceFile, ctr, superCall); } -} diff --git a/src/services/codefixes/fixEnableExperimentalDecorators.ts b/src/services/codefixes/fixEnableExperimentalDecorators.ts index a9e40d5a0957f..daee75e127e37 100644 --- a/src/services/codefixes/fixEnableExperimentalDecorators.ts +++ b/src/services/codefixes/fixEnableExperimentalDecorators.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "enableExperimentalDecorators"; const errorCodes = [ ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_in_your_tsconfig_or_jsconfig_to_remove_this_warning.code @@ -28,4 +28,3 @@ ts.codefix.registerCodeFix({ function doChange(changeTracker: ts.textChanges.ChangeTracker, configFile: ts.TsConfigSourceFile) { ts.codefix.setJsonCompilerOptionValue(changeTracker, configFile, "experimentalDecorators", ts.factory.createTrue()); } -} diff --git a/src/services/codefixes/fixEnableJsxFlag.ts b/src/services/codefixes/fixEnableJsxFlag.ts index c2a1b21ede38a..115dc38bb8860 100644 --- a/src/services/codefixes/fixEnableJsxFlag.ts +++ b/src/services/codefixes/fixEnableJsxFlag.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixID = "fixEnableJsxFlag"; const errorCodes = [ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided.code]; ts.codefix.registerCodeFix({ @@ -32,4 +32,3 @@ ts.codefix.registerCodeFix({ function doChange(changeTracker: ts.textChanges.ChangeTracker, configFile: ts.TsConfigSourceFile) { ts.codefix.setJsonCompilerOptionValue(changeTracker, configFile, "jsx", ts.factory.createStringLiteral("react")); } -} diff --git a/src/services/codefixes/fixExpectedComma.ts b/src/services/codefixes/fixExpectedComma.ts index d89ad302dcd7c..220cbb8e835b9 100644 --- a/src/services/codefixes/fixExpectedComma.ts +++ b/src/services/codefixes/fixExpectedComma.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "fixExpectedComma"; const expectedErrorCode = ts.Diagnostics._0_expected.code; const errorCodes = [expectedErrorCode]; @@ -43,4 +43,3 @@ function doChange(changes: ts.textChanges.ChangeTracker, sourceFile: ts.SourceFi const newNode = ts.factory.createToken(ts.SyntaxKind.CommaToken); changes.replaceNode(sourceFile, node, newNode); } -} diff --git a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts index bfe119edad32b..eff978215a41e 100644 --- a/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts +++ b/src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "extendsInterfaceBecomesImplements"; const errorCodes = [ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code]; ts.codefix.registerCodeFix({ @@ -49,4 +49,3 @@ function doChanges(changes: ts.textChanges.ChangeTracker, sourceFile: ts.SourceF changes.deleteRange(sourceFile, { pos: implementsToken.getStart(), end }); } } -} diff --git a/src/services/codefixes/fixForgottenThisPropertyAccess.ts b/src/services/codefixes/fixForgottenThisPropertyAccess.ts index 3917c792ef1a0..ff31cf9f96a66 100644 --- a/src/services/codefixes/fixForgottenThisPropertyAccess.ts +++ b/src/services/codefixes/fixForgottenThisPropertyAccess.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "forgottenThisPropertyAccess"; const didYouMeanStaticMemberCode = ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0.code; const errorCodes = [ @@ -42,4 +42,3 @@ function doChange(changes: ts.textChanges.ChangeTracker, sourceFile: ts.SourceFi ts.suppressLeadingAndTrailingTrivia(node); changes.replaceNode(sourceFile, node, ts.factory.createPropertyAccessExpression(className ? ts.factory.createIdentifier(className) : ts.factory.createThis(), node)); } -} diff --git a/src/services/codefixes/fixImplicitThis.ts b/src/services/codefixes/fixImplicitThis.ts index e0a09038a0743..b671f51215131 100644 --- a/src/services/codefixes/fixImplicitThis.ts +++ b/src/services/codefixes/fixImplicitThis.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "fixImplicitThis"; const errorCodes = [ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation.code]; ts.codefix.registerCodeFix({ @@ -53,4 +53,3 @@ function doChange(changes: ts.textChanges.ChangeTracker, sourceFile: ts.SourceFi } } } -} diff --git a/src/services/codefixes/fixImportNonExportedMember.ts b/src/services/codefixes/fixImportNonExportedMember.ts index f2a405083e58f..8424d1e14efbf 100644 --- a/src/services/codefixes/fixImportNonExportedMember.ts +++ b/src/services/codefixes/fixImportNonExportedMember.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "fixImportNonExportedMember"; const errorCodes = [ ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported.code, @@ -160,4 +160,3 @@ function getNodeOfSymbol(symbol: ts.Symbol) { const variableStatement = ts.isVariableDeclaration(declaration) ? ts.tryCast(declaration.parent.parent, ts.isVariableStatement) : undefined; return variableStatement && ts.length(variableStatement.declarationList.declarations) === 1 ? variableStatement : declaration; } -} diff --git a/src/services/codefixes/fixIncorrectNamedTupleSyntax.ts b/src/services/codefixes/fixIncorrectNamedTupleSyntax.ts index 6915759b44e7c..c5f6a180e6903 100644 --- a/src/services/codefixes/fixIncorrectNamedTupleSyntax.ts +++ b/src/services/codefixes/fixIncorrectNamedTupleSyntax.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "fixIncorrectNamedTupleSyntax"; const errorCodes = [ ts.Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type.code, @@ -49,4 +49,3 @@ function doChange(changes: ts.textChanges.ChangeTracker, sourceFile: ts.SourceFi } changes.replaceNode(sourceFile, namedTupleMember, updated); } -} diff --git a/src/services/codefixes/fixInvalidImportSyntax.ts b/src/services/codefixes/fixInvalidImportSyntax.ts index 0a6ea1bf0f946..1ca7242e60d0b 100644 --- a/src/services/codefixes/fixInvalidImportSyntax.ts +++ b/src/services/codefixes/fixInvalidImportSyntax.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixName = "invalidImportSyntax"; function getCodeFixesForImportDeclaration(context: ts.CodeFixContext, node: ts.ImportDeclaration): ts.CodeFixAction[] { @@ -92,4 +92,3 @@ function getImportCodeFixesForExpression(context: ts.CodeFixContext, expr: ts.No } return fixes; } -} diff --git a/src/services/codefixes/fixInvalidJsxCharacters.ts b/src/services/codefixes/fixInvalidJsxCharacters.ts index 372a85fca7e1c..5567ddceac631 100644 --- a/src/services/codefixes/fixInvalidJsxCharacters.ts +++ b/src/services/codefixes/fixInvalidJsxCharacters.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixIdExpression = "fixInvalidJsxCharacters_expression"; const fixIdHtmlEntity = "fixInvalidJsxCharacters_htmlEntity"; @@ -45,4 +45,3 @@ function doChange(changes: ts.textChanges.ChangeTracker, preferences: ts.UserPre const replacement = useHtmlEntity ? htmlEntity[character] : `{${ts.quote(sourceFile, preferences, character)}}`; changes.replaceRangeWithText(sourceFile, { pos: start, end: start + 1 }, replacement); } -} diff --git a/src/services/codefixes/fixJSDocTypes.ts b/src/services/codefixes/fixJSDocTypes.ts index 7d5b958f74d56..b898ef914a791 100644 --- a/src/services/codefixes/fixJSDocTypes.ts +++ b/src/services/codefixes/fixJSDocTypes.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixIdPlain = "fixJSDocTypes_plain"; const fixIdNullable = "fixJSDocTypes_nullable"; const errorCodes = [ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments.code]; @@ -80,4 +80,3 @@ function isTypeContainer(node: ts.Node): node is TypeContainer { return false; } } -} diff --git a/src/services/codefixes/fixMissingCallParentheses.ts b/src/services/codefixes/fixMissingCallParentheses.ts index 50bf1b5707f82..1d1681bf89078 100644 --- a/src/services/codefixes/fixMissingCallParentheses.ts +++ b/src/services/codefixes/fixMissingCallParentheses.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "fixMissingCallParentheses"; const errorCodes = [ ts.Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead.code, @@ -42,4 +42,3 @@ function getCallName(sourceFile: ts.SourceFile, start: number): ts.Identifier | return undefined; } -} diff --git a/src/services/codefixes/fixModuleAndTargetOptions.ts b/src/services/codefixes/fixModuleAndTargetOptions.ts index 56d96b0a7e374..36bd46ee3a1d0 100644 --- a/src/services/codefixes/fixModuleAndTargetOptions.ts +++ b/src/services/codefixes/fixModuleAndTargetOptions.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + ts.codefix.registerCodeFix({ errorCodes: [ ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_or_nodenext_and_the_target_option_is_set_to_es2017_or_higher.code, @@ -44,4 +44,3 @@ ts.codefix.registerCodeFix({ return codeFixes.length ? codeFixes : undefined; } }); -} diff --git a/src/services/codefixes/fixNaNEquality.ts b/src/services/codefixes/fixNaNEquality.ts index 212fe45aedbc0..56d203625f376 100644 --- a/src/services/codefixes/fixNaNEquality.ts +++ b/src/services/codefixes/fixNaNEquality.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "fixNaNEquality"; const errorCodes = [ ts.Diagnostics.This_condition_will_always_return_0.code, @@ -62,4 +62,3 @@ function getSuggestion(messageText: string | ts.DiagnosticMessageChain) { const [_, suggestion] = ts.flattenDiagnosticMessageText(messageText, "\n", 0).match(/\'(.*)\'/) || []; return suggestion; } -} diff --git a/src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts b/src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts index 5dca179898b1d..985c08c4cbe3c 100644 --- a/src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts +++ b/src/services/codefixes/fixNoPropertyAccessFromIndexSignature.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "fixNoPropertyAccessFromIndexSignature"; const errorCodes = [ ts.Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0.code @@ -33,4 +33,3 @@ function doChange(changes: ts.textChanges.ChangeTracker, sourceFile: ts.SourceFi function getPropertyAccessExpression(sourceFile: ts.SourceFile, pos: number): ts.PropertyAccessExpression { return ts.cast(ts.getTokenAtPosition(sourceFile, pos).parent, ts.isPropertyAccessExpression); } -} diff --git a/src/services/codefixes/fixOverrideModifier.ts b/src/services/codefixes/fixOverrideModifier.ts index 1b323b6a5bf84..c9d75d68191e6 100644 --- a/src/services/codefixes/fixOverrideModifier.ts +++ b/src/services/codefixes/fixOverrideModifier.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixName = "fixOverrideModifier"; const fixAddOverrideId = "fixAddOverrideModifier"; const fixRemoveOverrideId = "fixRemoveOverrideModifier"; @@ -189,5 +189,4 @@ function findContainerClassElementLike(sourceFile: ts.SourceFile, pos: number) { ts.Debug.assert(classElement && isClassElementLikeHasJSDoc(classElement)); return classElement; } -} diff --git a/src/services/codefixes/fixPropertyAssignment.ts b/src/services/codefixes/fixPropertyAssignment.ts index 487ab5423dff0..e267c20b925a6 100644 --- a/src/services/codefixes/fixPropertyAssignment.ts +++ b/src/services/codefixes/fixPropertyAssignment.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "fixPropertyAssignment"; const errorCodes = [ ts.Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code @@ -25,4 +25,3 @@ function doChange(changes: ts.textChanges.ChangeTracker, sourceFile: ts.SourceFi function getProperty(sourceFile: ts.SourceFile, pos: number): ts.ShorthandPropertyAssignment { return ts.cast(ts.getTokenAtPosition(sourceFile, pos).parent, ts.isShorthandPropertyAssignment); } -} diff --git a/src/services/codefixes/fixPropertyOverrideAccessor.ts b/src/services/codefixes/fixPropertyOverrideAccessor.ts index a0fc5067c7345..9f5cfe7e9abce 100644 --- a/src/services/codefixes/fixPropertyOverrideAccessor.ts +++ b/src/services/codefixes/fixPropertyOverrideAccessor.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const errorCodes = [ ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property.code, ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor.code, @@ -54,4 +54,3 @@ function doChange(file: ts.SourceFile, start: number, length: number, code: numb } return ts.codefix.generateAccessorFromProperty(file, context.program, startPosition, endPosition, context, ts.Diagnostics.Generate_get_and_set_accessors.message); } -} diff --git a/src/services/codefixes/fixReturnTypeInAsyncFunction.ts b/src/services/codefixes/fixReturnTypeInAsyncFunction.ts index 6983287f6481c..7a4488cad047f 100644 --- a/src/services/codefixes/fixReturnTypeInAsyncFunction.ts +++ b/src/services/codefixes/fixReturnTypeInAsyncFunction.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "fixReturnTypeInAsyncFunction"; const errorCodes = [ ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0.code, @@ -61,4 +61,3 @@ function getInfo(sourceFile: ts.SourceFile, checker: ts.TypeChecker, pos: number function doChange(changes: ts.textChanges.ChangeTracker, sourceFile: ts.SourceFile, returnTypeNode: ts.TypeNode, promisedTypeNode: ts.TypeNode): void { changes.replaceNode(sourceFile, returnTypeNode, ts.factory.createTypeReferenceNode("Promise", [promisedTypeNode])); } -} diff --git a/src/services/codefixes/fixSpelling.ts b/src/services/codefixes/fixSpelling.ts index 8dbc85bb4986b..5bde5fc4c6452 100644 --- a/src/services/codefixes/fixSpelling.ts +++ b/src/services/codefixes/fixSpelling.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "fixSpelling"; const errorCodes = [ ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, @@ -138,4 +138,3 @@ function getResolvedSourceFileFromImportDeclaration(sourceFile: ts.SourceFile, c return context.program.getSourceFile(resolvedModule.resolvedFileName); } -} diff --git a/src/services/codefixes/fixStrictClassInitialization.ts b/src/services/codefixes/fixStrictClassInitialization.ts index 14dee7b2e828d..a83a345c109fb 100644 --- a/src/services/codefixes/fixStrictClassInitialization.ts +++ b/src/services/codefixes/fixStrictClassInitialization.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixName = "strictClassInitialization"; const fixIdAddDefiniteAssignmentAssertions = "addMissingPropertyDefiniteAssignmentAssertions"; const fixIdAddUndefinedType = "addMissingPropertyUndefinedType"; @@ -154,4 +154,3 @@ function getDefaultValueFromType(checker: ts.TypeChecker, type: ts.Type): ts.Exp } return undefined; } -} diff --git a/src/services/codefixes/fixUnmatchedParameter.ts b/src/services/codefixes/fixUnmatchedParameter.ts index 5132c614b3de6..cd42253a94e12 100644 --- a/src/services/codefixes/fixUnmatchedParameter.ts +++ b/src/services/codefixes/fixUnmatchedParameter.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const deleteUnmatchedParameter = "deleteUnmatchedParameter"; const renameUnmatchedParameter = "renameUnmatchedParameter"; @@ -101,4 +101,3 @@ function getInfo(sourceFile: ts.SourceFile, pos: number): Info | undefined { } return undefined; } -} diff --git a/src/services/codefixes/fixUnreachableCode.ts b/src/services/codefixes/fixUnreachableCode.ts index a76f26dc4bdb1..ad527ea4a2315 100644 --- a/src/services/codefixes/fixUnreachableCode.ts +++ b/src/services/codefixes/fixUnreachableCode.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "fixUnreachableCode"; const errorCodes = [ts.Diagnostics.Unreachable_code_detected.code]; ts.codefix.registerCodeFix({ @@ -67,4 +67,3 @@ function lastWhere(a: readonly T[], pred: (value: T) => boolean): T | undefin } return last; } -} diff --git a/src/services/codefixes/fixUnreferenceableDecoratorMetadata.ts b/src/services/codefixes/fixUnreferenceableDecoratorMetadata.ts index e1b039a047cea..d48200d90ec1f 100644 --- a/src/services/codefixes/fixUnreferenceableDecoratorMetadata.ts +++ b/src/services/codefixes/fixUnreferenceableDecoratorMetadata.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "fixUnreferenceableDecoratorMetadata"; const errorCodes = [ts.Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled.code]; ts.codefix.registerCodeFix({ @@ -67,4 +67,3 @@ function doTypeOnlyImportChange(changes: ts.textChanges.ChangeTracker, sourceFil function doNamespaceImportChange(changes: ts.textChanges.ChangeTracker, sourceFile: ts.SourceFile, importDeclaration: ts.ImportSpecifier, program: ts.Program) { ts.refactor.doChangeNamedToNamespaceOrDefault(sourceFile, program, changes, importDeclaration.parent); } -} diff --git a/src/services/codefixes/fixUnusedIdentifier.ts b/src/services/codefixes/fixUnusedIdentifier.ts index 884cbb108120b..32d072a45244c 100644 --- a/src/services/codefixes/fixUnusedIdentifier.ts +++ b/src/services/codefixes/fixUnusedIdentifier.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixName = "unusedIdentifier"; const fixIdPrefix = "unusedIdentifier_prefix"; const fixIdDelete = "unusedIdentifier_delete"; @@ -347,4 +347,3 @@ function mayDeleteExpression(node: ts.Node) { return ((ts.isBinaryExpression(node.parent) && node.parent.left === node) || ((ts.isPostfixUnaryExpression(node.parent) || ts.isPrefixUnaryExpression(node.parent)) && node.parent.operand === node)) && ts.isExpressionStatement(node.parent.parent); } -} diff --git a/src/services/codefixes/fixUnusedLabel.ts b/src/services/codefixes/fixUnusedLabel.ts index 959599842009a..6e5b40149de3e 100644 --- a/src/services/codefixes/fixUnusedLabel.ts +++ b/src/services/codefixes/fixUnusedLabel.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "fixUnusedLabel"; const errorCodes = [ts.Diagnostics.Unused_label.code]; ts.codefix.registerCodeFix({ @@ -22,4 +22,3 @@ function doChange(changes: ts.textChanges.ChangeTracker, sourceFile: ts.SourceFi : ts.skipTrivia(sourceFile.text, ts.findChildOfKind(labeledStatement, ts.SyntaxKind.ColonToken, sourceFile)!.end, /*stopAfterLineBreak*/ true); changes.deleteRange(sourceFile, { pos, end }); } -} diff --git a/src/services/codefixes/generateAccessors.ts b/src/services/codefixes/generateAccessors.ts index 591056bcf3e2a..ac006a44f799e 100644 --- a/src/services/codefixes/generateAccessors.ts +++ b/src/services/codefixes/generateAccessors.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + type AcceptedDeclaration = ts.ParameterPropertyDeclaration | ts.PropertyDeclaration | ts.PropertyAssignment; type AcceptedNameType = ts.Identifier | ts.StringLiteral; type ContainerDeclaration = ts.ClassLikeDeclaration | ts.ObjectLiteralExpression; @@ -17,6 +17,7 @@ interface AccessorInfo { readonly renameAccessor: boolean; } +/** @internal */ export function generateAccessorFromProperty(file: ts.SourceFile, program: ts.Program, start: number, end: number, context: ts.textChanges.TextChangesContext, _actionName: string): ts.FileTextChanges[] | undefined { const fieldInfo = getAccessorConvertiblePropertyAtPosition(file, program, start, end); if (!fieldInfo || ts.refactor.isRefactorErrorInfo(fieldInfo)) return undefined; @@ -104,6 +105,7 @@ function prepareModifierFlagsForField(modifierFlags: ts.ModifierFlags): ts.Modif return modifierFlags; } +/** @internal */ export function getAccessorConvertiblePropertyAtPosition(file: ts.SourceFile, program: ts.Program, start: number, end: number, considerEmptySpans = true): Info | undefined { const node = ts.getTokenAtPosition(file, start); const cursorRequest = start === end && considerEmptySpans; @@ -250,6 +252,7 @@ function getDeclarationType(declaration: AcceptedDeclaration, program: ts.Progra return typeNode; } +/** @internal */ export function getAllSupers(decl: ClassOrInterface | undefined, checker: ts.TypeChecker): readonly ClassOrInterface[] { const res: ts.ClassLikeDeclaration[] = []; while (decl) { @@ -265,5 +268,5 @@ export function getAllSupers(decl: ClassOrInterface | undefined, checker: ts.Typ return res; } +/** @internal */ export type ClassOrInterface = ts.ClassLikeDeclaration | ts.InterfaceDeclaration; -} diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index c181dd918b78a..a3fbd5b21e24d 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + +/** @internal */ /** * Finds members of the resolved type that are missing in the class pointed to by class decl * and generates source code for the missing members. @@ -23,6 +24,7 @@ export function createMissingMemberNodes( } } +/** @internal */ export function getNoopSymbolTrackerWithResolver(context: TypeConstructionContext): ts.SymbolTracker { return { trackSymbol: () => false, @@ -30,6 +32,7 @@ export function getNoopSymbolTrackerWithResolver(context: TypeConstructionContex }; } +/** @internal */ export interface TypeConstructionContext { program: ts.Program; host: ts.LanguageServiceHost; @@ -37,12 +40,14 @@ export interface TypeConstructionContext { type AddNode = ts.PropertyDeclaration | ts.GetAccessorDeclaration | ts.SetAccessorDeclaration | ts.MethodDeclaration | ts.FunctionExpression | ts.ArrowFunction; +/** @internal */ export const enum PreserveOptionalFlags { Method = 1 << 0, Property = 1 << 1, All = Method | Property } +/** @internal */ /** * `addClassElement` will not be called if we can't figure out a representation for `symbol` in `enclosingDeclaration`. * @param body If defined, this will be the body of the member node passed to `addClassElement`. Otherwise, the body will default to a stub. @@ -209,6 +214,7 @@ export function addNewNodeForMemberSymbol( } } +/** @internal */ export function createSignatureDeclarationFromSignature( kind: | ts.SyntaxKind.MethodDeclaration @@ -318,6 +324,7 @@ export function createSignatureDeclarationFromSignature( return undefined; } +/** @internal */ export function createSignatureDeclarationFromCallExpression( kind: ts.SyntaxKind.MethodDeclaration | ts.SyntaxKind.FunctionDeclaration | ts.SyntaxKind.MethodSignature, context: ts.CodeFixContextBase, @@ -419,6 +426,7 @@ function createTypeParameterName(index: number) { : `T${index}`; } +/** @internal */ export function typeToAutoImportableTypeNode(checker: ts.TypeChecker, importAdder: ts.codefix.ImportAdder, type: ts.Type, contextNode: ts.Node | undefined, scriptTarget: ts.ScriptTarget, flags?: ts.NodeBuilderFlags, tracker?: ts.SymbolTracker): ts.TypeNode | undefined { let typeNode = checker.typeToTypeNode(type, contextNode, flags, tracker); if (typeNode && ts.isImportTypeNode(typeNode)) { @@ -441,6 +449,7 @@ function typeContainsTypeParameter(type: ts.Type) { return type.flags & ts.TypeFlags.TypeParameter; } +/** @internal */ export function getArgumentTypesAndTypeParameters(checker: ts.TypeChecker, importAdder: ts.codefix.ImportAdder, instanceTypes: ts.Type[], contextNode: ts.Node | undefined, scriptTarget: ts.ScriptTarget, flags?: ts.NodeBuilderFlags, tracker?: ts.SymbolTracker) { // Types to be used as the types of the parameters in the new function // E.g. from this source: @@ -637,6 +646,7 @@ function createStubbedMethodBody(quotePreference: ts.QuotePreference) { return createStubbedBody(ts.Diagnostics.Method_not_implemented.message, quotePreference); } +/** @internal */ export function createStubbedBody(text: string, quotePreference: ts.QuotePreference): ts.Block { return ts.factory.createBlock( [ts.factory.createThrowStatement( @@ -648,6 +658,7 @@ export function createStubbedBody(text: string, quotePreference: ts.QuotePrefere /*multiline*/ true); } +/** @internal */ export function setJsonCompilerOptionValues( changeTracker: ts.textChanges.ChangeTracker, configFile: ts.TsConfigSourceFile, @@ -680,6 +691,7 @@ export function setJsonCompilerOptionValues( } } +/** @internal */ export function setJsonCompilerOptionValue( changeTracker: ts.textChanges.ChangeTracker, configFile: ts.TsConfigSourceFile, @@ -689,14 +701,17 @@ export function setJsonCompilerOptionValue( setJsonCompilerOptionValues(changeTracker, configFile, [[optionName, optionValue]]); } +/** @internal */ export function createJsonPropertyAssignment(name: string, initializer: ts.Expression) { return ts.factory.createPropertyAssignment(ts.factory.createStringLiteral(name), initializer); } +/** @internal */ export function findJsonProperty(obj: ts.ObjectLiteralExpression, name: string): ts.PropertyAssignment | undefined { return ts.find(obj.properties, (p): p is ts.PropertyAssignment => ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name); } +/** @internal */ /** * Given a type node containing 'import("./a").SomeType>', * returns an equivalent type reference node with any nested ImportTypeNodes also replaced @@ -734,10 +749,12 @@ function replaceFirstIdentifierOfEntityName(name: ts.EntityName, newIdentifier: return ts.factory.createQualifiedName(replaceFirstIdentifierOfEntityName(name.left, newIdentifier), name.right); } +/** @internal */ export function importSymbols(importAdder: ts.codefix.ImportAdder, symbols: readonly ts.Symbol[]) { symbols.forEach(s => importAdder.addImportFromExportedSymbol(s, /*isValidTypeOnlyUseSite*/ true)); } +/** @internal */ export function findAncestorMatchingSpan(sourceFile: ts.SourceFile, span: ts.TextSpan): ts.Node { const end = ts.textSpanEnd(span); let token = ts.getTokenAtPosition(sourceFile, span.start); @@ -746,4 +763,3 @@ export function findAncestorMatchingSpan(sourceFile: ts.SourceFile, span: ts.Tex } return token; } -} diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index fd1b33cd6bdd4..03bd3ec9a2eb5 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export const importFixName = "import"; const importFixId = "fixMissingImport"; const errorCodes: readonly number[] = [ @@ -39,6 +40,7 @@ ts.codefix.registerCodeFix({ }, }); +/** @internal */ /** * Computes multiple import additions to a file and writes them to a ChangeTracker. */ @@ -49,6 +51,7 @@ export interface ImportAdder { writeFixes: (changeTracker: ts.textChanges.ChangeTracker) => void; } +/** @internal */ export function createImportAdder(sourceFile: ts.SourceFile, program: ts.Program, preferences: ts.UserPreferences, host: ts.LanguageServiceHost, cancellationToken?: ts.CancellationToken): ImportAdder { return createImportAdderWorker(sourceFile, program, /*useAutoImportProvider*/ false, preferences, host, cancellationToken); } @@ -236,6 +239,7 @@ function createImportAdderWorker(sourceFile: ts.SourceFile, program: ts.Program, } } +/** @internal */ /** * Computes module specifiers for multiple import additions to a file. */ @@ -249,6 +253,7 @@ function createImportAdderWorker(sourceFile: ts.SourceFile, program: ts.Program, ): { exportInfo?: ts.SymbolExportInfo, moduleSpecifier: string, computedWithoutCacheCount: number } | undefined; } +/** @internal */ export function createImportSpecifierResolver(importingFile: ts.SourceFile, program: ts.Program, host: ts.LanguageServiceHost, preferences: ts.UserPreferences): ImportSpecifierResolver { const packageJsonImportFilter = ts.createPackageJsonImportFilter(importingFile, preferences, host); const importMap = createExistingImportMap(program.getTypeChecker(), importingFile, program.getCompilerOptions()); @@ -334,6 +339,7 @@ interface FixAddToExistingImportInfo { readonly symbol: ts.Symbol; } +/** @internal */ export function getImportCompletionAction( targetSymbol: ts.Symbol, moduleSymbol: ts.Symbol, @@ -369,6 +375,7 @@ export function getImportCompletionAction( }; } +/** @internal */ export function getPromoteTypeOnlyCompletionAction(sourceFile: ts.SourceFile, symbolToken: ts.Identifier, program: ts.Program, host: ts.LanguageServiceHost, formatContext: ts.formatting.FormatContext, preferences: ts.UserPreferences) { const compilerOptions = program.getCompilerOptions(); const symbolName = ts.single(getSymbolNamesToImport(sourceFile, program.getTypeChecker(), symbolToken, compilerOptions)); @@ -852,6 +859,7 @@ function getUmdSymbol(token: ts.Node, checker: ts.TypeChecker): ts.Symbol | unde : undefined; } +/** @internal */ /** * @param forceImportKeyword Indicates that the user has already typed `import`, so the result must start with `import`. * (In other words, do not allow `const x = require("...")` for JS files.) @@ -1338,10 +1346,12 @@ function symbolHasMeaning({ declarations }: ts.Symbol, meaning: ts.SemanticMeani return ts.some(declarations, decl => !!(ts.getMeaningFromDeclaration(decl) & meaning)); } +/** @internal */ export function moduleSymbolToValidIdentifier(moduleSymbol: ts.Symbol, target: ts.ScriptTarget | undefined, forceCapitalize: boolean): string { return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target, forceCapitalize); } +/** @internal */ export function moduleSpecifierToValidIdentifier(moduleSpecifier: string, target: ts.ScriptTarget | undefined, forceCapitalize?: boolean): string { const baseName = ts.getBaseFileName(ts.removeSuffix(moduleSpecifier, "/index")); let res = ""; @@ -1371,4 +1381,3 @@ export function moduleSpecifierToValidIdentifier(moduleSpecifier: string, target // Need `|| "_"` to ensure result isn't empty. return !ts.isStringANonContextualKeyword(res) ? res || "_" : `_${res}`; } -} diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index 4bde6c423e643..efc864deaa7f1 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "inferFromUsage"; const errorCodes = [ // Variable declarations @@ -1130,4 +1130,3 @@ function inferTypeFromReferences(program: ts.Program, references: readonly ts.Id } } } -} diff --git a/src/services/codefixes/removeAccidentalCallParentheses.ts b/src/services/codefixes/removeAccidentalCallParentheses.ts index d31d704387d92..5bd5541019afd 100644 --- a/src/services/codefixes/removeAccidentalCallParentheses.ts +++ b/src/services/codefixes/removeAccidentalCallParentheses.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "removeAccidentalCallParentheses"; const errorCodes = [ ts.Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without.code, @@ -18,4 +18,3 @@ ts.codefix.registerCodeFix({ }, fixIds: [fixId], }); -} diff --git a/src/services/codefixes/removeUnnecessaryAwait.ts b/src/services/codefixes/removeUnnecessaryAwait.ts index 83876382b6f77..7b9e7b7b7b5fd 100644 --- a/src/services/codefixes/removeUnnecessaryAwait.ts +++ b/src/services/codefixes/removeUnnecessaryAwait.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "removeUnnecessaryAwait"; const errorCodes = [ ts.Diagnostics.await_has_no_effect_on_the_type_of_this_expression.code, @@ -40,4 +40,3 @@ function makeChange(changeTracker: ts.textChanges.ChangeTracker, sourceFile: ts. changeTracker.replaceNode(sourceFile, expressionToReplace, awaitExpression.expression); } -} diff --git a/src/services/codefixes/requireInTs.ts b/src/services/codefixes/requireInTs.ts index 37e61f5e7e3b8..c36a85dc70305 100644 --- a/src/services/codefixes/requireInTs.ts +++ b/src/services/codefixes/requireInTs.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "requireInTs"; const errorCodes = [ts.Diagnostics.require_call_may_be_converted_to_an_import.code]; ts.codefix.registerCodeFix({ @@ -69,4 +69,3 @@ function tryCreateNamedImportsFromObjectBindingPattern(node: ts.ObjectBindingPat return ts.factory.createNamedImports(importSpecifiers); } } -} diff --git a/src/services/codefixes/returnValueCorrect.ts b/src/services/codefixes/returnValueCorrect.ts index caa32c295ae38..84e8c6c4e6a89 100644 --- a/src/services/codefixes/returnValueCorrect.ts +++ b/src/services/codefixes/returnValueCorrect.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "returnValueCorrect"; const fixIdAddReturnStatement = "fixAddReturnStatement"; const fixRemoveBracesFromArrowFunctionBody = "fixRemoveBracesFromArrowFunctionBody"; @@ -240,4 +240,3 @@ function getActionForfixWrapTheBlockWithParen(context: ts.CodeFixContext, declar const changes = ts.textChanges.ChangeTracker.with(context, t => wrapBlockWithParen(t, context.sourceFile, declaration, expression)); return ts.codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Wrap_the_following_body_with_parentheses_which_should_be_an_object_literal, fixIdWrapTheBlockWithParen, ts.Diagnostics.Wrap_all_object_literal_with_parentheses); } -} diff --git a/src/services/codefixes/splitTypeOnlyImport.ts b/src/services/codefixes/splitTypeOnlyImport.ts index 479b4ef8a8422..0223ff85c947b 100644 --- a/src/services/codefixes/splitTypeOnlyImport.ts +++ b/src/services/codefixes/splitTypeOnlyImport.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const errorCodes = [ts.Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both.code]; const fixId = "splitTypeOnlyImport"; ts.codefix.registerCodeFix({ @@ -40,4 +40,3 @@ function splitTypeOnlyImport(changes: ts.textChanges.ChangeTracker, importDeclar importDeclaration.moduleSpecifier, importDeclaration.assertClause)); } -} diff --git a/src/services/codefixes/useBigintLiteral.ts b/src/services/codefixes/useBigintLiteral.ts index 9e58c7aa6c446..1011bf3e79408 100644 --- a/src/services/codefixes/useBigintLiteral.ts +++ b/src/services/codefixes/useBigintLiteral.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "useBigintLiteral"; const errorCodes = [ ts.Diagnostics.Numeric_literals_with_absolute_values_equal_to_2_53_or_greater_are_too_large_to_be_represented_accurately_as_integers.code, @@ -30,4 +30,3 @@ function makeChange(changeTracker: ts.textChanges.ChangeTracker, sourceFile: ts. changeTracker.replaceNode(sourceFile, numericLiteral, ts.factory.createBigIntLiteral(newText)); } -} diff --git a/src/services/codefixes/useDefaultImport.ts b/src/services/codefixes/useDefaultImport.ts index 27762c133c4be..a12a0d3610f36 100644 --- a/src/services/codefixes/useDefaultImport.ts +++ b/src/services/codefixes/useDefaultImport.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixId = "useDefaultImport"; const errorCodes = [ts.Diagnostics.Import_may_be_converted_to_a_default_import.code]; ts.codefix.registerCodeFix({ @@ -39,4 +39,3 @@ function getInfo(sourceFile: ts.SourceFile, pos: number): Info | undefined { function doChange(changes: ts.textChanges.ChangeTracker, sourceFile: ts.SourceFile, info: Info, preferences: ts.UserPreferences): void { changes.replaceNode(sourceFile, info.importNode, ts.makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, ts.getQuotePreference(sourceFile, preferences))); } -} diff --git a/src/services/codefixes/wrapJsxInFragment.ts b/src/services/codefixes/wrapJsxInFragment.ts index 13061f402b8b4..df89bd61da62c 100644 --- a/src/services/codefixes/wrapJsxInFragment.ts +++ b/src/services/codefixes/wrapJsxInFragment.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.codefix { +import * as ts from "../_namespaces/ts"; + const fixID = "wrapJsxInFragment"; const errorCodes = [ts.Diagnostics.JSX_expressions_must_have_one_parent_element.code]; ts.codefix.registerCodeFix({ @@ -64,4 +64,3 @@ function flattenInvalidBinaryExpr(node: ts.Node): ts.JsxChild[] | undefined { else return undefined; } } -} diff --git a/src/services/completions.ts b/src/services/completions.ts index e999c8a2994a9..3edcc910d06e1 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1,12 +1,17 @@ -/* @internal */ -namespace ts.Completions { +import * as ts from "./_namespaces/ts"; + // Exported only for tests +/** @internal */ export const moduleSpecifierResolutionLimit = 100; +/** @internal */ export const moduleSpecifierResolutionCacheAttemptLimit = 1000; +/** @internal */ export type Log = (message: string) => void; +/** @internal */ export type SortText = string & { __sortText: any }; +/** @internal */ export const SortText = { // Presets LocalDeclarationPriority: "10" as SortText, @@ -33,6 +38,7 @@ export const SortText = { }, }; +/** @internal */ /** * Special values for `CompletionInfo['source']` used to disambiguate * completion items with the same `name`. (Each completion item must @@ -246,6 +252,7 @@ function resolvingModuleSpecifiers( } } +/** @internal */ export function getCompletionsAtPosition( host: ts.LanguageServiceHost, program: ts.Program, @@ -1388,6 +1395,7 @@ function getSourceFromOrigin(origin: SymbolOriginInfo | undefined): string | und } } +/** @internal */ export function getCompletionEntriesFromSymbols( symbols: readonly ts.Symbol[], entries: ts.SortedArray, @@ -1624,12 +1632,14 @@ function getSymbolCompletionFromEntryId( }) || { type: "none" }; } +/** @internal */ export interface CompletionEntryIdentifier { name: string; source?: string; data?: ts.CompletionEntryData; } +/** @internal */ export function getCompletionEntryDetails( program: ts.Program, log: Log, @@ -1689,6 +1699,7 @@ function createSimpleDetails(name: string, kind: ts.ScriptElementKind, kind2: ts return createCompletionDetails(name, ts.ScriptElementKindModifier.none, kind, [ts.displayPart(name, kind2)]); } +/** @internal */ export function createCompletionDetailsForSymbol(symbol: ts.Symbol, checker: ts.TypeChecker, sourceFile: ts.SourceFile, location: ts.Node, cancellationToken: ts.CancellationToken, codeActions?: ts.CodeAction[], sourceDisplay?: ts.SymbolDisplayPart[]): ts.CompletionEntryDetails { const { displayParts, documentation, symbolKind, tags } = checker.runWithCancellationToken(cancellationToken, checker => @@ -1697,6 +1708,7 @@ export function createCompletionDetailsForSymbol(symbol: ts.Symbol, checker: ts. return createCompletionDetails(symbol.name, ts.SymbolDisplay.getSymbolModifiers(checker, symbol), symbolKind, displayParts, documentation, tags, codeActions, sourceDisplay); } +/** @internal */ export function createCompletionDetails(name: string, kindModifiers: string, kind: ts.ScriptElementKind, displayParts: ts.SymbolDisplayPart[], documentation?: ts.SymbolDisplayPart[], tags?: ts.JSDocTagInfo[], codeActions?: ts.CodeAction[], source?: ts.SymbolDisplayPart[]): ts.CompletionEntryDetails { return { name, kindModifiers, kind, displayParts, documentation, tags, codeActions, source, sourceDisplay: source }; } @@ -1792,6 +1804,7 @@ function getCompletionEntryCodeActionsAndSourceDisplay( return { sourceDisplay: [ts.textPart(moduleSpecifier)], codeActions: [codeAction] }; } +/** @internal */ export function getCompletionEntrySymbol( program: ts.Program, log: Log, @@ -1839,6 +1852,7 @@ type Request = | { readonly kind: CompletionDataKind.JsDocParameterName, tag: ts.JSDocParameterTag } | { readonly kind: CompletionDataKind.Keywords, keywordCompletions: readonly ts.CompletionEntry[], isNewIdentifierLocation: boolean }; +/** @internal */ export const enum CompletionKind { ObjectPropertyDeclaration, Global, @@ -4012,6 +4026,7 @@ function getJsDocTagAtPosition(node: ts.Node, position: number): ts.JSDocTag | u ts.isJSDoc(n) ? "quit" : false) as ts.JSDocTag | undefined; } +/** @internal */ export function getPropertiesForObjectExpression(contextualType: ts.Type, completionsType: ts.Type | undefined, obj: ts.ObjectLiteralExpression | ts.JsxAttributes, checker: ts.TypeChecker): ts.Symbol[] { const hasCompletionsType = completionsType && completionsType !== contextualType; const type = hasCompletionsType && !(completionsType.flags & ts.TypeFlags.AnyOrUnknown) @@ -4464,5 +4479,3 @@ function toUpperCharCode(charCode: number) { return charCode; } -} - diff --git a/src/services/documentHighlights.ts b/src/services/documentHighlights.ts index a9f8d85473b3a..5090ca29d94f1 100644 --- a/src/services/documentHighlights.ts +++ b/src/services/documentHighlights.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + export interface DocumentHighlights { fileName: string; highlightSpans: ts.HighlightSpan[]; @@ -518,4 +519,3 @@ export namespace DocumentHighlights { return !!ts.findAncestor(node.parent, owner => !ts.isLabeledStatement(owner) ? "quit" : owner.label.escapedText === labelName); } } -} diff --git a/src/services/documentRegistry.ts b/src/services/documentRegistry.ts index 31b9c8aeebedb..de55bcdd96815 100644 --- a/src/services/documentRegistry.ts +++ b/src/services/documentRegistry.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + /** * The document registry represents a store of SourceFile objects that can be shared between * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) @@ -397,4 +398,3 @@ function getKeyForCompilationSettings(settings: ts.CompilerOptions): DocumentReg function getDocumentRegistryBucketKeyWithMode(key: DocumentRegistryBucketKey, mode: ts.ModuleKind.ESNext | ts.ModuleKind.CommonJS | undefined) { return (mode ? `${key}|${mode}` : key) as DocumentRegistryBucketKeyWithMode; } -} diff --git a/src/services/exportAsModule.ts b/src/services/exportAsModule.ts index 6760e9c38c2d0..da2c68619ca4e 100644 --- a/src/services/exportAsModule.ts +++ b/src/services/exportAsModule.ts @@ -1,3 +1,5 @@ +import * as ts from "./_namespaces/ts"; + // Here we expose the TypeScript services as an external module // so that it may be consumed easily like a node module. // @ts-ignore diff --git a/src/services/exportInfoMap.ts b/src/services/exportInfoMap.ts index 6c435f1ce2799..0e3ae5e42b18d 100644 --- a/src/services/exportInfoMap.ts +++ b/src/services/exportInfoMap.ts @@ -1,5 +1,6 @@ -/*@internal*/ -namespace ts { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export const enum ImportKind { Named, Default, @@ -7,6 +8,7 @@ export const enum ImportKind { CommonJS, } +/** @internal */ export const enum ExportKind { Named, Default, @@ -14,6 +16,7 @@ export const enum ExportKind { UMD, } +/** @internal */ export interface SymbolExportInfo { readonly symbol: ts.Symbol; readonly moduleSymbol: ts.Symbol; @@ -44,6 +47,7 @@ interface CachedSymbolExportInfo { isFromPackageJson: boolean; } +/** @internal */ export interface ExportInfoMap { isUsableByFile(importingFile: ts.Path): boolean; clear(): void; @@ -56,12 +60,14 @@ export interface ExportInfoMap { onFileChanged(oldSourceFile: ts.SourceFile, newSourceFile: ts.SourceFile, typeAcquisitionEnabled: boolean): boolean; } +/** @internal */ export interface CacheableExportInfoMapHost { getCurrentProgram(): ts.Program | undefined; getPackageJsonAutoImportProvider(): ts.Program | undefined; getGlobalTypingsCacheLocation(): string | undefined; } +/** @internal */ export function createCacheableExportInfoMap(host: CacheableExportInfoMapHost): ExportInfoMap { let exportInfoId = 1; const exportInfo = ts.createMultiMap(); @@ -281,6 +287,7 @@ export function createCacheableExportInfoMap(host: CacheableExportInfoMapHost): } } +/** @internal */ export function isImportableFile( program: ts.Program, from: ts.SourceFile, @@ -334,6 +341,7 @@ function isImportablePath(fromPath: string, toPath: string, getCanonicalFileName || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); } +/** @internal */ export function forEachExternalModuleToImportFrom( program: ts.Program, host: ts.LanguageServiceHost, @@ -372,6 +380,7 @@ function forEachExternalModule(checker: ts.TypeChecker, allSourceFiles: readonly } } +/** @internal */ export function getExportInfoMap(importingFile: ts.SourceFile, host: ts.LanguageServiceHost, program: ts.Program, preferences: ts.UserPreferences, cancellationToken: ts.CancellationToken | undefined): ExportInfoMap { const start = ts.timestamp(); // Pulling the AutoImportProvider project will trigger its updateGraph if pending, @@ -436,6 +445,7 @@ export function getExportInfoMap(importingFile: ts.SourceFile, host: ts.Language return cache; } +/** @internal */ export function getDefaultLikeExportInfo(moduleSymbol: ts.Symbol, checker: ts.TypeChecker, compilerOptions: ts.CompilerOptions) { const exported = getDefaultLikeExportWorker(moduleSymbol, checker); if (!exported) return undefined; @@ -491,4 +501,3 @@ function getNameForExportDefault(symbol: ts.Symbol): string | undefined { } }); } -} diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 2f65a36a70713..731785b9fc59d 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -1,11 +1,14 @@ -/* @internal */ -namespace ts.FindAllReferences { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export interface SymbolAndEntries { readonly definition: Definition | undefined; readonly references: readonly Entry[]; } +/** @internal */ export const enum DefinitionKind { Symbol, Label, Keyword, This, String, TripleSlashReference } +/** @internal */ export type Definition = | { readonly type: DefinitionKind.Symbol; readonly symbol: ts.Symbol } | { readonly type: DefinitionKind.Label; readonly node: ts.Identifier } @@ -14,24 +17,32 @@ export type Definition = | { readonly type: DefinitionKind.String; readonly node: ts.StringLiteralLike } | { readonly type: DefinitionKind.TripleSlashReference; readonly reference: ts.FileReference, readonly file: ts.SourceFile }; +/** @internal */ export const enum EntryKind { Span, Node, StringLiteral, SearchedLocalFoundProperty, SearchedPropertyFoundLocal } +/** @internal */ export type NodeEntryKind = EntryKind.Node | EntryKind.StringLiteral | EntryKind.SearchedLocalFoundProperty | EntryKind.SearchedPropertyFoundLocal; +/** @internal */ export type Entry = NodeEntry | SpanEntry; +/** @internal */ export interface ContextWithStartAndEndNode { start: ts.Node; end: ts.Node; } +/** @internal */ export type ContextNode = ts.Node | ContextWithStartAndEndNode; +/** @internal */ export interface NodeEntry { readonly kind: NodeEntryKind; readonly node: ts.Node; readonly context?: ContextNode; } +/** @internal */ export interface SpanEntry { readonly kind: EntryKind.Span; readonly fileName: string; readonly textSpan: ts.TextSpan; } +/** @internal */ export function nodeEntry(node: ts.Node, kind: NodeEntryKind = EntryKind.Node): NodeEntry { return { kind, @@ -40,6 +51,7 @@ export function nodeEntry(node: ts.Node, kind: NodeEntryKind = EntryKind.Node): }; } +/** @internal */ export function isContextWithStartAndEndNode(node: ContextNode): node is ContextWithStartAndEndNode { return node && (node as ts.Node).kind === undefined; } @@ -110,6 +122,7 @@ function getContextNodeForNodeEntry(node: ts.Node): ContextNode | undefined { return undefined; } +/** @internal */ export function getContextNode(node: ts.NamedDeclaration | ts.BinaryExpression | ts.ForInOrOfStatement | undefined): ContextNode | undefined { if (!node) return undefined; switch (node.kind) { @@ -163,6 +176,7 @@ export function getContextNode(node: ts.NamedDeclaration | ts.BinaryExpression | } } +/** @internal */ export function toContextSpan(textSpan: ts.TextSpan, sourceFile: ts.SourceFile, context?: ContextNode): { contextSpan: ts.TextSpan } | undefined { if (!context) return undefined; const contextSpan = isContextWithStartAndEndNode(context) ? @@ -173,6 +187,7 @@ export function toContextSpan(textSpan: ts.TextSpan, sourceFile: ts.SourceFile, undefined; } +/** @internal */ export const enum FindReferencesUse { /** * When searching for references to a symbol, the location will not be adjusted (this is the default behavior when not specified). @@ -190,6 +205,7 @@ export const enum FindReferencesUse { Rename, } +/** @internal */ export interface Options { readonly findInStrings?: boolean; readonly findInComments?: boolean; @@ -204,6 +220,7 @@ export interface Options { readonly providePrefixAndSuffixTextForRename?: boolean; } +/** @internal */ export function findReferencedSymbols(program: ts.Program, cancellationToken: ts.CancellationToken, sourceFiles: readonly ts.SourceFile[], sourceFile: ts.SourceFile, position: number): ts.ReferencedSymbol[] | undefined { const node = ts.getTouchingPropertyName(sourceFile, position); const options = { use: FindReferencesUse.References }; @@ -227,6 +244,7 @@ function isDefinitionForReference(node: ts.Node): boolean { || (node.kind === ts.SyntaxKind.ConstructorKeyword && ts.isConstructorDeclaration(node.parent)); } +/** @internal */ export function getImplementationsAtPosition(program: ts.Program, cancellationToken: ts.CancellationToken, sourceFiles: readonly ts.SourceFile[], sourceFile: ts.SourceFile, position: number): ts.ImplementationLocation[] | undefined { const node = ts.getTouchingPropertyName(sourceFile, position); let referenceEntries: Entry[] | undefined; @@ -284,6 +302,7 @@ function getImplementationReferenceEntries(program: ts.Program, cancellationToke } } +/** @internal */ export function findReferenceOrRenameEntries( program: ts.Program, cancellationToken: ts.CancellationToken, sourceFiles: readonly ts.SourceFile[], node: ts.Node, position: number, options: Options | undefined, convertEntry: ToReferenceOrRenameEntry, @@ -291,8 +310,10 @@ export function findReferenceOrRenameEntries( return ts.map(flattenEntries(Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)), entry => convertEntry(entry, node, program.getTypeChecker())); } +/** @internal */ export type ToReferenceOrRenameEntry = (entry: Entry, originalNode: ts.Node, checker: ts.TypeChecker) => T; +/** @internal */ export function getReferenceEntriesForNode( position: number, node: ts.Node, @@ -394,6 +415,7 @@ function getDefinitionKindAndDisplayParts(symbol: ts.Symbol, checker: ts.TypeChe return { displayParts, kind: symbolKind }; } +/** @internal */ export function toRenameLocation(entry: Entry, originalNode: ts.Node, checker: ts.TypeChecker, providePrefixAndSuffixText: boolean): ts.RenameLocation { return { ...entryToDocumentSpan(entry), ...(providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker)) }; } @@ -407,6 +429,7 @@ function toReferencedSymbolEntry(entry: Entry, symbol: ts.Symbol | undefined): t }; } +/** @internal */ export function toReferenceEntry(entry: Entry): ts.ReferenceEntry { const documentSpan = entryToDocumentSpan(entry); if (entry.kind === EntryKind.Span) { @@ -519,6 +542,7 @@ function implementationKindDisplayParts(node: ts.Node, checker: ts.TypeChecker): } } +/** @internal */ export function toHighlightSpan(entry: Entry): { fileName: string, span: ts.HighlightSpan } { const documentSpan = entryToDocumentSpan(entry); if (entry.kind === EntryKind.Span) { @@ -552,6 +576,7 @@ function getTextSpan(node: ts.Node, sourceFile: ts.SourceFile, endNode?: ts.Node return ts.createTextSpanFromBounds(start, end); } +/** @internal */ export function getTextSpanOfEntry(entry: Entry) { return entry.kind === EntryKind.Span ? entry.textSpan : getTextSpan(entry.node, entry.node.getSourceFile()); @@ -563,6 +588,7 @@ function isWriteAccessForReference(node: ts.Node): boolean { return !!decl && declarationIsWriteAccess(decl) || node.kind === ts.SyntaxKind.DefaultKeyword || ts.isWriteAccess(node); } +/** @internal */ /** Whether a reference, `node`, is a definition of the `target` symbol */ export function isDeclarationOfSymbol(node: ts.Node, target: ts.Symbol | undefined): boolean { if (!target) return false; @@ -636,6 +662,7 @@ function declarationIsWriteAccess(decl: ts.Declaration): boolean { } } +/** @internal */ /** Encapsulates the core find-all-references algorithm. */ export namespace Core { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ @@ -2399,4 +2426,3 @@ export namespace Core { return options.use === FindReferencesUse.Rename && options.providePrefixAndSuffixTextForRename; } } -} diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index fbf2ecd1c7e4b..2cfd59a44daaf 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -1,23 +1,28 @@ -/* @internal */ -namespace ts.formatting { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export interface FormatContext { readonly options: ts.FormatCodeSettings; readonly getRules: ts.formatting.RulesMap; readonly host: ts.FormattingHost; } +/** @internal */ export interface TextRangeWithKind extends ts.TextRange { kind: T; } +/** @internal */ export type TextRangeWithTriviaKind = TextRangeWithKind; +/** @internal */ export interface TokenInfo { leadingTrivia: TextRangeWithTriviaKind[] | undefined; token: TextRangeWithKind; trailingTrivia: TextRangeWithTriviaKind[] | undefined; } +/** @internal */ export function createTextRangeWithKind(pos: number, end: number, kind: T): TextRangeWithKind { const textRangeWithKind: TextRangeWithKind = { pos, end, kind }; if (ts.Debug.isDebugging) { @@ -74,6 +79,7 @@ interface DynamicIndentation { recomputeIndentation(lineAddedByFormatting: boolean, parent: ts.Node): void; } +/** @internal */ export function formatOnEnter(position: number, sourceFile: ts.SourceFile, formatContext: FormatContext): ts.TextChange[] { const line = sourceFile.getLineAndCharacterOfPosition(position).line; if (line === 0) { @@ -103,11 +109,13 @@ export function formatOnEnter(position: number, sourceFile: ts.SourceFile, forma return formatSpan(span, sourceFile, formatContext, ts.formatting.FormattingRequestKind.FormatOnEnter); } +/** @internal */ export function formatOnSemicolon(position: number, sourceFile: ts.SourceFile, formatContext: FormatContext): ts.TextChange[] { const semicolon = findImmediatelyPrecedingTokenOfKind(position, ts.SyntaxKind.SemicolonToken, sourceFile); return formatNodeLines(findOutermostNodeWithinListLevel(semicolon), sourceFile, formatContext, ts.formatting.FormattingRequestKind.FormatOnSemicolon); } +/** @internal */ export function formatOnOpeningCurly(position: number, sourceFile: ts.SourceFile, formatContext: FormatContext): ts.TextChange[] { const openingCurly = findImmediatelyPrecedingTokenOfKind(position, ts.SyntaxKind.OpenBraceToken, sourceFile); if (!openingCurly) { @@ -136,11 +144,13 @@ export function formatOnOpeningCurly(position: number, sourceFile: ts.SourceFile return formatSpan(textRange, sourceFile, formatContext, ts.formatting.FormattingRequestKind.FormatOnOpeningCurlyBrace); } +/** @internal */ export function formatOnClosingCurly(position: number, sourceFile: ts.SourceFile, formatContext: FormatContext): ts.TextChange[] { const precedingToken = findImmediatelyPrecedingTokenOfKind(position, ts.SyntaxKind.CloseBraceToken, sourceFile); return formatNodeLines(findOutermostNodeWithinListLevel(precedingToken), sourceFile, formatContext, ts.formatting.FormattingRequestKind.FormatOnClosingCurlyBrace); } +/** @internal */ export function formatDocument(sourceFile: ts.SourceFile, formatContext: FormatContext): ts.TextChange[] { const span = { pos: 0, @@ -149,6 +159,7 @@ export function formatDocument(sourceFile: ts.SourceFile, formatContext: FormatC return formatSpan(span, sourceFile, formatContext, ts.formatting.FormattingRequestKind.FormatDocument); } +/** @internal */ export function formatSelection(start: number, end: number, sourceFile: ts.SourceFile, formatContext: FormatContext): ts.TextChange[] { // format from the beginning of the line const span = { @@ -343,6 +354,7 @@ function getOwnOrInheritedDelta(n: ts.Node, options: ts.FormatCodeSettings, sour return 0; } +/** @internal */ export function formatNodeGivenIndentation(node: ts.Node, sourceFileLike: ts.SourceFileLike, languageVariant: ts.LanguageVariant, initialIndentation: number, delta: number, formatContext: FormatContext): ts.TextChange[] { const range = { pos: node.pos, end: node.end }; return ts.formatting.getFormattingScanner(sourceFileLike.text, languageVariant, range.pos, range.end, scanner => formatSpanWorker( @@ -1288,6 +1300,7 @@ function formatSpanWorker( const enum LineAction { None, LineAdded, LineRemoved } +/** @internal */ /** * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. */ @@ -1400,6 +1413,7 @@ let internedSizes: { tabSize: number; indentSize: number; }; let internedTabsIndentation: string[] | undefined; let internedSpacesIndentation: string[] | undefined; +/** @internal */ export function getIndentationString(indentation: number, options: ts.EditorSettings): string { // reset interned strings if FormatCodeOptions were changed const resetInternedStrings = @@ -1447,4 +1461,3 @@ export function getIndentationString(indentation: number, options: ts.EditorSett return remainder ? spacesString + ts.repeatString(" ", remainder) : spacesString; } } -} diff --git a/src/services/formatting/formattingContext.ts b/src/services/formatting/formattingContext.ts index 877b07785778b..e8e83bba014e8 100644 --- a/src/services/formatting/formattingContext.ts +++ b/src/services/formatting/formattingContext.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts.formatting { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export const enum FormattingRequestKind { FormatDocument, FormatSelection, @@ -9,6 +10,7 @@ export const enum FormattingRequestKind { FormatOnClosingCurlyBrace } +/** @internal */ export class FormattingContext { public currentTokenSpan!: ts.formatting.TextRangeWithKind; public nextTokenSpan!: ts.formatting.TextRangeWithKind; @@ -99,4 +101,3 @@ export class FormattingContext { return false; } } -} diff --git a/src/services/formatting/formattingScanner.ts b/src/services/formatting/formattingScanner.ts index abb2206d284ae..cd2f83b8c9d74 100644 --- a/src/services/formatting/formattingScanner.ts +++ b/src/services/formatting/formattingScanner.ts @@ -1,8 +1,9 @@ -/* @internal */ -namespace ts.formatting { +import * as ts from "../_namespaces/ts"; + const standardScanner = ts.createScanner(ts.ScriptTarget.Latest, /*skipTrivia*/ false, ts.LanguageVariant.Standard); const jsxScanner = ts.createScanner(ts.ScriptTarget.Latest, /*skipTrivia*/ false, ts.LanguageVariant.JSX); +/** @internal */ export interface FormattingScanner { advance(): void; getStartPos(): number; @@ -26,6 +27,7 @@ const enum ScanAction { RescanJsxAttributeValue, } +/** @internal */ export function getFormattingScanner(text: string, languageVariant: ts.LanguageVariant, startPos: number, endPos: number, cb: (scanner: FormattingScanner) => T): T { const scanner = languageVariant === ts.LanguageVariant.JSX ? jsxScanner : standardScanner; @@ -306,4 +308,3 @@ export function getFormattingScanner(text: string, languageVariant: ts.Langua trailingTrivia = undefined; } } -} diff --git a/src/services/formatting/rule.ts b/src/services/formatting/rule.ts index ddf28e37e18b9..4802a6f815560 100644 --- a/src/services/formatting/rule.ts +++ b/src/services/formatting/rule.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts.formatting { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export interface Rule { // Used for debugging to identify each rule based on the property name it's assigned to. readonly debugName: string; @@ -8,9 +9,12 @@ export interface Rule { readonly flags: RuleFlags; } +/** @internal */ export type ContextPredicate = (context: ts.formatting.FormattingContext) => boolean; +/** @internal */ export const anyContext: readonly ContextPredicate[] = ts.emptyArray; +/** @internal */ export const enum RuleAction { StopProcessingSpaceActions = 1 << 0, StopProcessingTokenActions = 1 << 1, @@ -25,13 +29,14 @@ export const enum RuleAction { ModifyTokenAction = DeleteToken | InsertTrailingSemicolon, } +/** @internal */ export const enum RuleFlags { None, CanDeleteNewLines, } +/** @internal */ export interface TokenRange { readonly tokens: readonly ts.SyntaxKind[]; readonly isSpecific: boolean; } -} diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts index 57eaa26e1a2a7..972147ef1b948 100644 --- a/src/services/formatting/rules.ts +++ b/src/services/formatting/rules.ts @@ -1,11 +1,13 @@ -/* @internal */ -namespace ts.formatting { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export interface RuleSpec { readonly leftTokenRange: ts.formatting.TokenRange; readonly rightTokenRange: ts.formatting.TokenRange; readonly rule: ts.formatting.Rule; } +/** @internal */ export function getAllRules(): RuleSpec[] { const allTokens: ts.SyntaxKind[] = []; for (let token = ts.SyntaxKind.FirstToken; token <= ts.SyntaxKind.LastToken; token++) { @@ -900,4 +902,3 @@ function isNotPropertyAccessOnIntegerLiteral(context: ts.formatting.FormattingCo || !ts.isNumericLiteral(context.contextNode.expression) || context.contextNode.expression.getText().indexOf(".") !== -1; } -} diff --git a/src/services/formatting/rulesMap.ts b/src/services/formatting/rulesMap.ts index b823e844eda84..84f838a7f0669 100644 --- a/src/services/formatting/rulesMap.ts +++ b/src/services/formatting/rulesMap.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts.formatting { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export function getFormatContext(options: ts.FormatCodeSettings, host: ts.FormattingHost): ts.formatting.FormatContext { return { options, getRules: getRulesMap(), host }; } @@ -34,6 +35,7 @@ function getRuleActionExclusion(ruleAction: ts.formatting.RuleAction): ts.format return mask; } +/** @internal */ export type RulesMap = (context: ts.formatting.FormattingContext) => readonly ts.formatting.Rule[] | undefined; function createRulesMap(rules: readonly ts.formatting.RuleSpec[]): RulesMap { const map = buildMap(rules); @@ -137,4 +139,3 @@ function increaseInsertionIndex(indexBitmap: number, maskPosition: RulesPosition ts.Debug.assert((value & mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); return (indexBitmap & ~(mask << maskPosition)) | (value << maskPosition); } -} diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index 6314f40eeb564..9d43456f199ff 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts.formatting { +import * as ts from "../_namespaces/ts"; + +/** @internal */ export namespace SmartIndenter { const enum Value { @@ -707,4 +708,3 @@ export namespace SmartIndenter { return startLine === endLine; } } -} diff --git a/src/services/getEditsForFileRename.ts b/src/services/getEditsForFileRename.ts index 8c7a27a26eb8b..961d77aad62d0 100644 --- a/src/services/getEditsForFileRename.ts +++ b/src/services/getEditsForFileRename.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export function getEditsForFileRename( program: ts.Program, oldFileOrDirPath: string, @@ -22,6 +23,7 @@ export function getEditsForFileRename( /** If 'path' refers to an old directory, returns path in the new directory. */ type PathUpdater = (path: string) => string | undefined; // exported for tests +/** @internal */ export function getPathUpdater(oldFileOrDirPath: string, newFileOrDirPath: string, getCanonicalFileName: ts.GetCanonicalFileName, sourceMapper: ts.SourceMapper | undefined): PathUpdater { const canonicalOldPath = getCanonicalFileName(oldFileOrDirPath); return path => { @@ -258,4 +260,3 @@ function forEachProperty(objectLiteral: ts.Expression, cb: (property: ts.Propert } } } -} diff --git a/src/services/globalThisShim.ts b/src/services/globalThisShim.ts index 899bb009895c0..81e88c60ff62f 100644 --- a/src/services/globalThisShim.ts +++ b/src/services/globalThisShim.ts @@ -1,3 +1,5 @@ +import * as ts from "./_namespaces/ts"; + // We polyfill `globalThis` here so re can reliably patch the global scope // in the contexts we want to in the same way across script and module formats @@ -6,7 +8,11 @@ // #region The polyfill starts here. /* eslint-disable no-var */ /* @internal */ -declare var window: {}; +declare global { + // Module transform: converted from ambient declaration + /** @internal */ + var window: {}; +} /* eslint-enable no-var */ ((() => { if (typeof globalThis === "object") return; diff --git a/src/services/goToDefinition.ts b/src/services/goToDefinition.ts index 1c95e808e794f..a3fb1220e66bc 100644 --- a/src/services/goToDefinition.ts +++ b/src/services/goToDefinition.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts.GoToDefinition { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export function getDefinitionAtPosition(program: ts.Program, sourceFile: ts.SourceFile, position: number, searchOtherFilesOnly?: boolean, stopAtAlias?: boolean): readonly ts.DefinitionInfo[] | undefined { const resolvedRef = getReferenceAtPosition(sourceFile, position, program); const fileReferenceDefinition = resolvedRef && [getDefinitionInfoForFileReference(resolvedRef.reference.fileName, resolvedRef.fileName, resolvedRef.unverified)] || ts.emptyArray; @@ -191,6 +192,7 @@ function getDefinitionFromOverriddenMember(typeChecker: ts.TypeChecker, node: ts return getDefinitionFromSymbol(typeChecker, symbol, node); } +/** @internal */ export function getReferenceAtPosition(sourceFile: ts.SourceFile, position: number, program: ts.Program): { reference: ts.FileReference, fileName: string, unverified: boolean, file?: ts.SourceFile } | undefined { const referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); if (referencePath) { @@ -233,6 +235,7 @@ export function getReferenceAtPosition(sourceFile: ts.SourceFile, position: numb } /// Goto type +/** @internal */ export function getTypeDefinitionAtPosition(typeChecker: ts.TypeChecker, sourceFile: ts.SourceFile, position: number): readonly ts.DefinitionInfo[] | undefined { const node = ts.getTouchingPropertyName(sourceFile, position); if (node === sourceFile) { @@ -273,6 +276,7 @@ function tryGetReturnTypeOfFunction(symbol: ts.Symbol, type: ts.Type, checker: t return undefined; } +/** @internal */ export function getDefinitionAndBoundSpan(program: ts.Program, sourceFile: ts.SourceFile, position: number): ts.DefinitionInfoAndBoundSpan | undefined { const definitions = getDefinitionAtPosition(program, sourceFile, position); @@ -401,6 +405,7 @@ function getDefinitionFromSymbol(typeChecker: ts.TypeChecker, symbol: ts.Symbol, } } +/** @internal */ /** Creates a DefinitionInfo from a Declaration, using the declaration's name if possible. */ export function createDefinitionInfo(declaration: ts.Declaration, checker: ts.TypeChecker, symbol: ts.Symbol, node: ts.Node, unverified?: boolean, failedAliasResolution?: boolean): ts.DefinitionInfo { const symbolName = checker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol @@ -470,6 +475,7 @@ function createDefinitionFromSignatureDeclaration(typeChecker: ts.TypeChecker, d return createDefinitionInfo(decl, typeChecker, decl.symbol, decl, /*unverified*/ false, failedAliasResolution); } +/** @internal */ export function findReferenceInPosition(refs: readonly ts.FileReference[], pos: number): ts.FileReference | undefined { return ts.find(refs, ref => ts.textRangeContainsPositionInclusive(ref, pos)); } @@ -510,4 +516,3 @@ function isConstructorLike(node: ts.Node): boolean { return false; } } -} diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index c1cbe18d90a34..703e742e18695 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -1,6 +1,8 @@ +import * as ts from "./_namespaces/ts"; + /* Code for finding imports of an exported symbol. Used only by FindAllReferences. */ -/* @internal */ -namespace ts.FindAllReferences { + +/** @internal */ export interface ImportsResult { /** For every import of the symbol, the location and local symbol for the import. */ importSearches: readonly [ts.Identifier, ts.Symbol][]; @@ -9,8 +11,10 @@ export interface ImportsResult { /** List of source files that may (or may not) use the symbol via a namespace. (For UMD modules this is every file.) */ indirectUsers: readonly ts.SourceFile[]; } +/** @internal */ export type ImportTracker = (exportSymbol: ts.Symbol, exportInfo: ExportInfo, isForRename: boolean) => ImportsResult; +/** @internal */ /** Creates the imports map and returns an ImportTracker that uses it. Call this lazily to avoid calling `getDirectImportsMap` unnecessarily. */ export function createImportTracker(sourceFiles: readonly ts.SourceFile[], sourceFilesSet: ts.ReadonlySet, checker: ts.TypeChecker, cancellationToken: ts.CancellationToken | undefined): ImportTracker { const allDirectImports = getDirectImportsMap(sourceFiles, checker, cancellationToken); @@ -20,14 +24,17 @@ export function createImportTracker(sourceFiles: readonly ts.SourceFile[], sourc }; } +/** @internal */ /** Info about an exported symbol to perform recursive search on. */ export interface ExportInfo { exportingModuleSymbol: ts.Symbol; exportKind: ExportKind; } +/** @internal */ export const enum ExportKind { Named, Default, ExportEquals } +/** @internal */ export const enum ImportExport { Import, Export } interface AmbientModuleDeclaration extends ts.ModuleDeclaration { body?: ts.ModuleBlock; } @@ -350,11 +357,13 @@ function findNamespaceReExports(sourceFileLike: SourceFileLike, name: ts.Identif }); } +/** @internal */ export type ModuleReference = /** "import" also includes require() calls. */ | { kind: "import", literal: ts.StringLiteralLike } /** or */ | { kind: "reference", referencingFile: ts.SourceFile, ref: ts.FileReference }; +/** @internal */ export function findModuleReferences(program: ts.Program, sourceFiles: readonly ts.SourceFile[], searchModuleSymbol: ts.Symbol): ModuleReference[] { const refs: ModuleReference[] = []; const checker = program.getTypeChecker(); @@ -443,16 +452,19 @@ function forEachImport(sourceFile: ts.SourceFile, action: (importStatement: Impo } } +/** @internal */ export interface ImportedSymbol { kind: ImportExport.Import; symbol: ts.Symbol; } +/** @internal */ export interface ExportedSymbol { kind: ImportExport.Export; symbol: ts.Symbol; exportInfo: ExportInfo; } +/** @internal */ /** * Given a local reference, we might notice that it's an import/export and recursively search for references of that. * If at an import, look locally for the symbol it imports. @@ -628,6 +640,7 @@ function isNodeImport(node: ts.Node): boolean { } } +/** @internal */ export function getExportInfo(exportSymbol: ts.Symbol, exportKind: ExportKind, checker: ts.TypeChecker): ExportInfo | undefined { const moduleSymbol = exportSymbol.parent; if (!moduleSymbol) return undefined; // This can happen if an `export` is not at the top-level (which is a compile error). @@ -682,4 +695,3 @@ function isAmbientModuleDeclaration(node: ts.Node): node is AmbientModuleDeclara function isExternalModuleImportEquals(eq: ts.ImportEqualsDeclaration): eq is ts.ImportEqualsDeclaration & { moduleReference: { expression: ts.StringLiteral } } { return eq.moduleReference.kind === ts.SyntaxKind.ExternalModuleReference && eq.moduleReference.expression.kind === ts.SyntaxKind.StringLiteral; } -} diff --git a/src/services/inlayHints.ts b/src/services/inlayHints.ts index 18a6e86384ae7..b04dbec126022 100644 --- a/src/services/inlayHints.ts +++ b/src/services/inlayHints.ts @@ -1,5 +1,4 @@ -/* @internal */ -namespace ts.InlayHints { +import * as ts from "./_namespaces/ts"; const maxHintsLength = 30; @@ -15,6 +14,7 @@ function shouldShowLiteralParameterNameHintsOnly(preferences: ts.UserPreferences return preferences.includeInlayParameterNameHints === "literals"; } +/** @internal */ export function provideInlayHints(context: ts.InlayHintsContext): ts.InlayHint[] { const { file, program, span, cancellationToken, preferences } = context; const sourceFileText = file.text; @@ -335,4 +335,3 @@ export function provideInlayHints(context: ts.InlayHintsContext): ts.InlayHint[] return true; } } -} diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index c1db9ae85b365..8e5cf8c6309e7 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.JsDoc { +import * as ts from "./_namespaces/ts"; + const jsDocTagNames = [ "abstract", "access", @@ -83,6 +83,7 @@ const jsDocTagNames = [ let jsDocTagNameCompletionEntries: ts.CompletionEntry[]; let jsDocTagCompletionEntries: ts.CompletionEntry[]; +/** @internal */ export function getJsDocCommentsFromDeclarations(declarations: readonly ts.Declaration[], checker?: ts.TypeChecker): ts.SymbolDisplayPart[] { // Only collect doc comments from duplicate declarations once: // In case of a union property there might be same declaration multiple times @@ -135,6 +136,7 @@ function getCommentHavingNodes(declaration: ts.Declaration): readonly (ts.JSDoc } } +/** @internal */ export function getJsDocTagsFromDeclarations(declarations?: ts.Declaration[], checker?: ts.TypeChecker): ts.JSDocTagInfo[] { // Only collect doc comments from duplicate declarations once. const infos: ts.JSDocTagInfo[] = []; @@ -244,6 +246,7 @@ function getTagNameDisplayPart(kind: ts.SyntaxKind): (text: string) => ts.Symbol } } +/** @internal */ export function getJSDocTagNameCompletions(): ts.CompletionEntry[] { return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, tagName => { return { @@ -255,8 +258,10 @@ export function getJSDocTagNameCompletions(): ts.CompletionEntry[] { })); } +/** @internal */ export const getJSDocTagNameCompletionDetails = getJSDocTagCompletionDetails; +/** @internal */ export function getJSDocTagCompletions(): ts.CompletionEntry[] { return jsDocTagCompletionEntries || (jsDocTagCompletionEntries = ts.map(jsDocTagNames, tagName => { return { @@ -268,6 +273,7 @@ export function getJSDocTagCompletions(): ts.CompletionEntry[] { })); } +/** @internal */ export function getJSDocTagCompletionDetails(name: string): ts.CompletionEntryDetails { return { name, @@ -280,6 +286,7 @@ export function getJSDocTagCompletionDetails(name: string): ts.CompletionEntryDe }; } +/** @internal */ export function getJSDocParameterNameCompletions(tag: ts.JSDocParameterTag): ts.CompletionEntry[] { if (!ts.isIdentifier(tag.name)) { return ts.emptyArray; @@ -302,6 +309,7 @@ export function getJSDocParameterNameCompletions(tag: ts.JSDocParameterTag): ts. }); } +/** @internal */ export function getJSDocParameterNameCompletionDetails(name: string): ts.CompletionEntryDetails { return { name, @@ -314,6 +322,7 @@ export function getJSDocParameterNameCompletionDetails(name: string): ts.Complet }; } +/** @internal */ /** * Checks if position points to a valid position to add JSDoc comments, and if so, * returns the appropriate template. Otherwise returns an empty string. @@ -509,4 +518,3 @@ function getRightHandSideOfAssignment(rightHandSide: ts.Expression): ts.Function return ts.find((rightHandSide as ts.ClassExpression).members, ts.isConstructorDeclaration); } } -} diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index c3a467798cb63..91389e873c790 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.NavigateTo { +import * as ts from "./_namespaces/ts"; + interface RawNavigateToItem { readonly name: string; readonly fileName: string; @@ -8,6 +8,7 @@ interface RawNavigateToItem { readonly declaration: ts.Declaration; } +/** @internal */ export function getNavigateToItems(sourceFiles: readonly ts.SourceFile[], checker: ts.TypeChecker, cancellationToken: ts.CancellationToken, searchValue: string, maxResultCount: number | undefined, excludeDtsFiles: boolean): ts.NavigateToItem[] { const patternMatcher = ts.createPatternMatcher(searchValue); if (!patternMatcher) return ts.emptyArray; @@ -133,4 +134,3 @@ function createNavigateToItem(rawItem: RawNavigateToItem): ts.NavigateToItem { containerKind: containerName ? ts.getNodeKind(container) : ts.ScriptElementKind.unknown, }; } -} diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 319a5859245df..8554bd1d1fa98 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.NavigationBar { +import * as ts from "./_namespaces/ts"; + /** * Matches all whitespace characters in a string. Eg: * @@ -52,6 +52,7 @@ interface NavigationBarNode { indent: number; // # of parents } +/** @internal */ export function getNavigationBarItems(sourceFile: ts.SourceFile, cancellationToken: ts.CancellationToken): ts.NavigationBarItem[] { curCancellationToken = cancellationToken; curSourceFile = sourceFile; @@ -63,6 +64,7 @@ export function getNavigationBarItems(sourceFile: ts.SourceFile, cancellationTok } } +/** @internal */ export function getNavigationTree(sourceFile: ts.SourceFile, cancellationToken: ts.CancellationToken): ts.NavigationTree { curCancellationToken = cancellationToken; curSourceFile = sourceFile; @@ -983,4 +985,3 @@ function cleanText(text: string): string { // \u2029 - Paragraph separator return text.replace(/\\?(\r?\n|\r|\u2028|\u2029)/g, ""); } -} diff --git a/src/services/organizeImports.ts b/src/services/organizeImports.ts index 4f4132fb530c9..469b608585def 100644 --- a/src/services/organizeImports.ts +++ b/src/services/organizeImports.ts @@ -1,6 +1,6 @@ -/* @internal */ -namespace ts.OrganizeImports { +import * as ts from "./_namespaces/ts"; +/** @internal */ /** * Organize imports by: * 1) Removing unused imports @@ -234,6 +234,7 @@ function getExternalModuleName(specifier: ts.Expression) { } // Internal for testing +/** @internal */ /** * @param importGroup a list of ImportDeclarations, all with the same module name. */ @@ -374,6 +375,7 @@ function getCategorizedImports(importGroup: readonly ts.ImportDeclaration[]) { } // Internal for testing +/** @internal */ /** * @param exportGroup a list of ExportDeclarations, all with the same module name. */ @@ -465,6 +467,7 @@ function sortSpecifiers(specifiers: readon return ts.stableSort(specifiers, compareImportOrExportSpecifiers); } +/** @internal */ export function compareImportOrExportSpecifiers(s1: T, s2: T) { return ts.compareBooleans(s1.isTypeOnly, s2.isTypeOnly) || compareIdentifiers(s1.propertyName || s1.name, s2.propertyName || s2.name) @@ -472,6 +475,7 @@ export function compareImportOrExportSpecifiers { return ts.arrayIsSorted(imports, compareImportsOrRequireStatements); } +/** @internal */ export function importSpecifiersAreSorted(imports: readonly ts.ImportSpecifier[]): imports is ts.SortedReadonlyArray { return ts.arrayIsSorted(imports, compareImportOrExportSpecifiers); } +/** @internal */ export function getImportDeclarationInsertionIndex(sortedImports: ts.SortedReadonlyArray, newImport: ts.AnyImportOrRequireStatement) { const index = ts.binarySearch(sortedImports, newImport, ts.identity, compareImportsOrRequireStatements); return index < 0 ? ~index : index; } +/** @internal */ export function getImportSpecifierInsertionIndex(sortedImports: ts.SortedReadonlyArray, newImport: ts.ImportSpecifier) { const index = ts.binarySearch(sortedImports, newImport, ts.identity, compareImportOrExportSpecifiers); return index < 0 ? ~index : index; } +/** @internal */ export function compareImportsOrRequireStatements(s1: ts.AnyImportOrRequireStatement, s2: ts.AnyImportOrRequireStatement) { return compareModuleSpecifiers(getModuleSpecifierExpression(s1), getModuleSpecifierExpression(s2)) || compareImportKind(s1, s2); } @@ -558,4 +567,3 @@ function tryGetNamedBindingElements(namedImport: ts.ImportDeclaration) { ? namedImport.importClause.namedBindings.elements : undefined; } -} diff --git a/src/services/outliningElementsCollector.ts b/src/services/outliningElementsCollector.ts index ecb0860334a69..406bd6e747562 100644 --- a/src/services/outliningElementsCollector.ts +++ b/src/services/outliningElementsCollector.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts.OutliningElementsCollector { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export function collectElements(sourceFile: ts.SourceFile, cancellationToken: ts.CancellationToken): ts.OutliningSpan[] { const res: ts.OutliningSpan[] = []; addNodeOutliningSpans(sourceFile, cancellationToken, res); @@ -341,4 +342,3 @@ function tryGetFunctionOpenToken(node: ts.SignatureDeclaration, body: ts.Block, } return ts.findChildOfKind(body, ts.SyntaxKind.OpenBraceToken, sourceFile); } -} diff --git a/src/services/patternMatcher.ts b/src/services/patternMatcher.ts index 930ad79299990..179826818136c 100644 --- a/src/services/patternMatcher.ts +++ b/src/services/patternMatcher.ts @@ -1,6 +1,7 @@ -/* @internal */ -namespace ts { +import * as ts from "./_namespaces/ts"; + // Note(cyrusn): this enum is ordered from strongest match type to weakest match type. +/** @internal */ export enum PatternMatchKind { exact, prefix, @@ -10,6 +11,7 @@ export enum PatternMatchKind { // Information about a match made by the pattern matcher between a candidate and the // search pattern. +/** @internal */ export interface PatternMatch { // What kind of match this was. Exact matches are better than prefix matches which are // better than substring matches which are better than CamelCase matches. @@ -24,6 +26,7 @@ export interface PatternMatch { // The pattern matcher maintains an internal cache of information as it is used. Therefore, // you should not keep it around forever and should get and release the matcher appropriately // once you no longer need it. +/** @internal */ export interface PatternMatcher { // Used to match a candidate against the last segment of a possibly dotted pattern. This // is useful as a quick check to prevent having to compute a container before calling @@ -97,6 +100,7 @@ function createPatternMatch(kind: PatternMatchKind, isCaseSensitive: boolean): P }; } +/** @internal */ export function createPatternMatcher(pattern: string): PatternMatcher | undefined { // We'll often see the same candidate string many times when searching (For example, when // we see the name of a module that is used everywhere, or the name of an overload). As @@ -461,10 +465,12 @@ function createTextChunk(text: string): TextChunk { }; } +/** @internal */ export function breakIntoCharacterSpans(identifier: string): ts.TextSpan[] { return breakIntoSpans(identifier, /*word:*/ false); } +/** @internal */ export function breakIntoWordSpans(identifier: string): ts.TextSpan[] { return breakIntoSpans(identifier, /*word:*/ true); } @@ -590,4 +596,3 @@ function everyInRange(start: number, end: number, pred: (n: number) => boolean): function every(s: string, pred: (ch: number, index: number) => boolean, start = 0, end = s.length): boolean { return everyInRange(start, end, i => pred(s.charCodeAt(i), i)); } -} diff --git a/src/services/preProcess.ts b/src/services/preProcess.ts index bb0e230992bf1..960375d3f1d1c 100644 --- a/src/services/preProcess.ts +++ b/src/services/preProcess.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + export function preProcessFile(sourceText: string, readImportFiles = true, detectJavaScriptImports = false): ts.PreProcessedFileInfo { const pragmaContext: ts.PragmaContext = { languageVersion: ts.ScriptTarget.ES5, // controls whether the token scanner considers unicode identifiers or not - shouldn't matter, since we're only using it for trivia @@ -432,4 +433,3 @@ export function preProcessFile(sourceText: string, readImportFiles = true, detec return { referencedFiles: pragmaContext.referencedFiles, typeReferenceDirectives: pragmaContext.typeReferenceDirectives, libReferenceDirectives: pragmaContext.libReferenceDirectives, importedFiles, isLibFile: !!pragmaContext.hasNoDefaultLib, ambientExternalModules: ambientModuleNames }; } } -} diff --git a/src/services/refactorProvider.ts b/src/services/refactorProvider.ts index f90b56eb84107..c8045abf28b59 100644 --- a/src/services/refactorProvider.ts +++ b/src/services/refactorProvider.ts @@ -1,14 +1,16 @@ -/* @internal */ -namespace ts.refactor { +import * as ts from "./_namespaces/ts"; + // A map with the refactor code as key, the refactor itself as value // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want const refactors = new ts.Map(); +/** @internal */ /** @param name An unique code associated with each refactor. Does not have to be human-readable. */ export function registerRefactor(name: string, refactor: ts.Refactor) { refactors.set(name, refactor); } +/** @internal */ export function getApplicableRefactors(context: ts.RefactorContext): ts.ApplicableRefactorInfo[] { return ts.arrayFrom(ts.flatMapIterator(refactors.values(), refactor => context.cancellationToken && context.cancellationToken.isCancellationRequested() || @@ -16,8 +18,8 @@ export function getApplicableRefactors(context: ts.RefactorContext): ts.Applicab refactor.getAvailableActions(context))); } +/** @internal */ export function getEditsForRefactor(context: ts.RefactorContext, refactorName: string, actionName: string): ts.RefactorEditInfo | undefined { const refactor = refactors.get(refactorName); return refactor && refactor.getEditsForAction(context, actionName); } -} diff --git a/src/services/refactors/addOrRemoveBracesToArrowFunction.ts b/src/services/refactors/addOrRemoveBracesToArrowFunction.ts index eaca581557bfe..63edc5a6c75c4 100644 --- a/src/services/refactors/addOrRemoveBracesToArrowFunction.ts +++ b/src/services/refactors/addOrRemoveBracesToArrowFunction.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.refactor.addOrRemoveBracesToArrowFunction { +import * as ts from "../_namespaces/ts"; + const refactorName = "Add or remove braces in an arrow function"; const refactorDescription = ts.Diagnostics.Add_or_remove_braces_in_an_arrow_function.message; @@ -118,4 +118,3 @@ function getConvertibleArrowFunctionAtPosition(file: ts.SourceFile, startPositio } return undefined; } -} diff --git a/src/services/refactors/convertArrowFunctionOrFunctionExpression.ts b/src/services/refactors/convertArrowFunctionOrFunctionExpression.ts index 7ceb67cde20a1..1a17f45015675 100644 --- a/src/services/refactors/convertArrowFunctionOrFunctionExpression.ts +++ b/src/services/refactors/convertArrowFunctionOrFunctionExpression.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.refactor.convertArrowFunctionOrFunctionExpression { +import * as ts from "../_namespaces/ts"; + const refactorName = "Convert arrow function or function expression"; const refactorDescription = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_arrow_function_or_function_expression); @@ -255,4 +255,3 @@ function canBeConvertedToExpression(body: ts.Block, head: ts.Statement): head is function isFunctionReferencedInFile(sourceFile: ts.SourceFile, typeChecker: ts.TypeChecker, node: ts.FunctionExpression): boolean { return !!node.name && ts.FindAllReferences.Core.isSymbolReferencedInFile(node.name, typeChecker, sourceFile); } -} diff --git a/src/services/refactors/convertExport.ts b/src/services/refactors/convertExport.ts index 75a0678157e69..87fb81b59820a 100644 --- a/src/services/refactors/convertExport.ts +++ b/src/services/refactors/convertExport.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.refactor { +import * as ts from "../_namespaces/ts"; + const refactorName = "Convert export"; const defaultToNamedAction = { @@ -274,4 +274,3 @@ function getExportingModuleSymbol(node: ts.Node, checker: ts.TypeChecker) { } return symbol; } -} diff --git a/src/services/refactors/convertImport.ts b/src/services/refactors/convertImport.ts index 142297ae7bc31..1f744eb721532 100644 --- a/src/services/refactors/convertImport.ts +++ b/src/services/refactors/convertImport.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.refactor { +import * as ts from "../_namespaces/ts"; + const refactorName = "Convert import"; const actions = { @@ -156,6 +156,7 @@ function getLeftOfPropertyAccessOrQualifiedName(propertyAccessOrQualifiedName: t return ts.isPropertyAccessExpression(propertyAccessOrQualifiedName) ? propertyAccessOrQualifiedName.expression : propertyAccessOrQualifiedName.left; } +/** @internal */ export function doChangeNamedToNamespaceOrDefault(sourceFile: ts.SourceFile, program: ts.Program, changes: ts.textChanges.ChangeTracker, toConvert: ts.NamedImports, shouldUseDefault = getShouldUseDefault(program, toConvert.parent)): void { const checker = program.getTypeChecker(); const importDecl = toConvert.parent.parent; @@ -229,4 +230,3 @@ function updateImport(old: ts.ImportDeclaration, defaultImportName: ts.Identifie return ts.factory.createImportDeclaration(/*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, defaultImportName, elements && elements.length ? ts.factory.createNamedImports(elements) : undefined), old.moduleSpecifier, /*assertClause*/ undefined); } -} diff --git a/src/services/refactors/convertOverloadListToSingleSignature.ts b/src/services/refactors/convertOverloadListToSingleSignature.ts index 20eeda7500a3e..76617e69222f8 100644 --- a/src/services/refactors/convertOverloadListToSingleSignature.ts +++ b/src/services/refactors/convertOverloadListToSingleSignature.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.refactor.addOrRemoveBracesToArrowFunction { +import * as ts from "../_namespaces/ts"; + const refactorName = "Convert overload list to single signature"; const refactorDescription = ts.Diagnostics.Convert_overload_list_to_single_signature.message; @@ -223,4 +223,3 @@ function getConvertableOverloadListAtPosition(file: ts.SourceFile, startPosition return signatureDecls; } -} diff --git a/src/services/refactors/convertParamsToDestructuredObject.ts b/src/services/refactors/convertParamsToDestructuredObject.ts index e7488688a9a3d..ef50dda564c10 100644 --- a/src/services/refactors/convertParamsToDestructuredObject.ts +++ b/src/services/refactors/convertParamsToDestructuredObject.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.refactor.convertParamsToDestructuredObject { +import * as ts from "../_namespaces/ts"; + const refactorName = "Convert parameters to destructured object"; const minimumParameterLength = 1; const refactorDescription = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_parameters_to_destructured_object); @@ -667,4 +667,3 @@ interface ClassReferences { accessExpressions: ts.Node[]; typeUsages: ts.Node[]; } -} diff --git a/src/services/refactors/convertStringOrTemplateLiteral.ts b/src/services/refactors/convertStringOrTemplateLiteral.ts index f7e7e47cb3533..0aac4ad28febf 100644 --- a/src/services/refactors/convertStringOrTemplateLiteral.ts +++ b/src/services/refactors/convertStringOrTemplateLiteral.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.refactor.convertStringOrTemplateLiteral { +import * as ts from "../_namespaces/ts"; + const refactorName = "Convert to template string"; const refactorDescription = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_template_string); @@ -248,4 +248,3 @@ function getExpressionFromParenthesesOrExpression(node: ts.Expression) { } return node; } -} diff --git a/src/services/refactors/convertToOptionalChainExpression.ts b/src/services/refactors/convertToOptionalChainExpression.ts index 9a59047f8306e..4845367702010 100644 --- a/src/services/refactors/convertToOptionalChainExpression.ts +++ b/src/services/refactors/convertToOptionalChainExpression.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.refactor.convertToOptionalChainExpression { +import * as ts from "../_namespaces/ts"; + const refactorName = "Convert to optional chain expression"; const convertToOptionalChainExpressionMessage = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_optional_chain_expression); @@ -297,4 +297,3 @@ function doChange(sourceFile: ts.SourceFile, checker: ts.TypeChecker, changes: t } } } -} diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 3aba22360d269..4470114e796bf 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.refactor.extractSymbol { +import * as ts from "../_namespaces/ts"; + const refactorName = "Extract Symbol"; const extractConstantAction = { @@ -21,6 +21,7 @@ ts.refactor.registerRefactor(refactorName, { getAvailableActions: getRefactorActionsToExtractSymbol, }); +/** @internal */ /** * Compute the associated code actions * Exported for tests. @@ -168,6 +169,7 @@ export function getRefactorActionsToExtractSymbol(context: ts.RefactorContext): } /* Exported for tests */ +/** @internal */ export function getRefactorEditsToExtractSymbol(context: ts.RefactorContext, actionName: string): ts.RefactorEditInfo | undefined { const rangeToExtract = getRangeToExtract(context.file, ts.getRefactorContextSpan(context)); const targetRange = rangeToExtract.targetRange!; // TODO:GH#18217 @@ -190,6 +192,7 @@ export function getRefactorEditsToExtractSymbol(context: ts.RefactorContext, act } // Move these into diagnostic messages if they become user-facing +/** @internal */ export namespace Messages { function createMessage(message: string): ts.DiagnosticMessage { return { message, code: 0, category: ts.DiagnosticCategory.Message, key: message }; @@ -261,6 +264,7 @@ type RangeToExtract = { */ type Scope = ts.FunctionLikeDeclaration | ts.SourceFile | ts.ModuleBlock | ts.ClassLikeDeclaration; +/** @internal */ /** * getRangeToExtract takes a span inside a text file and returns either an expression or an array * of statements representing the minimum set of nodes needed to extract the entire span. This @@ -2048,4 +2052,3 @@ function isInJSXContent(node: ts.Node) { function isStringLiteralJsxAttribute(node: ts.Node): node is ts.StringLiteral { return ts.isStringLiteral(node) && node.parent && ts.isJsxAttribute(node.parent); } -} diff --git a/src/services/refactors/extractType.ts b/src/services/refactors/extractType.ts index 4dea9ddfe3a15..fa44567a61798 100644 --- a/src/services/refactors/extractType.ts +++ b/src/services/refactors/extractType.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.refactor { +import * as ts from "../_namespaces/ts"; + const refactorName = "Extract type"; const extractToTypeAliasAction = { @@ -249,4 +249,3 @@ function doTypedefChange(changes: ts.textChanges.ChangeTracker, file: ts.SourceF changes.insertNodeBefore(file, firstStatement, ts.factory.createJSDocComment(/* comment */ undefined, ts.factory.createNodeArray(ts.concatenate(templates, [node]))), /* blankLineBetween */ true); changes.replaceNode(file, selection, ts.factory.createTypeReferenceNode(name, typeParameters.map(id => ts.factory.createTypeReferenceNode(id.name, /* typeArguments */ undefined)))); } -} diff --git a/src/services/refactors/generateGetAccessorAndSetAccessor.ts b/src/services/refactors/generateGetAccessorAndSetAccessor.ts index e822c9c132f84..b3559d1d3a242 100644 --- a/src/services/refactors/generateGetAccessorAndSetAccessor.ts +++ b/src/services/refactors/generateGetAccessorAndSetAccessor.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.refactor.generateGetAccessorAndSetAccessor { +import * as ts from "../_namespaces/ts"; + const actionName = "Generate 'get' and 'set' accessors"; const actionDescription = ts.Diagnostics.Generate_get_and_set_accessors.message; @@ -48,4 +48,3 @@ ts.refactor.registerRefactor(actionName, { return ts.emptyArray; } }); -} diff --git a/src/services/refactors/helpers.ts b/src/services/refactors/helpers.ts index dc1cbdcf32a2b..24ffc608fa727 100644 --- a/src/services/refactors/helpers.ts +++ b/src/services/refactors/helpers.ts @@ -1,5 +1,4 @@ -/* @internal */ -namespace ts.refactor { +/** @internal */ /** * Returned by refactor functions when some error message needs to be surfaced to users. */ @@ -7,6 +6,7 @@ export interface RefactorErrorInfo { error: string; } +/** @internal */ /** * Checks if some refactor info has refactor error info. */ @@ -14,6 +14,7 @@ export function isRefactorErrorInfo(info: unknown): info is RefactorErrorInfo { return (info as RefactorErrorInfo).error !== undefined; } +/** @internal */ /** * Checks if string "known" begins with string "requested". * Used to match requested kinds with a known kind. @@ -22,4 +23,3 @@ export function refactorKindBeginsWith(known: string, requested: string | undefi if(!requested) return true; return known.substr(0, requested.length) === requested; } -} diff --git a/src/services/refactors/inferFunctionReturnType.ts b/src/services/refactors/inferFunctionReturnType.ts index 70d8f6e288dfc..ca1989188a925 100644 --- a/src/services/refactors/inferFunctionReturnType.ts +++ b/src/services/refactors/inferFunctionReturnType.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.refactor.inferFunctionReturnType { +import * as ts from "../_namespaces/ts"; + const refactorName = "Infer function return type"; const refactorDescription = ts.Diagnostics.Infer_function_return_type.message; @@ -114,4 +114,3 @@ function tryGetReturnType(typeChecker: ts.TypeChecker, node: ConvertibleDeclarat return typeChecker.getReturnTypeOfSignature(signature); } } -} diff --git a/src/services/refactors/moveToNewFile.ts b/src/services/refactors/moveToNewFile.ts index e65c332b825b9..09cb56a8ca2b4 100644 --- a/src/services/refactors/moveToNewFile.ts +++ b/src/services/refactors/moveToNewFile.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.refactor { +import * as ts from "../_namespaces/ts"; + const refactorName = "Move to a new file"; const description = ts.getLocaleSpecificMessage(ts.Diagnostics.Move_to_a_new_file); @@ -850,4 +850,3 @@ function createExportAssignment(name: string): ts.Statement { ts.SyntaxKind.EqualsToken, ts.factory.createIdentifier(name))); } -} diff --git a/src/services/rename.ts b/src/services/rename.ts index 45b77b9ee00bf..0ff1d52d9d34e 100644 --- a/src/services/rename.ts +++ b/src/services/rename.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts.Rename { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export function getRenameInfo(program: ts.Program, sourceFile: ts.SourceFile, position: number, preferences: ts.UserPreferences): ts.RenameInfo { const node = ts.getAdjustedRenameLocation(ts.getTouchingPropertyName(sourceFile, position)); if (nodeIsEligibleForRename(node)) { @@ -171,6 +172,7 @@ function createTriggerSpanForNode(node: ts.Node, sourceFile: ts.SourceFile) { return ts.createTextSpan(start, width); } +/** @internal */ export function nodeIsEligibleForRename(node: ts.Node): boolean { switch (node.kind) { case ts.SyntaxKind.Identifier: @@ -185,4 +187,3 @@ export function nodeIsEligibleForRename(node: ts.Node): boolean { return false; } } -} diff --git a/src/services/services.ts b/src/services/services.ts index 3168a2263a74e..42861b04adb65 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + /** The version of the language service API */ export const servicesVersion = "0.8"; @@ -2872,4 +2873,3 @@ export function getDefaultLibFilePath(options: ts.CompilerOptions): string { } ts.setObjectAllocator(getServicesObjectAllocator()); -} diff --git a/src/services/shims.ts b/src/services/shims.ts index 6ba8dea0c5422..d4de66db93b3c 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -1,3 +1,5 @@ +import * as ts from "./_namespaces/ts"; + // // Copyright (c) Microsoft Corporation. All rights reserved. // @@ -21,8 +23,6 @@ let debugObjectHost: { CollectGarbage(): void } = (function (this: any) { // esl // We need to use 'null' to interface with the managed side. /* eslint-disable local/no-in-operator */ -/* @internal */ -namespace ts { interface DiscoverTypingsInfo { fileNames: string[]; // The file names that belong to the same project. projectRootPath: string; // The path to the project root directory @@ -34,6 +34,7 @@ interface DiscoverTypingsInfo { typesRegistry: ts.ReadonlyESMap>; // The map of available typings in npm to maps of TS versions to their latest supported versions } +/** @internal */ export interface ScriptSnapshotShim { /** Gets a portion of the script snapshot specified by [start, end). */ getText(start: number, end: number): string; @@ -53,12 +54,14 @@ export interface ScriptSnapshotShim { dispose?(): void; } +/** @internal */ export interface Logger { log(s: string): void; trace(s: string): void; error(s: string): void; } +/** @internal */ /** Public interface of the host of a language service shim instance. */ export interface LanguageServiceShimHost extends Logger { getCompilationSettings(): string; @@ -87,6 +90,7 @@ export interface LanguageServiceShimHost extends Logger { directoryExists(directoryName: string): boolean; } +/** @internal */ /** Public interface of the core-services host instance used in managed side */ export interface CoreServicesShimHost extends Logger { directoryExists(directoryName: string): boolean; @@ -116,22 +120,26 @@ export interface CoreServicesShimHost extends Logger { /// // Note: This is being using by the host (VS) and is marshaled back and forth. // When changing this make sure the changes are reflected in the managed side as well +/** @internal */ export interface ShimsFileReference { path: string; position: number; length: number; } +/** @internal */ /** Public interface of a language service instance shim. */ export interface ShimFactory { registerShim(shim: Shim): void; unregisterShim(shim: Shim): void; } +/** @internal */ export interface Shim { dispose(_dummy: {}): void; } +/** @internal */ export interface LanguageServiceShim extends Shim { languageService: ts.LanguageService; @@ -292,11 +300,13 @@ export interface LanguageServiceShim extends Shim { uncommentSelection(fileName: string, textChange: ts.TextRange): string; } +/** @internal */ export interface ClassifierShim extends Shim { getEncodedLexicalClassifications(text: string, lexState: ts.EndOfLineState, syntacticClassifierAbsent?: boolean): string; getClassificationsForLine(text: string, lexState: ts.EndOfLineState, syntacticClassifierAbsent?: boolean): string; } +/** @internal */ export interface CoreServicesShim extends Shim { getAutomaticTypeDirectiveNames(compilerOptionsJson: string): string; getPreProcessedFileInfo(fileName: string, sourceText: ts.IScriptSnapshot): string; @@ -346,6 +356,7 @@ class ScriptSnapshotShimAdapter implements ts.IScriptSnapshot { } } +/** @internal */ export class LanguageServiceShimHostAdapter implements ts.LanguageServiceHost { private loggingEnabled = false; private tracingEnabled = false; @@ -505,6 +516,7 @@ export class LanguageServiceShimHostAdapter implements ts.LanguageServiceHost { } } +/** @internal */ export class CoreServicesShimHostAdapter implements ts.ParseConfigHost, ts.ModuleResolutionHost, ts.JsTyping.TypingResolutionHost { public directoryExists: (directoryName: string) => boolean; @@ -607,6 +619,7 @@ class ShimBase implements Shim { } } +/** @internal */ export interface RealizedDiagnostic { message: string; start: number; @@ -616,6 +629,7 @@ export interface RealizedDiagnostic { reportsUnnecessary?: {}; reportsDeprecated?: {}; } +/** @internal */ export function realizeDiagnostics(diagnostics: readonly ts.Diagnostic[], newLine: string): RealizedDiagnostic[] { return diagnostics.map(d => realizeDiagnostic(d, newLine)); } @@ -1287,6 +1301,7 @@ class CoreServicesShimObject extends ShimBase implements CoreServicesShim { } } +/** @internal */ export class TypeScriptServicesFactory implements ShimFactory { private _shims: Shim[] = []; private documentRegistry: ts.DocumentRegistry | undefined; @@ -1355,6 +1370,5 @@ export class TypeScriptServicesFactory implements ShimFactory { throw new Error("Invalid operation"); } } -} /* eslint-enable local/no-in-operator */ diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 631a28dc35776..70d33a34a5478 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.SignatureHelp { +import * as ts from "./_namespaces/ts"; + const enum InvocationKind { Call, TypeArgs, Contextual } interface CallInvocation { readonly kind: InvocationKind.Call; readonly node: ts.CallLikeExpression; } interface TypeArgsInvocation { readonly kind: InvocationKind.TypeArgs; readonly called: ts.Identifier; } @@ -20,6 +20,7 @@ interface ArgumentListInfo { readonly argumentCount: number; } +/** @internal */ export function getSignatureHelpItems(program: ts.Program, sourceFile: ts.SourceFile, position: number, triggerReason: ts.SignatureHelpTriggerReason | undefined, cancellationToken: ts.CancellationToken): ts.SignatureHelpItems | undefined { const typeChecker = program.getTypeChecker(); @@ -158,11 +159,13 @@ function containsPrecedingToken(startingToken: ts.Node, sourceFile: ts.SourceFil return ts.Debug.fail("Could not find preceding token"); } +/** @internal */ export interface ArgumentInfoForCompletions { readonly invocation: ts.CallLikeExpression; readonly argumentIndex: number; readonly argumentCount: number; } +/** @internal */ export function getArgumentInfoForCompletions(node: ts.Node, position: number, sourceFile: ts.SourceFile): ArgumentInfoForCompletions | undefined { const info = getImmediatelyContainingArgumentInfo(node, position, sourceFile); return !info || info.isTypeParameterList || info.invocation.kind !== InvocationKind.Call ? undefined @@ -663,4 +666,3 @@ function createSignatureHelpParameterForTypeParameter(typeParameter: ts.TypePara }); return { name: typeParameter.symbol.name, documentation: typeParameter.symbol.getDocumentationComment(checker), displayParts, isOptional: false, isRest: false }; } -} diff --git a/src/services/smartSelection.ts b/src/services/smartSelection.ts index fdcf6d4d47c00..d1476ecb36b4e 100644 --- a/src/services/smartSelection.ts +++ b/src/services/smartSelection.ts @@ -1,5 +1,6 @@ -/* @internal */ -namespace ts.SmartSelectionRange { +import * as ts from "./_namespaces/ts"; + +/** @internal */ export function getSmartSelectionRange(pos: number, sourceFile: ts.SourceFile): ts.SelectionRange { let selectionRange: ts.SelectionRange = { textSpan: ts.createTextSpanFromBounds(sourceFile.getFullStart(), sourceFile.getEnd()) @@ -317,4 +318,3 @@ function getEndPos(sourceFile: ts.SourceFile, node: ts.Node): number { return node.getEnd(); } } -} diff --git a/src/services/sourcemaps.ts b/src/services/sourcemaps.ts index d42c79a4af940..1a88018867a95 100644 --- a/src/services/sourcemaps.ts +++ b/src/services/sourcemaps.ts @@ -1,7 +1,8 @@ -/* @internal */ -namespace ts { +import * as ts from "./_namespaces/ts"; + const base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; +/** @internal */ export interface SourceMapper { toLineColumnOffset(fileName: string, position: number): ts.LineAndCharacter; tryGetSourcePosition(info: ts.DocumentPosition): ts.DocumentPosition | undefined; @@ -9,6 +10,7 @@ export interface SourceMapper { clearCache(): void; } +/** @internal */ export interface SourceMapperHost { useCaseSensitiveFileNames(): boolean; getCurrentDirectory(): string; @@ -20,6 +22,7 @@ export interface SourceMapperHost { log(s: string): void; } +/** @internal */ export function getSourceMapper(host: SourceMapperHost): SourceMapper { const getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); const currentDirectory = host.getCurrentDirectory(); @@ -132,12 +135,14 @@ export function getSourceMapper(host: SourceMapperHost): SourceMapper { } } +/** @internal */ /** * string | undefined to contents of map file to create DocumentPositionMapper from it * DocumentPositionMapper | false to give back cached DocumentPositionMapper */ export type ReadMapFile = (mapFileName: string, mapFileNameFromDts: string | undefined) => string | undefined | ts.DocumentPositionMapper | false; +/** @internal */ export function getDocumentPositionMapper( host: ts.DocumentPositionMapperHost, generatedFileName: string, @@ -196,4 +201,3 @@ function createSourceFileLike(text: string, lineMap?: ts.SourceFileLike["lineMap } }; } -} diff --git a/src/services/stringCompletions.ts b/src/services/stringCompletions.ts index a542d8e0bd1f8..acaed2f724190 100644 --- a/src/services/stringCompletions.ts +++ b/src/services/stringCompletions.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts.Completions.StringCompletions { +import * as ts from "./_namespaces/ts"; + interface NameAndKindSet { add(value: NameAndKind): void; has(name: string): boolean; @@ -25,6 +25,7 @@ function createNameAndKindSet(): NameAndKindSet { }; } +/** @internal */ export function getStringLiteralCompletions( sourceFile: ts.SourceFile, position: number, @@ -98,6 +99,7 @@ function convertStringLiteralCompletions( } } +/** @internal */ export function getStringLiteralCompletionDetails(name: string, sourceFile: ts.SourceFile, position: number, contextToken: ts.Node | undefined, checker: ts.TypeChecker, options: ts.CompilerOptions, host: ts.LanguageServiceHost, cancellationToken: ts.CancellationToken, preferences: ts.UserPreferences) { if (!contextToken || !ts.isStringLiteralLike(contextToken)) return undefined; const completions = getStringLiteralCompletionEntries(sourceFile, contextToken, position, checker, options, host, preferences); @@ -992,4 +994,3 @@ function isRequireCallArgument(node: ts.Node) { return ts.isCallExpression(node.parent) && ts.firstOrUndefined(node.parent.arguments) === node && ts.isIdentifier(node.parent.expression) && node.parent.expression.escapedText === "require"; } -} diff --git a/src/services/suggestionDiagnostics.ts b/src/services/suggestionDiagnostics.ts index 7f0e7db9004f2..1b16f19e6c553 100644 --- a/src/services/suggestionDiagnostics.ts +++ b/src/services/suggestionDiagnostics.ts @@ -1,7 +1,8 @@ -/* @internal */ -namespace ts { +import * as ts from "./_namespaces/ts"; + const visitedNestedConvertibleFunctions = new ts.Map(); +/** @internal */ export function computeSuggestionDiagnostics(sourceFile: ts.SourceFile, program: ts.Program, cancellationToken: ts.CancellationToken): ts.DiagnosticWithLocation[] { program.getSemanticDiagnostics(sourceFile, cancellationToken); const diags: ts.DiagnosticWithLocation[] = []; @@ -120,6 +121,7 @@ function isConvertibleFunction(node: ts.FunctionLikeDeclaration, checker: ts.Typ returnsPromise(node, checker); } +/** @internal */ export function returnsPromise(node: ts.FunctionLikeDeclaration, checker: ts.TypeChecker): boolean { const signature = checker.getSignatureFromDeclaration(node); const returnType = signature ? checker.getReturnTypeOfSignature(signature) : undefined; @@ -134,11 +136,13 @@ function hasReturnStatementWithPromiseHandler(body: ts.Block, checker: ts.TypeCh return !!ts.forEachReturnStatement(body, statement => isReturnStatementWithFixablePromiseHandler(statement, checker)); } +/** @internal */ export function isReturnStatementWithFixablePromiseHandler(node: ts.Node, checker: ts.TypeChecker): node is ts.ReturnStatement & { expression: ts.CallExpression } { return ts.isReturnStatement(node) && !!node.expression && isFixablePromiseHandler(node.expression, checker); } // Should be kept up to date with transformExpression in convertToAsyncFunction.ts +/** @internal */ export function isFixablePromiseHandler(node: ts.Node, checker: ts.TypeChecker): boolean { // ensure outermost call exists and is a promise handler if (!isPromiseHandler(node) || !hasSupportedNumberOfArguments(node) || !node.arguments.every(arg => isFixablePromiseArgument(arg, checker))) { @@ -228,6 +232,7 @@ function canBeConvertedToClass(node: ts.Node, checker: ts.TypeChecker): boolean return false; } +/** @internal */ export function canBeConvertedToAsync(node: ts.Node): node is ts.FunctionDeclaration | ts.MethodDeclaration | ts.FunctionExpression | ts.ArrowFunction { switch (node.kind) { case ts.SyntaxKind.FunctionDeclaration: @@ -239,4 +244,3 @@ export function canBeConvertedToAsync(node: ts.Node): node is ts.FunctionDeclara return false; } } -} diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index fb7002164c4be..23408dcae270e 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -1,8 +1,9 @@ -/* @internal */ -namespace ts.SymbolDisplay { +import * as ts from "./_namespaces/ts"; + const symbolDisplayNodeBuilderFlags = ts.NodeBuilderFlags.OmitParameterModifiers | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.UseAliasDefinedOutsideCurrentScope; // TODO(drosen): use contextual SemanticMeaning. +/** @internal */ export function getSymbolKind(typeChecker: ts.TypeChecker, symbol: ts.Symbol, location: ts.Node): ts.ScriptElementKind { const result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); if (result !== ts.ScriptElementKind.unknown) { @@ -108,6 +109,7 @@ function getNormalizedSymbolModifiers(symbol: ts.Symbol) { return []; } +/** @internal */ export function getSymbolModifiers(typeChecker: ts.TypeChecker, symbol: ts.Symbol): string { if (!symbol) { return ts.ScriptElementKindModifier.none; @@ -136,6 +138,7 @@ interface SymbolDisplayPartsDocumentationAndSymbolKind { } // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location +/** @internal */ export function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker: ts.TypeChecker, symbol: ts.Symbol, sourceFile: ts.SourceFile, enclosingDeclaration: ts.Node | undefined, location: ts.Node, semanticMeaning = ts.getMeaningFromLocation(location), alias?: ts.Symbol): SymbolDisplayPartsDocumentationAndSymbolKind { const displayParts: ts.SymbolDisplayPart[] = []; @@ -766,4 +769,3 @@ function isLocalVariableOrFunction(symbol: ts.Symbol) { return true; }); } -} diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index 7d9efe5020a22..06904686618c2 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -1,5 +1,4 @@ -/* @internal */ -namespace ts.textChanges { +import * as ts from "./_namespaces/ts"; /** * Currently for simplicity we store recovered positions on the node itself. @@ -27,13 +26,16 @@ function setEnd(n: ts.TextRange, end: number): void { (n as any).__end = end; } +/** @internal */ export interface ConfigurableStart { leadingTriviaOption?: LeadingTriviaOption; } +/** @internal */ export interface ConfigurableEnd { trailingTriviaOption?: TrailingTriviaOption; } +/** @internal */ export enum LeadingTriviaOption { /** Exclude all leading trivia (use getStart()) */ Exclude, @@ -53,6 +55,7 @@ export enum LeadingTriviaOption { StartLine, } +/** @internal */ export enum TrailingTriviaOption { /** Exclude all trailing trivia (use getEnd()) */ Exclude, @@ -79,6 +82,7 @@ function hasCommentsBeforeLineBreak(text: string, start: number) { return false; } +/** @internal */ /** * Usually node.pos points to a position immediately after the previous token. * If this position is used as a beginning of the span to remove - it might lead to removing the trailing trivia of the previous node, i.e: @@ -99,6 +103,7 @@ const useNonAdjustedPositions: ConfigurableStartEnd = { trailingTriviaOption: TrailingTriviaOption.Exclude, }; +/** @internal */ export interface InsertNodeOptions { /** * Text to be inserted before the new node @@ -118,6 +123,7 @@ export interface InsertNodeOptions { delta?: number; } +/** @internal */ export interface ReplaceWithMultipleNodesOptions extends InsertNodeOptions { readonly joiner?: string; } @@ -136,6 +142,7 @@ interface BaseChange { readonly range: ts.TextRange; } +/** @internal */ export interface ChangeNodeOptions extends ConfigurableStartEnd, InsertNodeOptions {} interface ReplaceWithSingleNode extends BaseChange { readonly kind: ChangeKind.ReplaceWithSingleNode; @@ -282,20 +289,25 @@ function isSeparator(node: ts.Node, candidate: ts.Node | undefined): candidate i return !!candidate && !!node.parent && (candidate.kind === ts.SyntaxKind.CommaToken || (candidate.kind === ts.SyntaxKind.SemicolonToken && node.parent.kind === ts.SyntaxKind.ObjectLiteralExpression)); } +/** @internal */ export interface TextChangesContext { host: ts.LanguageServiceHost; formatContext: ts.formatting.FormatContext; preferences: ts.UserPreferences; } +/** @internal */ export type TypeAnnotatable = ts.SignatureDeclaration | ts.VariableDeclaration | ts.ParameterDeclaration | ts.PropertyDeclaration | ts.PropertySignature; +/** @internal */ export type ThisTypeAnnotatable = ts.FunctionDeclaration | ts.FunctionExpression; +/** @internal */ export function isThisTypeAnnotatable(containingFunction: ts.SignatureDeclaration): containingFunction is ThisTypeAnnotatable { return ts.isFunctionExpression(containingFunction) || ts.isFunctionDeclaration(containingFunction); } +/** @internal */ export class ChangeTracker { private readonly changes: Change[] = []; private readonly newFiles: { readonly oldFile: ts.SourceFile | undefined, readonly fileName: string, readonly statements: readonly (ts.Statement | ts.SyntaxKind.NewLineTrivia)[] }[] = []; @@ -1023,8 +1035,10 @@ function getMembersOrProperties(node: ts.ClassLikeDeclaration | ts.InterfaceDecl return ts.isObjectLiteralExpression(node) ? node.properties : node.members; } +/** @internal */ export type ValidateNonFormattedText = (node: ts.Node, text: string) => void; +/** @internal */ export function getNewFileText(statements: readonly ts.Statement[], scriptKind: ts.ScriptKind, newLineCharacter: string, formatContext: ts.formatting.FormatContext): string { return changesToText.newFileChangesWorker(/*oldFile*/ undefined, scriptKind, statements, newLineCharacter, formatContext); } @@ -1128,6 +1142,7 @@ namespace changesToText { } } +/** @internal */ export function applyChanges(text: string, changes: readonly ts.TextChange[]): string { for (let i = changes.length - 1; i >= 0; i--) { const { span, newText } = changes[i]; @@ -1149,6 +1164,7 @@ const textChangesTransformationContext: ts.TransformationContext = { ts.nullTransformationContext.factory.baseFactory), }; +/** @internal */ export function assignPositionsToNode(node: ts.Node): ts.Node { const visited = ts.visitEachChild(node, assignPositionsToNode, textChangesTransformationContext, assignPositionsToNodeArray, assignPositionsToNode); // create proxy node for non synthesized nodes @@ -1170,6 +1186,7 @@ function assignPositionsToNodeArray(nodes: ts.NodeArray, visitor: ts.Visito interface TextChangesWriter extends ts.EmitTextWriter, ts.PrintHandlers {} +/** @internal */ export function createWriter(newLine: string): TextChangesWriter { let lastNonTriviaPosition = 0; @@ -1417,6 +1434,7 @@ function getInsertionPositionAtSourceFileTop(sourceFile: ts.SourceFile): number } } +/** @internal */ export function isValidLocationToAddComment(sourceFile: ts.SourceFile, position: number) { return !ts.isInComment(sourceFile, position) && !ts.isInString(sourceFile, position) && !ts.isInTemplateString(sourceFile, position) && !ts.isInJSXText(sourceFile, position); } @@ -1589,6 +1607,7 @@ namespace deleteDeclaration { } } +/** @internal */ /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ // Exported for tests only! (TODO: improve tests to not need this) export function deleteNode(changes: ChangeTracker, sourceFile: ts.SourceFile, node: ts.Node, options: ConfigurableStartEnd = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }): void { @@ -1616,4 +1635,3 @@ function deleteNodeInList(changes: ChangeTracker, deletedNodesInLists: ts.Set(source: T | T[], transformers: ts.T const result = ts.transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, ts.factory, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true); result.diagnostics = ts.concatenate(result.diagnostics, diagnostics); return result; -} } \ No newline at end of file diff --git a/src/services/transpile.ts b/src/services/transpile.ts index 6c1ab8d761d2e..e080de22ce1f5 100644 --- a/src/services/transpile.ts +++ b/src/services/transpile.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "./_namespaces/ts"; + export interface TranspileOptions { compilerOptions?: ts.CompilerOptions; fileName?: string; @@ -150,4 +151,3 @@ export function fixupCompilerOptions(options: ts.CompilerOptions, diagnostics: t return options; } -} diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index 2099fe308c911..f87f896dabb0e 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -1,7 +1,7 @@ { "extends": "../tsconfig-base", "compilerOptions": { - "outFile": "../../built/local/services.js" + "outDir": "../../built/local" }, "references": [ { "path": "../compiler" }, @@ -136,6 +136,37 @@ "transform.ts", "shims.ts", "globalThisShim.ts", - "exportAsModule.ts" + "exportAsModule.ts", + "_namespaces/ts.BreakpointResolver.ts", + "_namespaces/ts.ts", + "_namespaces/ts.CallHierarchy.ts", + "_namespaces/ts.classifier.v2020.ts", + "_namespaces/ts.classifier.ts", + "_namespaces/ts.codefix.ts", + "_namespaces/ts.Completions.ts", + "_namespaces/ts.FindAllReferences.ts", + "_namespaces/ts.GoToDefinition.ts", + "_namespaces/ts.InlayHints.ts", + "_namespaces/ts.JsDoc.ts", + "_namespaces/ts.NavigateTo.ts", + "_namespaces/ts.NavigationBar.ts", + "_namespaces/ts.OrganizeImports.ts", + "_namespaces/ts.OutliningElementsCollector.ts", + "_namespaces/ts.refactor.ts", + "_namespaces/ts.Rename.ts", + "_namespaces/ts.SignatureHelp.ts", + "_namespaces/ts.SmartSelectionRange.ts", + "_namespaces/ts.Completions.StringCompletions.ts", + "_namespaces/ts.SymbolDisplay.ts", + "_namespaces/ts.textChanges.ts", + "_namespaces/ts.formatting.ts", + "_namespaces/ts.refactor.addOrRemoveBracesToArrowFunction.ts", + "_namespaces/ts.refactor.convertArrowFunctionOrFunctionExpression.ts", + "_namespaces/ts.refactor.convertParamsToDestructuredObject.ts", + "_namespaces/ts.refactor.convertStringOrTemplateLiteral.ts", + "_namespaces/ts.refactor.convertToOptionalChainExpression.ts", + "_namespaces/ts.refactor.extractSymbol.ts", + "_namespaces/ts.refactor.generateGetAccessorAndSetAccessor.ts", + "_namespaces/ts.refactor.inferFunctionReturnType.ts" ] } diff --git a/src/services/types.ts b/src/services/types.ts index 76defeb165697..8b820376798e4 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -1,118 +1,149 @@ -namespace ts { -export interface Node { - getSourceFile(): ts.SourceFile; - getChildCount(sourceFile?: ts.SourceFile): number; - getChildAt(index: number, sourceFile?: ts.SourceFile): ts.Node; - getChildren(sourceFile?: ts.SourceFile): ts.Node[]; - /* @internal */ - getChildren(sourceFile?: ts.SourceFileLike): ts.Node[]; // eslint-disable-line @typescript-eslint/unified-signatures - getStart(sourceFile?: ts.SourceFile, includeJsDocComment?: boolean): number; - /* @internal */ - getStart(sourceFile?: ts.SourceFileLike, includeJsDocComment?: boolean): number; // eslint-disable-line @typescript-eslint/unified-signatures - getFullStart(): number; - getEnd(): number; - getWidth(sourceFile?: ts.SourceFileLike): number; - getFullWidth(): number; - getLeadingTriviaWidth(sourceFile?: ts.SourceFile): number; - getFullText(sourceFile?: ts.SourceFile): string; - getText(sourceFile?: ts.SourceFile): string; - getFirstToken(sourceFile?: ts.SourceFile): ts.Node | undefined; - /* @internal */ - getFirstToken(sourceFile?: ts.SourceFileLike): ts.Node | undefined; // eslint-disable-line @typescript-eslint/unified-signatures - getLastToken(sourceFile?: ts.SourceFile): ts.Node | undefined; - /* @internal */ - getLastToken(sourceFile?: ts.SourceFileLike): ts.Node | undefined; // eslint-disable-line @typescript-eslint/unified-signatures - // See ts.forEachChild for documentation. - forEachChild(cbNode: (node: ts.Node) => T | undefined, cbNodeArray?: (nodes: ts.NodeArray) => T | undefined): T | undefined; -} - -export interface Identifier { - readonly text: string; -} - -export interface PrivateIdentifier { - readonly text: string; -} - -export interface Symbol { - readonly name: string; - getFlags(): ts.SymbolFlags; - getEscapedName(): ts.__String; - getName(): string; - getDeclarations(): ts.Declaration[] | undefined; - getDocumentationComment(typeChecker: ts.TypeChecker | undefined): SymbolDisplayPart[]; - /* @internal */ - getContextualDocumentationComment(context: ts.Node | undefined, checker: ts.TypeChecker | undefined): SymbolDisplayPart[] - getJsDocTags(checker?: ts.TypeChecker): JSDocTagInfo[]; - /* @internal */ - getContextualJsDocTags(context: ts.Node | undefined, checker: ts.TypeChecker | undefined): JSDocTagInfo[]; -} - -export interface Type { - getFlags(): ts.TypeFlags; - getSymbol(): ts.Symbol | undefined; - getProperties(): ts.Symbol[]; - getProperty(propertyName: string): ts.Symbol | undefined; - getApparentProperties(): ts.Symbol[]; - getCallSignatures(): readonly ts.Signature[]; - getConstructSignatures(): readonly ts.Signature[]; - getStringIndexType(): ts.Type | undefined; - getNumberIndexType(): ts.Type | undefined; - getBaseTypes(): ts.BaseType[] | undefined; - getNonNullableType(): ts.Type; - /*@internal*/ getNonOptionalType(): ts.Type; - /*@internal*/ isNullableType(): boolean; - getConstraint(): ts.Type | undefined; - getDefault(): ts.Type | undefined; - - isUnion(): this is ts.UnionType; - isIntersection(): this is ts.IntersectionType; - isUnionOrIntersection(): this is ts.UnionOrIntersectionType; - isLiteral(): this is ts.LiteralType; - isStringLiteral(): this is ts.StringLiteralType; - isNumberLiteral(): this is ts.NumberLiteralType; - isTypeParameter(): this is ts.TypeParameter; - isClassOrInterface(): this is ts.InterfaceType; - isClass(): this is ts.InterfaceType; - isIndexType(): this is ts.IndexType; -} - -export interface TypeReference { - typeArguments?: readonly ts.Type[]; -} - -export interface Signature { - getDeclaration(): ts.SignatureDeclaration; - getTypeParameters(): ts.TypeParameter[] | undefined; - getParameters(): ts.Symbol[]; - getTypeParameterAtPosition(pos: number): ts.Type; - getReturnType(): ts.Type; - getDocumentationComment(typeChecker: ts.TypeChecker | undefined): SymbolDisplayPart[]; - getJsDocTags(): JSDocTagInfo[]; -} - -export interface SourceFile { - /* @internal */ version: string; - /* @internal */ scriptSnapshot: IScriptSnapshot | undefined; - /* @internal */ nameTable: ts.UnderscoreEscapedMap | undefined; - - /* @internal */ getNamedDeclarations(): ts.ESMap; - - getLineAndCharacterOfPosition(pos: number): ts.LineAndCharacter; - getLineEndOfPosition(pos: number): number; - getLineStarts(): readonly number[]; - getPositionOfLineAndCharacter(line: number, character: number): number; - update(newText: string, textChangeRange: ts.TextChangeRange): ts.SourceFile; - - /* @internal */ sourceMapper?: ts.DocumentPositionMapper; -} - -export interface SourceFileLike { - getLineAndCharacterOfPosition(pos: number): ts.LineAndCharacter; -} - -export interface SourceMapSource { - getLineAndCharacterOfPosition(pos: number): ts.LineAndCharacter; +import * as ts from "./_namespaces/ts"; + +declare module "../compiler/types" { + // Module transform: converted from interface augmentation + export interface Node { + getSourceFile(): ts.SourceFile; + getChildCount(sourceFile?: ts.SourceFile): number; + getChildAt(index: number, sourceFile?: ts.SourceFile): ts.Node; + getChildren(sourceFile?: ts.SourceFile): ts.Node[]; + /* @internal */ + getChildren(sourceFile?: ts.SourceFileLike): ts.Node[]; // eslint-disable-line @typescript-eslint/unified-signatures + getStart(sourceFile?: ts.SourceFile, includeJsDocComment?: boolean): number; + /* @internal */ + getStart(sourceFile?: ts.SourceFileLike, includeJsDocComment?: boolean): number; // eslint-disable-line @typescript-eslint/unified-signatures + getFullStart(): number; + getEnd(): number; + getWidth(sourceFile?: ts.SourceFileLike): number; + getFullWidth(): number; + getLeadingTriviaWidth(sourceFile?: ts.SourceFile): number; + getFullText(sourceFile?: ts.SourceFile): string; + getText(sourceFile?: ts.SourceFile): string; + getFirstToken(sourceFile?: ts.SourceFile): ts.Node | undefined; + /* @internal */ + getFirstToken(sourceFile?: ts.SourceFileLike): ts.Node | undefined; // eslint-disable-line @typescript-eslint/unified-signatures + getLastToken(sourceFile?: ts.SourceFile): ts.Node | undefined; + /* @internal */ + getLastToken(sourceFile?: ts.SourceFileLike): ts.Node | undefined; // eslint-disable-line @typescript-eslint/unified-signatures + // See ts.forEachChild for documentation. + forEachChild(cbNode: (node: ts.Node) => T | undefined, cbNodeArray?: (nodes: ts.NodeArray) => T | undefined): T | undefined; + } +} + +declare module "../compiler/types" { + // Module transform: converted from interface augmentation + export interface Identifier { + readonly text: string; + } +} + +declare module "../compiler/types" { + // Module transform: converted from interface augmentation + export interface PrivateIdentifier { + readonly text: string; + } +} + +declare module "../compiler/types" { + // Module transform: converted from interface augmentation + export interface Symbol { + readonly name: string; + getFlags(): ts.SymbolFlags; + getEscapedName(): ts.__String; + getName(): string; + getDeclarations(): ts.Declaration[] | undefined; + getDocumentationComment(typeChecker: ts.TypeChecker | undefined): SymbolDisplayPart[]; + /* @internal */ + getContextualDocumentationComment(context: ts.Node | undefined, checker: ts.TypeChecker | undefined): SymbolDisplayPart[] + getJsDocTags(checker?: ts.TypeChecker): JSDocTagInfo[]; + /* @internal */ + getContextualJsDocTags(context: ts.Node | undefined, checker: ts.TypeChecker | undefined): JSDocTagInfo[]; + } +} + +declare module "../compiler/types" { + // Module transform: converted from interface augmentation + export interface Type { + getFlags(): ts.TypeFlags; + getSymbol(): ts.Symbol | undefined; + getProperties(): ts.Symbol[]; + getProperty(propertyName: string): ts.Symbol | undefined; + getApparentProperties(): ts.Symbol[]; + getCallSignatures(): readonly ts.Signature[]; + getConstructSignatures(): readonly ts.Signature[]; + getStringIndexType(): ts.Type | undefined; + getNumberIndexType(): ts.Type | undefined; + getBaseTypes(): ts.BaseType[] | undefined; + getNonNullableType(): ts.Type; + /*@internal*/ getNonOptionalType(): ts.Type; + /*@internal*/ isNullableType(): boolean; + getConstraint(): ts.Type | undefined; + getDefault(): ts.Type | undefined; + + isUnion(): this is ts.UnionType; + isIntersection(): this is ts.IntersectionType; + isUnionOrIntersection(): this is ts.UnionOrIntersectionType; + isLiteral(): this is ts.LiteralType; + isStringLiteral(): this is ts.StringLiteralType; + isNumberLiteral(): this is ts.NumberLiteralType; + isTypeParameter(): this is ts.TypeParameter; + isClassOrInterface(): this is ts.InterfaceType; + isClass(): this is ts.InterfaceType; + isIndexType(): this is ts.IndexType; + } +} + +declare module "../compiler/types" { + // Module transform: converted from interface augmentation + export interface TypeReference { + typeArguments?: readonly ts.Type[]; + } +} + +declare module "../compiler/types" { + // Module transform: converted from interface augmentation + export interface Signature { + getDeclaration(): ts.SignatureDeclaration; + getTypeParameters(): ts.TypeParameter[] | undefined; + getParameters(): ts.Symbol[]; + getTypeParameterAtPosition(pos: number): ts.Type; + getReturnType(): ts.Type; + getDocumentationComment(typeChecker: ts.TypeChecker | undefined): SymbolDisplayPart[]; + getJsDocTags(): JSDocTagInfo[]; + } +} + +declare module "../compiler/types" { + // Module transform: converted from interface augmentation + export interface SourceFile { + /* @internal */ version: string; + /* @internal */ scriptSnapshot: IScriptSnapshot | undefined; + /* @internal */ nameTable: ts.UnderscoreEscapedMap | undefined; + + /* @internal */ getNamedDeclarations(): ts.ESMap; + + getLineAndCharacterOfPosition(pos: number): ts.LineAndCharacter; + getLineEndOfPosition(pos: number): number; + getLineStarts(): readonly number[]; + getPositionOfLineAndCharacter(line: number, character: number): number; + update(newText: string, textChangeRange: ts.TextChangeRange): ts.SourceFile; + + /* @internal */ sourceMapper?: ts.DocumentPositionMapper; + } +} + +declare module "../compiler/types" { + // Module transform: converted from interface augmentation + export interface SourceFileLike { + getLineAndCharacterOfPosition(pos: number): ts.LineAndCharacter; + } +} + +declare module "../compiler/types" { + // Module transform: converted from interface augmentation + export interface SourceMapSource { + getLineAndCharacterOfPosition(pos: number): ts.LineAndCharacter; + } } /** @@ -1675,4 +1706,3 @@ export interface InlayHintsContext { span: ts.TextSpan; preferences: ts.UserPreferences; } -} diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 024d672b7b2b4..761096a4ee688 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1,19 +1,29 @@ +import * as ts from "./_namespaces/ts"; + /* @internal */ // Don't expose that we use this // Based on lib.es6.d.ts -interface PromiseConstructor { - new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; - reject(reason: any): Promise; - all(values: (T | PromiseLike)[]): Promise; +declare global { + // Module transform: converted from ambient declaration + /** @internal */ + interface PromiseConstructor { + new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; + reject(reason: any): Promise; + all(values: (T | PromiseLike)[]): Promise; + } } /* @internal */ -declare var Promise: PromiseConstructor; // eslint-disable-line no-var +declare global { + // Module transform: converted from ambient declaration + /** @internal */ + var Promise: PromiseConstructor; +} // eslint-disable-line no-var -/* @internal */ -namespace ts { // These utilities are common to multiple language service features. //#region +/** @internal */ export const scanner: ts.Scanner = ts.createScanner(ts.ScriptTarget.Latest, /*skipTrivia*/ true); +/** @internal */ export const enum SemanticMeaning { None = 0x0, Value = 0x1, @@ -22,6 +32,7 @@ export const enum SemanticMeaning { All = Value | Type | Namespace } +/** @internal */ export function getMeaningFromDeclaration(node: ts.Node): SemanticMeaning { switch (node.kind) { case ts.SyntaxKind.VariableDeclaration: @@ -87,6 +98,7 @@ export function getMeaningFromDeclaration(node: ts.Node): SemanticMeaning { return SemanticMeaning.All; } +/** @internal */ export function getMeaningFromLocation(node: ts.Node): SemanticMeaning { node = getAdjustedReferenceLocation(node); const parent = node.parent; @@ -137,6 +149,7 @@ function getMeaningFromRightHandSideOfImportEquals(node: ts.Node): SemanticMeani return name && name.parent.kind === ts.SyntaxKind.ImportEqualsDeclaration ? SemanticMeaning.All : SemanticMeaning.Namespace; } +/** @internal */ export function isInRightSideOfInternalImportEqualsDeclaration(node: ts.Node) { while (node.parent.kind === ts.SyntaxKind.QualifiedName) { node = node.parent; @@ -206,26 +219,32 @@ function isTypeReference(node: ts.Node): boolean { return false; } +/** @internal */ export function isCallExpressionTarget(node: ts.Node, includeElementAccess = false, skipPastOuterExpressions = false): boolean { return isCalleeWorker(node, ts.isCallExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions); } +/** @internal */ export function isNewExpressionTarget(node: ts.Node, includeElementAccess = false, skipPastOuterExpressions = false): boolean { return isCalleeWorker(node, ts.isNewExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions); } +/** @internal */ export function isCallOrNewExpressionTarget(node: ts.Node, includeElementAccess = false, skipPastOuterExpressions = false): boolean { return isCalleeWorker(node, ts.isCallOrNewExpression, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions); } +/** @internal */ export function isTaggedTemplateTag(node: ts.Node, includeElementAccess = false, skipPastOuterExpressions = false): boolean { return isCalleeWorker(node, ts.isTaggedTemplateExpression, selectTagOfTaggedTemplateExpression, includeElementAccess, skipPastOuterExpressions); } +/** @internal */ export function isDecoratorTarget(node: ts.Node, includeElementAccess = false, skipPastOuterExpressions = false): boolean { return isCalleeWorker(node, ts.isDecorator, selectExpressionOfCallOrNewExpressionOrDecorator, includeElementAccess, skipPastOuterExpressions); } +/** @internal */ export function isJsxOpeningLikeElementTagName(node: ts.Node, includeElementAccess = false, skipPastOuterExpressions = false): boolean { return isCalleeWorker(node, ts.isJsxOpeningLikeElement, selectTagNameOfJsxOpeningLikeElement, includeElementAccess, skipPastOuterExpressions); } @@ -250,14 +269,17 @@ function isCalleeWorker= range.end; } +/** @internal */ export function rangeContainsStartEnd(range: ts.TextRange, start: number, end: number): boolean { return range.pos <= start && range.end >= end; } +/** @internal */ export function rangeOverlapsWithStartEnd(r1: ts.TextRange, start: number, end: number) { return startEndOverlapsWithStartEnd(r1.pos, r1.end, start, end); } +/** @internal */ export function nodeOverlapsWithStartEnd(node: ts.Node, sourceFile: ts.SourceFile, start: number, end: number) { return startEndOverlapsWithStartEnd(node.getStart(sourceFile), node.end, start, end); } +/** @internal */ export function startEndOverlapsWithStartEnd(start1: number, end1: number, start2: number, end2: number) { const start = Math.max(start1, start2); const end = Math.min(end1, end2); return start < end; } +/** @internal */ /** * Assumes `candidate.start <= position` holds. */ @@ -693,6 +742,7 @@ function nodeEndsWith(n: ts.Node, expectedLastToken: ts.SyntaxKind, sourceFile: return false; } +/** @internal */ export function findListItemInfo(node: ts.Node): ListItemInfo | undefined { const list = findContainingList(node); @@ -713,14 +763,17 @@ export function findListItemInfo(node: ts.Node): ListItemInfo | undefined { }; } +/** @internal */ export function hasChildOfKind(n: ts.Node, kind: ts.SyntaxKind, sourceFile: ts.SourceFile): boolean { return !!findChildOfKind(n, kind, sourceFile); } +/** @internal */ export function findChildOfKind(n: ts.Node, kind: T["kind"], sourceFile: ts.SourceFileLike): T | undefined { return ts.find(n.getChildren(sourceFile), (c): c is T => c.kind === kind); } +/** @internal */ export function findContainingList(node: ts.Node): ts.SyntaxList | undefined { // The node might be a list element (nonsynthetic) or a comma (synthetic). Either way, it will // be parented by the container of the SyntaxList, not the SyntaxList itself. @@ -789,6 +842,7 @@ function getAncestorTypeNode(node: ts.Node) { return lastTypeNode; } +/** @internal */ export function getContextualTypeFromParentOrAncestorTypeNode(node: ts.Expression, checker: ts.TypeChecker): ts.Type | undefined { if (node.flags & (ts.NodeFlags.JSDoc & ~ts.NodeFlags.JavaScriptFile)) return undefined; @@ -1082,6 +1136,7 @@ function getAdjustedLocation(node: ts.Node, forRename: boolean): ts.Node { return node; } +/** @internal */ /** * Adjusts the location used for "find references" and "go to definition" when the cursor was not * on a property name. @@ -1090,6 +1145,7 @@ export function getAdjustedReferenceLocation(node: ts.Node): ts.Node { return getAdjustedLocation(node, /*forRename*/ false); } +/** @internal */ /** * Adjusts the location used for "rename" when the cursor was not on a property name. */ @@ -1097,6 +1153,7 @@ export function getAdjustedRenameLocation(node: ts.Node): ts.Node { return getAdjustedLocation(node, /*forRename*/ true); } +/** @internal */ /** * Gets the token whose text has range [start, end) and * position >= start and (position < end or (position === end && token is literal or keyword or identifier)) @@ -1105,6 +1162,7 @@ export function getTouchingPropertyName(sourceFile: ts.SourceFile, position: num return getTouchingToken(sourceFile, position, n => ts.isPropertyNameLiteral(n) || ts.isKeyword(n.kind) || ts.isPrivateIdentifier(n)); } +/** @internal */ /** * Returns the token if position is in [start, end). * If position === end, returns the preceding token if includeItemAtEndPosition(previousToken) === true @@ -1113,6 +1171,7 @@ export function getTouchingToken(sourceFile: ts.SourceFile, position: number, in return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ false, includePrecedingTokenAtEndPosition, /*includeEndPosition*/ false); } +/** @internal */ /** Returns a token if position is in [start-of-leading-trivia, end) */ export function getTokenAtPosition(sourceFile: ts.SourceFile, position: number): ts.Node { return getTokenAtPositionWorker(sourceFile, position, /*allowPositionInLeadingTrivia*/ true, /*includePrecedingTokenAtEndPosition*/ undefined, /*includeEndPosition*/ false); @@ -1214,6 +1273,7 @@ function getTokenAtPositionWorker(sourceFile: ts.SourceFile, position: number, a } } +/** @internal */ /** * Returns the first token where position is in [start, end), * excluding `JsxText` tokens containing only whitespace. @@ -1228,6 +1288,7 @@ export function findFirstNonJsxWhitespaceToken(sourceFile: ts.SourceFile, positi return tokenAtPosition; } +/** @internal */ /** * The token on the left of the position is the token that strictly includes the position * or sits to the left of the cursor if it is on a boundary. For example @@ -1247,6 +1308,7 @@ export function findTokenOnLeftOfPosition(file: ts.SourceFile, position: number) return findPrecedingToken(position, file); } +/** @internal */ export function findNextToken(previousToken: ts.Node, parent: ts.Node, sourceFile: ts.SourceFileLike): ts.Node | undefined { return find(parent); @@ -1266,12 +1328,15 @@ export function findNextToken(previousToken: ts.Node, parent: ts.Node, sourceFil } } +/** @internal */ /** * Finds the rightmost token satisfying `token.end <= position`, * excluding `JsxText` tokens containing only whitespace. */ export function findPrecedingToken(position: number, sourceFile: ts.SourceFileLike, startNode: ts.Node, excludeJsdoc?: boolean): ts.Node | undefined; +/** @internal */ export function findPrecedingToken(position: number, sourceFile: ts.SourceFile, startNode?: ts.Node, excludeJsdoc?: boolean): ts.Node | undefined; +/** @internal */ export function findPrecedingToken(position: number, sourceFile: ts.SourceFileLike, startNode?: ts.Node, excludeJsdoc?: boolean): ts.Node | undefined { const result = find((startNode || sourceFile) as ts.Node); ts.Debug.assert(!(result && isWhiteSpaceOnlyJsxText(result))); @@ -1370,6 +1435,7 @@ function findRightmostChildNodeWithTokens(children: ts.Node[], exclusiveStartPos } } +/** @internal */ export function isInString(sourceFile: ts.SourceFile, position: number, previousToken = findPrecedingToken(position, sourceFile)): boolean { if (previousToken && ts.isStringTextContainingNode(previousToken)) { const start = previousToken.getStart(sourceFile); @@ -1391,6 +1457,7 @@ export function isInString(sourceFile: ts.SourceFile, position: number, previous return false; } +/** @internal */ /** * returns true if the position is in between the open and close elements of an JSX expression. */ @@ -1434,11 +1501,13 @@ function isWhiteSpaceOnlyJsxText(node: ts.Node): boolean { return ts.isJsxText(node) && node.containsOnlyTriviaWhiteSpaces; } +/** @internal */ export function isInTemplateString(sourceFile: ts.SourceFile, position: number) { const token = getTokenAtPosition(sourceFile, position); return ts.isTemplateLiteralKind(token.kind) && position > token.getStart(sourceFile); } +/** @internal */ export function isInJSXText(sourceFile: ts.SourceFile, position: number) { const token = getTokenAtPosition(sourceFile, position); if (ts.isJsxText(token)) { @@ -1453,6 +1522,7 @@ export function isInJSXText(sourceFile: ts.SourceFile, position: number) { return false; } +/** @internal */ export function isInsideJsxElement(sourceFile: ts.SourceFile, position: number): boolean { function isInsideJsxElementTraversal(node: ts.Node): boolean { while (node) { @@ -1482,6 +1552,7 @@ export function isInsideJsxElement(sourceFile: ts.SourceFile, position: number): return isInsideJsxElementTraversal(getTokenAtPosition(sourceFile, position)); } +/** @internal */ export function findPrecedingMatchingToken(token: ts.Node, matchingTokenKind: ts.SyntaxKind.OpenBraceToken | ts.SyntaxKind.OpenParenToken | ts.SyntaxKind.OpenBracketToken, sourceFile: ts.SourceFile) { const closeTokenText = ts.tokenToString(token.kind)!; const matchingTokenText = ts.tokenToString(matchingTokenKind)!; @@ -1521,12 +1592,14 @@ export function findPrecedingMatchingToken(token: ts.Node, matchingTokenKind: ts } } +/** @internal */ export function removeOptionality(type: ts.Type, isOptionalExpression: boolean, isOptionalChain: boolean) { return isOptionalExpression ? type.getNonNullableType() : isOptionalChain ? type.getNonOptionalType() : type; } +/** @internal */ export function isPossiblyTypeArgumentPosition(token: ts.Node, sourceFile: ts.SourceFile, checker: ts.TypeChecker): boolean { const info = getPossibleTypeArgumentsInfo(token, sourceFile); return info !== undefined && (ts.isPartOfTypeNode(info.called) || @@ -1534,6 +1607,7 @@ export function isPossiblyTypeArgumentPosition(token: ts.Node, sourceFile: ts.So isPossiblyTypeArgumentPosition(info.called, sourceFile, checker)); } +/** @internal */ export function getPossibleGenericSignatures(called: ts.Expression, typeArgumentCount: number, checker: ts.TypeChecker): readonly ts.Signature[] { let type = checker.getTypeAtLocation(called); if (ts.isOptionalChain(called.parent)) { @@ -1544,16 +1618,19 @@ export function getPossibleGenericSignatures(called: ts.Expression, typeArgument return signatures.filter(candidate => !!candidate.typeParameters && candidate.typeParameters.length >= typeArgumentCount); } +/** @internal */ export interface PossibleTypeArgumentInfo { readonly called: ts.Identifier; readonly nTypeArguments: number; } +/** @internal */ export interface PossibleProgramFileInfo { ProgramFiles?: string[]; } // Get info for an expression like `f <` that may be the start of type arguments. +/** @internal */ export function getPossibleTypeArgumentsInfo(tokenIn: ts.Node | undefined, sourceFile: ts.SourceFile): PossibleTypeArgumentInfo | undefined { // This is a rare case, but one that saves on a _lot_ of work if true - if the source file has _no_ `<` character, // then there obviously can't be any type arguments - no expensive brace-matching backwards scanning required @@ -1658,6 +1735,7 @@ export function getPossibleTypeArgumentsInfo(tokenIn: ts.Node | undefined, sourc return undefined; } +/** @internal */ /** * Returns true if the cursor at position in sourceFile is within a comment. * @@ -1668,6 +1746,7 @@ export function isInComment(sourceFile: ts.SourceFile, position: number, tokenAt return ts.formatting.getRangeOfEnclosingComment(sourceFile, position, /*precedingToken*/ undefined, tokenAtPosition); } +/** @internal */ export function hasDocComment(sourceFile: ts.SourceFile, position: number): boolean { const token = getTokenAtPosition(sourceFile, position); return !!ts.findAncestor(token, ts.isJSDoc); @@ -1679,6 +1758,7 @@ function nodeHasTokens(n: ts.Node, sourceFile: ts.SourceFileLike): boolean { return n.kind === ts.SyntaxKind.EndOfFileToken ? !!(n as ts.EndOfFileToken).jsDoc : n.getWidth(sourceFile) !== 0; } +/** @internal */ export function getNodeModifiers(node: ts.Node, excludeFlags = ts.ModifierFlags.None): string { const result: string[] = []; const flags = ts.isDeclaration(node) @@ -1698,6 +1778,7 @@ export function getNodeModifiers(node: ts.Node, excludeFlags = ts.ModifierFlags. return result.length > 0 ? result.join(",") : ts.ScriptElementKindModifier.none; } +/** @internal */ export function getTypeArgumentOrTypeParameterList(node: ts.Node): ts.NodeArray | undefined { if (node.kind === ts.SyntaxKind.TypeReference || node.kind === ts.SyntaxKind.CallExpression) { return (node as ts.CallExpression).typeArguments; @@ -1710,10 +1791,12 @@ export function getTypeArgumentOrTypeParameterList(node: ts.Node): ts.NodeArray< return undefined; } +/** @internal */ export function isComment(kind: ts.SyntaxKind): boolean { return kind === ts.SyntaxKind.SingleLineCommentTrivia || kind === ts.SyntaxKind.MultiLineCommentTrivia; } +/** @internal */ export function isStringOrRegularExpressionOrTemplateLiteral(kind: ts.SyntaxKind): boolean { if (kind === ts.SyntaxKind.StringLiteral || kind === ts.SyntaxKind.RegularExpressionLiteral @@ -1723,15 +1806,18 @@ export function isStringOrRegularExpressionOrTemplateLiteral(kind: ts.SyntaxKind return false; } +/** @internal */ export function isPunctuation(kind: ts.SyntaxKind): boolean { return ts.SyntaxKind.FirstPunctuation <= kind && kind <= ts.SyntaxKind.LastPunctuation; } +/** @internal */ export function isInsideTemplateLiteral(node: ts.TemplateLiteralToken, position: number, sourceFile: ts.SourceFile): boolean { return ts.isTemplateLiteralKind(node.kind) && (node.getStart(sourceFile) < position && position < node.end) || (!!node.isUnterminated && position === node.end); } +/** @internal */ export function isAccessibilityModifier(kind: ts.SyntaxKind) { switch (kind) { case ts.SyntaxKind.PublicKeyword: @@ -1743,12 +1829,14 @@ export function isAccessibilityModifier(kind: ts.SyntaxKind) { return false; } +/** @internal */ export function cloneCompilerOptions(options: ts.CompilerOptions): ts.CompilerOptions { const result = ts.clone(options); ts.setConfigFileInOptions(result, options && options.configFile); return result; } +/** @internal */ export function isArrayLiteralOrObjectLiteralDestructuringPattern(node: ts.Node) { if (node.kind === ts.SyntaxKind.ArrayLiteralExpression || node.kind === ts.SyntaxKind.ObjectLiteralExpression) { @@ -1779,10 +1867,12 @@ export function isArrayLiteralOrObjectLiteralDestructuringPattern(node: ts.Node) return false; } +/** @internal */ export function isInReferenceComment(sourceFile: ts.SourceFile, position: number): boolean { return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ true); } +/** @internal */ export function isInNonReferenceComment(sourceFile: ts.SourceFile, position: number): boolean { return isInReferenceCommentWorker(sourceFile, position, /*shouldBeReference*/ false); } @@ -1792,6 +1882,7 @@ function isInReferenceCommentWorker(sourceFile: ts.SourceFile, position: number, return !!range && shouldBeReference === tripleSlashDirectivePrefixRegex.test(sourceFile.text.substring(range.pos, range.end)); } +/** @internal */ export function getReplacementSpanForContextToken(contextToken: ts.Node | undefined) { if (!contextToken) return undefined; @@ -1804,35 +1895,43 @@ export function getReplacementSpanForContextToken(contextToken: ts.Node | undefi } } +/** @internal */ export function createTextSpanFromNode(node: ts.Node, sourceFile?: ts.SourceFile, endNode?: ts.Node): ts.TextSpan { return ts.createTextSpanFromBounds(node.getStart(sourceFile), (endNode || node).getEnd()); } +/** @internal */ export function createTextSpanFromStringLiteralLikeContent(node: ts.StringLiteralLike) { if (node.isUnterminated) return undefined; return ts.createTextSpanFromBounds(node.getStart() + 1, node.getEnd() - 1); } +/** @internal */ export function createTextRangeFromNode(node: ts.Node, sourceFile: ts.SourceFile): ts.TextRange { return ts.createRange(node.getStart(sourceFile), node.end); } +/** @internal */ export function createTextSpanFromRange(range: ts.TextRange): ts.TextSpan { return ts.createTextSpanFromBounds(range.pos, range.end); } +/** @internal */ export function createTextRangeFromSpan(span: ts.TextSpan): ts.TextRange { return ts.createRange(span.start, span.start + span.length); } +/** @internal */ export function createTextChangeFromStartLength(start: number, length: number, newText: string): ts.TextChange { return createTextChange(ts.createTextSpan(start, length), newText); } +/** @internal */ export function createTextChange(span: ts.TextSpan, newText: string): ts.TextChange { return { span, newText }; } +/** @internal */ export const typeKeywords: readonly ts.SyntaxKind[] = [ ts.SyntaxKind.AnyKeyword, ts.SyntaxKind.AssertsKeyword, @@ -1855,25 +1954,31 @@ export const typeKeywords: readonly ts.SyntaxKind[] = [ ts.SyntaxKind.UnknownKeyword, ]; +/** @internal */ export function isTypeKeyword(kind: ts.SyntaxKind): boolean { return ts.contains(typeKeywords, kind); } +/** @internal */ export function isTypeKeywordToken(node: ts.Node): node is ts.Token { return node.kind === ts.SyntaxKind.TypeKeyword; } +/** @internal */ export function isTypeKeywordTokenOrIdentifier(node: ts.Node) { return isTypeKeywordToken(node) || ts.isIdentifier(node) && node.text === "type"; } +/** @internal */ /** True if the symbol is for an external module, as opposed to a namespace. */ export function isExternalModuleSymbol(moduleSymbol: ts.Symbol): boolean { return !!(moduleSymbol.flags & ts.SymbolFlags.Module) && moduleSymbol.name.charCodeAt(0) === ts.CharacterCodes.doubleQuote; } +/** @internal */ /** Returns `true` the first time it encounters a node and `false` afterwards. */ export type NodeSeenTracker = (node: T) => boolean; +/** @internal */ export function nodeSeenTracker(): NodeSeenTracker { const seen: true[] = []; return node => { @@ -1882,10 +1987,12 @@ export function nodeSeenTracker(): NodeSeenTracker { }; } +/** @internal */ export function getSnapshotText(snap: ts.IScriptSnapshot): string { return snap.getText(0, snap.getLength()); } +/** @internal */ export function repeatString(str: string, count: number): string { let result = ""; for (let i = 0; i < count; i++) { @@ -1894,10 +2001,12 @@ export function repeatString(str: string, count: number): string { return result; } +/** @internal */ export function skipConstraint(type: ts.Type): ts.Type { return type.isTypeParameter() ? type.getConstraint() || type : type; } +/** @internal */ export function getNameFromPropertyName(name: ts.PropertyName): string | undefined { return name.kind === ts.SyntaxKind.ComputedPropertyName // treat computed property names where expression is string/numeric literal as just string/numeric literal @@ -1905,16 +2014,20 @@ export function getNameFromPropertyName(name: ts.PropertyName): string | undefin : ts.isPrivateIdentifier(name) ? ts.idText(name) : ts.getTextOfIdentifierOrLiteral(name); } +/** @internal */ export function programContainsModules(program: ts.Program): boolean { return program.getSourceFiles().some(s => !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!(s.externalModuleIndicator || s.commonJsModuleIndicator)); } +/** @internal */ export function programContainsEsModules(program: ts.Program): boolean { return program.getSourceFiles().some(s => !s.isDeclarationFile && !program.isSourceFileFromExternalLibrary(s) && !!s.externalModuleIndicator); } +/** @internal */ export function compilerOptionsIndicateEsModules(compilerOptions: ts.CompilerOptions): boolean { return !!compilerOptions.module || ts.getEmitScriptTarget(compilerOptions) >= ts.ScriptTarget.ES2015 || !!compilerOptions.noEmit; } +/** @internal */ export function createModuleSpecifierResolutionHost(program: ts.Program, host: ts.LanguageServiceHost): ts.ModuleSpecifierResolutionHost { // Mix in `getSymlinkCache` from Program when host doesn't have it // in order for non-Project hosts to have a symlinks cache. @@ -1935,6 +2048,7 @@ export function createModuleSpecifierResolutionHost(program: ts.Program, host: t }; } +/** @internal */ export function getModuleSpecifierResolverHost(program: ts.Program, host: ts.LanguageServiceHost): ts.SymbolTracker["moduleResolverHost"] { return { ...createModuleSpecifierResolutionHost(program, host), @@ -1942,18 +2056,22 @@ export function getModuleSpecifierResolverHost(program: ts.Program, host: ts.Lan }; } +/** @internal */ export function moduleResolutionRespectsExports(moduleResolution: ts.ModuleResolutionKind): boolean { return moduleResolution >= ts.ModuleResolutionKind.Node16 && moduleResolution <= ts.ModuleResolutionKind.NodeNext; } +/** @internal */ export function moduleResolutionUsesNodeModules(moduleResolution: ts.ModuleResolutionKind): boolean { return moduleResolution === ts.ModuleResolutionKind.NodeJs || moduleResolution >= ts.ModuleResolutionKind.Node16 && moduleResolution <= ts.ModuleResolutionKind.NodeNext; } +/** @internal */ export function makeImportIfNecessary(defaultImport: ts.Identifier | undefined, namedImports: readonly ts.ImportSpecifier[] | undefined, moduleSpecifier: string, quotePreference: QuotePreference): ts.ImportDeclaration | undefined { return defaultImport || namedImports && namedImports.length ? makeImport(defaultImport, namedImports, moduleSpecifier, quotePreference) : undefined; } +/** @internal */ export function makeImport(defaultImport: ts.Identifier | undefined, namedImports: readonly ts.ImportSpecifier[] | undefined, moduleSpecifier: string | ts.Expression, quotePreference: QuotePreference, isTypeOnly?: boolean): ts.ImportDeclaration { return ts.factory.createImportDeclaration( /*modifiers*/ undefined, @@ -1964,16 +2082,20 @@ export function makeImport(defaultImport: ts.Identifier | undefined, namedImport /*assertClause*/ undefined); } +/** @internal */ export function makeStringLiteral(text: string, quotePreference: QuotePreference): ts.StringLiteral { return ts.factory.createStringLiteral(text, quotePreference === QuotePreference.Single); } +/** @internal */ export const enum QuotePreference { Single, Double } +/** @internal */ export function quotePreferenceFromString(str: ts.StringLiteral, sourceFile: ts.SourceFile): QuotePreference { return ts.isStringDoubleQuoted(str, sourceFile) ? QuotePreference.Double : QuotePreference.Single; } +/** @internal */ export function getQuotePreference(sourceFile: ts.SourceFile, preferences: ts.UserPreferences): QuotePreference { if (preferences.quotePreference && preferences.quotePreference !== "auto") { return preferences.quotePreference === "single" ? QuotePreference.Single : QuotePreference.Double; @@ -1986,6 +2108,7 @@ export function getQuotePreference(sourceFile: ts.SourceFile, preferences: ts.Us } } +/** @internal */ export function getQuoteFromPreference(qp: QuotePreference): string { switch (qp) { case QuotePreference.Single: return "'"; @@ -1994,11 +2117,13 @@ export function getQuoteFromPreference(qp: QuotePreference): string { } } +/** @internal */ export function symbolNameNoDefault(symbol: ts.Symbol): string | undefined { const escaped = symbolEscapedNameNoDefault(symbol); return escaped === undefined ? undefined : ts.unescapeLeadingUnderscores(escaped); } +/** @internal */ export function symbolEscapedNameNoDefault(symbol: ts.Symbol): ts.__String | undefined { if (symbol.escapedName !== ts.InternalSymbolName.Default) { return symbol.escapedName; @@ -2010,6 +2135,7 @@ export function symbolEscapedNameNoDefault(symbol: ts.Symbol): ts.__String | und }); } +/** @internal */ export function isModuleSpecifierLike(node: ts.Node): node is ts.StringLiteralLike { return ts.isStringLiteralLike(node) && ( ts.isExternalModuleReference(node.parent) || @@ -2018,8 +2144,10 @@ export function isModuleSpecifierLike(node: ts.Node): node is ts.StringLiteralLi ts.isImportCall(node.parent) && node.parent.arguments[0] === node); } +/** @internal */ export type ObjectBindingElementWithoutPropertyName = ts.BindingElement & { name: ts.Identifier }; +/** @internal */ export function isObjectBindingElementWithoutPropertyName(bindingElement: ts.Node): bindingElement is ObjectBindingElementWithoutPropertyName { return ts.isBindingElement(bindingElement) && ts.isObjectBindingPattern(bindingElement.parent) && @@ -2027,11 +2155,13 @@ export function isObjectBindingElementWithoutPropertyName(bindingElement: ts.Nod !bindingElement.propertyName; } +/** @internal */ export function getPropertySymbolFromBindingElement(checker: ts.TypeChecker, bindingElement: ObjectBindingElementWithoutPropertyName): ts.Symbol | undefined { const typeOfPattern = checker.getTypeAtLocation(bindingElement.parent); return typeOfPattern && checker.getPropertyOfType(typeOfPattern, bindingElement.name.text); } +/** @internal */ export function getParentNodeInSpan(node: ts.Node | undefined, file: ts.SourceFile, span: ts.TextSpan): ts.Node | undefined { if (!node) return undefined; @@ -2049,10 +2179,12 @@ function spanContainsNode(span: ts.TextSpan, node: ts.Node, file: ts.SourceFile) node.getEnd() <= ts.textSpanEnd(span); } +/** @internal */ export function findModifier(node: ts.Node, kind: ts.Modifier["kind"]): ts.Modifier | undefined { return ts.canHaveModifiers(node) ? ts.find(node.modifiers, (m): m is ts.Modifier => m.kind === kind) : undefined; } +/** @internal */ export function insertImports(changes: ts.textChanges.ChangeTracker, sourceFile: ts.SourceFile, imports: ts.AnyImportOrRequireStatement | readonly ts.AnyImportOrRequireStatement[], blankLineBetween: boolean): void { const decl = ts.isArray(imports) ? imports[0] : imports; const importKindPredicate: (node: ts.Node) => node is ts.AnyImportOrRequireStatement = decl.kind === ts.SyntaxKind.VariableStatement ? ts.isRequireVariableStatement : ts.isAnyImportSyntax; @@ -2087,18 +2219,22 @@ export function insertImports(changes: ts.textChanges.ChangeTracker, sourceFile: } } +/** @internal */ export function getTypeKeywordOfTypeOnlyImport(importClause: ts.ImportClause, sourceFile: ts.SourceFile): ts.Token { ts.Debug.assert(importClause.isTypeOnly); return ts.cast(importClause.getChildAt(0, sourceFile), isTypeKeywordToken); } +/** @internal */ export function textSpansEqual(a: ts.TextSpan | undefined, b: ts.TextSpan | undefined): boolean { return !!a && !!b && a.start === b.start && a.length === b.length; } +/** @internal */ export function documentSpansEqual(a: ts.DocumentSpan, b: ts.DocumentSpan): boolean { return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); } +/** @internal */ /** * Iterates through 'array' by index and performs the callback on each element of array until the callback * returns a truthy value, then returns that value. @@ -2118,6 +2254,7 @@ export function forEachUnique(array: readonly T[] | undefined, callback: ( return undefined; } +/** @internal */ export function isTextWhiteSpaceLike(text: string, startPos: number, endPos: number): boolean { for (let i = startPos; i < endPos; i++) { if (!ts.isWhiteSpaceLike(text.charCodeAt(i))) { @@ -2128,11 +2265,13 @@ export function isTextWhiteSpaceLike(text: string, startPos: number, endPos: num return true; } +/** @internal */ export function getMappedLocation(location: ts.DocumentPosition, sourceMapper: ts.SourceMapper, fileExists: ((path: string) => boolean) | undefined): ts.DocumentPosition | undefined { const mapsTo = sourceMapper.tryGetSourcePosition(location); return mapsTo && (!fileExists || fileExists(ts.normalizePath(mapsTo.fileName)) ? mapsTo : undefined); } +/** @internal */ export function getMappedDocumentSpan(documentSpan: ts.DocumentSpan, sourceMapper: ts.SourceMapper, fileExists?: (path: string) => boolean): ts.DocumentSpan | undefined { const { fileName, textSpan } = documentSpan; const newPosition = getMappedLocation({ fileName, pos: textSpan.start }, sourceMapper, fileExists); @@ -2154,6 +2293,7 @@ export function getMappedDocumentSpan(documentSpan: ts.DocumentSpan, sourceMappe }; } +/** @internal */ export function getMappedContextSpan(documentSpan: ts.DocumentSpan, sourceMapper: ts.SourceMapper, fileExists?: (path: string) => boolean): ts.TextSpan | undefined { const contextSpanStart = documentSpan.contextSpan && getMappedLocation( { fileName: documentSpan.fileName, pos: documentSpan.contextSpan.start }, @@ -2174,6 +2314,7 @@ export function getMappedContextSpan(documentSpan: ts.DocumentSpan, sourceMapper // Display-part writer helpers // #region +/** @internal */ export function isFirstDeclarationOfSymbolParameter(symbol: ts.Symbol) { const declaration = symbol.declarations ? ts.firstOrUndefined(symbol.declarations) : undefined; return !!ts.findAncestor(declaration, n => @@ -2273,6 +2414,7 @@ function getDisplayPartWriter(): ts.DisplayPartsSymbolWriter { } } +/** @internal */ export function symbolPart(text: string, symbol: ts.Symbol) { return displayPart(text, displayPartKind(symbol)); @@ -2300,34 +2442,42 @@ export function symbolPart(text: string, symbol: ts.Symbol) { } } +/** @internal */ export function displayPart(text: string, kind: ts.SymbolDisplayPartKind): ts.SymbolDisplayPart { return { text, kind: ts.SymbolDisplayPartKind[kind] }; } +/** @internal */ export function spacePart() { return displayPart(" ", ts.SymbolDisplayPartKind.space); } +/** @internal */ export function keywordPart(kind: ts.SyntaxKind) { return displayPart(ts.tokenToString(kind)!, ts.SymbolDisplayPartKind.keyword); } +/** @internal */ export function punctuationPart(kind: ts.SyntaxKind) { return displayPart(ts.tokenToString(kind)!, ts.SymbolDisplayPartKind.punctuation); } +/** @internal */ export function operatorPart(kind: ts.SyntaxKind) { return displayPart(ts.tokenToString(kind)!, ts.SymbolDisplayPartKind.operator); } +/** @internal */ export function parameterNamePart(text: string) { return displayPart(text, ts.SymbolDisplayPartKind.parameterName); } +/** @internal */ export function propertyNamePart(text: string) { return displayPart(text, ts.SymbolDisplayPartKind.propertyName); } +/** @internal */ export function textOrKeywordPart(text: string) { const kind = ts.stringToToken(text); return kind === undefined @@ -2335,22 +2485,27 @@ export function textOrKeywordPart(text: string) { : keywordPart(kind); } +/** @internal */ export function textPart(text: string) { return displayPart(text, ts.SymbolDisplayPartKind.text); } +/** @internal */ export function typeAliasNamePart(text: string) { return displayPart(text, ts.SymbolDisplayPartKind.aliasName); } +/** @internal */ export function typeParameterNamePart(text: string) { return displayPart(text, ts.SymbolDisplayPartKind.typeParameterName); } +/** @internal */ export function linkTextPart(text: string) { return displayPart(text, ts.SymbolDisplayPartKind.linkText); } +/** @internal */ export function linkNamePart(text: string, target: ts.Declaration): ts.JSDocLinkDisplayPart { return { text, @@ -2362,10 +2517,12 @@ export function linkNamePart(text: string, target: ts.Declaration): ts.JSDocLink }; } +/** @internal */ export function linkPart(text: string) { return displayPart(text, ts.SymbolDisplayPartKind.link); } +/** @internal */ export function buildLinkParts(link: ts.JSDocLink | ts.JSDocLinkCode | ts.JSDocLinkPlain, checker?: ts.TypeChecker): ts.SymbolDisplayPart[] { const prefix = ts.isJSDocLink(link) ? "link" : ts.isJSDocLinkCode(link) ? "linkcode" @@ -2418,6 +2575,7 @@ function findLinkNameEnd(text: string) { } const carriageReturnLineFeed = "\r\n"; +/** @internal */ /** * The default is CRLF. */ @@ -2427,10 +2585,12 @@ export function getNewLineOrDefaultFromHost(host: ts.FormattingHost, formatSetti carriageReturnLineFeed; } +/** @internal */ export function lineBreakPart() { return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); } +/** @internal */ export function mapToDisplayParts(writeDisplayParts: (writer: ts.DisplayPartsSymbolWriter) => void): ts.SymbolDisplayPart[] { try { writeDisplayParts(displayPartWriter); @@ -2441,18 +2601,21 @@ export function mapToDisplayParts(writeDisplayParts: (writer: ts.DisplayPartsSym } } +/** @internal */ export function typeToDisplayParts(typechecker: ts.TypeChecker, type: ts.Type, enclosingDeclaration?: ts.Node, flags: ts.TypeFormatFlags = ts.TypeFormatFlags.None): ts.SymbolDisplayPart[] { return mapToDisplayParts(writer => { typechecker.writeType(type, enclosingDeclaration, flags | ts.TypeFormatFlags.MultilineObjectLiterals | ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope, writer); }); } +/** @internal */ export function symbolToDisplayParts(typeChecker: ts.TypeChecker, symbol: ts.Symbol, enclosingDeclaration?: ts.Node, meaning?: ts.SymbolFlags, flags: ts.SymbolFormatFlags = ts.SymbolFormatFlags.None): ts.SymbolDisplayPart[] { return mapToDisplayParts(writer => { typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags | ts.SymbolFormatFlags.UseAliasDefinedOutsideCurrentScope, writer); }); } +/** @internal */ export function signatureToDisplayParts(typechecker: ts.TypeChecker, signature: ts.Signature, enclosingDeclaration?: ts.Node, flags: ts.TypeFormatFlags = ts.TypeFormatFlags.None): ts.SymbolDisplayPart[] { flags |= ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope | ts.TypeFormatFlags.MultilineObjectLiterals | ts.TypeFormatFlags.WriteTypeArgumentsOfSignature | ts.TypeFormatFlags.OmitParameterModifiers; return mapToDisplayParts(writer => { @@ -2460,6 +2623,7 @@ export function signatureToDisplayParts(typechecker: ts.TypeChecker, signature: }); } +/** @internal */ export function nodeToDisplayParts(node: ts.Node, enclosingDeclaration: ts.Node): ts.SymbolDisplayPart[] { const file = enclosingDeclaration.getSourceFile(); return mapToDisplayParts(writer => { @@ -2468,16 +2632,19 @@ export function nodeToDisplayParts(node: ts.Node, enclosingDeclaration: ts.Node) }); } +/** @internal */ export function isImportOrExportSpecifierName(location: ts.Node): location is ts.Identifier { return !!location.parent && ts.isImportOrExportSpecifier(location.parent) && location.parent.propertyName === location; } +/** @internal */ export function getScriptKind(fileName: string, host: ts.LanguageServiceHost): ts.ScriptKind { // First check to see if the script kind was specified by the host. Chances are the host // may override the default script kind for the file extension. return ts.ensureScriptKind(fileName, host.getScriptKind && host.getScriptKind(fileName)); } +/** @internal */ export function getSymbolTarget(symbol: ts.Symbol, checker: ts.TypeChecker): ts.Symbol { let next: ts.Symbol = symbol; while (isAliasSymbol(next) || (isTransientSymbol(next) && next.target)) { @@ -2499,10 +2666,12 @@ function isAliasSymbol(symbol: ts.Symbol): boolean { return (symbol.flags & ts.SymbolFlags.Alias) !== 0; } +/** @internal */ export function getUniqueSymbolId(symbol: ts.Symbol, checker: ts.TypeChecker) { return ts.getSymbolId(ts.skipAlias(symbol, checker)); } +/** @internal */ export function getFirstNonSpaceCharacterPosition(text: string, position: number) { while (ts.isWhiteSpaceLike(text.charCodeAt(position))) { position += 1; @@ -2510,6 +2679,7 @@ export function getFirstNonSpaceCharacterPosition(text: string, position: number return position; } +/** @internal */ export function getPrecedingNonSpaceCharacterPosition(text: string, position: number) { while (position > -1 && ts.isWhiteSpaceSingleLine(text.charCodeAt(position))) { position -= 1; @@ -2517,6 +2687,7 @@ export function getPrecedingNonSpaceCharacterPosition(text: string, position: nu return position + 1; } +/** @internal */ /** * Creates a deep, memberwise clone of a node with no source map location. * @@ -2529,6 +2700,7 @@ export function getSynthesizedDeepClone(node: T, return clone; } +/** @internal */ export function getSynthesizedDeepCloneWithReplacements( node: T, includeTrivia: boolean, @@ -2572,12 +2744,16 @@ function getSynthesizedDeepCloneWorker(node: T, replaceNode?: return visited; } +/** @internal */ export function getSynthesizedDeepClones(nodes: ts.NodeArray, includeTrivia?: boolean): ts.NodeArray; +/** @internal */ export function getSynthesizedDeepClones(nodes: ts.NodeArray | undefined, includeTrivia?: boolean): ts.NodeArray | undefined; +/** @internal */ export function getSynthesizedDeepClones(nodes: ts.NodeArray | undefined, includeTrivia = true): ts.NodeArray | undefined { return nodes && ts.factory.createNodeArray(nodes.map(n => getSynthesizedDeepClone(n, includeTrivia)), nodes.hasTrailingComma); } +/** @internal */ export function getSynthesizedDeepClonesWithReplacements( nodes: ts.NodeArray, includeTrivia: boolean, @@ -2586,6 +2762,7 @@ export function getSynthesizedDeepClonesWithReplacements( return ts.factory.createNodeArray(nodes.map(n => getSynthesizedDeepCloneWithReplacements(n, includeTrivia, replaceNode)), nodes.hasTrailingComma); } +/** @internal */ /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ @@ -2594,6 +2771,7 @@ export function suppressLeadingAndTrailingTrivia(node: ts.Node) { suppressTrailingTrivia(node); } +/** @internal */ /** * Sets EmitFlags to suppress leading trivia on the node. */ @@ -2601,6 +2779,7 @@ export function suppressLeadingTrivia(node: ts.Node) { addEmitFlagsRecursively(node, ts.EmitFlags.NoLeadingComments, getFirstChild); } +/** @internal */ /** * Sets EmitFlags to suppress trailing trivia on the node. */ @@ -2608,6 +2787,7 @@ export function suppressTrailingTrivia(node: ts.Node) { addEmitFlagsRecursively(node, ts.EmitFlags.NoTrailingComments, ts.getLastChild); } +/** @internal */ export function copyComments(sourceNode: ts.Node, targetNode: ts.Node) { const sourceFile = sourceNode.getSourceFile(); const text = sourceFile.text; @@ -2639,6 +2819,7 @@ function getFirstChild(node: ts.Node): ts.Node | undefined { return node.forEachChild(child => child); } +/** @internal */ export function getUniqueName(baseName: string, sourceFile: ts.SourceFile): string { let nameText = baseName; for (let i = 1; !ts.isFileLevelUniqueName(sourceFile, nameText); i++) { @@ -2647,6 +2828,7 @@ export function getUniqueName(baseName: string, sourceFile: ts.SourceFile): stri return nameText; } +/** @internal */ /** * @return The index of the (only) reference to the extracted symbol. We want the cursor * to be on the reference, rather than the declaration, because it's closer to where the @@ -2678,15 +2860,18 @@ export function getRenameLocation(edits: readonly ts.FileTextChanges[], renameFi return lastPos; } +/** @internal */ export function copyLeadingComments(sourceNode: ts.Node, targetNode: ts.Node, sourceFile: ts.SourceFile, commentKind?: ts.CommentKind, hasTrailingNewLine?: boolean) { ts.forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticLeadingComment)); } +/** @internal */ export function copyTrailingComments(sourceNode: ts.Node, targetNode: ts.Node, sourceFile: ts.SourceFile, commentKind?: ts.CommentKind, hasTrailingNewLine?: boolean) { ts.forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, ts.addSyntheticTrailingComment)); } +/** @internal */ /** * This function copies the trailing comments for the token that comes before `sourceNode`, as leading comments of `targetNode`. * This is useful because sometimes a comment that refers to `sourceNode` will be a leading comment for `sourceNode`, according to the @@ -2730,6 +2915,7 @@ export function needsParentheses(expression: ts.Expression): boolean { || ts.isAsExpression(expression) && ts.isObjectLiteralExpression(expression.expression); } +/** @internal */ export function getContextualTypeFromParent(node: ts.Expression, checker: ts.TypeChecker): ts.Type | undefined { const { parent } = node; switch (parent.kind) { @@ -2748,6 +2934,7 @@ export function getContextualTypeFromParent(node: ts.Expression, checker: ts.Typ } } +/** @internal */ export function quote(sourceFile: ts.SourceFile, preferences: ts.UserPreferences, text: string): string { // Editors can pass in undefined or empty string - we want to infer the preference in those cases. const quotePreference = getQuotePreference(sourceFile, preferences); @@ -2755,6 +2942,7 @@ export function quote(sourceFile: ts.SourceFile, preferences: ts.UserPreferences return quotePreference === QuotePreference.Single ? `'${ts.stripQuotes(quoted).replace(/'/g, "\\'").replace(/\\"/g, '"')}'` : quoted; } +/** @internal */ export function isEqualityOperatorKind(kind: ts.SyntaxKind): kind is ts.EqualityOperator { switch (kind) { case ts.SyntaxKind.EqualsEqualsEqualsToken: @@ -2767,6 +2955,7 @@ export function isEqualityOperatorKind(kind: ts.SyntaxKind): kind is ts.Equality } } +/** @internal */ export function isStringLiteralOrTemplate(node: ts.Node): node is ts.StringLiteralLike | ts.TemplateExpression | ts.TaggedTemplateExpression { switch (node.kind) { case ts.SyntaxKind.StringLiteral: @@ -2779,16 +2968,20 @@ export function isStringLiteralOrTemplate(node: ts.Node): node is ts.StringLiter } } +/** @internal */ export function hasIndexSignature(type: ts.Type): boolean { return !!type.getStringIndexType() || !!type.getNumberIndexType(); } +/** @internal */ export function getSwitchedType(caseClause: ts.CaseClause, checker: ts.TypeChecker): ts.Type | undefined { return checker.getTypeAtLocation(caseClause.parent.parent.expression); } +/** @internal */ export const ANONYMOUS = "anonymous function"; +/** @internal */ export function getTypeNodeIfAccessible(type: ts.Type, enclosingScope: ts.Node, program: ts.Program, host: ts.LanguageServiceHost): ts.TypeNode | undefined { const checker = program.getTypeChecker(); let typeIsAccessible = true; @@ -2826,6 +3019,7 @@ function syntaxRequiresTrailingModuleBlockOrSemicolonOrASI(kind: ts.SyntaxKind) return kind === ts.SyntaxKind.ModuleDeclaration; } +/** @internal */ export function syntaxRequiresTrailingSemicolonOrASI(kind: ts.SyntaxKind) { return kind === ts.SyntaxKind.VariableStatement || kind === ts.SyntaxKind.ExpressionStatement @@ -2844,6 +3038,7 @@ export function syntaxRequiresTrailingSemicolonOrASI(kind: ts.SyntaxKind) { || kind === ts.SyntaxKind.ExportAssignment; } +/** @internal */ export const syntaxMayBeASICandidate = ts.or( syntaxRequiresTrailingCommaOrSemicolonOrASI, syntaxRequiresTrailingFunctionBlockOrSemicolonOrASI, @@ -2893,6 +3088,7 @@ function nodeIsASICandidate(node: ts.Node, sourceFile: ts.SourceFileLike): boole return startLine !== endLine; } +/** @internal */ export function positionIsASICandidate(pos: number, context: ts.Node, sourceFile: ts.SourceFileLike): boolean { const contextAncestor = ts.findAncestor(context, ancestor => { if (ancestor.end !== pos) { @@ -2904,6 +3100,7 @@ export function positionIsASICandidate(pos: number, context: ts.Node, sourceFile return !!contextAncestor && nodeIsASICandidate(contextAncestor, sourceFile); } +/** @internal */ export function probablyUsesSemicolons(sourceFile: ts.SourceFile): boolean { let withSemicolon = 0; let withoutSemicolon = 0; @@ -2951,22 +3148,27 @@ export function probablyUsesSemicolons(sourceFile: ts.SourceFile): boolean { return withSemicolon / withoutSemicolon > 1 / nStatementsToObserve; } +/** @internal */ export function tryGetDirectories(host: Pick, directoryName: string): string[] { return tryIOAndConsumeErrors(host, host.getDirectories, directoryName) || []; } +/** @internal */ export function tryReadDirectory(host: Pick, path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[]): readonly string[] { return tryIOAndConsumeErrors(host, host.readDirectory, path, extensions, exclude, include) || ts.emptyArray; } +/** @internal */ export function tryFileExists(host: Pick, path: string): boolean { return tryIOAndConsumeErrors(host, host.fileExists, path); } +/** @internal */ export function tryDirectoryExists(host: ts.LanguageServiceHost, path: string): boolean { return tryAndIgnoreErrors(() => ts.directoryProbablyExists(path, host)) || false; } +/** @internal */ export function tryAndIgnoreErrors(cb: () => T): T | undefined { try { return cb(); @@ -2976,10 +3178,12 @@ export function tryAndIgnoreErrors(cb: () => T): T | undefined { } } +/** @internal */ export function tryIOAndConsumeErrors(host: unknown, toApply: ((...a: any[]) => T) | undefined, ...args: any[]) { return tryAndIgnoreErrors(() => toApply && toApply.apply(host, args)); } +/** @internal */ export function findPackageJsons(startDirectory: string, host: Pick, stopDirectory?: string): string[] { const paths: string[] = []; ts.forEachAncestorDirectory(startDirectory, ancestor => { @@ -2994,6 +3198,7 @@ export function findPackageJsons(startDirectory: string, host: Pick { @@ -3006,6 +3211,7 @@ export function findPackageJson(directory: string, host: ts.LanguageServiceHost) return packageJson; } +/** @internal */ export function getPackageJsonsVisibleToFile(fileName: string, host: ts.LanguageServiceHost): readonly ts.ProjectPackageJsonInfo[] { if (!host.fileExists) { return []; @@ -3025,6 +3231,7 @@ export function getPackageJsonsVisibleToFile(fileName: string, host: ts.Language return packageJsons; } +/** @internal */ export function createPackageJsonInfo(fileName: string, host: { readFile?(fileName: string): string | undefined }): ts.ProjectPackageJsonInfo | undefined { if (!host.readFile) { return undefined; @@ -3078,6 +3285,7 @@ export function createPackageJsonInfo(fileName: string, host: { readFile?(fileNa } } +/** @internal */ export interface PackageJsonImportFilter { allowsImportingAmbientModule: (moduleSymbol: ts.Symbol, moduleSpecifierResolutionHost: ts.ModuleSpecifierResolutionHost) => boolean; allowsImportingSourceFile: (sourceFile: ts.SourceFile, moduleSpecifierResolutionHost: ts.ModuleSpecifierResolutionHost) => boolean; @@ -3089,6 +3297,7 @@ export interface PackageJsonImportFilter { allowsImportingSpecifier: (moduleSpecifier: string) => boolean; } +/** @internal */ export function createPackageJsonImportFilter(fromFile: ts.SourceFile, preferences: ts.UserPreferences, host: ts.LanguageServiceHost): PackageJsonImportFilter { const packageJsons = ( (host.getPackageJsonsVisibleToFile && host.getPackageJsonsVisibleToFile(fromFile.fileName)) || getPackageJsonsVisibleToFile(fromFile.fileName, host) @@ -3207,18 +3416,22 @@ function tryParseJson(text: string) { } } +/** @internal */ export function consumesNodeCoreModules(sourceFile: ts.SourceFile): boolean { return ts.some(sourceFile.imports, ({ text }) => ts.JsTyping.nodeCoreModules.has(text)); } +/** @internal */ export function isInsideNodeModules(fileOrDirectory: string): boolean { return ts.contains(ts.getPathComponents(fileOrDirectory), "node_modules"); } +/** @internal */ export function isDiagnosticWithLocation(diagnostic: ts.Diagnostic): diagnostic is ts.DiagnosticWithLocation { return diagnostic.file !== undefined && diagnostic.start !== undefined && diagnostic.length !== undefined; } +/** @internal */ export function findDiagnosticForNode(node: ts.Node, sortedFileDiagnostics: readonly ts.Diagnostic[]): ts.DiagnosticWithLocation | undefined { const span: Partial = createTextSpanFromNode(node); const index = ts.binarySearchKey(sortedFileDiagnostics, span, ts.identity, ts.compareTextSpans); @@ -3229,6 +3442,7 @@ export function findDiagnosticForNode(node: ts.Node, sortedFileDiagnostics: read } } +/** @internal */ export function getDiagnosticsWithinSpan(span: ts.TextSpan, sortedFileDiagnostics: readonly ts.Diagnostic[]): readonly ts.DiagnosticWithLocation[] { let index = ts.binarySearchKey(sortedFileDiagnostics, span.start, diag => diag.start, ts.compareValues); if (index < 0) { @@ -3275,18 +3489,24 @@ export function getFixableErrorSpanExpression(sourceFile: ts.SourceFile, span: t return expression; } +/** @internal */ /** * If the provided value is an array, the mapping function is applied to each element; otherwise, the mapping function is applied * to the provided value itself. */ export function mapOneOrMany(valueOrArray: T | readonly T[], f: (x: T, i: number) => U): U | U[]; +/** @internal */ export function mapOneOrMany(valueOrArray: T | readonly T[] | undefined, f: (x: T, i: number) => U): U | U[] | undefined; +/** @internal */ export function mapOneOrMany(valueOrArray: T | readonly T[], f: (x: T, i: number) => U, resultSelector: (x: U[]) => U): U; +/** @internal */ export function mapOneOrMany(valueOrArray: T | readonly T[] | undefined, f: (x: T, i: number) => U, resultSelector: (x: U[]) => U): U | undefined; +/** @internal */ export function mapOneOrMany(valueOrArray: T | readonly T[] | undefined, f: (x: T, i: number) => U, resultSelector: (x: U[]) => U | U[] = ts.identity): U | U[] | undefined { return valueOrArray ? ts.isArray(valueOrArray) ? resultSelector(ts.map(valueOrArray, f)) : f(valueOrArray, 0) : undefined; } +/** @internal */ /** * If the provided value is an array, the first element of the array is returned; otherwise, the provided value is returned instead. */ @@ -3294,6 +3514,7 @@ export function firstOrOnly(valueOrArray: T | readonly T[]): T { return ts.isArray(valueOrArray) ? ts.first(valueOrArray) : valueOrArray; } +/** @internal */ export function getNamesForExportedSymbol(symbol: ts.Symbol, scriptTarget: ts.ScriptTarget | undefined): string | [lowercase: string, capitalized: string] { if (needsNameFromDeclaration(symbol)) { const fromDeclaration = getDefaultLikeExportNameFromDeclaration(symbol); @@ -3306,6 +3527,7 @@ export function getNamesForExportedSymbol(symbol: ts.Symbol, scriptTarget: ts.Sc return symbol.name; } +/** @internal */ export function getNameForExportedSymbol(symbol: ts.Symbol, scriptTarget: ts.ScriptTarget | undefined, preferCapitalized?: boolean) { if (needsNameFromDeclaration(symbol)) { // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. @@ -3336,6 +3558,7 @@ function getSymbolParentOrFail(symbol: ts.Symbol) { }).join(", ")}.`); } +/** @internal */ /** * Useful to check whether a string contains another string at a specific index * without allocating another string or traversing the entire contents of the outer string. @@ -3365,14 +3588,17 @@ export function stringContainsAt(haystack: string, needle: string, startIndex: n return true; } +/** @internal */ export function startsWithUnderscore(name: string): boolean { return name.charCodeAt(0) === ts.CharacterCodes._; } +/** @internal */ export function isGlobalDeclaration(declaration: ts.Declaration) { return !isNonGlobalDeclaration(declaration); } +/** @internal */ export function isNonGlobalDeclaration(declaration: ts.Declaration) { const sourceFile = declaration.getSourceFile(); // If the file is not a module, the declaration is global @@ -3383,10 +3609,12 @@ export function isNonGlobalDeclaration(declaration: ts.Declaration) { return ts.isInJSFile(declaration) || !ts.findAncestor(declaration, ts.isGlobalScopeAugmentation); } +/** @internal */ export function isDeprecatedDeclaration(decl: ts.Declaration) { return !!(ts.getCombinedNodeFlagsAlwaysIncludeJSDoc(decl) & ts.ModifierFlags.Deprecated); } +/** @internal */ export function shouldUseUriStyleNodeCoreModules(file: ts.SourceFile, program: ts.Program): boolean { const decisionFromFile = ts.firstDefined(file.imports, node => { if (ts.JsTyping.nodeCoreModules.has(node.text)) { @@ -3396,17 +3624,21 @@ export function shouldUseUriStyleNodeCoreModules(file: ts.SourceFile, program: t return decisionFromFile ?? program.usesUriStyleNodeCoreModules; } +/** @internal */ export function getNewLineKind(newLineCharacter: string): ts.NewLineKind { return newLineCharacter === "\n" ? ts.NewLineKind.LineFeed : ts.NewLineKind.CarriageReturnLineFeed; } +/** @internal */ export type DiagnosticAndArguments = ts.DiagnosticMessage | [ts.DiagnosticMessage, string] | [ts.DiagnosticMessage, string, string]; +/** @internal */ export function diagnosticToString(diag: DiagnosticAndArguments): string { return ts.isArray(diag) ? ts.formatStringFromArgs(ts.getLocaleSpecificMessage(diag[0]), diag.slice(1) as readonly string[]) : ts.getLocaleSpecificMessage(diag); } +/** @internal */ /** * Get format code settings for a code writing context (e.g. when formatting text changes or completions code). */ @@ -3419,13 +3651,12 @@ export function getFormatCodeSettingsForWriting({ options }: ts.formatting.Forma }; } +/** @internal */ export function jsxModeNeedsExplicitImport(jsx: ts.JsxEmit | undefined) { return jsx === ts.JsxEmit.React || jsx === ts.JsxEmit.ReactNative; } +/** @internal */ export function isSourceFileFromLibrary(program: ts.Program, node: ts.SourceFile) { return program.isSourceFileFromExternalLibrary(node) || program.isSourceFileDefaultLibrary(node); } - -// #endregion -} diff --git a/src/testRunner/_namespaces/FourSlash.ts b/src/testRunner/_namespaces/FourSlash.ts new file mode 100644 index 0000000000000..b314d7d2e24bf --- /dev/null +++ b/src/testRunner/_namespaces/FourSlash.ts @@ -0,0 +1,4 @@ +/* Generated file to emulate the FourSlash namespace. */ + +export * from "../../harness/_namespaces/FourSlash"; +export * from "../fourslashRef"; diff --git a/src/testRunner/_namespaces/Harness.Parallel.Host.ts b/src/testRunner/_namespaces/Harness.Parallel.Host.ts new file mode 100644 index 0000000000000..8104cc9ecfdf6 --- /dev/null +++ b/src/testRunner/_namespaces/Harness.Parallel.Host.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the Harness.Parallel.Host namespace. */ + +export * from "../parallel/host"; diff --git a/src/testRunner/_namespaces/Harness.Parallel.Worker.ts b/src/testRunner/_namespaces/Harness.Parallel.Worker.ts new file mode 100644 index 0000000000000..ecca4b9659e6e --- /dev/null +++ b/src/testRunner/_namespaces/Harness.Parallel.Worker.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the Harness.Parallel.Worker namespace. */ + +export * from "../parallel/worker"; diff --git a/src/testRunner/_namespaces/Harness.Parallel.ts b/src/testRunner/_namespaces/Harness.Parallel.ts new file mode 100644 index 0000000000000..10087db7557c3 --- /dev/null +++ b/src/testRunner/_namespaces/Harness.Parallel.ts @@ -0,0 +1,7 @@ +/* Generated file to emulate the Harness.Parallel namespace. */ + +export * from "../parallel/shared"; +import * as Host from "./Harness.Parallel.Host"; +export { Host }; +import * as Worker from "./Harness.Parallel.Worker"; +export { Worker }; diff --git a/src/testRunner/_namespaces/Harness.ts b/src/testRunner/_namespaces/Harness.ts new file mode 100644 index 0000000000000..eeef44fbd754b --- /dev/null +++ b/src/testRunner/_namespaces/Harness.ts @@ -0,0 +1,11 @@ +/* Generated file to emulate the Harness namespace. */ + +export * from "../../harness/_namespaces/Harness"; +export * from "../../loggedIO/_namespaces/Harness"; +export * from "../fourslashRunner"; +export * from "../compilerRunner"; +export * from "../externalCompileRunner"; +export * from "../test262Runner"; +export * from "../runner"; +import * as Parallel from "./Harness.Parallel"; +export { Parallel }; diff --git a/src/testRunner/_namespaces/Playback.ts b/src/testRunner/_namespaces/Playback.ts new file mode 100644 index 0000000000000..756f8f0e4eddc --- /dev/null +++ b/src/testRunner/_namespaces/Playback.ts @@ -0,0 +1,4 @@ +/* Generated file to emulate the Playback namespace. */ + +export * from "../../loggedIO/_namespaces/Playback"; +export * from "../playbackRef"; diff --git a/src/testRunner/_namespaces/RWC.ts b/src/testRunner/_namespaces/RWC.ts new file mode 100644 index 0000000000000..a2d6ebf4fa866 --- /dev/null +++ b/src/testRunner/_namespaces/RWC.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the RWC namespace. */ + +export * from "../rwcRunner"; diff --git a/src/testRunner/_namespaces/Utils.ts b/src/testRunner/_namespaces/Utils.ts new file mode 100644 index 0000000000000..69e9f1e29d042 --- /dev/null +++ b/src/testRunner/_namespaces/Utils.ts @@ -0,0 +1,4 @@ +/* Generated file to emulate the Utils namespace. */ + +export * from "../../harness/_namespaces/Utils"; +export * from "../utilsRef"; diff --git a/src/testRunner/_namespaces/compiler.ts b/src/testRunner/_namespaces/compiler.ts new file mode 100644 index 0000000000000..b0836c2749afc --- /dev/null +++ b/src/testRunner/_namespaces/compiler.ts @@ -0,0 +1,4 @@ +/* Generated file to emulate the compiler namespace. */ + +export * from "../../harness/_namespaces/compiler"; +export * from "../compilerRef"; diff --git a/src/testRunner/_namespaces/documents.ts b/src/testRunner/_namespaces/documents.ts new file mode 100644 index 0000000000000..ceeb38f29c6b9 --- /dev/null +++ b/src/testRunner/_namespaces/documents.ts @@ -0,0 +1,4 @@ +/* Generated file to emulate the documents namespace. */ + +export * from "../../harness/_namespaces/documents"; +export * from "../documentsRef"; diff --git a/src/testRunner/_namespaces/evaluator.ts b/src/testRunner/_namespaces/evaluator.ts new file mode 100644 index 0000000000000..26676e38c3e55 --- /dev/null +++ b/src/testRunner/_namespaces/evaluator.ts @@ -0,0 +1,4 @@ +/* Generated file to emulate the evaluator namespace. */ + +export * from "../../harness/_namespaces/evaluator"; +export * from "../evaluatorRef"; diff --git a/src/testRunner/_namespaces/fakes.ts b/src/testRunner/_namespaces/fakes.ts new file mode 100644 index 0000000000000..f783f8f72b1dc --- /dev/null +++ b/src/testRunner/_namespaces/fakes.ts @@ -0,0 +1,4 @@ +/* Generated file to emulate the fakes namespace. */ + +export * from "../../harness/_namespaces/fakes"; +export * from "../fakesRef"; diff --git a/src/testRunner/_namespaces/project.ts b/src/testRunner/_namespaces/project.ts new file mode 100644 index 0000000000000..c9d999adbfff1 --- /dev/null +++ b/src/testRunner/_namespaces/project.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the project namespace. */ + +export * from "../projectsRunner"; diff --git a/src/testRunner/_namespaces/ts.projectSystem.ts b/src/testRunner/_namespaces/ts.projectSystem.ts new file mode 100644 index 0000000000000..48038443996c7 --- /dev/null +++ b/src/testRunner/_namespaces/ts.projectSystem.ts @@ -0,0 +1,69 @@ +/* Generated file to emulate the ts.projectSystem namespace. */ + +export * from "../unittests/tsserver/helpers"; +export * from "../unittests/tsserver/applyChangesToOpenFiles"; +export * from "../unittests/tsserver/autoImportProvider"; +export * from "../unittests/tsserver/auxiliaryProject"; +export * from "../unittests/tsserver/cachingFileSystemInformation"; +export * from "../unittests/tsserver/cancellationToken"; +export * from "../unittests/tsserver/compileOnSave"; +export * from "../unittests/tsserver/completions"; +export * from "../unittests/tsserver/completionsIncomplete"; +export * from "../unittests/tsserver/configFileSearch"; +export * from "../unittests/tsserver/configuredProjects"; +export * from "../unittests/tsserver/declarationFileMaps"; +export * from "../unittests/tsserver/documentRegistry"; +export * from "../unittests/tsserver/duplicatePackages"; +export * from "../unittests/tsserver/dynamicFiles"; +export * from "../unittests/tsserver/events/largeFileReferenced"; +export * from "../unittests/tsserver/events/projectLanguageServiceState"; +export * from "../unittests/tsserver/events/projectLoading"; +export * from "../unittests/tsserver/events/projectUpdatedInBackground"; +export * from "../unittests/tsserver/exportMapCache"; +export * from "../unittests/tsserver/externalProjects"; +export * from "../unittests/tsserver/forceConsistentCasingInFileNames"; +export * from "../unittests/tsserver/formatSettings"; +export * from "../unittests/tsserver/getApplicableRefactors"; +export * from "../unittests/tsserver/getEditsForFileRename"; +export * from "../unittests/tsserver/getExportReferences"; +export * from "../unittests/tsserver/getFileReferences"; +export * from "../unittests/tsserver/importHelpers"; +export * from "../unittests/tsserver/inlayHints"; +export * from "../unittests/tsserver/inferredProjects"; +export * from "../unittests/tsserver/jsdocTag"; +export * from "../unittests/tsserver/languageService"; +export * from "../unittests/tsserver/maxNodeModuleJsDepth"; +export * from "../unittests/tsserver/metadataInResponse"; +export * from "../unittests/tsserver/moduleResolution"; +export * from "../unittests/tsserver/moduleSpecifierCache"; +export * from "../unittests/tsserver/navTo"; +export * from "../unittests/tsserver/occurences"; +export * from "../unittests/tsserver/openFile"; +export * from "../unittests/tsserver/packageJsonInfo"; +export * from "../unittests/tsserver/partialSemanticServer"; +export * from "../unittests/tsserver/plugins"; +export * from "../unittests/tsserver/projectErrors"; +export * from "../unittests/tsserver/projectReferenceCompileOnSave"; +export * from "../unittests/tsserver/projectReferenceErrors"; +export * from "../unittests/tsserver/projectReferences"; +export * from "../unittests/tsserver/projectReferencesSourcemap"; +export * from "../unittests/tsserver/projects"; +export * from "../unittests/tsserver/projectsWithReferences"; +export * from "../unittests/tsserver/refactors"; +export * from "../unittests/tsserver/reload"; +export * from "../unittests/tsserver/reloadProjects"; +export * from "../unittests/tsserver/rename"; +export * from "../unittests/tsserver/resolutionCache"; +export * from "../unittests/tsserver/skipLibCheck"; +export * from "../unittests/tsserver/smartSelection"; +export * from "../unittests/tsserver/symlinkCache"; +export * from "../unittests/tsserver/symLinks"; +export * from "../unittests/tsserver/syntacticServer"; +export * from "../unittests/tsserver/syntaxOperations"; +export * from "../unittests/tsserver/telemetry"; +export * from "../unittests/tsserver/typeAquisition"; +export * from "../unittests/tsserver/typeOnlyImportChains"; +export * from "../unittests/tsserver/typeReferenceDirectives"; +export * from "../unittests/tsserver/typingsInstaller"; +export * from "../unittests/tsserver/watchEnvironment"; +export * from "../unittests/tsserver/webServer"; diff --git a/src/testRunner/_namespaces/ts.server.ts b/src/testRunner/_namespaces/ts.server.ts new file mode 100644 index 0000000000000..55f4afed9df57 --- /dev/null +++ b/src/testRunner/_namespaces/ts.server.ts @@ -0,0 +1,9 @@ +/* Generated file to emulate the ts.server namespace. */ + +export * from "../../jsTyping/_namespaces/ts.server"; +export * from "../../server/_namespaces/ts.server"; +export * from "../../webServer/_namespaces/ts.server"; +export * from "../../typingsInstallerCore/_namespaces/ts.server"; +export * from "../../harness/_namespaces/ts.server"; +export * from "../../loggedIO/_namespaces/ts.server"; +export * from "../unittests/tsserver/session"; diff --git a/src/testRunner/_namespaces/ts.textStorage.ts b/src/testRunner/_namespaces/ts.textStorage.ts new file mode 100644 index 0000000000000..1243be98aed05 --- /dev/null +++ b/src/testRunner/_namespaces/ts.textStorage.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.textStorage namespace. */ + +export * from "../unittests/tsserver/textStorage"; diff --git a/src/testRunner/_namespaces/ts.ts b/src/testRunner/_namespaces/ts.ts new file mode 100644 index 0000000000000..61c9fa3aed284 --- /dev/null +++ b/src/testRunner/_namespaces/ts.ts @@ -0,0 +1,97 @@ +/* Generated file to emulate the ts namespace. */ + +export * from "../../compiler/_namespaces/ts"; +export * from "../../executeCommandLine/_namespaces/ts"; +export * from "../../services/_namespaces/ts"; +export * from "../../jsTyping/_namespaces/ts"; +export * from "../../server/_namespaces/ts"; +export * from "../../webServer/_namespaces/ts"; +export * from "../../typingsInstallerCore/_namespaces/ts"; +export * from "../../deprecatedCompat/_namespaces/ts"; +export * from "../../harness/_namespaces/ts"; +export * from "../../loggedIO/_namespaces/ts"; +export * from "../unittests/services/extract/helpers"; +export * from "../unittests/tsbuild/helpers"; +export * from "../unittests/tsc/helpers"; +export * from "../unittests/asserts"; +export * from "../unittests/base64"; +export * from "../unittests/builder"; +export * from "../unittests/comments"; +export * from "../unittests/compilerCore"; +export * from "../unittests/convertToBase64"; +export * from "../unittests/customTransforms"; +export * from "../unittests/factory"; +export * from "../unittests/incrementalParser"; +export * from "../unittests/jsDocParsing"; +export * from "../unittests/jsonParserRecovery"; +export * from "../unittests/moduleResolution"; +export * from "../unittests/parsePseudoBigInt"; +export * from "../unittests/printer"; +export * from "../unittests/programApi"; +export * from "../unittests/reuseProgramStructure"; +export * from "../unittests/semver"; +export * from "../unittests/transform"; +export * from "../unittests/config/commandLineParsing"; +export * from "../unittests/config/configurationExtension"; +export * from "../unittests/config/convertCompilerOptionsFromJson"; +export * from "../unittests/config/convertTypeAcquisitionFromJson"; +export * from "../unittests/config/initializeTSConfig"; +export * from "../unittests/config/matchFiles"; +export * from "../unittests/config/projectReferences"; +export * from "../unittests/config/showConfig"; +export * from "../unittests/config/tsconfigParsing"; +export * from "../unittests/config/tsconfigParsingWatchOptions"; +export * from "../unittests/services/cancellableLanguageServiceOperations"; +export * from "../unittests/services/convertToAsyncFunction"; +export * from "../unittests/services/extract/constants"; +export * from "../unittests/services/extract/functions"; +export * from "../unittests/services/extract/symbolWalker"; +export * from "../unittests/services/extract/ranges"; +export * from "../unittests/services/hostNewLineSupport"; +export * from "../unittests/services/languageService"; +export * from "../unittests/services/organizeImports"; +export * from "../unittests/services/textChanges"; +export * from "../unittests/services/transpile"; +export * from "../unittests/tsbuild/amdModulesWithOut"; +export * from "../unittests/tsbuild/clean"; +export * from "../unittests/tsbuild/commandLine"; +export * from "../unittests/tsbuild/configFileErrors"; +export * from "../unittests/tsbuild/configFileExtends"; +export * from "../unittests/tsbuild/containerOnlyReferenced"; +export * from "../unittests/tsbuild/declarationEmit"; +export * from "../unittests/tsbuild/demo"; +export * from "../unittests/tsbuild/emitDeclarationOnly"; +export * from "../unittests/tsbuild/emptyFiles"; +export * from "../unittests/tsbuild/exitCodeOnBogusFile"; +export * from "../unittests/tsbuild/graphOrdering"; +export * from "../unittests/tsbuild/inferredTypeFromTransitiveModule"; +export * from "../unittests/tsbuild/javascriptProjectEmit"; +export * from "../unittests/tsbuild/lateBoundSymbol"; +export * from "../unittests/tsbuild/moduleSpecifiers"; +export * from "../unittests/tsbuild/noEmit"; +export * from "../unittests/tsbuild/noEmitOnError"; +export * from "../unittests/tsbuild/outFile"; +export * from "../unittests/tsbuild/outputPaths"; +export * from "../unittests/tsbuild/publicApi"; +export * from "../unittests/tsbuild/referencesWithRootDirInParent"; +export * from "../unittests/tsbuild/resolveJsonModule"; +export * from "../unittests/tsbuild/sample"; +export * from "../unittests/tsbuild/transitiveReferences"; +export * from "../unittests/tsc/composite"; +export * from "../unittests/tsc/declarationEmit"; +export * from "../unittests/tsc/forceConsistentCasingInFileNames"; +export * from "../unittests/tsc/incremental"; +export * from "../unittests/tsc/listFilesOnly"; +export * from "../unittests/tsc/projectReferences"; +export * from "../unittests/tsc/redirect"; +export * from "../unittests/tsc/runWithoutArgs"; +export * from "../unittests/tsserver/versionCache"; +export * from "../unittests/debugDeprecation"; +import * as tscWatch from "./ts.tscWatch"; +export { tscWatch }; +import * as projectSystem from "./ts.projectSystem"; +export { projectSystem }; +import * as server from "./ts.server"; +export { server }; +import * as textStorage from "./ts.textStorage"; +export { textStorage }; diff --git a/src/testRunner/_namespaces/ts.tscWatch.ts b/src/testRunner/_namespaces/ts.tscWatch.ts new file mode 100644 index 0000000000000..3220ae1aa9239 --- /dev/null +++ b/src/testRunner/_namespaces/ts.tscWatch.ts @@ -0,0 +1,28 @@ +/* Generated file to emulate the ts.tscWatch namespace. */ + +export * from "../unittests/tscWatch/helpers"; +export * from "../unittests/tsbuild/moduleResolution"; +export * from "../unittests/tsbuildWatch/configFileErrors"; +export * from "../unittests/tsbuildWatch/demo"; +export * from "../unittests/tsbuildWatch/moduleResolution"; +export * from "../unittests/tsbuildWatch/noEmit"; +export * from "../unittests/tsbuildWatch/noEmitOnError"; +export * from "../unittests/tsbuildWatch/programUpdates"; +export * from "../unittests/tsbuildWatch/projectsBuilding"; +export * from "../unittests/tsbuildWatch/publicApi"; +export * from "../unittests/tsbuildWatch/reexport"; +export * from "../unittests/tsbuildWatch/watchEnvironment"; +export * from "../unittests/tsc/cancellationToken"; +export * from "../unittests/tscWatch/consoleClearing"; +export * from "../unittests/tscWatch/emit"; +export * from "../unittests/tscWatch/nodeNextWatch"; +export * from "../unittests/tscWatch/emitAndErrorUpdates"; +export * from "../unittests/tscWatch/forceConsistentCasingInFileNames"; +export * from "../unittests/tscWatch/incremental"; +export * from "../unittests/tscWatch/moduleResolution"; +export * from "../unittests/tscWatch/programUpdates"; +export * from "../unittests/tscWatch/projectsWithReferences"; +export * from "../unittests/tscWatch/resolutionCache"; +export * from "../unittests/tscWatch/sourceOfProjectReferenceRedirect"; +export * from "../unittests/tscWatch/watchApi"; +export * from "../unittests/tscWatch/watchEnvironment"; diff --git a/src/testRunner/_namespaces/vfs.ts b/src/testRunner/_namespaces/vfs.ts new file mode 100644 index 0000000000000..3a8b4f1e4acbe --- /dev/null +++ b/src/testRunner/_namespaces/vfs.ts @@ -0,0 +1,4 @@ +/* Generated file to emulate the vfs namespace. */ + +export * from "../../harness/_namespaces/vfs"; +export * from "../vfsRef"; diff --git a/src/testRunner/_namespaces/vpath.ts b/src/testRunner/_namespaces/vpath.ts new file mode 100644 index 0000000000000..4b1fd139b3b5a --- /dev/null +++ b/src/testRunner/_namespaces/vpath.ts @@ -0,0 +1,4 @@ +/* Generated file to emulate the vpath namespace. */ + +export * from "../../harness/_namespaces/vpath"; +export * from "../vpathRef"; diff --git a/src/testRunner/compilerRef.ts b/src/testRunner/compilerRef.ts index b76e4e72fbb88..c524071b842bd 100644 --- a/src/testRunner/compilerRef.ts +++ b/src/testRunner/compilerRef.ts @@ -1,2 +1,2 @@ // empty ref to compiler so it can be referenced by unittests -namespace compiler {} \ No newline at end of file +export { }; diff --git a/src/testRunner/compilerRunner.ts b/src/testRunner/compilerRunner.ts index 2681cc908a1c8..2cbcf5d9a019a 100644 --- a/src/testRunner/compilerRunner.ts +++ b/src/testRunner/compilerRunner.ts @@ -1,4 +1,9 @@ -namespace Harness { +import * as Harness from "./_namespaces/Harness"; +import * as vpath from "./_namespaces/vpath"; +import * as ts from "./_namespaces/ts"; +import * as compiler from "./_namespaces/compiler"; +import * as Utils from "./_namespaces/Utils"; + export const enum CompilerTestType { Conformance, Regressions, @@ -340,4 +345,3 @@ class CompilerTest { return { unitName: unitName || this.makeUnitName(lastUnit.name, rootDir), content: lastUnit.content, fileOptions: lastUnit.fileOptions }; } } -} diff --git a/src/testRunner/documentsRef.ts b/src/testRunner/documentsRef.ts index d3d92746b4ed7..e1abbfb2d9c6d 100644 --- a/src/testRunner/documentsRef.ts +++ b/src/testRunner/documentsRef.ts @@ -1,2 +1,2 @@ // empty ref to documents so it can be referenced by unittests -namespace documents {} \ No newline at end of file +export { }; diff --git a/src/testRunner/evaluatorRef.ts b/src/testRunner/evaluatorRef.ts index cc81ec2402db5..965acc02d95be 100644 --- a/src/testRunner/evaluatorRef.ts +++ b/src/testRunner/evaluatorRef.ts @@ -1,2 +1,2 @@ // empty ref to evaluator so it can be referenced by unittests -namespace evaluator {} \ No newline at end of file +export { }; diff --git a/src/testRunner/externalCompileRunner.ts b/src/testRunner/externalCompileRunner.ts index b3cdab611f15f..21497e3a957cc 100644 --- a/src/testRunner/externalCompileRunner.ts +++ b/src/testRunner/externalCompileRunner.ts @@ -1,4 +1,6 @@ -namespace Harness { +import * as Harness from "./_namespaces/Harness"; +import * as ts from "./_namespaces/ts"; + const fs: typeof import("fs") = require("fs"); const path: typeof import("path") = require("path"); const del: typeof import("del") = require("del"); @@ -320,4 +322,3 @@ function splitBy(xs: T[], isStart: (x: T) => boolean): T[][] { } return result; } -} diff --git a/src/testRunner/fakesRef.ts b/src/testRunner/fakesRef.ts index b19d4cc8c80ed..ef7d690d5b64c 100644 --- a/src/testRunner/fakesRef.ts +++ b/src/testRunner/fakesRef.ts @@ -1,2 +1,2 @@ // empty ref to fakes so it can be referenced by unittests -namespace fakes {} \ No newline at end of file +export { }; diff --git a/src/testRunner/fourslashRef.ts b/src/testRunner/fourslashRef.ts index 23a50810a46af..7436f5ad2d7a2 100644 --- a/src/testRunner/fourslashRef.ts +++ b/src/testRunner/fourslashRef.ts @@ -1,2 +1,2 @@ // empty ref to FourSlash so it can be referenced by unittests -namespace FourSlash {} \ No newline at end of file +export { }; diff --git a/src/testRunner/fourslashRunner.ts b/src/testRunner/fourslashRunner.ts index 10a98bbebb0aa..80150babf747a 100644 --- a/src/testRunner/fourslashRunner.ts +++ b/src/testRunner/fourslashRunner.ts @@ -1,4 +1,7 @@ -namespace Harness { +import * as Harness from "./_namespaces/Harness"; +import * as FourSlash from "./_namespaces/FourSlash"; +import * as ts from "./_namespaces/ts"; + export class FourSlashRunner extends Harness.RunnerBase { protected basePath: string; protected testSuiteName: Harness.TestRunnerKind; @@ -69,4 +72,3 @@ export class GeneratedFourslashRunner extends FourSlashRunner { this.basePath += "/generated/"; } } -} diff --git a/src/testRunner/parallel/host.ts b/src/testRunner/parallel/host.ts index a8ddbfc58b46f..df852c07c5678 100644 --- a/src/testRunner/parallel/host.ts +++ b/src/testRunner/parallel/host.ts @@ -1,4 +1,7 @@ -namespace Harness.Parallel.Host { +import * as Harness from "../_namespaces/Harness"; +import * as Utils from "../_namespaces/Utils"; +import * as ts from "../_namespaces/ts"; + export function start() { const Mocha = require("mocha") as typeof import("mocha"); const Base = Mocha.reporters.Base; @@ -626,4 +629,3 @@ export function start() { // eslint-disable-next-line no-restricted-globals setTimeout(() => startDelayed(perfData, totalCost), 0); // Do real startup on next tick, so all unit tests have been collected } -} diff --git a/src/testRunner/parallel/shared.ts b/src/testRunner/parallel/shared.ts index 8df7b476d0d8b..141d9a7c3428e 100644 --- a/src/testRunner/parallel/shared.ts +++ b/src/testRunner/parallel/shared.ts @@ -1,4 +1,6 @@ -namespace Harness.Parallel { +import * as Harness from "../_namespaces/Harness"; +import * as ts from "../_namespaces/ts"; + export interface RunnerTask { runner: Harness.TestRunnerKind; file: string; @@ -85,4 +87,3 @@ export function shimNoopTestInterface(global: Mocha.MochaGlobals) { global.it.skip = global.xit = global.xspecify = ts.noop as Mocha.PendingTestFunction; global.it.only = ts.noop as Mocha.ExclusiveTestFunction; } -} diff --git a/src/testRunner/parallel/worker.ts b/src/testRunner/parallel/worker.ts index fed4d129a6d28..5c07637a5efd5 100644 --- a/src/testRunner/parallel/worker.ts +++ b/src/testRunner/parallel/worker.ts @@ -1,4 +1,6 @@ -namespace Harness.Parallel.Worker { +import * as Harness from "../_namespaces/Harness"; +import * as ts from "../_namespaces/ts"; + export function start() { function hookUncaughtExceptions() { if (!exceptionsHooked) { @@ -315,4 +317,3 @@ export function start() { process.on("message", processHostMessage); } -} diff --git a/src/testRunner/playbackRef.ts b/src/testRunner/playbackRef.ts index 8fcb9965e0923..9a46d5740c446 100644 --- a/src/testRunner/playbackRef.ts +++ b/src/testRunner/playbackRef.ts @@ -1,2 +1,2 @@ // empty ref to Playback so it can be referenced by unittests -namespace Playback {} \ No newline at end of file +export { }; diff --git a/src/testRunner/projectsRunner.ts b/src/testRunner/projectsRunner.ts index d43d1ec835381..6c1cfddaa07b2 100644 --- a/src/testRunner/projectsRunner.ts +++ b/src/testRunner/projectsRunner.ts @@ -1,4 +1,11 @@ -namespace project { +import * as ts from "./_namespaces/ts"; +import * as documents from "./_namespaces/documents"; +import * as Harness from "./_namespaces/Harness"; +import * as fakes from "./_namespaces/fakes"; +import * as vfs from "./_namespaces/vfs"; +import * as vpath from "./_namespaces/vpath"; +import * as Utils from "./_namespaces/Utils"; + // Test case is json of below type in tests/cases/project/ interface ProjectRunnerTestCase { scenario: string; @@ -463,4 +470,3 @@ function createCompilerOptions(testCase: ProjectRunnerTestCase & ts.CompilerOpti return compilerOptions; } -} diff --git a/src/testRunner/runner.ts b/src/testRunner/runner.ts index 8c72955eab876..885602c4d2835 100644 --- a/src/testRunner/runner.ts +++ b/src/testRunner/runner.ts @@ -1,4 +1,10 @@ -namespace Harness { +import * as Harness from "./_namespaces/Harness"; +import * as vpath from "./_namespaces/vpath"; +import * as ts from "./_namespaces/ts"; +import * as FourSlash from "./_namespaces/FourSlash"; +import * as project from "./_namespaces/project"; +import * as RWC from "./_namespaces/RWC"; + /* eslint-disable prefer-const */ export let runners: Harness.RunnerBase[] = []; export let iterations = 1; @@ -281,4 +287,3 @@ function startTestEnvironment() { } startTestEnvironment(); -} diff --git a/src/testRunner/rwcRunner.ts b/src/testRunner/rwcRunner.ts index ab6c0c69cd94b..a60657574ed0a 100644 --- a/src/testRunner/rwcRunner.ts +++ b/src/testRunner/rwcRunner.ts @@ -1,5 +1,10 @@ +import * as Playback from "./_namespaces/Playback"; +import * as Harness from "./_namespaces/Harness"; +import * as compiler from "./_namespaces/compiler"; +import * as ts from "./_namespaces/ts"; +import * as vpath from "./_namespaces/vpath"; + // In harness baselines, null is different than undefined. See `generateActual` in `harness.ts`. -namespace RWC { function runWithIOLog(ioLog: Playback.IoLog, fn: (oldIO: Harness.IO) => void) { const oldIO = Harness.IO; @@ -232,4 +237,3 @@ export class RWCRunner extends Harness.RunnerBase { runRWCTest(jsonFileName); } } -} diff --git a/src/testRunner/test262Runner.ts b/src/testRunner/test262Runner.ts index 11dcc50e7ed70..5d37cf49c1069 100644 --- a/src/testRunner/test262Runner.ts +++ b/src/testRunner/test262Runner.ts @@ -1,4 +1,8 @@ -namespace Harness { +import * as Harness from "./_namespaces/Harness"; +import * as ts from "./_namespaces/ts"; +import * as compiler from "./_namespaces/compiler"; +import * as Utils from "./_namespaces/Utils"; + // In harness baselines, null is different than undefined. See `generateActual` in `harness.ts`. export class Test262BaselineRunner extends Harness.RunnerBase { private static readonly basePath = "internal/cases/test262"; @@ -106,5 +110,4 @@ export class Test262BaselineRunner extends Harness.RunnerBase { this.tests.forEach(test => this.runTest(typeof test === "string" ? test : test.file)); } } -} } \ No newline at end of file diff --git a/src/testRunner/tsconfig.json b/src/testRunner/tsconfig.json index 5210426aad95f..f83f4e9584c6a 100644 --- a/src/testRunner/tsconfig.json +++ b/src/testRunner/tsconfig.json @@ -1,7 +1,7 @@ { "extends": "../tsconfig-noncomposite-base", "compilerOptions": { - "outFile": "../../built/local/run.js", + "outDir": "../../built/local", "composite": false, "declaration": false, "declarationMap": false, @@ -14,16 +14,16 @@ ] }, "references": [ - { "path": "../compiler", "prepend": true }, - { "path": "../executeCommandLine", "prepend": true }, - { "path": "../services", "prepend": true }, - { "path": "../jsTyping", "prepend": true }, - { "path": "../server", "prepend": true }, - { "path": "../webServer", "prepend": true }, - { "path": "../typingsInstallerCore", "prepend": true }, - { "path": "../deprecatedCompat", "prepend": true }, - { "path": "../harness", "prepend": true }, - { "path": "../loggedIO", "prepend": true } + { "path": "../compiler" }, + { "path": "../executeCommandLine" }, + { "path": "../services" }, + { "path": "../jsTyping" }, + { "path": "../server" }, + { "path": "../webServer" }, + { "path": "../typingsInstallerCore" }, + { "path": "../deprecatedCompat" }, + { "path": "../harness" }, + { "path": "../loggedIO" } ], "files": [ @@ -244,6 +244,26 @@ "unittests/tsserver/versionCache.ts", "unittests/tsserver/watchEnvironment.ts", "unittests/tsserver/webServer.ts", - "unittests/debugDeprecation.ts" + "unittests/debugDeprecation.ts", + "_namespaces/compiler.ts", + "_namespaces/Harness.ts", + "_namespaces/documents.ts", + "_namespaces/evaluator.ts", + "_namespaces/fakes.ts", + "_namespaces/FourSlash.ts", + "_namespaces/Playback.ts", + "_namespaces/project.ts", + "_namespaces/RWC.ts", + "_namespaces/Utils.ts", + "_namespaces/vfs.ts", + "_namespaces/vpath.ts", + "_namespaces/Harness.Parallel.Host.ts", + "_namespaces/Harness.Parallel.ts", + "_namespaces/Harness.Parallel.Worker.ts", + "_namespaces/ts.ts", + "_namespaces/ts.tscWatch.ts", + "_namespaces/ts.projectSystem.ts", + "_namespaces/ts.server.ts", + "_namespaces/ts.textStorage.ts" ] } diff --git a/src/testRunner/unittests/asserts.ts b/src/testRunner/unittests/asserts.ts index f84762d89bbc5..23d8e20a0df95 100644 --- a/src/testRunner/unittests/asserts.ts +++ b/src/testRunner/unittests/asserts.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; + describe("unittests:: assert", () => { it("deepEqual", () => { assert.throws(() => assert.deepEqual(ts.factory.createNodeArray([ts.factory.createIdentifier("A")]), ts.factory.createNodeArray([ts.factory.createIdentifier("B")]))); @@ -9,4 +10,3 @@ describe("unittests:: assert", () => { assert.throws(() => ts.Debug.assertNever("hi" as never), "Debug Failure. Illegal value: \"hi\""); }); }); -} diff --git a/src/testRunner/unittests/base64.ts b/src/testRunner/unittests/base64.ts index c2563f4e511b2..c952da51ef486 100644 --- a/src/testRunner/unittests/base64.ts +++ b/src/testRunner/unittests/base64.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; + describe("unittests:: base64", () => { describe("base64decode", () => { it("can decode input strings correctly without needing a host implementation", () => { @@ -19,4 +20,3 @@ describe("unittests:: base64", () => { }); }); }); -} diff --git a/src/testRunner/unittests/builder.ts b/src/testRunner/unittests/builder.ts index 1165c83d37535..6494c6f3bed65 100644 --- a/src/testRunner/unittests/builder.ts +++ b/src/testRunner/unittests/builder.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; + describe("unittests:: builder", () => { it("emits dependent files", () => { const files: ts.NamedSourceText[] = [ @@ -127,4 +128,3 @@ function updateProgramFile(program: ts.ProgramWithSourceTexts, fileName: string, ts.updateProgramText(files, fileName, fileContent); }); } -} diff --git a/src/testRunner/unittests/comments.ts b/src/testRunner/unittests/comments.ts index 8246ff05f9c44..74d6919285616 100644 --- a/src/testRunner/unittests/comments.ts +++ b/src/testRunner/unittests/comments.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; + describe("comment parsing", () => { const withShebang = `#! node /** comment */ @@ -29,4 +30,3 @@ describe("comment parsing", () => { assert.strictEqual(result![0].kind, ts.SyntaxKind.SingleLineCommentTrivia); }); }); -} diff --git a/src/testRunner/unittests/compilerCore.ts b/src/testRunner/unittests/compilerCore.ts index 99995322c49bf..1b7f82118016f 100644 --- a/src/testRunner/unittests/compilerCore.ts +++ b/src/testRunner/unittests/compilerCore.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; + describe("unittests:: compilerCore", () => { describe("equalOwnProperties", () => { it("correctly equates objects", () => { @@ -192,4 +193,3 @@ describe("unittests:: compilerCore", () => { }); }); }); -} diff --git a/src/testRunner/unittests/config/commandLineParsing.ts b/src/testRunner/unittests/config/commandLineParsing.ts index 6d7784656d48a..fbad23d8e029b 100644 --- a/src/testRunner/unittests/config/commandLineParsing.ts +++ b/src/testRunner/unittests/config/commandLineParsing.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; + describe("unittests:: config:: commandLineParsing:: parseCommandLine", () => { function assertParseResult(subScenario: string, commandLine: string[], workerDiagnostic?: () => ts.ParseCommandLineWorkerDiagnostics) { it(subScenario, () => { @@ -243,4 +245,3 @@ describe("unittests:: config:: commandLineParsing:: parseBuildOptions", () => { assertParseResult("errors on invalid excludeFiles", ["--excludeFiles", "**/../*"]); }); }); -} diff --git a/src/testRunner/unittests/config/configurationExtension.ts b/src/testRunner/unittests/config/configurationExtension.ts index 4f615935d264f..8434eb350cf60 100644 --- a/src/testRunner/unittests/config/configurationExtension.ts +++ b/src/testRunner/unittests/config/configurationExtension.ts @@ -1,4 +1,7 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as vfs from "../../_namespaces/vfs"; +import * as fakes from "../../_namespaces/fakes"; + function createFileSystem(ignoreCase: boolean, cwd: string, root: string) { return new vfs.FileSystem(ignoreCase, { cwd, @@ -351,4 +354,3 @@ describe("unittests:: config:: configurationExtension", () => { }); }); }); -} diff --git a/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts b/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts index efc43d27aaabb..0310c01f74b73 100644 --- a/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts +++ b/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts @@ -1,4 +1,7 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as fakes from "../../_namespaces/fakes"; +import * as vfs from "../../_namespaces/vfs"; + describe("unittests:: config:: convertCompilerOptionsFromJson", () => { const formatDiagnosticHost: ts.FormatDiagnosticsHost = { getCurrentDirectory: () => "/apath/", @@ -776,4 +779,3 @@ describe("unittests:: config:: convertCompilerOptionsFromJson", () => { }); }); }); -} diff --git a/src/testRunner/unittests/config/convertTypeAcquisitionFromJson.ts b/src/testRunner/unittests/config/convertTypeAcquisitionFromJson.ts index bac4de4b35cac..4f091721ddedc 100644 --- a/src/testRunner/unittests/config/convertTypeAcquisitionFromJson.ts +++ b/src/testRunner/unittests/config/convertTypeAcquisitionFromJson.ts @@ -1,4 +1,7 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as fakes from "../../_namespaces/fakes"; +import * as vfs from "../../_namespaces/vfs"; + interface ExpectedResult { typeAcquisition: ts.TypeAcquisition; errors: ts.Diagnostic[]; } describe("unittests:: config:: convertTypeAcquisitionFromJson", () => { function assertTypeAcquisition(json: any, configFileName: string, expectedResult: ExpectedResult) { @@ -236,4 +239,3 @@ describe("unittests:: config:: convertTypeAcquisitionFromJson", () => { }); }); }); -} diff --git a/src/testRunner/unittests/config/initializeTSConfig.ts b/src/testRunner/unittests/config/initializeTSConfig.ts index eff7edf16fc22..fee5b10b6bdf4 100644 --- a/src/testRunner/unittests/config/initializeTSConfig.ts +++ b/src/testRunner/unittests/config/initializeTSConfig.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; + describe("unittests:: config:: initTSConfig", () => { function initTSConfigCorrectly(name: string, commandLinesArgs: string[]) { describe(name, () => { @@ -34,4 +36,3 @@ describe("unittests:: config:: initTSConfig", () => { initTSConfigCorrectly("Initialized TSConfig with --watch", ["--init", "--watch"]); }); -} diff --git a/src/testRunner/unittests/config/matchFiles.ts b/src/testRunner/unittests/config/matchFiles.ts index 4cb13e7680240..18589d09fb015 100644 --- a/src/testRunner/unittests/config/matchFiles.ts +++ b/src/testRunner/unittests/config/matchFiles.ts @@ -1,4 +1,7 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as fakes from "../../_namespaces/fakes"; +import * as vfs from "../../_namespaces/vfs"; + const caseInsensitiveBasePath = "c:/dev/"; const caseInsensitiveTsconfigPath = "c:/dev/tsconfig.json"; const caseInsensitiveHost = new fakes.ParseConfigHost(new vfs.FileSystem(/*ignoreCase*/ true, { cwd: caseInsensitiveBasePath, files: { @@ -1539,4 +1542,3 @@ describe("unittests:: config:: matchFiles", () => { validateMatches(expected, json, host, caseInsensitiveBasePath); }); }); -} diff --git a/src/testRunner/unittests/config/projectReferences.ts b/src/testRunner/unittests/config/projectReferences.ts index 7a6390cb55dd9..e45fbb59abd04 100644 --- a/src/testRunner/unittests/config/projectReferences.ts +++ b/src/testRunner/unittests/config/projectReferences.ts @@ -1,4 +1,7 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as fakes from "../../_namespaces/fakes"; +import * as vfs from "../../_namespaces/vfs"; + interface TestProjectSpecification { configFileName?: string; references?: readonly (string | ts.ProjectReference)[]; @@ -349,4 +352,3 @@ describe("unittests:: config:: project-references errors when a file in a compos }); }); }); -} diff --git a/src/testRunner/unittests/config/showConfig.ts b/src/testRunner/unittests/config/showConfig.ts index 7f9f7082c7797..438bee2f111ee 100644 --- a/src/testRunner/unittests/config/showConfig.ts +++ b/src/testRunner/unittests/config/showConfig.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; + describe("unittests:: config:: showConfig", () => { function showTSConfigCorrectly(name: string, commandLinesArgs: string[], configJson?: object) { describe(name, () => { @@ -190,4 +192,3 @@ describe("unittests:: config:: showConfig", () => { showTSConfigCorrectly(`Shows tsconfig for single option/${option.name}`, args, configObject); } }); -} diff --git a/src/testRunner/unittests/config/tsconfigParsing.ts b/src/testRunner/unittests/config/tsconfigParsing.ts index b95cfb37e1aff..fc1d5c467939b 100644 --- a/src/testRunner/unittests/config/tsconfigParsing.ts +++ b/src/testRunner/unittests/config/tsconfigParsing.ts @@ -1,4 +1,7 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as vfs from "../../_namespaces/vfs"; +import * as fakes from "../../_namespaces/fakes"; + describe("unittests:: config:: tsconfigParsing:: parseConfigFileTextToJson", () => { function assertParseResult(jsonText: string, expectedConfigObject: { config?: any; error?: ts.Diagnostic[] }) { const parsed = ts.parseConfigFileTextToJson("/apath/tsconfig.json", jsonText); @@ -431,4 +434,3 @@ describe("unittests:: config:: tsconfigParsing:: parseConfigFileTextToJson", () assert.deepEqual(parsedCommand.wildcardDirectories, { "/foo": ts.WatchDirectoryFlags.Recursive }); }); }); -} diff --git a/src/testRunner/unittests/config/tsconfigParsingWatchOptions.ts b/src/testRunner/unittests/config/tsconfigParsingWatchOptions.ts index c9a6a1d80bd32..0a64f23e25aca 100644 --- a/src/testRunner/unittests/config/tsconfigParsingWatchOptions.ts +++ b/src/testRunner/unittests/config/tsconfigParsingWatchOptions.ts @@ -1,4 +1,8 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as vfs from "../../_namespaces/vfs"; +import * as fakes from "../../_namespaces/fakes"; +import * as Harness from "../../_namespaces/Harness"; + describe("unittests:: config:: tsconfigParsingWatchOptions:: parseConfigFileTextToJson", () => { function createParseConfigHost(additionalFiles?: vfs.FileSet) { return new fakes.ParseConfigHost( @@ -170,4 +174,3 @@ describe("unittests:: config:: tsconfigParsingWatchOptions:: parseConfigFileText }, ]); }); -} diff --git a/src/testRunner/unittests/convertToBase64.ts b/src/testRunner/unittests/convertToBase64.ts index 09f2ffb8abe7b..68a2f0e6818b5 100644 --- a/src/testRunner/unittests/convertToBase64.ts +++ b/src/testRunner/unittests/convertToBase64.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; + describe("unittests:: convertToBase64", () => { function runTest(input: string): void { const actual = ts.convertToBase64(input); @@ -30,4 +31,3 @@ console.log(x);`); }); } }); -} diff --git a/src/testRunner/unittests/customTransforms.ts b/src/testRunner/unittests/customTransforms.ts index 38dec84f7c71d..2579aa008bb96 100644 --- a/src/testRunner/unittests/customTransforms.ts +++ b/src/testRunner/unittests/customTransforms.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; +import * as Harness from "../_namespaces/Harness"; + describe("unittests:: customTransforms", () => { function emitsCorrectly(name: string, sources: { file: string, text: string }[], customTransformers: ts.CustomTransformers, options: ts.CompilerOptions = {}) { it(name, () => { @@ -165,4 +167,3 @@ describe("unittests:: customTransforms", () => { ); }); -} diff --git a/src/testRunner/unittests/debugDeprecation.ts b/src/testRunner/unittests/debugDeprecation.ts index c6835d6d220a4..862c386d9481a 100644 --- a/src/testRunner/unittests/debugDeprecation.ts +++ b/src/testRunner/unittests/debugDeprecation.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; + describe("unittests:: debugDeprecation", () => { let loggingHost: ts.LoggingHost | undefined; beforeEach(() => { @@ -93,5 +94,4 @@ describe("unittests:: debugDeprecation", () => { assert.isFalse(logWritten); }); }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/evaluation/arraySpread.ts b/src/testRunner/unittests/evaluation/arraySpread.ts index 61220a62caf40..e8f37ba755dde 100644 --- a/src/testRunner/unittests/evaluation/arraySpread.ts +++ b/src/testRunner/unittests/evaluation/arraySpread.ts @@ -1,3 +1,5 @@ +import * as evaluator from "../../_namespaces/evaluator"; + describe("unittests:: evaluation:: arraySpread", () => { it("array spread preserves side-effects", async () => { const result = evaluator.evaluateTypeScript(` diff --git a/src/testRunner/unittests/evaluation/asyncArrow.ts b/src/testRunner/unittests/evaluation/asyncArrow.ts index 04a7af613fa38..6521e89e2befd 100644 --- a/src/testRunner/unittests/evaluation/asyncArrow.ts +++ b/src/testRunner/unittests/evaluation/asyncArrow.ts @@ -1,3 +1,5 @@ +import * as evaluator from "../../_namespaces/evaluator"; + describe("unittests:: evaluation:: asyncArrowEvaluation", () => { // https://github.com/Microsoft/TypeScript/issues/24722 it("this capture (es5)", async () => { diff --git a/src/testRunner/unittests/evaluation/asyncGenerator.ts b/src/testRunner/unittests/evaluation/asyncGenerator.ts index 8ca531f0759a1..0da25e30698f8 100644 --- a/src/testRunner/unittests/evaluation/asyncGenerator.ts +++ b/src/testRunner/unittests/evaluation/asyncGenerator.ts @@ -1,3 +1,6 @@ +import * as evaluator from "../../_namespaces/evaluator"; +import * as ts from "../../_namespaces/ts"; + describe("unittests:: evaluation:: asyncGeneratorEvaluation", () => { it("return (es5)", async () => { const result = evaluator.evaluateTypeScript(` diff --git a/src/testRunner/unittests/evaluation/autoAccessors.ts b/src/testRunner/unittests/evaluation/autoAccessors.ts index 0873cd061e7f7..078110cb44cd5 100644 --- a/src/testRunner/unittests/evaluation/autoAccessors.ts +++ b/src/testRunner/unittests/evaluation/autoAccessors.ts @@ -1,3 +1,6 @@ +import * as ts from "../../_namespaces/ts"; +import * as evaluator from "../../_namespaces/evaluator"; + describe("unittests:: evaluation:: autoAccessors", () => { const editions = [ { name: "es2022", target: ts.ScriptTarget.ES2022 }, diff --git a/src/testRunner/unittests/evaluation/awaiter.ts b/src/testRunner/unittests/evaluation/awaiter.ts index 65cb4e0ead945..87007d8925934 100644 --- a/src/testRunner/unittests/evaluation/awaiter.ts +++ b/src/testRunner/unittests/evaluation/awaiter.ts @@ -1,3 +1,5 @@ +import * as evaluator from "../../_namespaces/evaluator"; + describe("unittests:: evaluation:: awaiter", () => { // NOTE: This could break if the ECMAScript spec ever changes the timing behavior for Promises (again) it("await (es5)", async () => { diff --git a/src/testRunner/unittests/evaluation/destructuring.ts b/src/testRunner/unittests/evaluation/destructuring.ts index dcff12970b65c..c52c4d4b0a61a 100644 --- a/src/testRunner/unittests/evaluation/destructuring.ts +++ b/src/testRunner/unittests/evaluation/destructuring.ts @@ -1,3 +1,6 @@ +import * as evaluator from "../../_namespaces/evaluator"; +import * as ts from "../../_namespaces/ts"; + describe("unittests:: evaluation:: destructuring", () => { // https://github.com/microsoft/TypeScript/issues/39205 describe("correct order for array destructuring evaluation and initializers", () => { diff --git a/src/testRunner/unittests/evaluation/externalModules.ts b/src/testRunner/unittests/evaluation/externalModules.ts index 18bb0fa043f80..04a0b55abbf34 100644 --- a/src/testRunner/unittests/evaluation/externalModules.ts +++ b/src/testRunner/unittests/evaluation/externalModules.ts @@ -1,3 +1,5 @@ +import * as evaluator from "../../_namespaces/evaluator"; + describe("unittests:: evaluation:: externalModules", () => { // https://github.com/microsoft/TypeScript/issues/35420 it("Correct 'this' in function exported from external module", async () => { diff --git a/src/testRunner/unittests/evaluation/forAwaitOf.ts b/src/testRunner/unittests/evaluation/forAwaitOf.ts index c541d155bfca1..270d1c234e71f 100644 --- a/src/testRunner/unittests/evaluation/forAwaitOf.ts +++ b/src/testRunner/unittests/evaluation/forAwaitOf.ts @@ -1,3 +1,6 @@ +import * as evaluator from "../../_namespaces/evaluator"; +import * as ts from "../../_namespaces/ts"; + describe("unittests:: evaluation:: forAwaitOfEvaluation", () => { it("sync (es5)", async () => { const result = evaluator.evaluateTypeScript(` diff --git a/src/testRunner/unittests/evaluation/forOf.ts b/src/testRunner/unittests/evaluation/forOf.ts index 9efdf16d351cd..5afe159495f54 100644 --- a/src/testRunner/unittests/evaluation/forOf.ts +++ b/src/testRunner/unittests/evaluation/forOf.ts @@ -1,3 +1,6 @@ +import * as evaluator from "../../_namespaces/evaluator"; +import * as ts from "../../_namespaces/ts"; + describe("unittests:: evaluation:: forOfEvaluation", () => { it("es5 over a array with no Symbol", () => { const result = evaluator.evaluateTypeScript(` diff --git a/src/testRunner/unittests/evaluation/generator.ts b/src/testRunner/unittests/evaluation/generator.ts index e97dff75dde79..3d04fe189172c 100644 --- a/src/testRunner/unittests/evaluation/generator.ts +++ b/src/testRunner/unittests/evaluation/generator.ts @@ -1,3 +1,6 @@ +import * as evaluator from "../../_namespaces/evaluator"; +import * as ts from "../../_namespaces/ts"; + describe("unittests:: evaluation:: generatorEvaluation", () => { it("throw before start (es5)", () => { const { gen, output } = evaluator.evaluateTypeScript(` diff --git a/src/testRunner/unittests/evaluation/objectRest.ts b/src/testRunner/unittests/evaluation/objectRest.ts index 272ba51ffbeb5..ebbaa7219a7f6 100644 --- a/src/testRunner/unittests/evaluation/objectRest.ts +++ b/src/testRunner/unittests/evaluation/objectRest.ts @@ -1,3 +1,5 @@ +import * as evaluator from "../../_namespaces/evaluator"; + describe("unittests:: evaluation:: objectRest", () => { // https://github.com/microsoft/TypeScript/issues/31469 it("side effects in property assignment", async () => { diff --git a/src/testRunner/unittests/evaluation/optionalCall.ts b/src/testRunner/unittests/evaluation/optionalCall.ts index f92190dfb72b9..db92162a3e14f 100644 --- a/src/testRunner/unittests/evaluation/optionalCall.ts +++ b/src/testRunner/unittests/evaluation/optionalCall.ts @@ -1,3 +1,5 @@ +import * as evaluator from "../../_namespaces/evaluator"; + describe("unittests:: evaluation:: optionalCall", () => { it("f?.()", async () => { const result = evaluator.evaluateTypeScript(` diff --git a/src/testRunner/unittests/evaluation/superInStaticInitializer.ts b/src/testRunner/unittests/evaluation/superInStaticInitializer.ts index da1dc5fe888d9..b6d858c69e72f 100644 --- a/src/testRunner/unittests/evaluation/superInStaticInitializer.ts +++ b/src/testRunner/unittests/evaluation/superInStaticInitializer.ts @@ -1,3 +1,6 @@ +import * as evaluator from "../../_namespaces/evaluator"; +import * as ts from "../../_namespaces/ts"; + describe("unittests:: evaluation:: superInStaticInitializer", () => { it("super-property-get in es2015", () => { const result = evaluator.evaluateTypeScript(` diff --git a/src/testRunner/unittests/evaluation/templateLiteral.ts b/src/testRunner/unittests/evaluation/templateLiteral.ts index 2a4e23ee879d4..65fabb9d4ccbb 100644 --- a/src/testRunner/unittests/evaluation/templateLiteral.ts +++ b/src/testRunner/unittests/evaluation/templateLiteral.ts @@ -1,3 +1,5 @@ +import * as evaluator from "../../_namespaces/evaluator"; + describe("unittests:: evaluation:: templateLiteral", () => { it("toString() over valueOf()", () => { const result = evaluator.evaluateTypeScript(` diff --git a/src/testRunner/unittests/evaluation/updateExpressionInModule.ts b/src/testRunner/unittests/evaluation/updateExpressionInModule.ts index 443a1fb71a11b..071a975b78856 100644 --- a/src/testRunner/unittests/evaluation/updateExpressionInModule.ts +++ b/src/testRunner/unittests/evaluation/updateExpressionInModule.ts @@ -1,3 +1,6 @@ +import * as evaluator from "../../_namespaces/evaluator"; +import * as ts from "../../_namespaces/ts"; + describe("unittests:: evaluation:: updateExpressionInModule", () => { // only run BigInt tests if BigInt is supported in the host environment const itIfBigInt = typeof BigInt === "function" ? it : it.skip; diff --git a/src/testRunner/unittests/factory.ts b/src/testRunner/unittests/factory.ts index 22e1df385a512..493f951dfca5b 100644 --- a/src/testRunner/unittests/factory.ts +++ b/src/testRunner/unittests/factory.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; + describe("unittests:: FactoryAPI", () => { function assertSyntaxKind(node: ts.Node, expected: ts.SyntaxKind) { assert.strictEqual(node.kind, expected, `Actual: ${ts.Debug.formatSyntaxKind(node.kind)} Expected: ${ts.Debug.formatSyntaxKind(expected)}`); @@ -117,4 +118,3 @@ describe("unittests:: FactoryAPI", () => { }); }); -} diff --git a/src/testRunner/unittests/incrementalParser.ts b/src/testRunner/unittests/incrementalParser.ts index e51b474bd085a..6c3c896334e31 100644 --- a/src/testRunner/unittests/incrementalParser.ts +++ b/src/testRunner/unittests/incrementalParser.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; +import * as Utils from "../_namespaces/Utils"; + function withChange(text: ts.IScriptSnapshot, start: number, length: number, newText: string): { text: ts.IScriptSnapshot; textChangeRange: ts.TextChangeRange; } { const contents = ts.getSnapshotText(text); const newContents = contents.substr(0, start) + newText + contents.substring(start + length); @@ -990,4 +992,3 @@ module m3 { }\ }); } }); -} diff --git a/src/testRunner/unittests/jsDocParsing.ts b/src/testRunner/unittests/jsDocParsing.ts index 25566e0d4eef0..21f461439c2ee 100644 --- a/src/testRunner/unittests/jsDocParsing.ts +++ b/src/testRunner/unittests/jsDocParsing.ts @@ -1,4 +1,7 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; +import * as Harness from "../_namespaces/Harness"; +import * as Utils from "../_namespaces/Utils"; + describe("unittests:: JSDocParsing", () => { describe("TypeExpressions", () => { function parsesCorrectly(name: string, content: string) { @@ -406,4 +409,3 @@ oh.no }); }); }); -} diff --git a/src/testRunner/unittests/jsonParserRecovery.ts b/src/testRunner/unittests/jsonParserRecovery.ts index ae2bfa282d6e7..3eaf92790ffca 100644 --- a/src/testRunner/unittests/jsonParserRecovery.ts +++ b/src/testRunner/unittests/jsonParserRecovery.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; +import * as Harness from "../_namespaces/Harness"; + describe("unittests:: jsonParserRecovery", () => { function parsesToValidSourceFileWithErrors(name: string, text: string) { it(name, () => { @@ -36,4 +38,3 @@ describe("unittests:: jsonParserRecovery", () => { )`); }); -} diff --git a/src/testRunner/unittests/moduleResolution.ts b/src/testRunner/unittests/moduleResolution.ts index 3bbfbf3b34174..90c49fbb881f8 100644 --- a/src/testRunner/unittests/moduleResolution.ts +++ b/src/testRunner/unittests/moduleResolution.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; +import * as Harness from "../_namespaces/Harness"; + export function checkResolvedModule(actual: ts.ResolvedModuleFull | undefined, expected: ts.ResolvedModuleFull | undefined): boolean { if (!expected) { if (actual) { @@ -1574,4 +1576,3 @@ describe("unittests:: moduleResolution:: Type reference directive resolution: ", }); }); }); -} diff --git a/src/testRunner/unittests/parsePseudoBigInt.ts b/src/testRunner/unittests/parsePseudoBigInt.ts index d6d19bc7ad0bd..10f5e098362f9 100644 --- a/src/testRunner/unittests/parsePseudoBigInt.ts +++ b/src/testRunner/unittests/parsePseudoBigInt.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; + describe("unittests:: BigInt literal base conversions", () => { describe("parsePseudoBigInt", () => { const testNumbers: number[] = []; @@ -68,4 +69,3 @@ describe("unittests:: BigInt literal base conversions", () => { }); }); }); -} diff --git a/src/testRunner/unittests/paths.ts b/src/testRunner/unittests/paths.ts index cf2bde3acbee2..fcd8de8ebee75 100644 --- a/src/testRunner/unittests/paths.ts +++ b/src/testRunner/unittests/paths.ts @@ -1,3 +1,5 @@ +import * as ts from "../_namespaces/ts"; + describe("unittests:: core paths", () => { it("normalizeSlashes", () => { assert.strictEqual(ts.normalizeSlashes("a"), "a"); diff --git a/src/testRunner/unittests/printer.ts b/src/testRunner/unittests/printer.ts index 5c37ead401548..103c0e69dac69 100644 --- a/src/testRunner/unittests/printer.ts +++ b/src/testRunner/unittests/printer.ts @@ -1,4 +1,8 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; +import * as Harness from "../_namespaces/Harness"; +import * as fakes from "../_namespaces/fakes"; +import * as vfs from "../_namespaces/vfs"; + describe("unittests:: PrinterAPI", () => { function makePrintsCorrectly(prefix: string) { return function printsCorrectly(name: string, options: ts.PrinterOptions, printCallback: (printer: ts.Printer) => string) { @@ -311,4 +315,3 @@ describe("unittests:: PrinterAPI", () => { )); }); }); -} diff --git a/src/testRunner/unittests/programApi.ts b/src/testRunner/unittests/programApi.ts index 2e95e236310e9..ac8bd74f564ba 100644 --- a/src/testRunner/unittests/programApi.ts +++ b/src/testRunner/unittests/programApi.ts @@ -1,4 +1,9 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; +import * as documents from "../_namespaces/documents"; +import * as fakes from "../_namespaces/fakes"; +import * as vfs from "../_namespaces/vfs"; +import * as Harness from "../_namespaces/Harness"; + function verifyMissingFilePaths(missingPaths: readonly ts.Path[], expected: readonly string[]) { assert.isDefined(missingPaths); const map = new ts.Set(expected); @@ -220,4 +225,3 @@ describe("unittests:: programApi:: CompilerOptions relative paths", () => { assert.isEmpty(program.getSemanticDiagnostics()); }); }); -} diff --git a/src/testRunner/unittests/publicApi.ts b/src/testRunner/unittests/publicApi.ts index 00d8994520f54..54004b9a89a6f 100644 --- a/src/testRunner/unittests/publicApi.ts +++ b/src/testRunner/unittests/publicApi.ts @@ -1,3 +1,10 @@ +import * as Harness from "../_namespaces/Harness"; +import * as vfs from "../_namespaces/vfs"; +import * as fakes from "../_namespaces/fakes"; +import * as ts from "../_namespaces/ts"; +import * as compiler from "../_namespaces/compiler"; +import * as documents from "../_namespaces/documents"; + describe("unittests:: Public APIs", () => { function verifyApi(fileName: string) { const builtFile = `built/local/${fileName}`; diff --git a/src/testRunner/unittests/reuseProgramStructure.ts b/src/testRunner/unittests/reuseProgramStructure.ts index f6ac908cffbef..fbbcaf7595134 100644 --- a/src/testRunner/unittests/reuseProgramStructure.ts +++ b/src/testRunner/unittests/reuseProgramStructure.ts @@ -1,4 +1,4 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; const enum ChangedPart { references = 1 << 0, @@ -1181,4 +1181,3 @@ describe("unittests:: Reuse program structure:: isProgramUptoDate", () => { }); }); }); -} diff --git a/src/testRunner/unittests/semver.ts b/src/testRunner/unittests/semver.ts index 16812ea6f03da..241a2f7209e0b 100644 --- a/src/testRunner/unittests/semver.ts +++ b/src/testRunner/unittests/semver.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; +import * as Utils from "../_namespaces/Utils"; + import theory = Utils.theory; describe("unittests:: semver", () => { describe("Version", () => { @@ -923,4 +925,3 @@ describe("unittests:: semver", () => { ]); }); }); -} diff --git a/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts b/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts index 32574ddf46bbc..85fc11da92614 100644 --- a/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts +++ b/src/testRunner/unittests/services/cancellableLanguageServiceOperations.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; + describe("unittests:: services:: cancellableLanguageServiceOperations", () => { const file = ` function foo(): void; @@ -92,4 +94,3 @@ function assertCancelled(cb: () => void) { assert.exists(caught, "Expected operation to be cancelled, but was not"); assert.instanceOf(caught, ts.OperationCanceledException); } -} diff --git a/src/testRunner/unittests/services/colorization.ts b/src/testRunner/unittests/services/colorization.ts index 4a89ccad56e92..0afe3176f37c3 100644 --- a/src/testRunner/unittests/services/colorization.ts +++ b/src/testRunner/unittests/services/colorization.ts @@ -1,3 +1,6 @@ +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; + // lots of tests use quoted code /* eslint-disable no-template-curly-in-string */ diff --git a/src/testRunner/unittests/services/convertToAsyncFunction.ts b/src/testRunner/unittests/services/convertToAsyncFunction.ts index 7a12335b95d53..0df0a9691ccf9 100644 --- a/src/testRunner/unittests/services/convertToAsyncFunction.ts +++ b/src/testRunner/unittests/services/convertToAsyncFunction.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; + const libFile: ts.TestFSWithWatch.File = { path: "/a/lib/lib.d.ts", content: `/// @@ -1836,4 +1838,3 @@ function [#|f|](): Promise { } `); }); -} diff --git a/src/testRunner/unittests/services/documentRegistry.ts b/src/testRunner/unittests/services/documentRegistry.ts index e7c80486e975a..6281f73125276 100644 --- a/src/testRunner/unittests/services/documentRegistry.ts +++ b/src/testRunner/unittests/services/documentRegistry.ts @@ -1,3 +1,5 @@ +import * as ts from "../../_namespaces/ts"; + describe("unittests:: services:: DocumentRegistry", () => { it("documents are shared between projects", () => { const documentRegistry = ts.createDocumentRegistry(); diff --git a/src/testRunner/unittests/services/extract/constants.ts b/src/testRunner/unittests/services/extract/constants.ts index 31a5107a70fe9..55a30e21b83b0 100644 --- a/src/testRunner/unittests/services/extract/constants.ts +++ b/src/testRunner/unittests/services/extract/constants.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../../../_namespaces/ts"; + describe("unittests:: services:: extract:: extractConstants", () => { testExtractConstant("extractConstant_TopLevel", `let x = [#|1|];`); @@ -301,4 +302,3 @@ function testExtractConstant(caption: string, text: string) { function testExtractConstantFailed(caption: string, text: string) { ts.testExtractSymbolFailed(caption, text, ts.Diagnostics.Extract_constant); } -} diff --git a/src/testRunner/unittests/services/extract/functions.ts b/src/testRunner/unittests/services/extract/functions.ts index 6280f019ce06d..06f2943970e9e 100644 --- a/src/testRunner/unittests/services/extract/functions.ts +++ b/src/testRunner/unittests/services/extract/functions.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../../../_namespaces/ts"; + describe("unittests:: services:: extract:: extractFunctions", () => { testExtractFunction("extractFunction1", `namespace A { @@ -566,4 +567,3 @@ function F() { function testExtractFunction(caption: string, text: string, includeLib?: boolean) { ts.testExtractSymbol(caption, text, "extractFunction", ts.Diagnostics.Extract_function, includeLib); } -} diff --git a/src/testRunner/unittests/services/extract/helpers.ts b/src/testRunner/unittests/services/extract/helpers.ts index 095db3a0b070a..959b8447c73e6 100644 --- a/src/testRunner/unittests/services/extract/helpers.ts +++ b/src/testRunner/unittests/services/extract/helpers.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../../_namespaces/ts"; +import * as Harness from "../../../_namespaces/Harness"; + interface Range { pos: number; end: number; @@ -176,4 +178,3 @@ export function testExtractSymbolFailed(caption: string, text: string, descripti assert.isUndefined(ts.find(infos, info => info.description === description.message)); }); } -} diff --git a/src/testRunner/unittests/services/extract/ranges.ts b/src/testRunner/unittests/services/extract/ranges.ts index 8d7ca36ec04b3..71d35599130c9 100644 --- a/src/testRunner/unittests/services/extract/ranges.ts +++ b/src/testRunner/unittests/services/extract/ranges.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../../../_namespaces/ts"; + function testExtractRangeFailed(caption: string, s: string, expectedErrors: string[]) { return it(caption, () => { const t = ts.extractTest(s); @@ -405,4 +406,3 @@ switch (x) { testExtractRangeFailed("extract-method-not-for-token-expression-statement", `[#|a|]`, [ts.refactor.extractSymbol.Messages.cannotExtractIdentifier.message]); }); -} diff --git a/src/testRunner/unittests/services/extract/symbolWalker.ts b/src/testRunner/unittests/services/extract/symbolWalker.ts index 3f81d74a362c8..0f005bc712b8a 100644 --- a/src/testRunner/unittests/services/extract/symbolWalker.ts +++ b/src/testRunner/unittests/services/extract/symbolWalker.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../../_namespaces/ts"; +import * as Harness from "../../../_namespaces/Harness"; + describe("unittests:: services:: extract:: Symbol Walker", () => { function test(description: string, source: string, verifier: (file: ts.SourceFile, checker: ts.TypeChecker) => void) { it(description, () => { @@ -42,4 +44,3 @@ export default function foo(a: number, b: Bar): void {}`, (file, checker) => { assert.equal(stdLibRefSymbols, 1); // Expect 1 stdlib entry symbol - the implicit Array referenced by Bar.history }); }); -} diff --git a/src/testRunner/unittests/services/hostNewLineSupport.ts b/src/testRunner/unittests/services/hostNewLineSupport.ts index 7fff810df779a..d18b593d99125 100644 --- a/src/testRunner/unittests/services/hostNewLineSupport.ts +++ b/src/testRunner/unittests/services/hostNewLineSupport.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; + describe("unittests:: services:: hostNewLineSupport", () => { function testLSWithFiles(settings: ts.CompilerOptions, files: Harness.Compiler.TestFile[]) { function snapFor(path: string): ts.IScriptSnapshot | undefined { @@ -74,4 +76,3 @@ describe("unittests:: services:: hostNewLineSupport", () => { { newLine: ts.NewLineKind.LineFeed }); }); }); -} diff --git a/src/testRunner/unittests/services/languageService.ts b/src/testRunner/unittests/services/languageService.ts index 11ae565863c65..53631ce5bfb0b 100644 --- a/src/testRunner/unittests/services/languageService.ts +++ b/src/testRunner/unittests/services/languageService.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; + const _chai: typeof import("chai") = require("chai"); const expect: typeof _chai.expect = _chai.expect; describe("unittests:: services:: languageService", () => { @@ -271,4 +272,3 @@ export function Component(x: Config): any;` }); }); }); -} diff --git a/src/testRunner/unittests/services/organizeImports.ts b/src/testRunner/unittests/services/organizeImports.ts index 951ba74f057df..05fcabe6622e2 100644 --- a/src/testRunner/unittests/services/organizeImports.ts +++ b/src/testRunner/unittests/services/organizeImports.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; + describe("unittests:: services:: organizeImports", () => { describe("Sort imports", () => { it("Sort - non-relative vs non-relative", () => { @@ -1137,4 +1139,3 @@ export * from "lib"; } } }); -} diff --git a/src/testRunner/unittests/services/patternMatcher.ts b/src/testRunner/unittests/services/patternMatcher.ts index 9f3cbf4b6d7c6..d48dd97220b59 100644 --- a/src/testRunner/unittests/services/patternMatcher.ts +++ b/src/testRunner/unittests/services/patternMatcher.ts @@ -1,3 +1,5 @@ +import * as ts from "../../_namespaces/ts"; + describe("unittests:: services:: PatternMatcher", () => { describe("BreakIntoCharacterSpans", () => { it("EmptyIdentifier", () => { diff --git a/src/testRunner/unittests/services/preProcessFile.ts b/src/testRunner/unittests/services/preProcessFile.ts index a0ff91a26b1b4..3ff1a365d359c 100644 --- a/src/testRunner/unittests/services/preProcessFile.ts +++ b/src/testRunner/unittests/services/preProcessFile.ts @@ -1,3 +1,5 @@ +import * as ts from "../../_namespaces/ts"; + describe("unittests:: services:: PreProcessFile:", () => { function test(sourceText: string, readImportFile: boolean, detectJavaScriptImports: boolean, expectedPreProcess: ts.PreProcessedFileInfo): void { const resultPreProcess = ts.preProcessFile(sourceText, readImportFile, detectJavaScriptImports); diff --git a/src/testRunner/unittests/services/textChanges.ts b/src/testRunner/unittests/services/textChanges.ts index ba2ee2b065bcc..9c47393c81961 100644 --- a/src/testRunner/unittests/services/textChanges.ts +++ b/src/testRunner/unittests/services/textChanges.ts @@ -1,6 +1,8 @@ +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; + // Some tests have trailing whitespace -namespace ts { describe("unittests:: services:: textChanges", () => { function findChild(name: string, n: ts.Node) { return find(n)!; @@ -767,4 +769,3 @@ let x = foo }); } }); -} diff --git a/src/testRunner/unittests/services/transpile.ts b/src/testRunner/unittests/services/transpile.ts index 5663c9e1d8bda..4eed8f72ac042 100644 --- a/src/testRunner/unittests/services/transpile.ts +++ b/src/testRunner/unittests/services/transpile.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; + describe("unittests:: services:: Transpile", () => { interface TranspileTestSettings { @@ -500,4 +502,3 @@ export * as alias from './file';`, { } ); }); -} diff --git a/src/testRunner/unittests/transform.ts b/src/testRunner/unittests/transform.ts index c51b281d7c30f..00af9287364ef 100644 --- a/src/testRunner/unittests/transform.ts +++ b/src/testRunner/unittests/transform.ts @@ -1,4 +1,10 @@ -namespace ts { +import * as ts from "../_namespaces/ts"; +import * as Harness from "../_namespaces/Harness"; +import * as evaluator from "../_namespaces/evaluator"; +import * as vfs from "../_namespaces/vfs"; +import * as documents from "../_namespaces/documents"; +import * as fakes from "../_namespaces/fakes"; + describe("unittests:: TransformAPI", () => { function replaceUndefinedWithVoid0(context: ts.TransformationContext) { const previousOnSubstituteNode = context.onSubstituteNode; @@ -659,5 +665,4 @@ const MyClass = class { }); }); -} diff --git a/src/testRunner/unittests/tsbuild/amdModulesWithOut.ts b/src/testRunner/unittests/tsbuild/amdModulesWithOut.ts index 5f70424540fe7..d137e70ecc46a 100644 --- a/src/testRunner/unittests/tsbuild/amdModulesWithOut.ts +++ b/src/testRunner/unittests/tsbuild/amdModulesWithOut.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as vfs from "../../_namespaces/vfs"; + describe("unittests:: tsbuild:: outFile:: on amd modules with --out", () => { let outFileFs: vfs.FileSystem; before(() => { @@ -161,4 +163,3 @@ ${internal} export enum internalEnum { a, b, c }`); }); }); }); -} diff --git a/src/testRunner/unittests/tsbuild/clean.ts b/src/testRunner/unittests/tsbuild/clean.ts index 4ab55ef5bf5ac..c3182026a1965 100644 --- a/src/testRunner/unittests/tsbuild/clean.ts +++ b/src/testRunner/unittests/tsbuild/clean.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsbuild - clean", () => { ts.verifyTsc({ scenario: "clean", @@ -12,5 +13,4 @@ describe("unittests:: tsbuild - clean", () => { }), }), }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsbuild/commandLine.ts b/src/testRunner/unittests/tsbuild/commandLine.ts index 4adc4a3252ca0..4fe827ff86db0 100644 --- a/src/testRunner/unittests/tsbuild/commandLine.ts +++ b/src/testRunner/unittests/tsbuild/commandLine.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsbuild:: commandLine::", () => { describe("different options::", () => { function withOptionChange(subScenario: string, ...options: readonly string[]): ts.TestTscEdit { @@ -423,5 +424,4 @@ describe("unittests:: tsbuild:: commandLine::", () => { baselinePrograms: true, }); }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsbuild/configFileErrors.ts b/src/testRunner/unittests/tsbuild/configFileErrors.ts index a1871ed675b30..7ed7ad9b8a9f5 100644 --- a/src/testRunner/unittests/tsbuild/configFileErrors.ts +++ b/src/testRunner/unittests/tsbuild/configFileErrors.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; + describe("unittests:: tsbuild:: configFileErrors:: when tsconfig extends the missing file", () => { ts.verifyTsc({ scenario: "configFileErrors", @@ -55,4 +57,3 @@ describe("unittests:: tsbuild:: configFileErrors:: reports syntax errors in conf ] }); }); -} diff --git a/src/testRunner/unittests/tsbuild/configFileExtends.ts b/src/testRunner/unittests/tsbuild/configFileExtends.ts index c7c294a262008..85d868dc063b2 100644 --- a/src/testRunner/unittests/tsbuild/configFileExtends.ts +++ b/src/testRunner/unittests/tsbuild/configFileExtends.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsbuild:: configFileExtends:: when tsconfig extends another config", () => { function getConfigExtendsWithIncludeFs() { return ts.loadProjectFromFiles({ @@ -48,5 +49,4 @@ describe("unittests:: tsbuild:: configFileExtends:: when tsconfig extends anothe fs: getConfigExtendsWithIncludeFs, commandLineArgs: ["--b", "/src/webpack/tsconfig.json", "--v", "--listFiles"], }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsbuild/containerOnlyReferenced.ts b/src/testRunner/unittests/tsbuild/containerOnlyReferenced.ts index a20dd2c87b0dd..45e4be8380647 100644 --- a/src/testRunner/unittests/tsbuild/containerOnlyReferenced.ts +++ b/src/testRunner/unittests/tsbuild/containerOnlyReferenced.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsbuild:: when containerOnly project is referenced", () => { ts.verifyTscWithEdits({ scenario: "containerOnlyReferenced", @@ -39,4 +40,3 @@ describe("unittests:: tsbuild:: when containerOnly project is referenced", () => }], }); }); -} diff --git a/src/testRunner/unittests/tsbuild/declarationEmit.ts b/src/testRunner/unittests/tsbuild/declarationEmit.ts index 34d4ffbb440f6..e7dc2b9f50791 100644 --- a/src/testRunner/unittests/tsbuild/declarationEmit.ts +++ b/src/testRunner/unittests/tsbuild/declarationEmit.ts @@ -1,4 +1,7 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as vfs from "../../_namespaces/vfs"; +import * as Utils from "../../_namespaces/Utils"; + describe("unittests:: tsbuild:: declarationEmit", () => { function getFiles(): vfs.FileSet { return { @@ -115,4 +118,3 @@ export function fn4() { commandLineArgs: ["--b", "/src/packages/pkg2/tsconfig.json", "--verbose"] }); }); -} diff --git a/src/testRunner/unittests/tsbuild/demo.ts b/src/testRunner/unittests/tsbuild/demo.ts index 4499442655657..18666a748df61 100644 --- a/src/testRunner/unittests/tsbuild/demo.ts +++ b/src/testRunner/unittests/tsbuild/demo.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as vfs from "../../_namespaces/vfs"; + describe("unittests:: tsbuild:: on demo project", () => { let projFs: vfs.FileSystem; before(() => { @@ -46,4 +48,3 @@ describe("unittests:: tsbuild:: on demo project", () => { ) }); }); -} diff --git a/src/testRunner/unittests/tsbuild/emitDeclarationOnly.ts b/src/testRunner/unittests/tsbuild/emitDeclarationOnly.ts index af7e880248ecd..f7726fa349950 100644 --- a/src/testRunner/unittests/tsbuild/emitDeclarationOnly.ts +++ b/src/testRunner/unittests/tsbuild/emitDeclarationOnly.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as vfs from "../../_namespaces/vfs"; + describe("unittests:: tsbuild:: on project with emitDeclarationOnly set to true", () => { let projFs: vfs.FileSystem; before(() => { @@ -49,4 +51,3 @@ export interface A {`), ], }); }); -} diff --git a/src/testRunner/unittests/tsbuild/emptyFiles.ts b/src/testRunner/unittests/tsbuild/emptyFiles.ts index ccb1a8d553433..49d18ace609fd 100644 --- a/src/testRunner/unittests/tsbuild/emptyFiles.ts +++ b/src/testRunner/unittests/tsbuild/emptyFiles.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as vfs from "../../_namespaces/vfs"; + describe("unittests:: tsbuild - empty files option in tsconfig", () => { let projFs: vfs.FileSystem; before(() => { @@ -22,4 +24,3 @@ describe("unittests:: tsbuild - empty files option in tsconfig", () => { commandLineArgs: ["--b", "/src/with-references"], }); }); -} diff --git a/src/testRunner/unittests/tsbuild/exitCodeOnBogusFile.ts b/src/testRunner/unittests/tsbuild/exitCodeOnBogusFile.ts index d60fa6c1276f0..f75d4a191d9fe 100644 --- a/src/testRunner/unittests/tsbuild/exitCodeOnBogusFile.ts +++ b/src/testRunner/unittests/tsbuild/exitCodeOnBogusFile.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; + // https://github.com/microsoft/TypeScript/issues/33849 describe("unittests:: tsbuild:: exitCodeOnBogusFile:: test exit code", () => { ts.verifyTsc({ @@ -8,4 +9,3 @@ describe("unittests:: tsbuild:: exitCodeOnBogusFile:: test exit code", () => { commandLineArgs: ["-b", "bogus.json"] }); }); -} diff --git a/src/testRunner/unittests/tsbuild/graphOrdering.ts b/src/testRunner/unittests/tsbuild/graphOrdering.ts index c9228126018e3..06fd1f4b512a7 100644 --- a/src/testRunner/unittests/tsbuild/graphOrdering.ts +++ b/src/testRunner/unittests/tsbuild/graphOrdering.ts @@ -1,4 +1,7 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as fakes from "../../_namespaces/fakes"; +import * as vfs from "../../_namespaces/vfs"; + describe("unittests:: tsbuild - graph-ordering", () => { let host: fakes.SolutionBuilderHost | undefined; const deps: [string, string][] = [ @@ -88,4 +91,3 @@ describe("unittests:: tsbuild - graph-ordering", () => { return projFileNames; } }); -} diff --git a/src/testRunner/unittests/tsbuild/helpers.ts b/src/testRunner/unittests/tsbuild/helpers.ts index 8ed60721d62ac..09f38eecd9fb5 100644 --- a/src/testRunner/unittests/tsbuild/helpers.ts +++ b/src/testRunner/unittests/tsbuild/helpers.ts @@ -1,4 +1,9 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as fakes from "../../_namespaces/fakes"; +import * as vfs from "../../_namespaces/vfs"; +import * as Harness from "../../_namespaces/Harness"; +import * as vpath from "../../_namespaces/vpath"; + export function errorDiagnostic(message: fakes.ExpectedDiagnosticMessage): fakes.ExpectedErrorDiagnostic { return { message }; } @@ -762,4 +767,3 @@ export function addTripleSlashRef(fs: vfs.FileSystem, project: string, file: str const ${file}Const = new ${project}${file}(); `); } -} diff --git a/src/testRunner/unittests/tsbuild/inferredTypeFromTransitiveModule.ts b/src/testRunner/unittests/tsbuild/inferredTypeFromTransitiveModule.ts index 1c191779a4c04..4f3db7518f649 100644 --- a/src/testRunner/unittests/tsbuild/inferredTypeFromTransitiveModule.ts +++ b/src/testRunner/unittests/tsbuild/inferredTypeFromTransitiveModule.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as vfs from "../../_namespaces/vfs"; + describe("unittests:: tsbuild:: inferredTypeFromTransitiveModule::", () => { let projFs: vfs.FileSystem; before(() => { @@ -86,4 +88,3 @@ function changeBarParam(fs: vfs.FileSystem) { function changeBarParamBack(fs: vfs.FileSystem) { ts.replaceText(fs, "/src/bar.ts", "foobar()", "foobar(param: string)"); } -} diff --git a/src/testRunner/unittests/tsbuild/javascriptProjectEmit.ts b/src/testRunner/unittests/tsbuild/javascriptProjectEmit.ts index 02e0e455c1eb2..499ca98a60464 100644 --- a/src/testRunner/unittests/tsbuild/javascriptProjectEmit.ts +++ b/src/testRunner/unittests/tsbuild/javascriptProjectEmit.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; + describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { ts.verifyTsc({ scenario: "javascriptProjectEmit", @@ -269,4 +271,3 @@ describe("unittests:: tsbuild:: javascriptProjectEmit::", () => { commandLineArgs: ["-b", "/src"] }); }); -} diff --git a/src/testRunner/unittests/tsbuild/lateBoundSymbol.ts b/src/testRunner/unittests/tsbuild/lateBoundSymbol.ts index f689ce1cf000b..417be59e441e5 100644 --- a/src/testRunner/unittests/tsbuild/lateBoundSymbol.ts +++ b/src/testRunner/unittests/tsbuild/lateBoundSymbol.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsbuild:: lateBoundSymbol:: interface is merged and contains late bound member", () => { ts.verifyTscWithEdits({ subScenario: "interface is merged and contains late bound member", @@ -17,4 +18,3 @@ describe("unittests:: tsbuild:: lateBoundSymbol:: interface is merged and contai ] }); }); -} diff --git a/src/testRunner/unittests/tsbuild/moduleResolution.ts b/src/testRunner/unittests/tsbuild/moduleResolution.ts index 6c4e914804f9f..496131f2c45a0 100644 --- a/src/testRunner/unittests/tsbuild/moduleResolution.ts +++ b/src/testRunner/unittests/tsbuild/moduleResolution.ts @@ -1,4 +1,6 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; + describe("unittests:: tsbuild:: moduleResolution:: handles the modules and options from referenced project correctly", () => { function sys(optionsToExtend?: ts.CompilerOptions) { return ts.tscWatch.createWatchedSystem([ @@ -117,5 +119,4 @@ describe("unittests:: tsbuild:: moduleResolution:: impliedNodeFormat differs bet commandLineArgs: ["-b", "/src/projects/a", "/src/projects/b", "--verbose", "--traceResolution", "--explainFiles"], edits: ts.noChangeOnlyRuns }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsbuild/moduleSpecifiers.ts b/src/testRunner/unittests/tsbuild/moduleSpecifiers.ts index 9069187a5d48b..04d3f714a6c46 100644 --- a/src/testRunner/unittests/tsbuild/moduleSpecifiers.ts +++ b/src/testRunner/unittests/tsbuild/moduleSpecifiers.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; + // https://github.com/microsoft/TypeScript/issues/31696 describe("unittests:: tsbuild:: moduleSpecifiers:: synthesized module specifiers to referenced projects resolve correctly", () => { ts.verifyTsc({ @@ -185,4 +187,3 @@ describe("unittests:: tsbuild:: moduleSpecifiers:: synthesized module specifiers commandLineArgs: ["-b", "src/src-types", "src/src-dogs", "--verbose"] }); }); -} diff --git a/src/testRunner/unittests/tsbuild/noEmit.ts b/src/testRunner/unittests/tsbuild/noEmit.ts index c9c7b61161bb0..19cb8a5049647 100644 --- a/src/testRunner/unittests/tsbuild/noEmit.ts +++ b/src/testRunner/unittests/tsbuild/noEmit.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsbuild:: noEmit", () => { function verifyNoEmitWorker(subScenario: string, aTsContent: string, commandLineArgs: readonly string[]) { ts.verifyTscWithEdits({ @@ -30,5 +31,4 @@ describe("unittests:: tsbuild:: noEmit", () => { verifyNoEmit("syntax errors", `const a = "hello`); verifyNoEmit("semantic errors", `const a: number = "hello"`); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsbuild/noEmitOnError.ts b/src/testRunner/unittests/tsbuild/noEmitOnError.ts index d39103aa22a7d..c61f45a1cd8ec 100644 --- a/src/testRunner/unittests/tsbuild/noEmitOnError.ts +++ b/src/testRunner/unittests/tsbuild/noEmitOnError.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as vfs from "../../_namespaces/vfs"; + describe("unittests:: tsbuild - with noEmitOnError", () => { let projFs: vfs.FileSystem; before(() => { @@ -84,4 +86,3 @@ const a: string = "hello";`, "utf-8"), baselinePrograms: true, }); }); -} diff --git a/src/testRunner/unittests/tsbuild/outFile.ts b/src/testRunner/unittests/tsbuild/outFile.ts index 5f5a04393bdc0..08a80e200ec28 100644 --- a/src/testRunner/unittests/tsbuild/outFile.ts +++ b/src/testRunner/unittests/tsbuild/outFile.ts @@ -1,4 +1,7 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as vfs from "../../_namespaces/vfs"; +import * as fakes from "../../_namespaces/fakes"; + describe("unittests:: tsbuild:: outFile::", () => { let outFileFs: vfs.FileSystem; let outFileWithBuildFs: vfs.FileSystem; @@ -654,4 +657,3 @@ ${internal} enum internalEnum { a, b, c }`); }, }); }); -} diff --git a/src/testRunner/unittests/tsbuild/outputPaths.ts b/src/testRunner/unittests/tsbuild/outputPaths.ts index bca57e009eb9a..08f24dfcf6067 100644 --- a/src/testRunner/unittests/tsbuild/outputPaths.ts +++ b/src/testRunner/unittests/tsbuild/outputPaths.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as fakes from "../../_namespaces/fakes"; + describe("unittests:: tsbuild - output file paths", () => { const noChangeProject: ts.TestTscEdit = { modifyFs: ts.noop, @@ -103,4 +105,3 @@ describe("unittests:: tsbuild - output file paths", () => { edits, }, ["/src/dist/index.js", "/src/dist/index.d.ts"]); }); -} diff --git a/src/testRunner/unittests/tsbuild/publicApi.ts b/src/testRunner/unittests/tsbuild/publicApi.ts index 2d78ba26dc872..b61ba2f5d8991 100644 --- a/src/testRunner/unittests/tsbuild/publicApi.ts +++ b/src/testRunner/unittests/tsbuild/publicApi.ts @@ -1,4 +1,7 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as fakes from "../../_namespaces/fakes"; +import * as vfs from "../../_namespaces/vfs"; + describe("unittests:: tsbuild:: Public API with custom transformers when passed to build", () => { let sys: ts.TscCompileSystem; before(() => { @@ -119,4 +122,3 @@ ${patch ? vfs.formatPatch(patch) : ""}` }); ts.verifyTscBaseline(() => sys); }); -} diff --git a/src/testRunner/unittests/tsbuild/referencesWithRootDirInParent.ts b/src/testRunner/unittests/tsbuild/referencesWithRootDirInParent.ts index 85c6e5d564291..1d0d2f131a264 100644 --- a/src/testRunner/unittests/tsbuild/referencesWithRootDirInParent.ts +++ b/src/testRunner/unittests/tsbuild/referencesWithRootDirInParent.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as vfs from "../../_namespaces/vfs"; + describe("unittests:: tsbuild:: with rootDir of project reference in parentDirectory", () => { let projFs: vfs.FileSystem; before(() => { @@ -58,4 +60,3 @@ describe("unittests:: tsbuild:: with rootDir of project reference in parentDirec }, }); }); -} diff --git a/src/testRunner/unittests/tsbuild/resolveJsonModule.ts b/src/testRunner/unittests/tsbuild/resolveJsonModule.ts index 55cc53fd815de..0d765605c8f71 100644 --- a/src/testRunner/unittests/tsbuild/resolveJsonModule.ts +++ b/src/testRunner/unittests/tsbuild/resolveJsonModule.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as vfs from "../../_namespaces/vfs"; + describe("unittests:: tsbuild:: with resolveJsonModule option on project resolveJsonModuleAndComposite", () => { let projFs: vfs.FileSystem; before(() => { @@ -79,4 +81,3 @@ describe("unittests:: tsbuild:: with resolveJsonModule option on project importJ edits: ts.noChangeOnlyRuns }); }); -} diff --git a/src/testRunner/unittests/tsbuild/sample.ts b/src/testRunner/unittests/tsbuild/sample.ts index 628a9923e0d88..60e8e7b7213fb 100644 --- a/src/testRunner/unittests/tsbuild/sample.ts +++ b/src/testRunner/unittests/tsbuild/sample.ts @@ -1,4 +1,8 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as vfs from "../../_namespaces/vfs"; +import * as fakes from "../../_namespaces/fakes"; +import * as Harness from "../../_namespaces/Harness"; + describe("unittests:: tsbuild:: on 'sample1' project", () => { let projFs: vfs.FileSystem; let projFsWithBuild: vfs.FileSystem; @@ -587,4 +591,3 @@ class someClass2 { }`), }); }); }); -} diff --git a/src/testRunner/unittests/tsbuild/transitiveReferences.ts b/src/testRunner/unittests/tsbuild/transitiveReferences.ts index cc4f9055d078b..c3374cb37038a 100644 --- a/src/testRunner/unittests/tsbuild/transitiveReferences.ts +++ b/src/testRunner/unittests/tsbuild/transitiveReferences.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as vfs from "../../_namespaces/vfs"; + describe("unittests:: tsbuild:: when project reference is referenced transitively", () => { let projFs: vfs.FileSystem; before(() => { @@ -44,4 +46,3 @@ export const b = new A();`); modifyFs: fs => modifyFsBTsToNonRelativeImport(fs, "node"), }); }); -} diff --git a/src/testRunner/unittests/tsbuildWatch/configFileErrors.ts b/src/testRunner/unittests/tsbuildWatch/configFileErrors.ts index 5f3ee9ff45a4a..73e9fd0e5fb7a 100644 --- a/src/testRunner/unittests/tsbuildWatch/configFileErrors.ts +++ b/src/testRunner/unittests/tsbuildWatch/configFileErrors.ts @@ -1,4 +1,6 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; + describe("unittests:: tsbuildWatch:: watchMode:: configFileErrors:: reports syntax errors in config file", () => { function build(sys: ts.tscWatch.WatchedSystem) { sys.checkTimeoutQueueLengthAndRun(1); // build the project @@ -56,5 +58,4 @@ describe("unittests:: tsbuildWatch:: watchMode:: configFileErrors:: reports synt } ] }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsbuildWatch/demo.ts b/src/testRunner/unittests/tsbuildWatch/demo.ts index 71f32dcbbccc7..81ab4dda2daeb 100644 --- a/src/testRunner/unittests/tsbuildWatch/demo.ts +++ b/src/testRunner/unittests/tsbuildWatch/demo.ts @@ -1,4 +1,5 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsbuildWatch:: watchMode:: with demo project", () => { const projectLocation = `${ts.TestFSWithWatch.tsbuildProjectsLocation}/demo`; let coreFiles: ts.tscWatch.File[]; @@ -84,5 +85,4 @@ ${coreFiles[1].content}`), function projectFile(fileName: string): ts.tscWatch.File { return ts.TestFSWithWatch.getTsBuildProjectFile("demo", fileName); } -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsbuildWatch/moduleResolution.ts b/src/testRunner/unittests/tsbuildWatch/moduleResolution.ts index aea0398f5cf10..044ec4844aace 100644 --- a/src/testRunner/unittests/tsbuildWatch/moduleResolution.ts +++ b/src/testRunner/unittests/tsbuildWatch/moduleResolution.ts @@ -1,4 +1,6 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; + describe("unittests:: tsbuildWatch:: watchMode:: moduleResolution", () => { ts.tscWatch.verifyTscWatch({ scenario: "moduleResolutionCache", @@ -222,5 +224,4 @@ describe("unittests:: tsbuildWatch:: watchMode:: moduleResolution", () => { }, ] }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsbuildWatch/noEmit.ts b/src/testRunner/unittests/tsbuildWatch/noEmit.ts index df640c60759da..37623cd14ae2a 100644 --- a/src/testRunner/unittests/tsbuildWatch/noEmit.ts +++ b/src/testRunner/unittests/tsbuildWatch/noEmit.ts @@ -1,4 +1,5 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsbuildWatch:: watchMode:: with noEmit", () => { ts.tscWatch.verifyTscWatch({ scenario: "noEmit", @@ -29,5 +30,4 @@ describe("unittests:: tsbuildWatch:: watchMode:: with noEmit", () => { ], baselineIncremental: true }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsbuildWatch/noEmitOnError.ts b/src/testRunner/unittests/tsbuildWatch/noEmitOnError.ts index 7fe9ff3f5f9fb..c59bdc9d8690b 100644 --- a/src/testRunner/unittests/tsbuildWatch/noEmitOnError.ts +++ b/src/testRunner/unittests/tsbuildWatch/noEmitOnError.ts @@ -1,4 +1,5 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsbuildWatch:: watchMode:: with noEmitOnError", () => { function change(caption: string, content: string): ts.tscWatch.TscWatchCompileChange { return { @@ -42,5 +43,4 @@ const a: string = "hello";`), ], baselineIncremental: true }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsbuildWatch/programUpdates.ts b/src/testRunner/unittests/tsbuildWatch/programUpdates.ts index 7d53ec5b1ea20..3d0e24d006c29 100644 --- a/src/testRunner/unittests/tsbuildWatch/programUpdates.ts +++ b/src/testRunner/unittests/tsbuildWatch/programUpdates.ts @@ -1,4 +1,5 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; + import projectsLocation = ts.TestFSWithWatch.tsbuildProjectsLocation; describe("unittests:: tsbuildWatch:: watchMode:: program updates", () => { const enum SubProject { @@ -742,5 +743,4 @@ export function someFn() { }`), commandLineArgs: ["--b", "src/project", "-i", "-w"], changes: ts.emptyArray }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsbuildWatch/projectsBuilding.ts b/src/testRunner/unittests/tsbuildWatch/projectsBuilding.ts index 7c13efe39de71..b79c49a43b4fd 100644 --- a/src/testRunner/unittests/tsbuildWatch/projectsBuilding.ts +++ b/src/testRunner/unittests/tsbuildWatch/projectsBuilding.ts @@ -1,4 +1,5 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsbuildWatch:: watchMode:: projectsBuilding", () => { function pkgs(cb: (index: number) => T, count: number, startIndex?: number): T[] { const result: T[] = []; @@ -181,5 +182,4 @@ describe("unittests:: tsbuildWatch:: watchMode:: projectsBuilding", () => { ts.tscWatch.noopChange, ] }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsbuildWatch/publicApi.ts b/src/testRunner/unittests/tsbuildWatch/publicApi.ts index 46358d386230c..c58862bff6bd4 100644 --- a/src/testRunner/unittests/tsbuildWatch/publicApi.ts +++ b/src/testRunner/unittests/tsbuildWatch/publicApi.ts @@ -1,4 +1,5 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; + it("unittests:: tsbuildWatch:: watchMode:: Public API with custom transformers", () => { const solution: ts.tscWatch.File = { path: `${ts.tscWatch.projectRoot}/tsconfig.json`, @@ -101,5 +102,4 @@ export function f22() { } // trailing` }; return { before: [before], after: [after] }; } -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsbuildWatch/reexport.ts b/src/testRunner/unittests/tsbuildWatch/reexport.ts index ebcffb2f4efce..23d2857bf01ce 100644 --- a/src/testRunner/unittests/tsbuildWatch/reexport.ts +++ b/src/testRunner/unittests/tsbuildWatch/reexport.ts @@ -1,4 +1,5 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsbuildWatch:: watchMode:: with reexport when referenced project reexports definitions from another file", () => { ts.tscWatch.verifyTscWatch({ scenario: "reexport", @@ -37,5 +38,4 @@ describe("unittests:: tsbuildWatch:: watchMode:: with reexport when referenced p } ] }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsbuildWatch/watchEnvironment.ts b/src/testRunner/unittests/tsbuildWatch/watchEnvironment.ts index 5fa0096487425..7021a2ea8a522 100644 --- a/src/testRunner/unittests/tsbuildWatch/watchEnvironment.ts +++ b/src/testRunner/unittests/tsbuildWatch/watchEnvironment.ts @@ -1,4 +1,5 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsbuildWatch:: watchEnvironment:: tsbuild:: watchMode:: with different watch environments", () => { it("watchFile on same file multiple times because file is part of multiple projects", () => { const project = `${ts.TestFSWithWatch.tsbuildProjectsLocation}/myproject`; @@ -108,4 +109,3 @@ describe("unittests:: tsbuildWatch:: watchEnvironment:: tsbuild:: watchMode:: wi } }); }); -} diff --git a/src/testRunner/unittests/tsc/cancellationToken.ts b/src/testRunner/unittests/tsc/cancellationToken.ts index 574310427d326..21783b336aae4 100644 --- a/src/testRunner/unittests/tsc/cancellationToken.ts +++ b/src/testRunner/unittests/tsc/cancellationToken.ts @@ -1,4 +1,7 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; +import * as Harness from "../../_namespaces/Harness"; + describe("unittests:: tsc:: builder cancellationToken", () => { verifyCancellation(/*useBuildInfo*/ true, "when emitting buildInfo"); verifyCancellation(/*useBuildInfo*/ false, "when using state"); @@ -165,5 +168,4 @@ describe("unittests:: tsc:: builder cancellationToken", () => { } }); } -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsc/composite.ts b/src/testRunner/unittests/tsc/composite.ts index bd75fe35d6aa3..a71001d59f41a 100644 --- a/src/testRunner/unittests/tsc/composite.ts +++ b/src/testRunner/unittests/tsc/composite.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; + describe("unittests:: tsc:: composite::", () => { ts.verifyTsc({ scenario: "composite", @@ -103,4 +105,3 @@ describe("unittests:: tsc:: composite::", () => { ] }); }); -} diff --git a/src/testRunner/unittests/tsc/declarationEmit.ts b/src/testRunner/unittests/tsc/declarationEmit.ts index 45291327cf213..06ef754312afe 100644 --- a/src/testRunner/unittests/tsc/declarationEmit.ts +++ b/src/testRunner/unittests/tsc/declarationEmit.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; + describe("unittests:: tsc:: declarationEmit::", () => { interface VerifyDeclarationEmitInput { subScenario: string; @@ -247,4 +249,3 @@ ${pluginOneAction()}` changeCaseFileTestPath: str => ts.stringContains(str, "/pkg1"), }); }); -} diff --git a/src/testRunner/unittests/tsc/forceConsistentCasingInFileNames.ts b/src/testRunner/unittests/tsc/forceConsistentCasingInFileNames.ts index 856cdc5b40ac7..8b1ddf0961bc5 100644 --- a/src/testRunner/unittests/tsc/forceConsistentCasingInFileNames.ts +++ b/src/testRunner/unittests/tsc/forceConsistentCasingInFileNames.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; + describe("unittests:: tsc:: forceConsistentCasingInFileNames::", () => { ts.verifyTsc({ scenario: "forceConsistentCasingInFileNames", @@ -14,5 +16,4 @@ describe("unittests:: tsc:: forceConsistentCasingInFileNames::", () => { "/src/project/node_modules/fp-ts/lib/struct.d.ts": `export function foo(): void`, }), }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsc/helpers.ts b/src/testRunner/unittests/tsc/helpers.ts index ed5388ced839d..a8865794eb7dc 100644 --- a/src/testRunner/unittests/tsc/helpers.ts +++ b/src/testRunner/unittests/tsc/helpers.ts @@ -1,4 +1,8 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as fakes from "../../_namespaces/fakes"; +import * as vfs from "../../_namespaces/vfs"; +import * as Harness from "../../_namespaces/Harness"; + export type TscCompileSystem = fakes.System & { writtenFiles: ts.Set; baseLine(): { file: string; text: string; }; @@ -244,4 +248,3 @@ export function verifyTscCompileLike(verifier: ( export function verifyTsc(input: TestTscCompile) { verifyTscCompileLike(testTscCompile, input); } -} diff --git a/src/testRunner/unittests/tsc/incremental.ts b/src/testRunner/unittests/tsc/incremental.ts index 521af460adaa6..972b7efe84abb 100644 --- a/src/testRunner/unittests/tsc/incremental.ts +++ b/src/testRunner/unittests/tsc/incremental.ts @@ -1,4 +1,7 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; +import * as vfs from "../../_namespaces/vfs"; + describe("unittests:: tsc:: incremental::", () => { ts.verifyTscWithEdits({ scenario: "incremental", @@ -816,4 +819,3 @@ console.log(a);`, }); }); }); -} diff --git a/src/testRunner/unittests/tsc/listFilesOnly.ts b/src/testRunner/unittests/tsc/listFilesOnly.ts index 66a072418fc20..a81b1a7c82e4e 100644 --- a/src/testRunner/unittests/tsc/listFilesOnly.ts +++ b/src/testRunner/unittests/tsc/listFilesOnly.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; + describe("unittests:: tsc:: listFilesOnly::", () => { ts.verifyTsc({ scenario: "listFilesOnly", @@ -41,4 +43,3 @@ describe("unittests:: tsc:: listFilesOnly::", () => { ] }); }); -} diff --git a/src/testRunner/unittests/tsc/projectReferences.ts b/src/testRunner/unittests/tsc/projectReferences.ts index 7c2c84e36fb40..47b9486d02e0f 100644 --- a/src/testRunner/unittests/tsc/projectReferences.ts +++ b/src/testRunner/unittests/tsc/projectReferences.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsc:: projectReferences::", () => { ts.verifyTsc({ scenario: "projectReferences", @@ -39,4 +40,3 @@ describe("unittests:: tsc:: projectReferences::", () => { commandLineArgs: ["--p", "src/project"] }); }); -} diff --git a/src/testRunner/unittests/tsc/redirect.ts b/src/testRunner/unittests/tsc/redirect.ts index 676f47613716c..df174a6dd5487 100644 --- a/src/testRunner/unittests/tsc/redirect.ts +++ b/src/testRunner/unittests/tsc/redirect.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsc:: redirect::", () => { ts.verifyTsc({ scenario: "redirect", @@ -31,4 +32,3 @@ describe("unittests:: tsc:: redirect::", () => { commandLineArgs: ["-p", "src/project"], }); }); -} diff --git a/src/testRunner/unittests/tsc/runWithoutArgs.ts b/src/testRunner/unittests/tsc/runWithoutArgs.ts index 462282affa42a..6c7af42052327 100644 --- a/src/testRunner/unittests/tsc/runWithoutArgs.ts +++ b/src/testRunner/unittests/tsc/runWithoutArgs.ts @@ -1,4 +1,5 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsc:: runWithoutArgs::", () => { ts.verifyTsc({ scenario: "runWithoutArgs", @@ -24,4 +25,3 @@ describe("unittests:: tsc:: runWithoutArgs::", () => { }); }); -} diff --git a/src/testRunner/unittests/tscWatch/consoleClearing.ts b/src/testRunner/unittests/tscWatch/consoleClearing.ts index b7fb5f2c7642f..7039748e91638 100644 --- a/src/testRunner/unittests/tscWatch/consoleClearing.ts +++ b/src/testRunner/unittests/tscWatch/consoleClearing.ts @@ -1,4 +1,5 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsc-watch:: console clearing", () => { const scenario = "consoleClearing"; const file: ts.tscWatch.File = { @@ -63,4 +64,3 @@ describe("unittests:: tsc-watch:: console clearing", () => { }); }); }); -} diff --git a/src/testRunner/unittests/tscWatch/emit.ts b/src/testRunner/unittests/tscWatch/emit.ts index 5b497d872ab31..2ab59f8d376bd 100644 --- a/src/testRunner/unittests/tscWatch/emit.ts +++ b/src/testRunner/unittests/tscWatch/emit.ts @@ -1,4 +1,5 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; + const scenario = "emit"; describe("unittests:: tsc-watch:: emit with outFile or out setting", () => { function verifyOutAndOutFileSetting(subScenario: string, out?: string, outFile?: string) { @@ -517,4 +518,3 @@ describe("unittests:: tsc-watch:: emit with when module emit is specified as nod ], }); }); -} diff --git a/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts b/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts index 4273e37c8cbd2..40afb4bce56a7 100644 --- a/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts +++ b/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts @@ -1,4 +1,5 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsc-watch:: Emit times and Error updates in builder after program changes", () => { const config: ts.tscWatch.File = { path: `${ts.tscWatch.projectRoot}/tsconfig.json`, @@ -369,4 +370,3 @@ const a: string = "hello";`), }); }); }); -} diff --git a/src/testRunner/unittests/tscWatch/forceConsistentCasingInFileNames.ts b/src/testRunner/unittests/tscWatch/forceConsistentCasingInFileNames.ts index 894765410d5df..f301dc7708b94 100644 --- a/src/testRunner/unittests/tscWatch/forceConsistentCasingInFileNames.ts +++ b/src/testRunner/unittests/tscWatch/forceConsistentCasingInFileNames.ts @@ -1,4 +1,6 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; + describe("unittests:: tsc-watch:: forceConsistentCasingInFileNames", () => { const loggerFile: ts.tscWatch.File = { path: `${ts.tscWatch.projectRoot}/logger.ts`, @@ -358,4 +360,3 @@ a;b; changes: ts.emptyArray, }); }); -} diff --git a/src/testRunner/unittests/tscWatch/helpers.ts b/src/testRunner/unittests/tscWatch/helpers.ts index f92eadf7d4892..c4d059b896a95 100644 --- a/src/testRunner/unittests/tscWatch/helpers.ts +++ b/src/testRunner/unittests/tscWatch/helpers.ts @@ -1,4 +1,7 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; +import * as fakes from "../../_namespaces/fakes"; +import * as Harness from "../../_namespaces/Harness"; + export const projects = `/user/username/projects`; export const projectRoot = `${projects}/myproject`; export import WatchedSystem = ts.TestFSWithWatch.TestServerHost; @@ -435,4 +438,3 @@ export function solutionBuildWithBaseline(sys: WatchedSystem, solutionRoots: rea export function createSystemWithSolutionBuild(solutionRoots: readonly string[], files: ts.TestFSWithWatch.FileOrFolderOrSymLinkMap | readonly ts.TestFSWithWatch.FileOrFolderOrSymLink[], params?: ts.TestFSWithWatch.TestServerHostCreationParameters) { return solutionBuildWithBaseline(createWatchedSystem(files, params), solutionRoots); } -} diff --git a/src/testRunner/unittests/tscWatch/incremental.ts b/src/testRunner/unittests/tscWatch/incremental.ts index ef82ef9879f9d..3de067d433c48 100644 --- a/src/testRunner/unittests/tscWatch/incremental.ts +++ b/src/testRunner/unittests/tscWatch/incremental.ts @@ -1,4 +1,6 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; + describe("unittests:: tsc-watch:: emit file --incremental", () => { const project = "/users/username/projects/project"; @@ -388,4 +390,3 @@ export const Fragment: unique symbol; changes: ts.emptyArray }); }); -} diff --git a/src/testRunner/unittests/tscWatch/moduleResolution.ts b/src/testRunner/unittests/tscWatch/moduleResolution.ts index c89986afce10f..a03b0f8750824 100644 --- a/src/testRunner/unittests/tscWatch/moduleResolution.ts +++ b/src/testRunner/unittests/tscWatch/moduleResolution.ts @@ -1,4 +1,6 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; + describe("unittests:: tsc-watch:: moduleResolution", () => { ts.tscWatch.verifyTscWatch({ scenario: "moduleResolution", @@ -326,5 +328,4 @@ describe("unittests:: tsc-watch:: moduleResolution", () => { } ] }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tscWatch/nodeNextWatch.ts b/src/testRunner/unittests/tscWatch/nodeNextWatch.ts index d4578c15bcd5a..744b60a1d07be 100644 --- a/src/testRunner/unittests/tscWatch/nodeNextWatch.ts +++ b/src/testRunner/unittests/tscWatch/nodeNextWatch.ts @@ -1,4 +1,6 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; + describe("unittests:: tsc-watch:: nodeNextWatch:: emit when module emit is specified as nodenext", () => { ts.tscWatch.verifyTscWatch({ scenario: "nodenext watch emit", @@ -54,5 +56,4 @@ describe("unittests:: tsc-watch:: nodeNextWatch:: emit when module emit is speci } ], }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tscWatch/programUpdates.ts b/src/testRunner/unittests/tscWatch/programUpdates.ts index c1f3442791daa..725e652d13072 100644 --- a/src/testRunner/unittests/tscWatch/programUpdates.ts +++ b/src/testRunner/unittests/tscWatch/programUpdates.ts @@ -1,4 +1,6 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; + describe("unittests:: tsc-watch:: program updates", () => { const scenario = "programUpdates"; const configFilePath = "/a/b/tsconfig.json"; @@ -1949,4 +1951,3 @@ import { x } from "../b";`), ] }); }); -} diff --git a/src/testRunner/unittests/tscWatch/projectsWithReferences.ts b/src/testRunner/unittests/tscWatch/projectsWithReferences.ts index eae23d29debae..6a9d35661408f 100644 --- a/src/testRunner/unittests/tscWatch/projectsWithReferences.ts +++ b/src/testRunner/unittests/tscWatch/projectsWithReferences.ts @@ -1,4 +1,5 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsc-watch:: projects with references: invoking when references are already built", () => { ts.tscWatch.verifyTscWatch({ scenario: "projectsWithReferences", @@ -441,5 +442,4 @@ X;`, ], baselineDependencies: true }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tscWatch/resolutionCache.ts b/src/testRunner/unittests/tscWatch/resolutionCache.ts index d73d606b7b2af..df69419ac6c20 100644 --- a/src/testRunner/unittests/tscWatch/resolutionCache.ts +++ b/src/testRunner/unittests/tscWatch/resolutionCache.ts @@ -1,4 +1,5 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch module resolution caching", () => { const scenario = "resolutionCache"; it("caching works", () => { @@ -563,4 +564,3 @@ declare namespace NodeJS { }); }); }); -} diff --git a/src/testRunner/unittests/tscWatch/sourceOfProjectReferenceRedirect.ts b/src/testRunner/unittests/tscWatch/sourceOfProjectReferenceRedirect.ts index b07fca779b460..7be526e395220 100644 --- a/src/testRunner/unittests/tscWatch/sourceOfProjectReferenceRedirect.ts +++ b/src/testRunner/unittests/tscWatch/sourceOfProjectReferenceRedirect.ts @@ -1,4 +1,5 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; + import getFileFromProject = ts.TestFSWithWatch.getTsBuildProjectFile; describe("unittests:: tsc-watch:: watchAPI:: with sourceOfProjectReferenceRedirect", () => { interface VerifyWatchInput { @@ -170,4 +171,3 @@ bar(); }); }); }); -} diff --git a/src/testRunner/unittests/tscWatch/watchApi.ts b/src/testRunner/unittests/tscWatch/watchApi.ts index 8d1f363e64796..9f8219610b2f7 100644 --- a/src/testRunner/unittests/tscWatch/watchApi.ts +++ b/src/testRunner/unittests/tscWatch/watchApi.ts @@ -1,4 +1,6 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; + describe("unittests:: tsc-watch:: watchAPI:: tsc-watch with custom module resolution", () => { it("verify that module resolution with json extension works when returned without extension", () => { const configFileJson: any = { @@ -704,4 +706,3 @@ describe("unittests:: tsc-watch:: watchAPI:: when builder emit occurs with emitO verify("when emitting with emitOnlyDtsFiles"); verify("when emitting with emitOnlyDtsFiles with outFile", "outFile.js"); }); -} diff --git a/src/testRunner/unittests/tscWatch/watchEnvironment.ts b/src/testRunner/unittests/tscWatch/watchEnvironment.ts index 1df444ee3d110..ddeeaa64c5cfb 100644 --- a/src/testRunner/unittests/tscWatch/watchEnvironment.ts +++ b/src/testRunner/unittests/tscWatch/watchEnvironment.ts @@ -1,4 +1,5 @@ -namespace ts.tscWatch { +import * as ts from "../../_namespaces/ts"; + import Tsc_WatchDirectory = ts.TestFSWithWatch.Tsc_WatchDirectory; describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different polling/non polling options", () => { const scenario = "watchEnvironment"; @@ -688,4 +689,3 @@ describe("unittests:: tsc-watch:: watchEnvironment:: tsc-watch with different po }); }); }); -} diff --git a/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts b/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts index 22e85b3c19fd3..f778e72139824 100644 --- a/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts +++ b/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: applyChangesToOpenFiles", () => { const configFile: ts.projectSystem.File = { path: "/a/b/tsconfig.json", @@ -178,4 +179,3 @@ ${file.content}`; }); }); }); -} diff --git a/src/testRunner/unittests/tsserver/autoImportProvider.ts b/src/testRunner/unittests/tsserver/autoImportProvider.ts index b4a7fd2f0402f..5d2113bb64ed9 100644 --- a/src/testRunner/unittests/tsserver/autoImportProvider.ts +++ b/src/testRunner/unittests/tsserver/autoImportProvider.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + const angularFormsDts: ts.projectSystem.File = { path: "/node_modules/@angular/forms/forms.d.ts", content: "export declare class PatternValidator {}", @@ -350,4 +351,3 @@ function setup(files: ts.projectSystem.File[]) { }); } } -} diff --git a/src/testRunner/unittests/tsserver/auxiliaryProject.ts b/src/testRunner/unittests/tsserver/auxiliaryProject.ts index bf599f9caee08..58742f0e421aa 100644 --- a/src/testRunner/unittests/tsserver/auxiliaryProject.ts +++ b/src/testRunner/unittests/tsserver/auxiliaryProject.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + const aTs: ts.projectSystem.File = { path: "/a.ts", content: `import { B } from "./b";` @@ -44,4 +45,3 @@ describe("unittests:: tsserver:: auxiliaryProject", () => { assert.equal(bJsScriptInfo.getDefaultProject().projectKind, ts.server.ProjectKind.Inferred); }); }); -} diff --git a/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts b/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts index c3e14f2584843..5834c4592ca19 100644 --- a/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts +++ b/src/testRunner/unittests/tsserver/cachingFileSystemInformation.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectSystem CachingFileSystemInformation", () => { enum CalledMapsWithSingleArg { fileExists = "fileExists", @@ -573,4 +574,3 @@ describe("unittests:: tsserver:: CachingFileSystemInformation:: tsserverProjectS ts.projectSystem.checkProjectActualFiles(project, [module1.path, `${symlink.path}/module2.ts`, config.path, ts.projectSystem.libFile.path, `${symlink.path}/module3.ts`]); }); }); -} diff --git a/src/testRunner/unittests/tsserver/cancellationToken.ts b/src/testRunner/unittests/tsserver/cancellationToken.ts index bb6f2dc995b80..5c207e74d8eb5 100644 --- a/src/testRunner/unittests/tsserver/cancellationToken.ts +++ b/src/testRunner/unittests/tsserver/cancellationToken.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: 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; @@ -271,4 +272,3 @@ describe("unittests:: tsserver:: cancellationToken", () => { } }); }); -} diff --git a/src/testRunner/unittests/tsserver/compileOnSave.ts b/src/testRunner/unittests/tsserver/compileOnSave.ts index ef50608300877..327dfdef4265e 100644 --- a/src/testRunner/unittests/tsserver/compileOnSave.ts +++ b/src/testRunner/unittests/tsserver/compileOnSave.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + import CommandNames = ts.server.CommandNames; function createTestTypingsInstaller(host: ts.server.ServerHost) { return new ts.projectSystem.TestTypingsInstaller("/a/data/", /*throttleLimit*/5, host); @@ -1048,4 +1049,3 @@ describe("unittests:: tsserver:: compileOnSave:: CompileOnSaveAffectedFileListRe file: `${ts.tscWatch.projectRoot}/core/core.ts`, }); }); -} diff --git a/src/testRunner/unittests/tsserver/completions.ts b/src/testRunner/unittests/tsserver/completions.ts index 3e3e2ccbb8082..4e046ae6ebadb 100644 --- a/src/testRunner/unittests/tsserver/completions.ts +++ b/src/testRunner/unittests/tsserver/completions.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: completions", () => { it("works", () => { const aTs: ts.projectSystem.File = { @@ -264,4 +265,3 @@ export interface BrowserRouterProps { }); }); }); -} diff --git a/src/testRunner/unittests/tsserver/completionsIncomplete.ts b/src/testRunner/unittests/tsserver/completionsIncomplete.ts index 2adf233f4eebf..e0d3ee5ed4eb6 100644 --- a/src/testRunner/unittests/tsserver/completionsIncomplete.ts +++ b/src/testRunner/unittests/tsserver/completionsIncomplete.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + function createExportingModuleFile(path: string, exportPrefix: string, exportCount: number): ts.projectSystem.File { return { path, @@ -259,4 +260,3 @@ function setup(files: ts.projectSystem.File[]) { return details; } } -} diff --git a/src/testRunner/unittests/tsserver/configFileSearch.ts b/src/testRunner/unittests/tsserver/configFileSearch.ts index abf95ad0c71c3..8ed168c683b97 100644 --- a/src/testRunner/unittests/tsserver/configFileSearch.ts +++ b/src/testRunner/unittests/tsserver/configFileSearch.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: searching for config file", () => { it("should stop at projectRootPath if given", () => { const f1 = { @@ -133,4 +134,3 @@ describe("unittests:: tsserver:: searching for config file", () => { verifyConfigFileWatch("when projectRootPath is present but file is not from project root", "/a/b"); }); }); -} diff --git a/src/testRunner/unittests/tsserver/configuredProjects.ts b/src/testRunner/unittests/tsserver/configuredProjects.ts index de8f057d8a551..9e3ebe7e5ae3e 100644 --- a/src/testRunner/unittests/tsserver/configuredProjects.ts +++ b/src/testRunner/unittests/tsserver/configuredProjects.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: ConfiguredProjects", () => { it("create configured project without file list", () => { const configFile: ts.projectSystem.File = { @@ -1257,4 +1258,3 @@ describe("unittests:: tsserver:: ConfiguredProjects:: when reading tsconfig file }]); }); }); -} diff --git a/src/testRunner/unittests/tsserver/declarationFileMaps.ts b/src/testRunner/unittests/tsserver/declarationFileMaps.ts index 20812a8c092b8..ccc6b96263725 100644 --- a/src/testRunner/unittests/tsserver/declarationFileMaps.ts +++ b/src/testRunner/unittests/tsserver/declarationFileMaps.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + function documentSpanFromSubstring({ file, text, contextText, options, contextOptions }: ts.projectSystem.DocumentSpanFromSubstring): ts.DocumentSpan { const contextSpan = contextText !== undefined ? documentSpanFromSubstring({ file, text: contextText, options: contextOptions }) : undefined; return { @@ -768,4 +769,3 @@ describe("unittests:: tsserver:: with declaration file maps:: project references verifySingleInferredProject(session); }); }); -} diff --git a/src/testRunner/unittests/tsserver/documentRegistry.ts b/src/testRunner/unittests/tsserver/documentRegistry.ts index 559ea8112c69d..fbb291a738a24 100644 --- a/src/testRunner/unittests/tsserver/documentRegistry.ts +++ b/src/testRunner/unittests/tsserver/documentRegistry.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: document registry in project service", () => { const importModuleContent = `import {a} from "./module1"`; const file: ts.projectSystem.File = { @@ -90,4 +91,3 @@ describe("unittests:: tsserver:: document registry in project service", () => { assert.equal(moduleInfo.cacheSourceFile!.sourceFile.text, updatedModuleContent); }); }); -} diff --git a/src/testRunner/unittests/tsserver/duplicatePackages.ts b/src/testRunner/unittests/tsserver/duplicatePackages.ts index de61e5013577c..7dac9af67e01a 100644 --- a/src/testRunner/unittests/tsserver/duplicatePackages.ts +++ b/src/testRunner/unittests/tsserver/duplicatePackages.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: duplicate packages", () => { // Tests that 'moduleSpecifiers.ts' will import from the redirecting file, and not from the file it redirects to, if that can provide a global module specifier. it("works with import fixes", () => { @@ -51,4 +52,3 @@ describe("unittests:: tsserver:: duplicate packages", () => { } }); }); -} diff --git a/src/testRunner/unittests/tsserver/dynamicFiles.ts b/src/testRunner/unittests/tsserver/dynamicFiles.ts index dd0840cc914cf..19398777e39e6 100644 --- a/src/testRunner/unittests/tsserver/dynamicFiles.ts +++ b/src/testRunner/unittests/tsserver/dynamicFiles.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + export function verifyDynamic(service: ts.server.ProjectService, path: string) { const info = ts.Debug.checkDefined(service.filenameToScriptInfo.get(path), `Expected ${path} in :: ${JSON.stringify(ts.arrayFrom(service.filenameToScriptInfo.entries(), ([key, f]) => ({ key, fileName: f.fileName, path: f.path })))}`); assert.isTrue(info.isDynamic); @@ -257,4 +258,3 @@ describe("unittests:: tsserver:: dynamicFiles:: ", () => { }); }); }); -} diff --git a/src/testRunner/unittests/tsserver/events/largeFileReferenced.ts b/src/testRunner/unittests/tsserver/events/largeFileReferenced.ts index f98664b1c7ce5..57a295d8cf80a 100644 --- a/src/testRunner/unittests/tsserver/events/largeFileReferenced.ts +++ b/src/testRunner/unittests/tsserver/events/largeFileReferenced.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../../_namespaces/ts"; + describe("unittests:: tsserver:: events:: LargeFileReferencedEvent with large file", () => { function getLargeFile(useLargeTsFile: boolean) { @@ -72,4 +73,3 @@ describe("unittests:: tsserver:: events:: LargeFileReferencedEvent with large fi verifyLargeFile(/*useLargeTsFile*/ false); }); }); -} diff --git a/src/testRunner/unittests/tsserver/events/projectLanguageServiceState.ts b/src/testRunner/unittests/tsserver/events/projectLanguageServiceState.ts index 71c3a2b5ee214..7fcb0b56c42bd 100644 --- a/src/testRunner/unittests/tsserver/events/projectLanguageServiceState.ts +++ b/src/testRunner/unittests/tsserver/events/projectLanguageServiceState.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../../_namespaces/ts"; + describe("unittests:: tsserver:: events:: ProjectLanguageServiceStateEvent", () => { it("language service disabled events are triggered", () => { const f1 = { @@ -76,4 +77,3 @@ describe("unittests:: tsserver:: events:: ProjectLanguageServiceStateEvent", () ts.projectSystem.baselineTsserverLogs("projectLanguageServiceStateEvent", "large file size is determined correctly", service); }); }); -} diff --git a/src/testRunner/unittests/tsserver/events/projectLoading.ts b/src/testRunner/unittests/tsserver/events/projectLoading.ts index c5a1d4c4e0838..ee8d02415725c 100644 --- a/src/testRunner/unittests/tsserver/events/projectLoading.ts +++ b/src/testRunner/unittests/tsserver/events/projectLoading.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../../_namespaces/ts"; + describe("unittests:: tsserver:: events:: ProjectLoadingStart and ProjectLoadingFinish events", () => { const aTs: ts.projectSystem.File = { path: `${ts.tscWatch.projects}/a/a.ts`, @@ -229,4 +230,3 @@ describe("unittests:: tsserver:: events:: ProjectLoadingStart and ProjectLoading }); }); }); -} diff --git a/src/testRunner/unittests/tsserver/events/projectUpdatedInBackground.ts b/src/testRunner/unittests/tsserver/events/projectUpdatedInBackground.ts index 4dd4d96176a62..47d51d169c117 100644 --- a/src/testRunner/unittests/tsserver/events/projectUpdatedInBackground.ts +++ b/src/testRunner/unittests/tsserver/events/projectUpdatedInBackground.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../../_namespaces/ts"; + describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { function verifyFiles(caption: string, actual: readonly string[], expected: readonly string[]) { assert.equal(actual.length, expected.length, `Incorrect number of ${caption}. Actual: ${actual} Expected: ${expected}`); @@ -553,4 +554,3 @@ describe("unittests:: tsserver:: events:: ProjectsUpdatedInBackground", () => { } }); }); -} diff --git a/src/testRunner/unittests/tsserver/exportMapCache.ts b/src/testRunner/unittests/tsserver/exportMapCache.ts index 8107dcb43b489..4cbb70fd45640 100644 --- a/src/testRunner/unittests/tsserver/exportMapCache.ts +++ b/src/testRunner/unittests/tsserver/exportMapCache.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + const packageJson: ts.projectSystem.File = { path: "/package.json", content: `{ "dependencies": { "mobx": "*" } }` @@ -144,4 +145,3 @@ function setup() { }); } } -} diff --git a/src/testRunner/unittests/tsserver/externalProjects.ts b/src/testRunner/unittests/tsserver/externalProjects.ts index a52607b345151..cbd3ffced2317 100644 --- a/src/testRunner/unittests/tsserver/externalProjects.ts +++ b/src/testRunner/unittests/tsserver/externalProjects.ts @@ -1,4 +1,6 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; + describe("unittests:: tsserver:: ExternalProjects", () => { describe("can handle tsconfig file name with difference casing", () => { function verifyConfigFileCasing(lazyConfiguredProjectsFromExternalProject: boolean) { @@ -938,4 +940,3 @@ describe("unittests:: tsserver:: ExternalProjects", () => { ts.projectSystem.checkNumberOfProjects(projectService, { externalProjects: 1 }); }); }); -} diff --git a/src/testRunner/unittests/tsserver/forceConsistentCasingInFileNames.ts b/src/testRunner/unittests/tsserver/forceConsistentCasingInFileNames.ts index da8090958d639..74551041f8f54 100644 --- a/src/testRunner/unittests/tsserver/forceConsistentCasingInFileNames.ts +++ b/src/testRunner/unittests/tsserver/forceConsistentCasingInFileNames.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: forceConsistentCasingInFileNames", () => { it("works when extends is specified with a case insensitive file system", () => { const rootPath = "/Users/username/dev/project"; @@ -133,4 +134,3 @@ describe("unittests:: tsserver:: forceConsistentCasingInFileNames", () => { ts.projectSystem.baselineTsserverLogs("forceConsistentCasingInFileNames", "when changing module name with different casing", session); }); }); -} diff --git a/src/testRunner/unittests/tsserver/formatSettings.ts b/src/testRunner/unittests/tsserver/formatSettings.ts index 4b5a5bfb28490..0fde7703d3e07 100644 --- a/src/testRunner/unittests/tsserver/formatSettings.ts +++ b/src/testRunner/unittests/tsserver/formatSettings.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: format settings", () => { it("can be set globally", () => { const f1 = { @@ -36,4 +37,3 @@ describe("unittests:: tsserver:: format settings", () => { assert.deepEqual(s3, newPerFileSettings, "file settings should still be the same with per-file settings"); }); }); -} diff --git a/src/testRunner/unittests/tsserver/getApplicableRefactors.ts b/src/testRunner/unittests/tsserver/getApplicableRefactors.ts index 0e4018db5c48f..65497bb2bc3eb 100644 --- a/src/testRunner/unittests/tsserver/getApplicableRefactors.ts +++ b/src/testRunner/unittests/tsserver/getApplicableRefactors.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: getApplicableRefactors", () => { it("works when taking position", () => { const aTs: ts.projectSystem.File = { path: "/a.ts", content: "" }; @@ -9,4 +10,3 @@ describe("unittests:: tsserver:: getApplicableRefactors", () => { assert.deepEqual(response, []); }); }); -} diff --git a/src/testRunner/unittests/tsserver/getEditsForFileRename.ts b/src/testRunner/unittests/tsserver/getEditsForFileRename.ts index ca937ef3d7ca1..89e3d708beeb0 100644 --- a/src/testRunner/unittests/tsserver/getEditsForFileRename.ts +++ b/src/testRunner/unittests/tsserver/getEditsForFileRename.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: getEditsForFileRename", () => { it("works for host implementing 'resolveModuleNames' and 'getResolvedModuleWithFailedLookupLocationsFromCache'", () => { const userTs: ts.projectSystem.File = { @@ -102,4 +103,3 @@ describe("unittests:: tsserver:: getEditsForFileRename", () => { ]); }); }); -} diff --git a/src/testRunner/unittests/tsserver/getExportReferences.ts b/src/testRunner/unittests/tsserver/getExportReferences.ts index 9767b18f395ba..f1009a8d56f2d 100644 --- a/src/testRunner/unittests/tsserver/getExportReferences.ts +++ b/src/testRunner/unittests/tsserver/getExportReferences.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: getExportReferences", () => { const exportVariable = "export const value = 0;"; const exportArrayDestructured = "export const [valueA, valueB] = [0, 1];"; @@ -190,4 +191,3 @@ ${exportNestedObject} assert.deepEqual(response, expectResponse); }); }); -} diff --git a/src/testRunner/unittests/tsserver/getFileReferences.ts b/src/testRunner/unittests/tsserver/getFileReferences.ts index 340620de4aa05..1db68ae8ea9ad 100644 --- a/src/testRunner/unittests/tsserver/getFileReferences.ts +++ b/src/testRunner/unittests/tsserver/getFileReferences.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: getFileReferences", () => { const importA = `import "./a";`; const importCurlyFromA = `import {} from "./a";`; @@ -78,4 +79,3 @@ describe("unittests:: tsserver:: getFileReferences", () => { assert.deepEqual(response, expectResponse); }); }); -} diff --git a/src/testRunner/unittests/tsserver/helpers.ts b/src/testRunner/unittests/tsserver/helpers.ts index 2ff5ba101c72b..8163b8a249baf 100644 --- a/src/testRunner/unittests/tsserver/helpers.ts +++ b/src/testRunner/unittests/tsserver/helpers.ts @@ -1,4 +1,7 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; +import * as Utils from "../../_namespaces/Utils"; + export import TI = ts.server.typingsInstaller; export import protocol = ts.server.protocol; export import CommandNames = ts.server.CommandNames; @@ -939,4 +942,3 @@ export function verifyGetErrScenario(scenario: VerifyGetErrScenario) { verifyErrorsUsingGeterrForProject(scenario); verifyErrorsUsingSyncMethods(scenario); } -} diff --git a/src/testRunner/unittests/tsserver/importHelpers.ts b/src/testRunner/unittests/tsserver/importHelpers.ts index 791f18bb8c435..483ce6edda8fe 100644 --- a/src/testRunner/unittests/tsserver/importHelpers.ts +++ b/src/testRunner/unittests/tsserver/importHelpers.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: import helpers", () => { it("should not crash in tsserver", () => { const f1 = { @@ -15,4 +16,3 @@ describe("unittests:: tsserver:: import helpers", () => { service.checkNumberOfProjects({ externalProjects: 1 }); }); }); -} diff --git a/src/testRunner/unittests/tsserver/inferredProjects.ts b/src/testRunner/unittests/tsserver/inferredProjects.ts index b7e1e98442b18..12e51e98107de 100644 --- a/src/testRunner/unittests/tsserver/inferredProjects.ts +++ b/src/testRunner/unittests/tsserver/inferredProjects.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: Inferred projects", () => { it("create inferred project", () => { const appFile: ts.projectSystem.File = { @@ -451,4 +452,3 @@ describe("unittests:: tsserver:: Inferred projects", () => { host.checkTimeoutQueueLength(0); }); }); -} diff --git a/src/testRunner/unittests/tsserver/inlayHints.ts b/src/testRunner/unittests/tsserver/inlayHints.ts index bd68a86feb1d5..d5e41272ccdcc 100644 --- a/src/testRunner/unittests/tsserver/inlayHints.ts +++ b/src/testRunner/unittests/tsserver/inlayHints.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: inlayHints", () => { const configFile: ts.projectSystem.File = { path: "/a/b/tsconfig.json", @@ -60,4 +61,3 @@ describe("unittests:: tsserver:: inlayHints", () => { } }); }); -} diff --git a/src/testRunner/unittests/tsserver/jsdocTag.ts b/src/testRunner/unittests/tsserver/jsdocTag.ts index 5925a57f8d46f..ec0c44b1e16ca 100644 --- a/src/testRunner/unittests/tsserver/jsdocTag.ts +++ b/src/testRunner/unittests/tsserver/jsdocTag.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: jsdoc @link ", () => { const config: ts.projectSystem.File = { path: "/a/tsconfig.json", @@ -691,4 +692,3 @@ foo` }); }); }); -} diff --git a/src/testRunner/unittests/tsserver/languageService.ts b/src/testRunner/unittests/tsserver/languageService.ts index dedfc4a907814..5353b73ccdcb4 100644 --- a/src/testRunner/unittests/tsserver/languageService.ts +++ b/src/testRunner/unittests/tsserver/languageService.ts @@ -1,4 +1,6 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; + describe("unittests:: tsserver:: languageService", () => { it("should work correctly on case-sensitive file systems", () => { const lib = { @@ -65,4 +67,3 @@ describe("unittests:: tsserver:: languageService", () => { ts.Debug.assertEqual(proj2Diags.length, 1); }); }); -} diff --git a/src/testRunner/unittests/tsserver/maxNodeModuleJsDepth.ts b/src/testRunner/unittests/tsserver/maxNodeModuleJsDepth.ts index 5dd82acc6e8e3..928ec383d4f28 100644 --- a/src/testRunner/unittests/tsserver/maxNodeModuleJsDepth.ts +++ b/src/testRunner/unittests/tsserver/maxNodeModuleJsDepth.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: maxNodeModuleJsDepth for inferred projects", () => { it("should be set to 2 if the project has js root files", () => { const file1: ts.projectSystem.File = { @@ -52,4 +53,3 @@ describe("unittests:: tsserver:: maxNodeModuleJsDepth for inferred projects", () assert.isUndefined(project.getCompilationSettings().maxNodeModuleJsDepth); }); }); -} diff --git a/src/testRunner/unittests/tsserver/metadataInResponse.ts b/src/testRunner/unittests/tsserver/metadataInResponse.ts index b333a5173cb89..35d3081ebc60c 100644 --- a/src/testRunner/unittests/tsserver/metadataInResponse.ts +++ b/src/testRunner/unittests/tsserver/metadataInResponse.ts @@ -1,4 +1,6 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; + describe("unittests:: tsserver:: with metadata in response", () => { const metadata = "Extra Info"; function verifyOutput(host: ts.projectSystem.TestServerHost, expectedResponse: ts.projectSystem.protocol.Response) { @@ -101,4 +103,3 @@ describe("unittests:: tsserver:: with metadata in response", () => { }); }); }); -} diff --git a/src/testRunner/unittests/tsserver/moduleResolution.ts b/src/testRunner/unittests/tsserver/moduleResolution.ts index 82304ed3ee4f0..0ff53167e2662 100644 --- a/src/testRunner/unittests/tsserver/moduleResolution.ts +++ b/src/testRunner/unittests/tsserver/moduleResolution.ts @@ -1,4 +1,6 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; + describe("unittests:: tsserver:: moduleResolution", () => { describe("package json file is edited", () => { function setup(packageFileContents: string) { @@ -117,5 +119,4 @@ describe("unittests:: tsserver:: moduleResolution", () => { ts.projectSystem.baselineTsserverLogs("moduleResolution", "package json file is edited when package json with type module exists", session); }); }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsserver/moduleSpecifierCache.ts b/src/testRunner/unittests/tsserver/moduleSpecifierCache.ts index d251a1fd2c27c..59d05ef1a9b32 100644 --- a/src/testRunner/unittests/tsserver/moduleSpecifierCache.ts +++ b/src/testRunner/unittests/tsserver/moduleSpecifierCache.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + const packageJson: ts.projectSystem.File = { path: "/package.json", content: `{ "dependencies": { "mobx": "*" } }` @@ -147,4 +148,3 @@ function setup(createLogger?: (host: ts.projectSystem.TestServerHost) => ts.proj }); } } -} diff --git a/src/testRunner/unittests/tsserver/navTo.ts b/src/testRunner/unittests/tsserver/navTo.ts index 8d084d5a5eace..1d181b45510b6 100644 --- a/src/testRunner/unittests/tsserver/navTo.ts +++ b/src/testRunner/unittests/tsserver/navTo.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: navigate-to for javascript project", () => { function findNavToItem(items: ts.projectSystem.protocol.NavtoItem[], itemName: string, itemKind: string) { return ts.find(items, item => item.name === itemName && item.kind === itemKind); @@ -136,4 +137,3 @@ export const ghijkl = a.abcdef;` assert.isTrue(fooItem?.kindModifiers?.includes("deprecated")); }); }); -} diff --git a/src/testRunner/unittests/tsserver/occurences.ts b/src/testRunner/unittests/tsserver/occurences.ts index 10b227b54975e..d797525916245 100644 --- a/src/testRunner/unittests/tsserver/occurences.ts +++ b/src/testRunner/unittests/tsserver/occurences.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: occurrence highlight on string", () => { it("should be marked if only on string values", () => { const file1: ts.projectSystem.File = { @@ -44,4 +45,3 @@ describe("unittests:: tsserver:: occurrence highlight on string", () => { } }); }); -} diff --git a/src/testRunner/unittests/tsserver/openFile.ts b/src/testRunner/unittests/tsserver/openFile.ts index cd7ea20524d4e..ae8e284d616b3 100644 --- a/src/testRunner/unittests/tsserver/openFile.ts +++ b/src/testRunner/unittests/tsserver/openFile.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: Open-file", () => { it("can be reloaded with empty content", () => { const f = { @@ -184,4 +185,3 @@ bar();` ts.projectSystem.baselineTsserverLogs("openfile", "when file makes edits to add/remove comment directives, they are handled correcrly", session); }); }); -} diff --git a/src/testRunner/unittests/tsserver/packageJsonInfo.ts b/src/testRunner/unittests/tsserver/packageJsonInfo.ts index efaebd218c541..d6bf2116a8c5a 100644 --- a/src/testRunner/unittests/tsserver/packageJsonInfo.ts +++ b/src/testRunner/unittests/tsserver/packageJsonInfo.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + const tsConfig: ts.projectSystem.File = { path: "/tsconfig.json", content: "{}" @@ -109,4 +110,3 @@ function setup(files: readonly ts.projectSystem.File[] = [tsConfig, packageJson] const project = ts.projectSystem.configuredProjectAt(projectService, 0); return { host, session, project, projectService }; } -} diff --git a/src/testRunner/unittests/tsserver/partialSemanticServer.ts b/src/testRunner/unittests/tsserver/partialSemanticServer.ts index 00a7805410311..60d4adb1ae445 100644 --- a/src/testRunner/unittests/tsserver/partialSemanticServer.ts +++ b/src/testRunner/unittests/tsserver/partialSemanticServer.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: Semantic operations on partialSemanticServer", () => { function setup() { const file1: ts.projectSystem.File = { @@ -223,4 +224,3 @@ function fooB() { }` ts.projectSystem.baselineTsserverLogs("partialSemanticServer", "should support go-to-definition on module specifiers", session); }); }); -} diff --git a/src/testRunner/unittests/tsserver/plugins.ts b/src/testRunner/unittests/tsserver/plugins.ts index 189cd091b802c..2c27ea4687ad3 100644 --- a/src/testRunner/unittests/tsserver/plugins.ts +++ b/src/testRunner/unittests/tsserver/plugins.ts @@ -1,4 +1,6 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; + describe("unittests:: tsserver:: plugins loading", () => { const testProtocolCommand = "testProtocolCommand"; const testProtocolCommandRequest = "testProtocolCommandRequest"; @@ -145,5 +147,4 @@ describe("unittests:: tsserver:: plugins loading", () => { ts.projectSystem.baselineTsserverLogs("plugins", "gets external files with config file reload", session); }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsserver/projectErrors.ts b/src/testRunner/unittests/tsserver/projectErrors.ts index e5a9d43237734..49c06511870ed 100644 --- a/src/testRunner/unittests/tsserver/projectErrors.ts +++ b/src/testRunner/unittests/tsserver/projectErrors.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: Project Errors", () => { function checkProjectErrors(projectFiles: ts.server.ProjectFilesWithTSDiagnostics, expectedErrors: readonly string[]): void { assert.isTrue(projectFiles !== undefined, "missing project files"); @@ -888,4 +889,3 @@ describe("unittests:: tsserver:: Project Errors with npm install when", () => { verifyNpmInstall(/*timeoutDuringPartialInstallation*/ false); }); }); -} diff --git a/src/testRunner/unittests/tsserver/projectReferenceCompileOnSave.ts b/src/testRunner/unittests/tsserver/projectReferenceCompileOnSave.ts index 324de26f78480..f2a6941347b18 100644 --- a/src/testRunner/unittests/tsserver/projectReferenceCompileOnSave.ts +++ b/src/testRunner/unittests/tsserver/projectReferenceCompileOnSave.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: with project references and compile on save", () => { const dependecyLocation = `${ts.tscWatch.projectRoot}/dependency`; const usageLocation = `${ts.tscWatch.projectRoot}/usage`; @@ -1732,5 +1733,4 @@ describe("unittests:: tsserver:: with project references and compile on save wit }); ts.projectSystem.baselineTsserverLogs("projectReferenceCompileOnSave", "compile on save emits same output as project build with external project", session); }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsserver/projectReferenceErrors.ts b/src/testRunner/unittests/tsserver/projectReferenceErrors.ts index c391249546576..1dc9e6e020173 100644 --- a/src/testRunner/unittests/tsserver/projectReferenceErrors.ts +++ b/src/testRunner/unittests/tsserver/projectReferenceErrors.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: with project references and error reporting", () => { const dependecyLocation = `${ts.tscWatch.projectRoot}/dependency`; const usageLocation = `${ts.tscWatch.projectRoot}/usage`; @@ -128,4 +129,3 @@ fnErr(); verifyUsageAndDependency("with non module", dependencyTs, dependencyConfig, usageTs, usageConfig); }); }); -} diff --git a/src/testRunner/unittests/tsserver/projectReferences.ts b/src/testRunner/unittests/tsserver/projectReferences.ts index 7f075730a4729..85ca59c24f68d 100644 --- a/src/testRunner/unittests/tsserver/projectReferences.ts +++ b/src/testRunner/unittests/tsserver/projectReferences.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + export function createHostWithSolutionBuild(files: readonly ts.TestFSWithWatch.FileOrFolderOrSymLink[], rootNames: readonly string[]) { const host = ts.projectSystem.createServerHost(files); // ts build should succeed @@ -1590,4 +1591,3 @@ const b: B = new B();` /* eslint-enable local/boolean-trivia */ }); }); -} diff --git a/src/testRunner/unittests/tsserver/projectReferencesSourcemap.ts b/src/testRunner/unittests/tsserver/projectReferencesSourcemap.ts index 293866c24184e..fd644f629165c 100644 --- a/src/testRunner/unittests/tsserver/projectReferencesSourcemap.ts +++ b/src/testRunner/unittests/tsserver/projectReferencesSourcemap.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: with project references and tsbuild source map", () => { const dependecyLocation = `${ts.tscWatch.projectRoot}/dependency`; const dependecyDeclsLocation = `${ts.tscWatch.projectRoot}/decls`; @@ -3037,5 +3038,4 @@ ${dependencyTs.content}`); }); }); }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsserver/projects.ts b/src/testRunner/unittests/tsserver/projects.ts index b74e7b64991d5..a683a561738fa 100644 --- a/src/testRunner/unittests/tsserver/projects.ts +++ b/src/testRunner/unittests/tsserver/projects.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: Projects", () => { it("handles the missing files - that were added to program because they were added with /// { const file1: ts.projectSystem.File = { @@ -1693,4 +1694,3 @@ describe("unittests:: tsserver:: Projects", () => { }); }); }); -} diff --git a/src/testRunner/unittests/tsserver/projectsWithReferences.ts b/src/testRunner/unittests/tsserver/projectsWithReferences.ts index 93d0fe16df402..75700e7df0c55 100644 --- a/src/testRunner/unittests/tsserver/projectsWithReferences.ts +++ b/src/testRunner/unittests/tsserver/projectsWithReferences.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: projects with references: invoking when references are already built", () => { it("on sample project", () => { const coreConfig = ts.TestFSWithWatch.getTsBuildProjectFile("sample1", "core/tsconfig.json"); @@ -266,5 +267,4 @@ export class A {}` ts.projectSystem.baselineTsserverLogs("projectsWithReferences", "trasitive references without files with deleting transitively referenced config file", service); }); }); -}); -} \ No newline at end of file +}); \ No newline at end of file diff --git a/src/testRunner/unittests/tsserver/refactors.ts b/src/testRunner/unittests/tsserver/refactors.ts index f34c3b04d59fc..8468ef9ef7fee 100644 --- a/src/testRunner/unittests/tsserver/refactors.ts +++ b/src/testRunner/unittests/tsserver/refactors.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: refactors", () => { it("use formatting options", () => { const file = { @@ -152,4 +153,3 @@ describe("unittests:: tsserver:: refactors", () => { }); }); }); -} diff --git a/src/testRunner/unittests/tsserver/reload.ts b/src/testRunner/unittests/tsserver/reload.ts index 0f59e6ce27af1..2fa5355062cda 100644 --- a/src/testRunner/unittests/tsserver/reload.ts +++ b/src/testRunner/unittests/tsserver/reload.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: reload", () => { it("should work with temp file", () => { const f1 = { @@ -148,4 +149,3 @@ describe("unittests:: tsserver:: reload", () => { } }); }); -} diff --git a/src/testRunner/unittests/tsserver/reloadProjects.ts b/src/testRunner/unittests/tsserver/reloadProjects.ts index f173dbfeed6ec..b6f479f8fd02d 100644 --- a/src/testRunner/unittests/tsserver/reloadProjects.ts +++ b/src/testRunner/unittests/tsserver/reloadProjects.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: reloadProjects", () => { const configFile: ts.projectSystem.File = { path: `${ts.tscWatch.projectRoot}/tsconfig.json`, @@ -136,4 +137,3 @@ describe("unittests:: tsserver:: reloadProjects", () => { verifyFileUpdates(host, service, project); }); }); -} diff --git a/src/testRunner/unittests/tsserver/rename.ts b/src/testRunner/unittests/tsserver/rename.ts index 0e6ee721a67d7..e3d465eb703ca 100644 --- a/src/testRunner/unittests/tsserver/rename.ts +++ b/src/testRunner/unittests/tsserver/rename.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: rename", () => { it("works with fileToRename", () => { const aTs: ts.projectSystem.File = { path: "/a.ts", content: "export const a = 0;" }; @@ -300,4 +301,3 @@ describe("unittests:: tsserver:: rename", () => { }); }); }); -} diff --git a/src/testRunner/unittests/tsserver/resolutionCache.ts b/src/testRunner/unittests/tsserver/resolutionCache.ts index 35188442fdeba..3e37ab44c306d 100644 --- a/src/testRunner/unittests/tsserver/resolutionCache.ts +++ b/src/testRunner/unittests/tsserver/resolutionCache.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: resolutionCache:: tsserverProjectSystem extra resolution pass in server host", () => { it("can load typings that are proper modules", () => { const file1 = { @@ -600,4 +601,3 @@ export const x = 10;` }); }); }); -} diff --git a/src/testRunner/unittests/tsserver/session.ts b/src/testRunner/unittests/tsserver/session.ts index d0fa365a7774f..4e27b3983df03 100644 --- a/src/testRunner/unittests/tsserver/session.ts +++ b/src/testRunner/unittests/tsserver/session.ts @@ -1,4 +1,7 @@ -namespace ts.server { +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; +import * as Utils from "../../_namespaces/Utils"; + const _chai: typeof import("chai") = require("chai"); const expect: typeof _chai.expect = _chai.expect; let lastWrittenToHost: string; @@ -748,4 +751,3 @@ describe("unittests:: tsserver:: Session:: helpers", () => { assert.deepEqual(res, { line: 4, offset: 11 }); }); }); -} diff --git a/src/testRunner/unittests/tsserver/skipLibCheck.ts b/src/testRunner/unittests/tsserver/skipLibCheck.ts index 511c9101c9ebe..0ade6c7d47d61 100644 --- a/src/testRunner/unittests/tsserver/skipLibCheck.ts +++ b/src/testRunner/unittests/tsserver/skipLibCheck.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: with skipLibCheck", () => { it("should be turned on for js-only inferred projects", () => { const file1 = { @@ -226,4 +227,3 @@ describe("unittests:: tsserver:: with skipLibCheck", () => { assert.equal(errorResult[0].code, ts.Diagnostics.This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap.code); }); }); -} diff --git a/src/testRunner/unittests/tsserver/smartSelection.ts b/src/testRunner/unittests/tsserver/smartSelection.ts index fa781ffbe272c..f40f2d5e9c10c 100644 --- a/src/testRunner/unittests/tsserver/smartSelection.ts +++ b/src/testRunner/unittests/tsserver/smartSelection.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + function setup(fileName: string, content: string) { const file: ts.projectSystem.File = { path: fileName, content }; const host = ts.projectSystem.createServerHost([file, ts.projectSystem.libFile]); @@ -68,4 +69,3 @@ class Foo { end: { line: 9, offset: 2 } } } } } } } } } } }]); }); }); -} diff --git a/src/testRunner/unittests/tsserver/symLinks.ts b/src/testRunner/unittests/tsserver/symLinks.ts index e7e08644e4d59..5b9b0e6392039 100644 --- a/src/testRunner/unittests/tsserver/symLinks.ts +++ b/src/testRunner/unittests/tsserver/symLinks.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: symLinks", () => { it("rename in common file renames all project", () => { const projects = "/users/username/projects"; @@ -183,4 +184,3 @@ new C();` verifyModuleResolution(/*withPathMapping*/ true); }); }); -} diff --git a/src/testRunner/unittests/tsserver/symlinkCache.ts b/src/testRunner/unittests/tsserver/symlinkCache.ts index 385384e55af1a..e821aabdf258e 100644 --- a/src/testRunner/unittests/tsserver/symlinkCache.ts +++ b/src/testRunner/unittests/tsserver/symlinkCache.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + const appTsconfigJson: ts.projectSystem.File = { path: "/packages/app/tsconfig.json", content: ` @@ -89,4 +90,3 @@ function setup() { session, }; } -} diff --git a/src/testRunner/unittests/tsserver/syntacticServer.ts b/src/testRunner/unittests/tsserver/syntacticServer.ts index 91d210d10e5c9..ac40a78ce8e3d 100644 --- a/src/testRunner/unittests/tsserver/syntacticServer.ts +++ b/src/testRunner/unittests/tsserver/syntacticServer.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: Semantic operations on Syntax server", () => { function setup() { const file1: ts.projectSystem.File = { @@ -158,4 +159,3 @@ function fooB() { }` ts.projectSystem.checkProjectActualFiles(project, ts.emptyArray); }); }); -} diff --git a/src/testRunner/unittests/tsserver/syntaxOperations.ts b/src/testRunner/unittests/tsserver/syntaxOperations.ts index 79b76ad47f66b..505bffd884e39 100644 --- a/src/testRunner/unittests/tsserver/syntaxOperations.ts +++ b/src/testRunner/unittests/tsserver/syntaxOperations.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: syntax operations", () => { function navBarFull(session: ts.projectSystem.TestSession, file: ts.projectSystem.File) { return JSON.stringify(session.executeCommandSeq({ @@ -95,4 +96,3 @@ export function Test2() { assert.notStrictEqual(navBarResultUnitTest1WithChangedContent, navBarResultUnitTest1, "With changes in contents of unitTest file, we should see changed naviagation bar item result"); }); }); -} diff --git a/src/testRunner/unittests/tsserver/telemetry.ts b/src/testRunner/unittests/tsserver/telemetry.ts index c38b995f20aa8..a320a21e49d45 100644 --- a/src/testRunner/unittests/tsserver/telemetry.ts +++ b/src/testRunner/unittests/tsserver/telemetry.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: project telemetry", () => { it("does nothing for inferred project", () => { const file = makeFile("/a.js"); @@ -291,4 +292,3 @@ describe("unittests:: tsserver:: project telemetry", () => { function makeFile(path: string, content: {} = ""): ts.projectSystem.File { return { path, content: ts.isString(content) ? content : JSON.stringify(content) }; } -} diff --git a/src/testRunner/unittests/tsserver/textStorage.ts b/src/testRunner/unittests/tsserver/textStorage.ts index 1748c9960dd54..68c84e0b52823 100644 --- a/src/testRunner/unittests/tsserver/textStorage.ts +++ b/src/testRunner/unittests/tsserver/textStorage.ts @@ -1,4 +1,5 @@ -namespace ts.textStorage { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: Text storage", () => { const f = { path: "/a/app.ts", @@ -145,4 +146,3 @@ describe("unittests:: tsserver:: Text storage", () => { assert.strictEqual(newText.length, ts1.getTelemetryFileSize()); }); }); -} diff --git a/src/testRunner/unittests/tsserver/typeAquisition.ts b/src/testRunner/unittests/tsserver/typeAquisition.ts index f1893f76d59f5..ea501d5f914de 100644 --- a/src/testRunner/unittests/tsserver/typeAquisition.ts +++ b/src/testRunner/unittests/tsserver/typeAquisition.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: autoDiscovery", () => { it("does not depend on extension", () => { const file1 = { @@ -49,4 +50,3 @@ describe("unittests:: tsserver:: prefer typings to js", () => { ts.projectSystem.checkProjectActualFiles(ts.projectSystem.configuredProjectAt(projectService, 0), [f1.path, barTypings.path, config.path]); }); }); -} diff --git a/src/testRunner/unittests/tsserver/typeOnlyImportChains.ts b/src/testRunner/unittests/tsserver/typeOnlyImportChains.ts index 190eb40ccdad4..91857ce790936 100644 --- a/src/testRunner/unittests/tsserver/typeOnlyImportChains.ts +++ b/src/testRunner/unittests/tsserver/typeOnlyImportChains.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: typeOnlyImportChains", () => { it("named export -> type-only namespace import -> named export -> named import", () => { const a = { @@ -161,4 +162,3 @@ function assertUsageError(files: readonly ts.TestFSWithWatch.File[], openFile: t assert.lengthOf(diagnostics, 1); assert.equal(diagnostics[0].code, diagnostic.code); } -} diff --git a/src/testRunner/unittests/tsserver/typeReferenceDirectives.ts b/src/testRunner/unittests/tsserver/typeReferenceDirectives.ts index 1a395ece803e3..24a3de5650aba 100644 --- a/src/testRunner/unittests/tsserver/typeReferenceDirectives.ts +++ b/src/testRunner/unittests/tsserver/typeReferenceDirectives.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + describe("unittests:: tsserver:: typeReferenceDirectives", () => { it("when typeReferenceDirective contains UpperCasePackage", () => { const libProjectLocation = `${ts.tscWatch.projectRoot}/lib`; @@ -82,4 +83,3 @@ declare class TestLib { service.openClientFile(file.path); }); }); -} diff --git a/src/testRunner/unittests/tsserver/typingsInstaller.ts b/src/testRunner/unittests/tsserver/typingsInstaller.ts index 7cee60bca9d7e..65a0c908f9ac6 100644 --- a/src/testRunner/unittests/tsserver/typingsInstaller.ts +++ b/src/testRunner/unittests/tsserver/typingsInstaller.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + import validatePackageName = ts.JsTyping.validatePackageName; import NameValidationResult = ts.JsTyping.NameValidationResult; @@ -2178,4 +2179,3 @@ describe("unittests:: tsserver:: typingsInstaller:: tsserver:: with inferred Pro ts.projectSystem.checkProjectActualFiles(project, [file.path]); }); }); -} diff --git a/src/testRunner/unittests/tsserver/versionCache.ts b/src/testRunner/unittests/tsserver/versionCache.ts index 5af73b7118ebb..37179f926172d 100644 --- a/src/testRunner/unittests/tsserver/versionCache.ts +++ b/src/testRunner/unittests/tsserver/versionCache.ts @@ -1,4 +1,6 @@ -namespace ts { +import * as ts from "../../_namespaces/ts"; +import * as Harness from "../../_namespaces/Harness"; + function editFlat(position: number, deletedLength: number, newText: string, source: string) { return source.substring(0, position) + newText + source.substring(position + deletedLength, source.length); } @@ -325,4 +327,3 @@ describe(`unittests:: tsserver:: VersionCache stress test`, () => { } }); }); -} diff --git a/src/testRunner/unittests/tsserver/watchEnvironment.ts b/src/testRunner/unittests/tsserver/watchEnvironment.ts index 5570f43d0f6d2..99a0b3aff5729 100644 --- a/src/testRunner/unittests/tsserver/watchEnvironment.ts +++ b/src/testRunner/unittests/tsserver/watchEnvironment.ts @@ -1,4 +1,5 @@ -namespace ts.projectSystem { +import * as ts from "../../_namespaces/ts"; + import Tsc_WatchDirectory = ts.TestFSWithWatch.Tsc_WatchDirectory; describe("unittests:: tsserver:: watchEnvironment:: tsserverProjectSystem watchDirectories implementation", () => { function verifyCompletionListWithNewFileInSubFolder(scenario: string, tscWatchDirectory: Tsc_WatchDirectory) { @@ -477,4 +478,3 @@ describe("unittests:: tsserver:: watchEnvironment:: watchFile is single watcher ts.projectSystem.baselineTsserverLogs("watchEnvironment", "when watchFile is single watcher per file", session); }); }); -} diff --git a/src/testRunner/unittests/tsserver/webServer.ts b/src/testRunner/unittests/tsserver/webServer.ts index e4284b456ae4e..4e50f9297fcf0 100644 --- a/src/testRunner/unittests/tsserver/webServer.ts +++ b/src/testRunner/unittests/tsserver/webServer.ts @@ -1,5 +1,7 @@ +import * as ts from "../../_namespaces/ts"; +import * as Utils from "../../_namespaces/Utils"; + /* eslint-disable local/boolean-trivia */ -namespace ts.projectSystem { describe("unittests:: tsserver:: webServer", () => { class TestWorkerSession extends ts.server.WorkerSession { constructor(host: ts.server.ServerHost, webHost: ts.server.HostWithWriteMessage, options: Partial, logger: ts.server.Logger) { @@ -356,4 +358,3 @@ describe("unittests:: tsserver:: webServer", () => { }); }); }); -} diff --git a/src/testRunner/unittests/typeParameterIsPossiblyReferenced.ts b/src/testRunner/unittests/typeParameterIsPossiblyReferenced.ts index a34819dbd914e..89d0f9c81efef 100644 --- a/src/testRunner/unittests/typeParameterIsPossiblyReferenced.ts +++ b/src/testRunner/unittests/typeParameterIsPossiblyReferenced.ts @@ -1,3 +1,9 @@ +import * as fakes from "../_namespaces/fakes"; +import * as vfs from "../_namespaces/vfs"; +import * as Harness from "../_namespaces/Harness"; +import * as documents from "../_namespaces/documents"; +import * as ts from "../_namespaces/ts"; + describe("unittests :: internalApi :: typeParameterIsPossiblyReferenced", () => { it("with type parameter aliasing", () => { const content = ` diff --git a/src/testRunner/utilsRef.ts b/src/testRunner/utilsRef.ts index 6d34691c828b0..02df007be146d 100644 --- a/src/testRunner/utilsRef.ts +++ b/src/testRunner/utilsRef.ts @@ -1,2 +1,2 @@ // empty ref to Utils so it can be referenced by unittests -namespace Utils {} \ No newline at end of file +export { }; diff --git a/src/testRunner/vfsRef.ts b/src/testRunner/vfsRef.ts index 232efaab17874..7a9130a0d9c65 100644 --- a/src/testRunner/vfsRef.ts +++ b/src/testRunner/vfsRef.ts @@ -1,2 +1,2 @@ // empty ref to vfs so it can be referenced by unittests -namespace vfs {} \ No newline at end of file +export { }; diff --git a/src/testRunner/vpathRef.ts b/src/testRunner/vpathRef.ts index 80291760bca1e..13cb846ee5ee8 100644 --- a/src/testRunner/vpathRef.ts +++ b/src/testRunner/vpathRef.ts @@ -1,2 +1,2 @@ // empty ref to vpath so it can be referenced by unittests -namespace vpath {} \ No newline at end of file +export { }; diff --git a/src/tsc/_namespaces/ts.ts b/src/tsc/_namespaces/ts.ts new file mode 100644 index 0000000000000..8579e4a93bbff --- /dev/null +++ b/src/tsc/_namespaces/ts.ts @@ -0,0 +1,5 @@ +/* Generated file to emulate the ts namespace. */ + +export * from "../../compiler/_namespaces/ts"; +export * from "../../executeCommandLine/_namespaces/ts"; +export * from "../tsc"; diff --git a/src/tsc/tsc.ts b/src/tsc/tsc.ts index e9d75cd529795..ce8b356b685d9 100644 --- a/src/tsc/tsc.ts +++ b/src/tsc/tsc.ts @@ -1,4 +1,5 @@ -namespace ts {} // empty ts module so the module migration script knows this file depends on the `ts` project namespace +import * as ts from "./_namespaces/ts"; + // This file actually uses arguments passed on commandline and executes it // enable deprecation logging diff --git a/src/tsc/tsconfig.json b/src/tsc/tsconfig.json index f04028e2dd8c5..205112c6f8c24 100644 --- a/src/tsc/tsconfig.json +++ b/src/tsc/tsconfig.json @@ -1,13 +1,14 @@ { "extends": "../tsconfig-noncomposite-base", "compilerOptions": { - "outFile": "../../built/local/tsc.js" + "outDir": "../../built/local" }, "files": [ - "tsc.ts" + "tsc.ts", + "_namespaces/ts.ts" ], "references": [ - { "path": "../compiler", "prepend": true }, - { "path": "../executeCommandLine", "prepend": true } + { "path": "../compiler" }, + { "path": "../executeCommandLine" } ] } diff --git a/src/tsc/tsconfig.release.json b/src/tsc/tsconfig.release.json index cab02625cfb2a..8ddc790faf07f 100644 --- a/src/tsc/tsconfig.release.json +++ b/src/tsc/tsconfig.release.json @@ -1,7 +1,7 @@ { "extends": "./tsconfig.json", "compilerOptions": { - "outFile": "../../built/local/tsc.release.js", + "outDir": "../../built/local/release", "stripInternal": true, "preserveConstEnums": false, "declaration": false, @@ -11,7 +11,7 @@ "incremental": true }, "references": [ - { "path": "../compiler/tsconfig.release.json", "prepend": true }, - { "path": "../executeCommandLine/tsconfig.release.json", "prepend": true } + { "path": "../compiler/tsconfig.release.json" }, + { "path": "../executeCommandLine/tsconfig.release.json" } ] } diff --git a/src/tsserver/_namespaces/ts.server.ts b/src/tsserver/_namespaces/ts.server.ts new file mode 100644 index 0000000000000..c7eb056ac077a --- /dev/null +++ b/src/tsserver/_namespaces/ts.server.ts @@ -0,0 +1,8 @@ +/* Generated file to emulate the ts.server namespace. */ + +export * from "../../jsTyping/_namespaces/ts.server"; +export * from "../../server/_namespaces/ts.server"; +export * from "../../webServer/_namespaces/ts.server"; +export * from "../nodeServer"; +export * from "../webServer"; +export * from "../server"; diff --git a/src/tsserver/_namespaces/ts.ts b/src/tsserver/_namespaces/ts.ts new file mode 100644 index 0000000000000..70c879deb484a --- /dev/null +++ b/src/tsserver/_namespaces/ts.ts @@ -0,0 +1,10 @@ +/* Generated file to emulate the ts namespace. */ + +export * from "../../compiler/_namespaces/ts"; +export * from "../../services/_namespaces/ts"; +export * from "../../jsTyping/_namespaces/ts"; +export * from "../../server/_namespaces/ts"; +export * from "../../webServer/_namespaces/ts"; +export * from "../../deprecatedCompat/_namespaces/ts"; +import * as server from "./ts.server"; +export { server }; diff --git a/src/tsserver/nodeServer.ts b/src/tsserver/nodeServer.ts index 2aeaa26603cd4..836bf782c9d17 100644 --- a/src/tsserver/nodeServer.ts +++ b/src/tsserver/nodeServer.ts @@ -1,5 +1,5 @@ -/*@internal*/ -namespace ts.server { +import * as ts from "./_namespaces/ts"; + interface LogOptions { file?: string; detailLevel?: ts.server.LogLevel; @@ -88,6 +88,7 @@ function parseServerMode(): ts.LanguageServiceMode | string | undefined { } } +/** @internal */ export function initializeNodeSystem(): ts.server.StartInput { const sys = ts.Debug.checkDefined(ts.sys) as ts.server.ServerHost; const childProcess: { @@ -855,4 +856,3 @@ function startNodeSession(options: ts.server.StartSessionOptions, logger: ts.ser return ts.combinePaths(ts.normalizeSlashes(homePath), cacheFolder); } } -} diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index 5f089ad2111fd..ca846dee92b79 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -1,5 +1,5 @@ -/*@internal*/ -namespace ts.server { +import * as ts from "./_namespaces/ts"; + declare const addEventListener: any; declare const removeEventListener: any; function findArgumentStringArray(argName: string): readonly string[] { @@ -10,6 +10,7 @@ function findArgumentStringArray(argName: string): readonly string[] { return arg.split(",").filter(name => name !== ""); } +/** @internal */ export function getLogLevel(level: string | undefined) { if (level) { const l = level.toLowerCase(); @@ -22,6 +23,7 @@ export function getLogLevel(level: string | undefined) { return undefined; } +/** @internal */ export interface StartInput { args: readonly string[]; logger: ts.server.Logger; @@ -88,4 +90,3 @@ else { }; addEventListener("message", listener); } -} diff --git a/src/tsserver/tsconfig.json b/src/tsserver/tsconfig.json index 6643ecf2f1b7a..3631224da5be6 100644 --- a/src/tsserver/tsconfig.json +++ b/src/tsserver/tsconfig.json @@ -2,7 +2,7 @@ "extends": "../tsconfig-noncomposite-base", "compilerOptions": { - "outFile": "../../built/local/tsserver.js", + "outDir": "../../built/local", "types": [ "node" ] @@ -10,14 +10,16 @@ "files": [ "nodeServer.ts", "webServer.ts", - "server.ts" + "server.ts", + "_namespaces/ts.server.ts", + "_namespaces/ts.ts" ], "references": [ - { "path": "../compiler", "prepend": true }, - { "path": "../services", "prepend": true }, - { "path": "../jsTyping", "prepend": true }, - { "path": "../server", "prepend": true }, - { "path": "../webServer", "prepend": true }, - { "path": "../deprecatedCompat", "prepend": true } + { "path": "../compiler" }, + { "path": "../services" }, + { "path": "../jsTyping" }, + { "path": "../server" }, + { "path": "../webServer" }, + { "path": "../deprecatedCompat" } ] } diff --git a/src/tsserver/webServer.ts b/src/tsserver/webServer.ts index d93214989e56f..82534d68df0ed 100644 --- a/src/tsserver/webServer.ts +++ b/src/tsserver/webServer.ts @@ -1,5 +1,5 @@ -/*@internal*/ -namespace ts.server { +import * as ts from "./_namespaces/ts"; + declare const addEventListener: any; declare const postMessage: any; declare const close: any; @@ -32,6 +32,7 @@ function parseServerMode(): ts.LanguageServiceMode | string | undefined { } } +/** @internal */ export function initializeWebSystem(args: string[]): ts.server.StartInput { createWebSystem(args); const modeOrUnknown = parseServerMode(); @@ -140,4 +141,3 @@ function startWebSession(options: ts.server.StartSessionOptions, logger: ts.serv // Start listening session.listen(); } -} diff --git a/src/tsserverlibrary/_namespaces/ts.server.ts b/src/tsserverlibrary/_namespaces/ts.server.ts new file mode 100644 index 0000000000000..fb916b71f4d9a --- /dev/null +++ b/src/tsserverlibrary/_namespaces/ts.server.ts @@ -0,0 +1,5 @@ +/* Generated file to emulate the ts.server namespace. */ + +export * from "../../jsTyping/_namespaces/ts.server"; +export * from "../../server/_namespaces/ts.server"; +export * from "../tsserverlibrary"; diff --git a/src/tsserverlibrary/_namespaces/ts.ts b/src/tsserverlibrary/_namespaces/ts.ts new file mode 100644 index 0000000000000..3c0e2227e9322 --- /dev/null +++ b/src/tsserverlibrary/_namespaces/ts.ts @@ -0,0 +1,9 @@ +/* Generated file to emulate the ts namespace. */ + +export * from "../../compiler/_namespaces/ts"; +export * from "../../jsTyping/_namespaces/ts"; +export * from "../../services/_namespaces/ts"; +export * from "../../server/_namespaces/ts"; +export * from "../../deprecatedCompat/_namespaces/ts"; +import * as server from "./ts.server"; +export { server }; diff --git a/src/tsserverlibrary/tsconfig.json b/src/tsserverlibrary/tsconfig.json index 0450e98a8a4e7..84e469faca605 100644 --- a/src/tsserverlibrary/tsconfig.json +++ b/src/tsserverlibrary/tsconfig.json @@ -1,16 +1,18 @@ { "extends": "../tsconfig-library-base", "compilerOptions": { - "outFile": "../../built/local/tsserverlibrary.out.js" + "outDir": "../../built/local" }, "files": [ - "tsserverlibrary.ts" + "tsserverlibrary.ts", + "_namespaces/ts.server.ts", + "_namespaces/ts.ts" ], "references": [ - { "path": "../compiler", "prepend": true }, - { "path": "../jsTyping", "prepend": true }, - { "path": "../services", "prepend": true }, - { "path": "../server", "prepend": true }, - { "path": "../deprecatedCompat", "prepend": true } + { "path": "../compiler" }, + { "path": "../jsTyping" }, + { "path": "../services" }, + { "path": "../server" }, + { "path": "../deprecatedCompat" } ] } diff --git a/src/tsserverlibrary/tsserverlibrary.ts b/src/tsserverlibrary/tsserverlibrary.ts index b472a38a3a73a..8aa07479d794a 100644 --- a/src/tsserverlibrary/tsserverlibrary.ts +++ b/src/tsserverlibrary/tsserverlibrary.ts @@ -1 +1 @@ -namespace ts.server {} // empty ts module so the module migration script knows this file depends on the `ts` project namespace +export { }; diff --git a/src/typescriptServices/_namespaces/ts.ts b/src/typescriptServices/_namespaces/ts.ts new file mode 100644 index 0000000000000..dc052101899b2 --- /dev/null +++ b/src/typescriptServices/_namespaces/ts.ts @@ -0,0 +1,7 @@ +/* Generated file to emulate the ts namespace. */ + +export * from "../../compiler/_namespaces/ts"; +export * from "../../jsTyping/_namespaces/ts"; +export * from "../../services/_namespaces/ts"; +export * from "../../deprecatedCompat/_namespaces/ts"; +export * from "../typescriptServices"; diff --git a/src/typescriptServices/tsconfig.json b/src/typescriptServices/tsconfig.json index e2ec0c2700988..277b98f727fbd 100644 --- a/src/typescriptServices/tsconfig.json +++ b/src/typescriptServices/tsconfig.json @@ -1,15 +1,16 @@ { "extends": "../tsconfig-library-base", "compilerOptions": { - "outFile": "../../built/local/typescriptServices.out.js" + "outDir": "../../built/local" }, "files": [ - "typescriptServices.ts" + "typescriptServices.ts", + "_namespaces/ts.ts" ], "references": [ - { "path": "../compiler", "prepend": true }, - { "path": "../jsTyping", "prepend": true }, - { "path": "../services", "prepend": true }, - { "path": "../deprecatedCompat", "prepend": true } + { "path": "../compiler" }, + { "path": "../jsTyping" }, + { "path": "../services" }, + { "path": "../deprecatedCompat" } ] } diff --git a/src/typescriptServices/typescriptServices.ts b/src/typescriptServices/typescriptServices.ts index 1d3f84bf035fa..053e804db5811 100644 --- a/src/typescriptServices/typescriptServices.ts +++ b/src/typescriptServices/typescriptServices.ts @@ -1,5 +1,5 @@ -/* @internal */ -namespace ts { +import * as ts from "./_namespaces/ts"; + // enable deprecation logging declare const console: any; if (typeof console !== "undefined") { @@ -14,4 +14,3 @@ if (typeof console !== "undefined") { } }; } -} diff --git a/src/typingsInstaller/_namespaces/ts.server.ts b/src/typingsInstaller/_namespaces/ts.server.ts new file mode 100644 index 0000000000000..97838f9d9818c --- /dev/null +++ b/src/typingsInstaller/_namespaces/ts.server.ts @@ -0,0 +1,6 @@ +/* Generated file to emulate the ts.server namespace. */ + +export * from "../../jsTyping/_namespaces/ts.server"; +export * from "../../typingsInstallerCore/_namespaces/ts.server"; +import * as typingsInstaller from "./ts.server.typingsInstaller"; +export { typingsInstaller }; diff --git a/src/typingsInstaller/_namespaces/ts.server.typingsInstaller.ts b/src/typingsInstaller/_namespaces/ts.server.typingsInstaller.ts new file mode 100644 index 0000000000000..595dd244d302e --- /dev/null +++ b/src/typingsInstaller/_namespaces/ts.server.typingsInstaller.ts @@ -0,0 +1,4 @@ +/* Generated file to emulate the ts.server.typingsInstaller namespace. */ + +export * from "../../typingsInstallerCore/_namespaces/ts.server.typingsInstaller"; +export * from "../nodeTypingsInstaller"; diff --git a/src/typingsInstaller/_namespaces/ts.ts b/src/typingsInstaller/_namespaces/ts.ts new file mode 100644 index 0000000000000..efb16fe7a138d --- /dev/null +++ b/src/typingsInstaller/_namespaces/ts.ts @@ -0,0 +1,7 @@ +/* Generated file to emulate the ts namespace. */ + +export * from "../../compiler/_namespaces/ts"; +export * from "../../jsTyping/_namespaces/ts"; +export * from "../../typingsInstallerCore/_namespaces/ts"; +import * as server from "./ts.server"; +export { server }; diff --git a/src/typingsInstaller/nodeTypingsInstaller.ts b/src/typingsInstaller/nodeTypingsInstaller.ts index df5a5f3a6bbbb..0e2b0002980a0 100644 --- a/src/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/typingsInstaller/nodeTypingsInstaller.ts @@ -1,4 +1,5 @@ -namespace ts.server.typingsInstaller { +import * as ts from "./_namespaces/ts"; + const fs: { appendFileSync(file: string, content: string): void } = require("fs"); @@ -252,4 +253,3 @@ function indent(newline: string, str: string | undefined): string { ? `${newline} ` + str.replace(/\r?\n/, `${newline} `) : ""; } -} diff --git a/src/typingsInstaller/tsconfig.json b/src/typingsInstaller/tsconfig.json index 143409e9e9a98..ce1cd04846b6b 100644 --- a/src/typingsInstaller/tsconfig.json +++ b/src/typingsInstaller/tsconfig.json @@ -2,7 +2,7 @@ "extends": "../tsconfig-noncomposite-base", "compilerOptions": { "removeComments": true, - "outFile": "../../built/local/typingsInstaller.js", + "outDir": "../../built/local", "types": [ "node" ], @@ -12,11 +12,14 @@ ] }, "references": [ - { "path": "../compiler", "prepend": true }, - { "path": "../jsTyping", "prepend": true }, - { "path": "../typingsInstallerCore", "prepend": true } + { "path": "../compiler" }, + { "path": "../jsTyping" }, + { "path": "../typingsInstallerCore" } ], "files": [ - "nodeTypingsInstaller.ts" + "nodeTypingsInstaller.ts", + "_namespaces/ts.server.typingsInstaller.ts", + "_namespaces/ts.ts", + "_namespaces/ts.server.ts" ] } diff --git a/src/typingsInstallerCore/_namespaces/ts.server.ts b/src/typingsInstallerCore/_namespaces/ts.server.ts new file mode 100644 index 0000000000000..252296d2335cf --- /dev/null +++ b/src/typingsInstallerCore/_namespaces/ts.server.ts @@ -0,0 +1,5 @@ +/* Generated file to emulate the ts.server namespace. */ + +export * from "../../jsTyping/_namespaces/ts.server"; +import * as typingsInstaller from "./ts.server.typingsInstaller"; +export { typingsInstaller }; diff --git a/src/typingsInstallerCore/_namespaces/ts.server.typingsInstaller.ts b/src/typingsInstallerCore/_namespaces/ts.server.typingsInstaller.ts new file mode 100644 index 0000000000000..2964824604001 --- /dev/null +++ b/src/typingsInstallerCore/_namespaces/ts.server.typingsInstaller.ts @@ -0,0 +1,3 @@ +/* Generated file to emulate the ts.server.typingsInstaller namespace. */ + +export * from "../typingsInstaller"; diff --git a/src/typingsInstallerCore/_namespaces/ts.ts b/src/typingsInstallerCore/_namespaces/ts.ts new file mode 100644 index 0000000000000..aa90e7daa8eae --- /dev/null +++ b/src/typingsInstallerCore/_namespaces/ts.ts @@ -0,0 +1,6 @@ +/* Generated file to emulate the ts namespace. */ + +export * from "../../compiler/_namespaces/ts"; +export * from "../../jsTyping/_namespaces/ts"; +import * as server from "./ts.server"; +export { server }; diff --git a/src/typingsInstallerCore/tsconfig.json b/src/typingsInstallerCore/tsconfig.json index 2cc0d52d8de47..f1001c80d4e0a 100644 --- a/src/typingsInstallerCore/tsconfig.json +++ b/src/typingsInstallerCore/tsconfig.json @@ -1,7 +1,7 @@ { "extends": "../tsconfig-base", "compilerOptions": { - "outFile": "../../built/local/typingsInstallerCore.js", + "outDir": "../../built/local", "types": [ "node" ], @@ -15,6 +15,9 @@ { "path": "../jsTyping" } ], "files": [ - "typingsInstaller.ts" + "typingsInstaller.ts", + "_namespaces/ts.server.typingsInstaller.ts", + "_namespaces/ts.ts", + "_namespaces/ts.server.ts" ] } diff --git a/src/typingsInstallerCore/typingsInstaller.ts b/src/typingsInstallerCore/typingsInstaller.ts index 814448df502a5..15a7cf54c2793 100644 --- a/src/typingsInstallerCore/typingsInstaller.ts +++ b/src/typingsInstallerCore/typingsInstaller.ts @@ -1,4 +1,5 @@ -namespace ts.server.typingsInstaller { +import * as ts from "./_namespaces/ts"; + interface NpmConfig { devDependencies: ts.MapLike; } @@ -543,4 +544,3 @@ export abstract class TypingsInstaller { export function typingsName(packageName: string): string { return `@types/${packageName}@ts${ts.versionMajorMinor}`; } -} diff --git a/src/watchGuard/tsconfig.json b/src/watchGuard/tsconfig.json index b169f00c95bc7..09507204745e1 100644 --- a/src/watchGuard/tsconfig.json +++ b/src/watchGuard/tsconfig.json @@ -3,7 +3,7 @@ "compilerOptions": { "removeComments": true, "incremental": false, - "outFile": "../../built/local/watchGuard.js", + "outDir": "../../built/local", "types": [ "node" ], diff --git a/src/webServer/_namespaces/ts.server.ts b/src/webServer/_namespaces/ts.server.ts new file mode 100644 index 0000000000000..d21d521a900f5 --- /dev/null +++ b/src/webServer/_namespaces/ts.server.ts @@ -0,0 +1,5 @@ +/* Generated file to emulate the ts.server namespace. */ + +export * from "../../jsTyping/_namespaces/ts.server"; +export * from "../../server/_namespaces/ts.server"; +export * from "../webServer"; diff --git a/src/webServer/_namespaces/ts.ts b/src/webServer/_namespaces/ts.ts new file mode 100644 index 0000000000000..3060a64378787 --- /dev/null +++ b/src/webServer/_namespaces/ts.ts @@ -0,0 +1,8 @@ +/* Generated file to emulate the ts namespace. */ + +export * from "../../compiler/_namespaces/ts"; +export * from "../../jsTyping/_namespaces/ts"; +export * from "../../services/_namespaces/ts"; +export * from "../../server/_namespaces/ts"; +import * as server from "./ts.server"; +export { server }; diff --git a/src/webServer/tsconfig.json b/src/webServer/tsconfig.json index 9d0e1297f583c..6adb45247201e 100644 --- a/src/webServer/tsconfig.json +++ b/src/webServer/tsconfig.json @@ -2,7 +2,7 @@ "extends": "../tsconfig-base", "compilerOptions": { "removeComments": false, - "outFile": "../../built/local/webServer.js", + "outDir": "../../built/local", "preserveConstEnums": true, "types": [ "node" @@ -16,5 +16,7 @@ ], "files": [ "webServer.ts", + "_namespaces/ts.server.ts", + "_namespaces/ts.ts" ] } diff --git a/src/webServer/webServer.ts b/src/webServer/webServer.ts index b8d84b5d38f06..2bbde964da560 100644 --- a/src/webServer/webServer.ts +++ b/src/webServer/webServer.ts @@ -1,17 +1,19 @@ -/*@internal*/ +import * as ts from "./_namespaces/ts"; -namespace ts.server { declare const fetch: any; declare const importScripts: any; +/** @internal */ export interface HostWithWriteMessage { writeMessage(s: any): void; } +/** @internal */ export interface WebHost extends HostWithWriteMessage { readFile(path: string): string | undefined; fileExists(path: string): boolean; } +/** @internal */ export class BaseLogger implements ts.server.Logger { private seq = 0; private inGroup = false; @@ -80,12 +82,15 @@ export class BaseLogger implements ts.server.Logger { } } +/** @internal */ export type MessageLogLevel = "info" | "perf" | "error"; +/** @internal */ export interface LoggingMessage { readonly type: "log"; readonly level: MessageLogLevel; readonly body: string } +/** @internal */ export class MainProcessLogger extends BaseLogger { constructor(level: ts.server.LogLevel, private host: HostWithWriteMessage) { super(level); @@ -124,6 +129,7 @@ if (typeof importScripts === "function") { } } +/** @internal */ export function createWebSystem(host: WebHost, args: string[], getExecutingFilePath: () => string): ts.server.ServerHost { const returnEmptyString = () => ""; const getExecutingDirectoryPath = ts.memoize(() => ts.memoize(() => ts.ensureTrailingDirectorySeparator(ts.getDirectoryPath(getExecutingFilePath())))); @@ -217,6 +223,7 @@ export function createWebSystem(host: WebHost, args: string[], getExecutingFileP }; } +/** @internal */ export interface StartSessionOptions { globalPlugins: ts.server.SessionOptions["globalPlugins"]; pluginProbeLocations: ts.server.SessionOptions["pluginProbeLocations"]; @@ -228,6 +235,7 @@ export interface StartSessionOptions { syntaxOnly: ts.server.SessionOptions["syntaxOnly"]; serverMode: ts.server.SessionOptions["serverMode"]; } +/** @internal */ export class WorkerSession extends ts.server.Session<{}> { constructor(host: ts.server.ServerHost, private webHost: HostWithWriteMessage, options: StartSessionOptions, logger: ts.server.Logger, cancellationToken: ts.server.ServerCancellationToken, hrtime: ts.server.SessionOptions["hrtime"]) { super({ @@ -263,4 +271,3 @@ export class WorkerSession extends ts.server.Session<{}> { return JSON.stringify(message, undefined, 2); } } -}