ts-morph
Version:
TypeScript compiler wrapper for static analysis and code manipulation.
1,168 lines (1,117 loc) • 509 kB
TypeScript
import { errors, StandardizedFilePath, ts } from "@ts-morph/common";
/** Holds the compiler options. */
export declare class CompilerOptionsContainer extends SettingsContainer<ts.CompilerOptions> {
constructor(defaultSettings?: ts.CompilerOptions);
/**
* Sets one or all of the compiler options.
*
* WARNING: Setting the compiler options will cause a complete reparse of all the source files.
* @param settings - Compiler options to set.
*/
set(settings: Partial<ts.CompilerOptions>): void;
/** Gets the encoding from the compiler options or returns utf-8. */
getEncoding(): string;
}
/** Represents a file system that can be interacted with. */
export interface FileSystemHost {
/** Gets if this file system is case sensitive. */
isCaseSensitive(): boolean;
/** Asynchronously deletes the specified file or directory. */
delete(path: string): Promise<void>;
/** Synchronously deletes the specified file or directory */
deleteSync(path: string): void;
/**
* Reads all the child directories and files.
* @remarks Implementers should have this return the full file path.
*/
readDirSync(dirPath: string): RuntimeDirEntry[];
/** Asynchronously reads a file at the specified path. */
readFile(filePath: string, encoding?: string): Promise<string>;
/** Synchronously reads a file at the specified path. */
readFileSync(filePath: string, encoding?: string): string;
/** Asynchronously writes a file to the file system. */
writeFile(filePath: string, fileText: string): Promise<void>;
/** Synchronously writes a file to the file system. */
writeFileSync(filePath: string, fileText: string): void;
/** Asynchronously creates a directory at the specified path. */
mkdir(dirPath: string): Promise<void>;
/** Synchronously creates a directory at the specified path. */
mkdirSync(dirPath: string): void;
/** Asynchronously moves a file or directory. */
move(srcPath: string, destPath: string): Promise<void>;
/** Synchronously moves a file or directory. */
moveSync(srcPath: string, destPath: string): void;
/** Asynchronously copies a file or directory. */
copy(srcPath: string, destPath: string): Promise<void>;
/** Synchronously copies a file or directory. */
copySync(srcPath: string, destPath: string): void;
/**
* Asynchronously checks if a file exists.
* @remarks Implementers should throw an `errors.FileNotFoundError` when it does not exist.
*/
fileExists(filePath: string): Promise<boolean>;
/**
* Synchronously checks if a file exists.
* @remarks Implementers should throw an `errors.FileNotFoundError` when it does not exist.
*/
fileExistsSync(filePath: string): boolean;
/** Asynchronously checks if a directory exists. */
directoryExists(dirPath: string): Promise<boolean>;
/** Synchronously checks if a directory exists. */
directoryExistsSync(dirPath: string): boolean;
/** See https://nodejs.org/api/fs.html#fs_fs_realpathsync_path_options */
realpathSync(path: string): string;
/** Gets the current directory of the environment. */
getCurrentDirectory(): string;
/** Uses pattern matching to find files or directories. */
glob(patterns: ReadonlyArray<string>): Promise<string[]>;
/** Synchronously uses pattern matching to find files or directories. */
globSync(patterns: ReadonlyArray<string>): string[];
}
/** An implementation of a file system that exists in memory only. */
export declare class InMemoryFileSystemHost implements FileSystemHost {
#private;
/** Constructor. */
constructor();
/** @inheritdoc */
isCaseSensitive(): boolean;
/** @inheritdoc */
delete(path: string): Promise<void>;
/** @inheritdoc */
deleteSync(path: string): void;
/** @inheritdoc */
readDirSync(dirPath: string): RuntimeDirEntry[];
/** @inheritdoc */
readFile(filePath: string, encoding?: string): Promise<string>;
/** @inheritdoc */
readFileSync(filePath: string, encoding?: string): string;
/** @inheritdoc */
writeFile(filePath: string, fileText: string): Promise<void>;
/** @inheritdoc */
writeFileSync(filePath: string, fileText: string): void;
/** @inheritdoc */
mkdir(dirPath: string): Promise<void>;
/** @inheritdoc */
mkdirSync(dirPath: string): void;
/** @inheritdoc */
move(srcPath: string, destPath: string): Promise<void>;
/** @inheritdoc */
moveSync(srcPath: string, destPath: string): void;
/** @inheritdoc */
copy(srcPath: string, destPath: string): Promise<void>;
/** @inheritdoc */
copySync(srcPath: string, destPath: string): void;
/** @inheritdoc */
fileExists(filePath: string): Promise<boolean>;
/** @inheritdoc */
fileExistsSync(filePath: string): boolean;
/** @inheritdoc */
directoryExists(dirPath: string): Promise<boolean>;
/** @inheritdoc */
directoryExistsSync(dirPath: string): boolean;
/** @inheritdoc */
realpathSync(path: string): string;
/** @inheritdoc */
getCurrentDirectory(): string;
/** @inheritdoc */
glob(patterns: ReadonlyArray<string>): Promise<string[]>;
/** @inheritdoc */
globSync(patterns: ReadonlyArray<string>): string[];
}
/** Host for implementing custom module and/or type reference directive resolution. */
export interface ResolutionHost {
resolveModuleNames?: ts.LanguageServiceHost["resolveModuleNames"];
getResolvedModuleWithFailedLookupLocationsFromCache?: ts.LanguageServiceHost["getResolvedModuleWithFailedLookupLocationsFromCache"];
resolveTypeReferenceDirectives?: ts.LanguageServiceHost["resolveTypeReferenceDirectives"];
}
/**
* Factory used to create a resolution host.
* @remarks The compiler options are retrieved via a function in order to get the project's current compiler options.
*/
export type ResolutionHostFactory = (moduleResolutionHost: ts.ModuleResolutionHost, getCompilerOptions: () => ts.CompilerOptions) => ResolutionHost;
/** Collection of reusable resolution hosts. */
export declare const ResolutionHosts: {
deno: ResolutionHostFactory;
};
export interface RuntimeDirEntry {
name: string;
isFile: boolean;
isDirectory: boolean;
isSymlink: boolean;
}
export declare abstract class SettingsContainer<T extends object> {
#private;
protected _settings: T;
/**
* Constructor.
* @param defaultSettings - The settings to use by default.
*/
constructor(defaultSettings: T);
/** Resets the settings to the default. */
reset(): void;
/** Gets a copy of the settings as an object. */
get(): T;
/**
* Sets one or all of the settings.
* @param settings - Settings to set.
*/
set(settings: Partial<T>): void;
/**
* Subscribe to modifications in the settings container.
* @param action - Action to execute when the settings change.
*/
onModified(action: () => void): void;
}
declare const ArgumentError: typeof errors.ArgumentError;
declare const ArgumentNullOrWhitespaceError: typeof errors.ArgumentNullOrWhitespaceError;
declare const ArgumentOutOfRangeError: typeof errors.ArgumentOutOfRangeError;
declare const ArgumentTypeError: typeof errors.ArgumentTypeError;
declare const BaseError: typeof errors.BaseError;
declare const DirectoryNotFoundError: typeof errors.DirectoryNotFoundError;
declare const FileNotFoundError: typeof errors.FileNotFoundError;
declare const InvalidOperationError: typeof errors.InvalidOperationError;
declare const NotImplementedError: typeof errors.NotImplementedError;
declare const NotSupportedError: typeof errors.NotSupportedError;
declare const PathNotFoundError: typeof errors.PathNotFoundError;
export declare class Directory {
#private;
private constructor();
/**
* Checks if this directory is an ancestor of the provided directory.
* @param possibleDescendant - Directory or source file that's a possible descendant.
*/
isAncestorOf(possibleDescendant: Directory | SourceFile): boolean;
/**
* Checks if this directory is a descendant of the provided directory.
* @param possibleAncestor - Directory or source file that's a possible ancestor.
*/
isDescendantOf(possibleAncestor: Directory): boolean;
/** Gets the path to the directory. */
getPath(): StandardizedFilePath;
/** Gets the directory path's base name. */
getBaseName(): string;
/** Gets the parent directory or throws if it doesn't exist or was never added to the project. */
getParentOrThrow(message?: string | (() => string)): Directory;
/** Gets the parent directory if it exists and was added to the project. */
getParent(): Directory | undefined;
/**
* Gets a child directory with the specified path or throws if not found.
* @param path - Relative path from this directory or absolute path.
*/
getDirectoryOrThrow(path: string): Directory;
/**
* Gets a child directory by the specified condition or throws if not found.
* @param condition - Condition to check the directory with.
*/
getDirectoryOrThrow(condition: (directory: Directory) => boolean): Directory;
/**
* Gets a directory with the specified path or undefined if not found.
* @param path - Relative path from this directory or absolute path.
*/
getDirectory(path: string): Directory | undefined;
/**
* Gets a child directory by the specified condition or undefined if not found.
* @param condition - Condition to check the directory with.
*/
getDirectory(condition: (directory: Directory) => boolean): Directory | undefined;
/**
* Gets a child source file with the specified path or throws if not found.
* @param path - Relative or absolute path to the file.
*/
getSourceFileOrThrow(path: string): SourceFile;
/**
* Gets a child source file by the specified condition or throws if not found.
* @param condition - Condition to check the source file with.
*/
getSourceFileOrThrow(condition: (sourceFile: SourceFile) => boolean): SourceFile;
/**
* Gets a child source file with the specified path or undefined if not found.
* @param path - Relative or absolute path to the file.
*/
getSourceFile(path: string): SourceFile | undefined;
/**
* Gets a child source file by the specified condition or undefined if not found.
* @param condition - Condition to check the source file with.
*/
getSourceFile(condition: (sourceFile: SourceFile) => boolean): SourceFile | undefined;
/** Gets the child directories. */
getDirectories(): Directory[];
/** Gets the source files within this directory. */
getSourceFiles(): SourceFile[];
/**
* Gets all the source files added to the project relative to the directory that match a pattern.
* @param globPattern - Glob pattern for filtering out the source files.
*/
getSourceFiles(globPattern: string): SourceFile[];
/**
* Gets all the source files added to the project relative to the directory that match the provided patterns.
* @param globPatterns - Glob patterns for filtering out the source files.
*/
getSourceFiles(globPatterns: ReadonlyArray<string>): SourceFile[];
/** Gets the source files in the current directory and all the descendant directories. */
getDescendantSourceFiles(): SourceFile[];
/** Gets the descendant directories. */
getDescendantDirectories(): Directory[];
/**
* Add source files based on file globs.
* @param fileGlobs - File glob or globs to add files based on.
* @returns The matched source files.
*/
addSourceFilesAtPaths(fileGlobs: string | ReadonlyArray<string>): SourceFile[];
/**
* Adds an existing directory from the relative path or directory name, or returns undefined if it doesn't exist.
*
* Will return the directory if it was already added.
* @param relativeOrAbsoluteDirPath - Directory name or path to the directory that should be added.
* @param options - Options.
*/
addDirectoryAtPathIfExists(relativeOrAbsoluteDirPath: string, options?: DirectoryAddOptions): Directory | undefined;
/**
* Adds an existing directory from the relative path or directory name, or throws if it doesn't exist.
*
* Will return the directory if it was already added.
* @param relativeOrAbsoluteDirPath - Directory name or path to the directory that should be added.
* @throws DirectoryNotFoundError if the directory does not exist.
*/
addDirectoryAtPath(relativeOrAbsoluteDirPath: string, options?: DirectoryAddOptions): Directory;
/**
* Creates a directory if it doesn't exist.
* @param relativeOrAbsoluteDirPath - Relative or absolute path to the directory that should be created.
*/
createDirectory(relativeOrAbsoluteDirPath: string): Directory;
/**
* Creates a source file, relative to this directory.
*
* Note: The file will not be created and saved to the file system until .save() is called on the source file.
* @param relativeFilePath - Relative file path of the source file to create.
* @param sourceFileText - Text, structure, or writer function to create the source file text with.
* @param options - Options.
* @throws - InvalidOperationError if a source file already exists at the provided file name.
*/
createSourceFile(relativeFilePath: string, sourceFileText?: string | OptionalKind<SourceFileStructure> | WriterFunction, options?: SourceFileCreateOptions): SourceFile;
/**
* Adds an existing source file, relative to this directory, or returns undefined.
*
* Will return the source file if it was already added.
* @param relativeFilePath - Relative file path to add.
*/
addSourceFileAtPathIfExists(relativeFilePath: string): SourceFile | undefined;
/**
* Adds an existing source file, relative to this directory, or throws if it doesn't exist.
*
* Will return the source file if it was already added.
* @param relativeFilePath - Relative file path to add.
* @throws FileNotFoundError when the file doesn't exist.
*/
addSourceFileAtPath(relativeFilePath: string): SourceFile;
/**
* Emits the files in the directory.
* @param options - Options for emitting.
*/
emit(options?: {
emitOnlyDtsFiles?: boolean;
outDir?: string;
declarationDir?: string;
}): Promise<DirectoryEmitResult>;
/**
* Emits the files in the directory synchronously.
*
* Remarks: This might be very slow compared to the asynchronous version if there are a lot of files.
* @param options - Options for emitting.
*/
emitSync(options?: {
emitOnlyDtsFiles?: boolean;
outDir?: string;
declarationDir?: string;
}): DirectoryEmitResult;
/**
* Copies the directory to a subdirectory of the specified directory.
* @param dirPathOrDirectory Directory path or directory object to copy the directory to.
* @param options Options for copying.
* @returns The new copied directory.
*/
copyToDirectory(dirPathOrDirectory: string | Directory, options?: DirectoryCopyOptions): Directory;
/**
* Copies the directory to a new directory.
* @param relativeOrAbsolutePath - The relative or absolute path to the new directory.
* @param options - Options.
* @returns The directory the copy was made to.
*/
copy(relativeOrAbsolutePath: string, options?: DirectoryCopyOptions): Directory;
/**
* Immediately copies the directory to the specified path asynchronously.
* @param relativeOrAbsolutePath - Directory path as an absolute or relative path.
* @param options - Options for moving the directory.
* @remarks If includeTrackedFiles is true, then it will execute the pending operations in the current directory.
*/
copyImmediately(relativeOrAbsolutePath: string, options?: DirectoryCopyOptions): Promise<Directory>;
/**
* Immediately copies the directory to the specified path synchronously.
* @param relativeOrAbsolutePath - Directory path as an absolute or relative path.
* @param options - Options for moving the directory.
* @remarks If includeTrackedFiles is true, then it will execute the pending operations in the current directory.
*/
copyImmediatelySync(relativeOrAbsolutePath: string, options?: DirectoryCopyOptions): Directory;
/**
* Moves the directory to a subdirectory of the specified directory.
* @param dirPathOrDirectory Directory path or directory object to move the directory to.
* @param options Options for moving.
*/
moveToDirectory(dirPathOrDirectory: string | Directory, options?: DirectoryMoveOptions): this;
/**
* Moves the directory to a new path.
* @param relativeOrAbsolutePath - Directory path as an absolute or relative path.
* @param options - Options for moving the directory.
*/
move(relativeOrAbsolutePath: string, options?: DirectoryMoveOptions): this;
/**
* Immediately moves the directory to a new path asynchronously.
* @param relativeOrAbsolutePath - Directory path as an absolute or relative path.
* @param options - Options for moving the directory.
*/
moveImmediately(relativeOrAbsolutePath: string, options?: DirectoryMoveOptions): Promise<this>;
/**
* Immediately moves the directory to a new path synchronously.
* @param relativeOrAbsolutePath - Directory path as an absolute or relative path.
* @param options - Options for moving the directory.
*/
moveImmediatelySync(relativeOrAbsolutePath: string, options?: DirectoryMoveOptions): this;
/**
* Recreates the directory.
* @remarks This will delete all the descendant source files and directories in memory and queue a delete & mkdir to the file system.
*/
clear(): void;
/**
* Asynchronously recreates the directory.
* @remarks This will delete all the descendant source files and directories in memory and push a delete & mkdir to the file system.
*/
clearImmediately(): Promise<void>;
/**
* Synchronously recreates the directory.
* @remarks This will delete all the descendant source files and directories in memory and push a delete & mkdir to the file system.
*/
clearImmediatelySync(): void;
/**
* Queues a deletion of the directory to the file system.
*
* The directory will be deleted when calling ast.save(). If you wish to delete the file immediately, then use deleteImmediately().
*/
delete(): void;
/** Asyncronously deletes the directory and all its descendants from the file system. */
deleteImmediately(): Promise<void>;
/** Synchronously deletes the directory and all its descendants from the file system. */
deleteImmediatelySync(): void;
/**
* Forgets the directory and all its descendants from the Project.
*
* Note: Does not delete the directory from the file system.
*/
forget(): void;
/** Asynchronously saves the directory and all the unsaved source files to the disk. */
save(): Promise<void>;
/** Synchronously saves the directory and all the unsaved source files to the disk. */
saveSync(): void;
/**
* Gets the relative path to the specified path.
* @param fileOrDirPath - The file or directory path.
*/
getRelativePathTo(fileOrDirPath: string): string;
/**
* Gets the relative path to another source file.
* @param sourceFile - Source file.
*/
getRelativePathTo(sourceFile: SourceFile): string;
/**
* Gets the relative path to another directory.
* @param directory - Directory.
*/
getRelativePathTo(directory: Directory): string;
/**
* Gets the relative path to the specified file path as a module specifier.
* @param filePath - File path.
* @remarks To get to a directory, provide `path/to/directory/index.ts`.
*/
getRelativePathAsModuleSpecifierTo(filePath: string): string;
/**
* Gets the relative path to the specified source file as a module specifier.
* @param sourceFile - Source file.
*/
getRelativePathAsModuleSpecifierTo(sourceFile: SourceFile): string;
/**
* Gets the relative path to the specified directory as a module specifier.
* @param directory - Directory.
*/
getRelativePathAsModuleSpecifierTo(directory: Directory): string;
/** Gets the project. */
getProject(): Project;
/** Gets if the directory was forgotten. */
wasForgotten(): boolean;
}
export interface DirectoryAddOptions {
/**
* Whether to also recursively add all the directory's descendant directories.
* @remarks Defaults to false.
*/
recursive?: boolean;
}
export interface DirectoryCopyOptions extends SourceFileCopyOptions {
/**
* Includes all the files in the directory and sub-directory when copying.
* @remarks - Defaults to true.
*/
includeUntrackedFiles?: boolean;
}
export declare class DirectoryEmitResult {
#private;
private constructor();
/** Gets a collections of skipped file paths. */
getSkippedFilePaths(): StandardizedFilePath[];
/** Gets the output file paths. */
getOutputFilePaths(): StandardizedFilePath[];
}
export interface DirectoryMoveOptions extends SourceFileMoveOptions {
}
/** Occurs when there is a problem doing a manipulation. */
export declare class ManipulationError extends errors.InvalidOperationError {
readonly filePath: string;
readonly oldText: string;
readonly newText: string;
constructor(filePath: string, oldText: string, newText: string, errorMessage: string);
}
/** Project that holds source files. */
export declare class Project {
#private;
/**
* Initializes a new instance.
* @param options - Optional options.
*/
constructor(options?: ProjectOptions);
/** Gets the manipulation settings. */
get manipulationSettings(): ManipulationSettingsContainer;
/** Gets the compiler options for modification. */
get compilerOptions(): CompilerOptionsContainer;
/**
* Adds the source files the project's source files depend on to the project.
* @returns The added source files.
* @remarks * This should be done after source files are added to the project, preferably once to
* avoid doing more work than necessary.
* * This is done by default when creating a Project and providing a tsconfig.json and
* not specifying to not add the source files.
*/
resolveSourceFileDependencies(): SourceFile[];
/**
* Adds an existing directory from the path or returns undefined if it doesn't exist.
*
* Will return the directory if it was already added.
* @param dirPath - Path to add the directory at.
* @param options - Options.
*/
addDirectoryAtPathIfExists(dirPath: string, options?: DirectoryAddOptions): Directory | undefined;
/**
* Adds an existing directory from the path or throws if it doesn't exist.
*
* Will return the directory if it was already added.
* @param dirPath - Path to add the directory at.
* @param options - Options.
* @throws DirectoryNotFoundError when the directory does not exist.
*/
addDirectoryAtPath(dirPath: string, options?: DirectoryAddOptions): Directory;
/**
* Creates a directory at the specified path.
* @param dirPath - Path to create the directory at.
*/
createDirectory(dirPath: string): Directory;
/**
* Gets a directory by the specified path or throws if it doesn't exist.
* @param dirPath - Path to create the directory at.
*/
getDirectoryOrThrow(dirPath: string, message?: string | (() => string)): Directory;
/**
* Gets a directory by the specified path or returns undefined if it doesn't exist.
* @param dirPath - Directory path.
*/
getDirectory(dirPath: string): Directory | undefined;
/** Gets all the directories. */
getDirectories(): Directory[];
/** Gets the directories without a parent. */
getRootDirectories(): Directory[];
/**
* Adds source files based on file globs.
* @param fileGlobs - File glob or globs to add files based on.
* @returns The matched source files.
*/
addSourceFilesAtPaths(fileGlobs: string | ReadonlyArray<string>): SourceFile[];
/**
* Adds a source file from a file path if it exists or returns undefined.
*
* Will return the source file if it was already added.
* @param filePath - File path to get the file from.
*/
addSourceFileAtPathIfExists(filePath: string): SourceFile | undefined;
/**
* Adds an existing source file from a file path or throws if it doesn't exist.
*
* Will return the source file if it was already added.
* @param filePath - File path to get the file from.
* @throws FileNotFoundError when the file is not found.
*/
addSourceFileAtPath(filePath: string): SourceFile;
/**
* Adds all the source files from the specified tsconfig.json.
*
* Note that this is done by default when specifying a tsconfig file in the constructor and not explicitly setting the
* `skipAddingFilesFromTsConfig` option to `true`.
* @param tsConfigFilePath - File path to the tsconfig.json file.
*/
addSourceFilesFromTsConfig(tsConfigFilePath: string): SourceFile[];
/**
* Creates a source file at the specified file path with the specified text.
*
* Note: The file will not be created and saved to the file system until .save() is called on the source file.
* @param filePath - File path of the source file.
* @param sourceFileText - Text, structure, or writer function for the source file text.
* @param options - Options.
* @throws - InvalidOperationError if a source file already exists at the provided file path.
*/
createSourceFile(filePath: string, sourceFileText?: string | OptionalKind<SourceFileStructure> | WriterFunction, options?: SourceFileCreateOptions): SourceFile;
/**
* Removes a source file from the project.
* @param sourceFile - Source file to remove.
* @returns True if removed.
*/
removeSourceFile(sourceFile: SourceFile): boolean;
/**
* Gets a source file by a file name or file path. Throws an error if it doesn't exist.
* @param fileNameOrPath - File name or path that the path could end with or equal.
*/
getSourceFileOrThrow(fileNameOrPath: string): SourceFile;
/**
* Gets a source file by a search function. Throws an error if it doesn't exist.
* @param searchFunction - Search function.
*/
getSourceFileOrThrow(searchFunction: (file: SourceFile) => boolean): SourceFile;
/**
* Gets a source file by a file name or file path. Returns undefined if none exists.
* @param fileNameOrPath - File name or path that the path could end with or equal.
*/
getSourceFile(fileNameOrPath: string): SourceFile | undefined;
/**
* Gets a source file by a search function. Returns undefined if none exists.
* @param searchFunction - Search function.
*/
getSourceFile(searchFunction: (file: SourceFile) => boolean): SourceFile | undefined;
/** Gets all the source files added to the project. */
getSourceFiles(): SourceFile[];
/**
* Gets all the source files added to the project that match a pattern.
* @param globPattern - Glob pattern for filtering out the source files.
*/
getSourceFiles(globPattern: string): SourceFile[];
/**
* Gets all the source files added to the project that match the passed in patterns.
* @param globPatterns - Glob patterns for filtering out the source files.
*/
getSourceFiles(globPatterns: ReadonlyArray<string>): SourceFile[];
/**
* Gets the specified ambient module symbol or returns undefined if not found.
* @param moduleName - The ambient module name with or without quotes.
*/
getAmbientModule(moduleName: string): Symbol | undefined;
/**
* Gets the specified ambient module symbol or throws if not found.
* @param moduleName - The ambient module name with or without quotes.
*/
getAmbientModuleOrThrow(moduleName: string, message?: string | (() => string)): Symbol;
/**
* Gets the ambient module symbols (ex. modules in the
* @types folder or node_modules).
*/
getAmbientModules(): Symbol[];
/** Saves all the unsaved source files to the file system and deletes all deleted files. */
save(): Promise<void>;
/**
* Synchronously saves all the unsaved source files to the file system and deletes all deleted files.
*
* Remarks: This might be very slow compared to the asynchronous version if there are a lot of files.
*/
saveSync(): void;
/**
* Enables logging to the console.
* @param enabled - Enabled.
*/
enableLogging(enabled?: boolean): void;
/** Gets the pre-emit diagnostics. */
getPreEmitDiagnostics(): Diagnostic[];
/** Gets the language service. */
getLanguageService(): LanguageService;
/** Gets the program. */
getProgram(): Program;
/** Gets the type checker. */
getTypeChecker(): TypeChecker;
/** Gets the file system. */
getFileSystem(): FileSystemHost;
/**
* Asynchronously emits all the source files to the file system as JavaScript files.
* @param emitOptions - Optional emit options.
*/
emit(emitOptions?: EmitOptions): Promise<EmitResult>;
/**
* Synchronously emits all the source files to the file system as JavaScript files.
* @param emitOptions - Optional emit options.
*/
emitSync(emitOptions?: EmitOptions): EmitResult;
/**
* Emits all the source files to memory.
* @param emitOptions - Optional emit options.
*/
emitToMemory(emitOptions?: EmitOptions): MemoryEmitResult;
/** Gets the compiler options. */
getCompilerOptions(): CompilerOptions;
/** Gets the diagnostics found when parsing the tsconfig.json file provided in the project's constructor. */
getConfigFileParsingDiagnostics(): Diagnostic[];
/**
* Creates a writer with the current manipulation settings.
* @remarks Generally it's best to use a provided writer, but this may be useful in some scenarios.
*/
createWriter(): CodeBlockWriter;
/**
* Forgets the nodes created in the scope of the passed in block.
*
* This is an advanced method that can be used to easily "forget" all the nodes created within the scope of the block.
* @param block - Block of code to run. Use the `remember` callback or return a node to remember it.
*/
forgetNodesCreatedInBlock<T = void>(block: (remember: (...node: Node[]) => void) => T): T;
/**
* Forgets the nodes created in the scope of the passed in block asynchronously.
*
* This is an advanced method that can be used to easily "forget" all the nodes created within the scope of the block.
* @param block - Block of code to run. Use the `remember` callback or return a node to remember it.
*/
forgetNodesCreatedInBlock<T = void>(block: (remember: (...node: Node[]) => void) => Promise<T>): Promise<T>;
/**
* Formats an array of diagnostics with their color and context into a string.
* @param diagnostics - Diagnostics to get a string of.
* @param options - Collection of options. For example, the new line character to use (defaults to the OS' new line character).
*/
formatDiagnosticsWithColorAndContext(diagnostics: ReadonlyArray<Diagnostic>, opts?: {
newLineChar?: "\n" | "\r\n";
}): string;
/** Gets a ts.ModuleResolutionHost for the project. */
getModuleResolutionHost(): ts.ModuleResolutionHost;
}
/** Options for creating a project. */
export interface ProjectOptions {
/** Compiler options */
compilerOptions?: CompilerOptions;
/** File path to the tsconfig.json file. */
tsConfigFilePath?: string;
/** Can be overriden by `tsConfigFilePath` or `compilerOptions`. */
defaultCompilerOptions?: CompilerOptions;
/**
* Whether to skip adding the source files from the specified tsconfig.json.
* @default false
*/
skipAddingFilesFromTsConfig?: boolean;
/**
* Skip resolving file dependencies when providing a ts config file path and adding the files from tsconfig.
* @default false
*/
skipFileDependencyResolution?: boolean;
/**
* Skip loading the lib files. Unlike the compiler API, ts-morph does not load these
* from the node_modules folder, but instead loads them from some other JS code
* and uses a fake path for their existence. If you want to use a custom lib files
* folder path, then provide one using the libFolderPath options.
* @default false
*/
skipLoadingLibFiles?: boolean;
/** The folder to use for loading lib files. */
libFolderPath?: string;
/** Manipulation settings */
manipulationSettings?: Partial<ManipulationSettings>;
/**
* Whether to use an in-memory file system.
* @default false
*/
useInMemoryFileSystem?: boolean;
/**
* Optional file system host. Useful for mocking access to the file system.
* @remarks Consider using `useInMemoryFileSystem` instead.
*/
fileSystem?: FileSystemHost;
/** Creates a resolution host for specifying custom module and/or type reference directive resolution. */
resolutionHost?: ResolutionHostFactory;
}
/** Options for creating a source file. */
export interface SourceFileCreateOptions {
/**
* Whether a source file should be overwritten if it exists. Defaults to false.
* @remarks When false, the method will throw when a file exists.
*/
overwrite?: boolean;
/** Specifies the script kind of the source file. */
scriptKind?: ScriptKind;
}
export type Constructor<T> = new (...args: any[]) => T;
export type InstanceOf<T> = T extends new (...args: any[]) => infer U ? U : never;
export type WriterFunction = (writer: CodeBlockWriter) => void;
/**
* Creates a wrapped node from a compiler node.
* @param node - Node to create a wrapped node from.
* @param info - Info for creating the wrapped node.
*/
export declare function createWrappedNode<T extends ts.Node = ts.Node>(node: T, opts?: CreateWrappedNodeOptions): CompilerNodeToWrappedType<T>;
export interface CreateWrappedNodeOptions {
/** Compiler options. */
compilerOptions?: CompilerOptions;
/** Optional source file of the node. Will make it not bother going up the tree to find the source file. */
sourceFile?: ts.SourceFile;
/** Type checker. */
typeChecker?: ts.TypeChecker;
}
/**
* Prints the provided node using the compiler's printer.
* @param node - Compiler node.
* @param options - Options.
* @remarks If the node was not constructed with the compiler API factory methods and the node
* does not have parents set, then use the other overload that accepts a source file.
*/
export declare function printNode(node: ts.Node, options?: PrintNodeOptions): string;
/**
* Prints the provided node using the compiler's printer.
* @param node - Compiler node.
* @param sourceFile - Compiler source file.
* @param options - Options.
*/
export declare function printNode(node: ts.Node, sourceFile: ts.SourceFile, options?: PrintNodeOptions): string;
/** Options for printing a node. */
export interface PrintNodeOptions {
/** Whether to remove comments or not. */
removeComments?: boolean;
/**
* New line kind.
*
* Defaults to line feed.
*/
newLineKind?: NewLineKind;
/**
* From the compiler api: "A value indicating the purpose of a node. This is primarily used to
* distinguish between an `Identifier` used in an expression position, versus an
* `Identifier` used as an `IdentifierName` as part of a declaration. For most nodes you
* should just pass `Unspecified`."
*
* Defaults to `Unspecified`.
*/
emitHint?: EmitHint;
/**
* The script kind.
*
* @remarks This is only useful when passing in a compiler node that was constructed
* with the compiler API factory methods.
*
* Defaults to TSX.
*/
scriptKind?: ScriptKind;
}
export type SourceFileReferencingNodes = ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration | CallExpression;
export interface CompilerOptionsFromTsConfigOptions {
encoding?: string;
fileSystem?: FileSystemHost;
}
export interface CompilerOptionsFromTsConfigResult {
options: CompilerOptions;
errors: Diagnostic[];
}
/**
* Gets the compiler options from a specified tsconfig.json
* @param filePath - File path to the tsconfig.json.
* @param options - Options.
*/
export declare function getCompilerOptionsFromTsConfig(filePath: string, options?: CompilerOptionsFromTsConfigOptions): CompilerOptionsFromTsConfigResult;
/** Functions for writing code. */
export declare class Writers {
private constructor();
/**
* Gets a writer function for writing the provided object as an object literal expression.
* @param obj - Object to write.
*/
static object(obj: {
[key: string]: WriterFunctionOrValue | undefined;
}): WriterFunction;
/** Gets a writer function for writing an object type. */
static objectType(structure: TypeElementMemberedNodeStructure): WriterFunction;
/** Gets a writer function for writing a union type (ex. `FirstType | SecondType`). */
static unionType(firstType: WriterFunctionOrValue, secondType: WriterFunctionOrValue, ...additionalTypes: WriterFunctionOrValue[]): (writer: CodeBlockWriter) => void;
/** Gets a writer function for writing an intersection type (ex. `FirstType & SecondType`). */
static intersectionType(firstType: WriterFunctionOrValue, secondType: WriterFunctionOrValue, ...additionalTypes: WriterFunctionOrValue[]): (writer: CodeBlockWriter) => void;
/** Gets a writer function for writing a type assertion (ex. `type as assertionType`). */
static assertion(type: WriterFunctionOrValue, assertionType: WriterFunctionOrValue): (writer: CodeBlockWriter) => void;
/**
* Gets a writer function for writing a return statement returning the provided value (ex. `return value;`).
* @param value - Value to be returned.
*/
static returnStatement(value: WriterFunctionOrValue): WriterFunction;
}
export type WriterFunctionOrValue = string | number | WriterFunction;
export type AssertionKey = Identifier | StringLiteral;
export type PropertyName = Identifier | StringLiteral | NumericLiteral | ComputedPropertyName | PrivateIdentifier | NoSubstitutionTemplateLiteral | BigIntLiteral;
export type ModuleName = Identifier | StringLiteral;
export type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration;
export type ArrayBindingElement = BindingElement | OmittedExpression;
export type BindingName = Identifier | BindingPattern;
export type BindingPattern = ObjectBindingPattern | ArrayBindingPattern;
export type BooleanLiteral = TrueLiteral | FalseLiteral;
export type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator | JsxCallLike | InstanceofExpression;
export type EntityNameExpression = Identifier | PropertyAccessExpression;
export type DeclarationName = PropertyName | JsxAttributeName | StringLiteralLike | ElementAccessExpression | BindingPattern | EntityNameExpression;
export type EntityName = Identifier | QualifiedName;
export type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement | JsxFragment;
export type JsxAttributeName = Identifier | JsxNamespacedName;
export type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute;
export type JsxCallLike = JsxOpeningLikeElement | JsxOpeningFragment;
export type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement;
export type JsxTagNameExpression = Identifier | ThisExpression | JsxTagNamePropertyAccess | JsxNamespacedName;
export interface JsxTagNamePropertyAccess extends PropertyAccessExpression {
getExpression(): Identifier | ThisExpression | JsxTagNamePropertyAccess;
}
export type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | MethodDeclaration | AccessorDeclaration;
export type CaseOrDefaultClause = CaseClause | DefaultClause;
export type ModuleReference = EntityName | ExternalModuleReference;
export type StringLiteralLike = StringLiteral | NoSubstitutionTemplateLiteral;
export type TypeElementTypes = PropertySignature | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration | IndexSignatureDeclaration | GetAccessorDeclaration | SetAccessorDeclaration;
export type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral;
/**
* Local target declarations.
* @remarks This may be missing some types. Please open an issue if this returns a type not listed here.
*/
export type LocalTargetDeclarations = SourceFile | ClassDeclaration | InterfaceDeclaration | EnumDeclaration | FunctionDeclaration | VariableDeclaration | TypeAliasDeclaration | ModuleDeclaration | ExportAssignment;
/**
* Declarations that can be exported from a module.
* @remarks This may be missing some types. Please open an issue if this returns a type not listed here.
*/
export type ExportedDeclarations = ClassDeclaration | InterfaceDeclaration | EnumDeclaration | FunctionDeclaration | VariableDeclaration | TypeAliasDeclaration | ModuleDeclaration | Expression | SourceFile;
export declare function AmbientableNode<T extends Constructor<AmbientableNodeExtensionType>>(Base: T): Constructor<AmbientableNode> & T;
export interface AmbientableNode {
/** If the node has the declare keyword. */
hasDeclareKeyword(): boolean;
/** Gets the declare keyword or undefined if none exists. */
getDeclareKeyword(): Node | undefined;
/** Gets the declare keyword or throws if it doesn't exist. */
getDeclareKeywordOrThrow(message?: string | (() => string)): Node;
/** Gets if the node is ambient. */
isAmbient(): boolean;
/**
* Sets if this node has a declare keyword.
* @param value - To add the declare keyword or not.
*/
setHasDeclareKeyword(value?: boolean): this;
}
type AmbientableNodeExtensionType = Node & ModifierableNode;
export declare function ArgumentedNode<T extends Constructor<ArgumentedNodeExtensionType>>(Base: T): Constructor<ArgumentedNode> & T;
export interface ArgumentedNode {
/** Gets all the arguments of the node. */
getArguments(): Node[];
/**
* Adds an argument.
* @param argumentText - Argument text to add.
*/
addArgument(argumentText: string | WriterFunction): Node;
/**
* Adds arguments.
* @param argumentTexts - Argument texts to add.
*/
addArguments(argumentTexts: ReadonlyArray<string | WriterFunction> | WriterFunction): Node[];
/**
* Inserts an argument.
* @param index - Child index to insert at.
* @param argumentText - Argument text to insert.
*/
insertArgument(index: number, argumentText: string | WriterFunction): Node;
/**
* Inserts arguments.
* @param index - Child index to insert at.
* @param argumentTexts - Argument texts to insert.
*/
insertArguments(index: number, argumentTexts: ReadonlyArray<string | WriterFunction> | WriterFunction): Node[];
/**
* Removes an argument.
* @param arg - Argument to remove.
*/
removeArgument(arg: Node): this;
/**
* Removes an argument.
* @param index - Index to remove.
*/
removeArgument(index: number): this;
}
type ArgumentedNodeExtensionType = Node<ts.Node & {
arguments?: ts.NodeArray<ts.Node>;
}>;
export declare function AsyncableNode<T extends Constructor<AsyncableNodeExtensionType>>(Base: T): Constructor<AsyncableNode> & T;
export interface AsyncableNode {
/** If it's async. */
isAsync(): boolean;
/** Gets the async keyword or undefined if none exists. */
getAsyncKeyword(): Node<ts.AsyncKeyword> | undefined;
/** Gets the async keyword or throws if none exists. */
getAsyncKeywordOrThrow(message?: string | (() => string)): Node<ts.AsyncKeyword>;
/**
* Sets if the node is async.
* @param value - If it should be async or not.
*/
setIsAsync(value: boolean): this;
}
type AsyncableNodeExtensionType = Node & ModifierableNode;
export declare function AwaitableNode<T extends Constructor<AwaitableNodeExtensionType>>(Base: T): Constructor<AwaitableNode> & T;
export interface AwaitableNode {
/** If it's an awaited node. */
isAwaited(): boolean;
/** Gets the await token or undefined if none exists. */
getAwaitKeyword(): Node<ts.AwaitKeyword> | undefined;
/** Gets the await token or throws if none exists. */
getAwaitKeywordOrThrow(message?: string | (() => string)): Node<ts.AwaitKeyword>;
/**
* Sets if the node is awaited.
* @param value - If it should be awaited or not.
*/
setIsAwaited(value: boolean): this;
}
type AwaitableNodeExtensionType = Node<ts.Node & {
awaitModifier?: ts.AwaitKeyword;
}>;
export declare function BodiedNode<T extends Constructor<BodiedNodeExtensionType>>(Base: T): Constructor<BodiedNode> & T;
export interface BodiedNode {
/** Gets the body. */
getBody(): Node;
/**
* Sets the body text.
* @param textOrWriterFunction - Text or writer function to set as the body.
*/
setBodyText(textOrWriterFunction: string | WriterFunction): this;
/** Gets the body text without leading whitespace, leading indentation, or trailing whitespace. */
getBodyText(): string;
}
type BodiedNodeExtensionType = Node<ts.Node & {
body: ts.Node;
}>;
export declare function BodyableNode<T extends Constructor<BodyableNodeExtensionType>>(Base: T): Constructor<BodyableNode> & T;
export interface BodyableNode {
/** Gets the body or throws an error if it doesn't exist. */
getBodyOrThrow(message?: string | (() => string)): Node;
/** Gets the body if it exists. */
getBody(): Node | undefined;
/** Gets the body text without leading whitespace, leading indentation, or trailing whitespace. Returns undefined if there is no body. */
getBodyText(): string | undefined;
/** Gets if the node has a body. */
hasBody(): boolean;
/**
* Sets the body text. A body is required to do this operation.
* @param textOrWriterFunction - Text or writer function to set as the body.
*/
setBodyText(textOrWriterFunction: string | WriterFunction): this;
/** Adds a body if it doesn't exists. */
addBody(): this;
/** Removes the body if it exists. */
removeBody(): this;
}
type BodyableNodeExtensionType = Node<ts.Node & {
body?: ts.Node;
}>;
export declare function ChildOrderableNode<T extends Constructor<ChildOrderableNodeExtensionType>>(Base: T): Constructor<ChildOrderableNode> & T;
export interface ChildOrderableNode {
/** Sets the child order of the node within the parent. */
setOrder(order: number): this;
}
type ChildOrderableNodeExtensionType = Node;
export declare function DecoratableNode<T extends Constructor<DecoratableNodeExtensionType>>(Base: T): Constructor<DecoratableNode> & T;
export interface DecoratableNode {
/**
* Gets a decorator or undefined if it doesn't exist.
* @param name - Name of the parameter.
*/
getDecorator(name: string): Decorator | undefined;
/**
* Gets a decorator or undefined if it doesn't exist.
* @param findFunction - Function to use to find the parameter.
*/
getDecorator(findFunction: (declaration: Decorator) => boolean): Decorator | undefined;
/**
* Gets a decorator or throws if it doesn't exist.
* @param name - Name of the parameter.
*/
getDecoratorOrThrow(name: string): Decorator;
/**
* Gets a decorator or throws if it doesn't exist.
* @param findFunction - Function to use to find the parameter.
*/
getDecoratorOrThrow(findFunction: (declaration: Decorator) => boolean): Decorator;
/** Gets all the decorators of the node. */
getDecorators(): Decorator[];
/**
* Adds a decorator.
* @param structure - Structure of the decorator.
*/
addDecorator(structure: OptionalKind<DecoratorStructure>): Decorator;
/**
* Adds decorators.
* @param structures - Structures of the decorators.
*/
addDecorators(structures: ReadonlyArray<OptionalKind<DecoratorStructure>>): Decorator[];
/**
* Inserts a decorator.
* @param index - Child index to insert at. Specify a negative index to insert from the reverse.
* @param structure - Structure of the decorator.
*/
insertDecorator(index: number, structure: OptionalKind<DecoratorStructure>): Decorator;
/**
* Insert decorators.
* @param index - Child index to insert at.
* @param structures - Structures to insert.
*/
insertDecorators(index: number, structures: ReadonlyArray<OptionalKind<DecoratorStructure>>): Decorator[];
}
type DecoratableNodeExtensionType = Node<ts.Node> & ModifierableNode;
export declare function DotDotDotTokenableNode<T extends Constructor<DotDotDotTokenableNodeExtensionType>>(Base: T): Constructor<DotDotDotTokenableNode> & T;
export interface DotDotDotTokenableNode {
/** Gets the dot dot dot token (...) if it exists or returns undefined */
getDotDotDotToken(): Node<ts.DotDotDotToken> | undefined;
/** Gets the dot dot dot token (...) if it exists or throws if not. */
getDotDotDotTokenOrThrow(message?: string | (() => string)): Node<ts.DotDotDotToken>;
}
type DotDotDotTokenableNodeExtensionType = Node<ts.Node & {
dotDotDotToken?: ts.DotDotDotToken;
}>;
export declare function ExclamationTokenableNode<T extends Constructor<ExclamationTokenableNodeExtensionType>>(Base: T): Constructor<ExclamationTokenableNode> & T;
export interface ExclamationTokenableNode {
/** If it has a exclamation token. */
hasExclamationToken(): boolean;
/** Gets the exclamation token node or returns undefined if it doesn't exist. */
getExclamationTokenNode(): Node<ts.ExclamationToken> | undefined;
/** Gets the exclamation token node or throws. */
getExclamationTokenNodeOrThrow(message?: string | (() => string)): Node<ts.ExclamationToken>;
/**
* Sets if this node has a exclamation token.
* @param value - If it should have a exclamation token or not.
*/
setHasExclamationToken(value: boolean): this;
}
type ExclamationTokenableNodeExtensionType = Node<ts.Node & {
exclamationToken?: ts.ExclamationToken;
}>;
export declare function ExportableNode<T extends Constructor<ExportableNodeExtensionType>>(Base: T): Constructor<ExportableNode> & T;
export interface ExportableNode extends ExportGetableNode {
/**
* Sets if this node is a default export of a file.
* @param value - If it should be a default export or not.
*/
setIsDefaultExport(value: boolean): this;
/**
* Sets if the node is exported.
*
* Note: Will remove the default keyword if set.
* @param value - If it should be exported or not.
*/
setIsExported(value: boolean): this;
}
type ExportableNodeExtensionType = Node & ModifierableNode;
export declare function ExportGetableNode<T extends Constructor<ExportGetableNodeExtensionType>>(Base: T): Constructor<ExportGeta