-
Notifications
You must be signed in to change notification settings - Fork 1
server API
Creates a new instance of TypeScript Server.
Returns Object An object containing methods to interact with TypeScript Server.
Initializes the TypeScript Server instance.
This function starts a new process for the TypeScript Server using Node's child_process.spawn.
It sets up listeners for the 'stdout' and 'stderr' streams of the TypeScript Server process,
handling incoming data and errors respectively. It also handles the 'close' event of the process.
The function configures a timeout to reject the promise if the server does not start within a specified time.
-
nodestring The path to the Node.js executable. If not provided, defaults to 'node'. (optional, default"") -
tsServerstring The path to the TypeScript Server executable. If not provided, defaults to the 'tsserver' path in the 'node_modules' directory. (optional, default"")
Returns Promise<void> A promise that resolves when the TypeScript Server is ready, or rejects if there is an error or timeout.
Handles incoming data from the TypeScript Server.
-
rawDatastring Raw data received from tsserver.
Processes a complete message from tsserver.
-
messagestring A complete message in JSON format.
Checks if the buffer has a complete message based on Content-Length.
Returns boolean True if a complete message is present in the buffer.
Sends a command to the TypeScript Server. Special handling for 'open' command as it does not receive a response.
-
commandObject The command object to send. -
timeoutnumber The timeout in milliseconds for the command. (optional, default5000)
Returns Promise<Object> A promise that resolves with the response from tsserver.
Sends an 'open file' command to the TypeScript Server.
-
filePathstring The path to the TypeScript file to open. -
timeoutnumber The timeout in milliseconds for the command. (optional, default5000)
Returns Promise<Object> A promise that resolves with the response from tsserver.
Sends a 'change' command to the TypeScript Server.
-
filePathstring The path to the file. -
startObject The start position of the change (line and offset). -
endObject The end position of the change (line and offset). -
newTextstring The new text to replace in the range.
Sends a 'close' command to the TypeScript Server.
-
filePathstring The path to the file being closed.
Sends a 'definition' request to the TypeScript Server.
-
filePathstring The path to the file. -
linenumber The line number of the position. -
offsetnumber The offset in the line of the position.
Returns Promise<Object> A promise that resolves with the response from tsserver.
Sends a 'quickinfo' request to the TypeScript Server.
-
filePathstring The path to the file. -
linenumber The line number of the position. -
offsetnumber The offset in the line of the position.
Returns Promise<Object> A promise that resolves with the response from tsserver.
Sends a 'references' request to the TypeScript Server.
-
filePathstring The path to the file. -
linenumber The line number of the position. -
offsetnumber The offset in the line of the position.
Returns Promise<Object> A promise that resolves with the response from tsserver.
Sends a 'FindSourceDefinition' request to the TypeScript Server.
-
filePathstring The path to the file. -
linenumber The line number of the position. -
offsetnumber The offset in the line of the position.
Returns Promise<Object> A promise that resolves with the response from tsserver.
Sends a 'completionInfo' command to the TypeScript Server.
-
filePathstring The path to the file. -
linenumber The line number of the position. -
offsetnumber The offset in the line of the position.
Returns Promise<Object> A promise that resolves with the response from tsserver.
Sends a 'completionEntryDetails' request to the TypeScript Server.
-
filePathstring The path to the file. -
linenumber The line number of the position. -
offsetnumber The offset in the line of the position. -
entryNamestring The name of the completion entry.
Returns Promise<Object> A promise that resolves with the response from tsserver.
Sends a 'compileOnSaveAffectedFileList' request to the TypeScript Server.
-
filePathstring The path to the file.
Returns Promise<Object> A promise that resolves with the response from tsserver.
Sends a 'compileOnSaveEmitFile' command to the TypeScript Server.
-
filePathstring The path to the TypeScript file. -
forcedboolean Force emit even if there are errors. (optional, defaultfalse) -
includeLinePositionboolean Include line position in the response. (optional, defaultfalse) -
richResponseboolean If true, returns response as an object with detailed emit results. (optional, defaultfalse)
Returns Promise<(boolean | EmitResult)> A promise that resolves with a boolean indicating success
or an EmitResult object containing detailed information about the emit process.
- If a boolean: true if the emit was successful, false otherwise.
- If an EmitResult object:
- emitSkipped: A boolean indicating whether the emit was skipped.
- diagnostics: An array of Diagnostic or DiagnosticWithLinePosition objects, providing
detailed information about each diagnostic message.
- Diagnostic: An object representing a diagnostic message, typically containing:
- start: The starting position of the diagnostic message.
- length: The length of the diagnostic message.
- text: The text of the diagnostic message.
- DiagnosticWithLinePosition: An extended version of Diagnostic, including line and
character position information:
- start: The starting position of the diagnostic message (line and character).
- end: The ending position of the diagnostic message (line and character).
- text: The text of the diagnostic message.
Sends a 'definitionAndBoundSpan' request to the TypeScript Server.
-
filePathstring The path to the file. -
linenumber The line number of the position. -
offsetnumber The offset in the line of the position.
Returns Promise<Object> A promise that resolves with the response from tsserver.
Sends an 'implementation' request to the TypeScript Server.
-
filePathstring The path to the file. -
linenumber The line number of the position. -
offsetnumber The offset in the line of the position.
Returns Promise<Object> A promise that resolves with the response from tsserver.
Sends a 'format' request to the TypeScript Server.
-
filePathstring The path to the file. -
startLinenumber The starting line number of the format range. -
startOffsetnumber The starting offset in the start line. -
endLinenumber The ending line number of the format range. -
endOffsetnumber The ending offset in the end line. -
formatOptionsobject? Optional formatting options. (optional, default{})
Returns Promise<Object> A promise that resolves with the response from tsserver.
Sends an 'exit' command to the TypeScript Server to gracefully shut it down.
Sends a 'formatonkey' request to the TypeScript Server. This command is used for formatting code at a specific position in a file, typically in response to a keystroke. It's commonly used for auto-formatting a line of code when a specific key (like a closing brace or semi-colon) is pressed.
-
filePathstring The path to the TypeScript file. The path should be absolute or relative to the TypeScript server's current working directory. -
linenumber The 1-based line number in the file where the key was pressed. This and the offset together point to the specific position in the file. -
offsetnumber The 1-based character offset in the line where the key was pressed. This is typically the position right after where the key was pressed. -
keystring The character corresponding to the key pressed. This is typically a single character like ';' or '}' that triggers the formatting action. -
formatOptionsobject? Optional formatting options to customize the formatting behavior. These options might include settings like tab size, indent size, whether to insert spaces, and so on. Example: { tabSize: 4, indentSize: 4, insertSpace: true } (optional, default{})
Returns Promise<Object> A promise that resolves with the response from tsserver. The response typically includes an array of code edits that should be applied to the file to achieve the desired formatting. Each edit suggests changes like text insertions, deletions, or replacements.
Sends a 'geterr' request to the TypeScript Server. This command instructs the server to compute and return errors (diagnostics) for the specified files. The diagnostics are not returned directly by this function but are instead sent back by the server as separate events or messages. This function is useful for asynchronously obtaining diagnostic information like errors and warnings from the server.
-
filePathsArray<string> An array of paths to the files for which to get errors. Each path should be either absolute or relative to the TypeScript server's current working directory. -
delaynumber The delay in milliseconds to wait before the server processes the request. This delay can be used to batch or throttle error requests, especially when dealing with a large number of file changes or edits.
Returns Promise<void> A promise that resolves when the command has been sent to the server. The resolution of this promise indicates that the request was successfully dispatched, but it does not imply that the errors have been received. The actual errors (diagnostics) will be sent back by the server asynchronously as separate events or messages, which should be handled separately in the client's message handling logic.Example usage: getErrors(['path/to/file1.ts', 'path/to/file2.ts'], 500).then(() => { console.log('Error request sent. Waiting for diagnostics...'); });Note: The client should implement additional logic to listen for and handle the diagnostic events or messages sent by the server in response to this request.
Sends a 'geterrForProject' request to the TypeScript Server. This command instructs the server to compute and return errors (diagnostics) for all files in a specific project. The diagnostics are not returned directly by this function but are instead sent back by the server as separate events or messages. This function is useful for asynchronously obtaining a comprehensive diagnostic overview of an entire project.
-
filePathstring The path to any file within the project. The server uses this file to identify the project context. The path should be absolute or relative to the TypeScript server's current working directory. -
delaynumber The delay in milliseconds before the server processes the request. This delay can be used to batch or throttle diagnostic requests, especially useful when dealing with large projects or numerous file changes.
Returns Promise<void> A promise that resolves when the command has been sent to the server. The resolution of this promise indicates that the request was successfully dispatched, but it does not imply that the errors have been received. The actual errors (diagnostics) for the entire project will be sent back by the server asynchronously as separate events or messages, which should be handled separately in the client's message handling logic.Example usage: getErrorsForProject('path/to/anyFileInProject.ts', 500).then(() => { console.log('Project error request sent. Waiting for diagnostics...'); });Note: The client should implement additional logic to listen for and handle the diagnostic events or messages sent by the server in response to this request. These diagnostics will cover the entire scope of the project associated with the provided file path.
Sends a 'semanticDiagnosticsSync' request to the TypeScript Server. This command is used to synchronously request semantic diagnostics (such as type errors) for a specific file. It's useful when immediate and up-to-date semantic error information is needed for a file, such as during file saves or build operations.
-
filePathstring The path to the TypeScript file for which semantic diagnostics are requested. The path should be absolute or relative to the TypeScript server's current working directory. -
includeLinePositionboolean If set to true, the response will include detailed line and character position information for each diagnostic. This is useful for integrations that require precise location data, such as IDEs or advanced text editors. (optional, defaultfalse)
Returns Promise<Object> A promise that resolves with the semantic diagnostics response from tsserver.
The response includes an array of diagnostic objects, each representing a
semantic error or warning found in the file. Each diagnostic object typically
contains the following information:
- start: The starting position of the error (line and character).
- length: The length of the error in characters.
- text: The error message text.
- category: The error category ('error', 'warning', or 'suggestion').
- code: The error code (useful for further reference or lookups).
If includeLinePosition is true, additional line and character position
information will be included in each diagnostic.Example usage: getSemanticDiagnosticsSync('path/to/file.ts', true).then(response => {
console.log('Semantic diagnostics with line positions:', response);
}).catch(error => {
console.error('Error getting semantic diagnostics:', error);
});Note: This function performs a synchronous request, meaning it waits for the TypeScript server
to compute and return the diagnostics. The response is directly related to the current
state of the file at the time of the request.
Sends a 'syntacticDiagnosticsSync' request to the TypeScript Server. This command is used to synchronously obtain syntactic diagnostic information (like parsing errors) for a specified file. Syntactic diagnostics are concerned with issues related to the parsing of the source code. This function is particularly useful for quickly identifying syntax errors in a TypeScript file.
-
filePathstring The path to the TypeScript file. The path should be absolute or relative to the TypeScript server's current working directory. -
includeLinePositionboolean Specifies whether to include line and character position information in the diagnostics. When set to true, each diagnostic includes detailed position information, which is useful for displaying errors directly in an editor. (optional, defaultfalse)
Returns Promise<Object> A promise that resolves with the response from tsserver containing syntactic
diagnostics. The response is an array of diagnostic objects. Each diagnostic object
typically contains:
- start: The starting position of the diagnostic message.
- length: The length of the diagnostic message.
- text: The text of the diagnostic message.
If includeLinePosition is true, the diagnostic object also includes:
- startLocation: An object with line and character position of the start.
- endLocation: An object with line and character position of the end.Example usage: getSyntacticDiagnosticsSync('path/to/file.ts', true).then(response => {
console.log('Syntactic diagnostics:', response);
});
Sends a 'suggestionDiagnosticsSync' request to the TypeScript Server. This command is used to synchronously obtain suggestion diagnostic information for a specified file. Suggestion diagnostics include tips and hints that may not necessarily be errors or warnings but could suggest improvements or best practices in the code.
-
filePathstring The path to the TypeScript file. This should be an absolute path or relative to the TypeScript server's current working directory. -
includeLinePositionboolean Specifies whether to include line and character position information in the diagnostics. When set to true, each diagnostic includes detailed position information, which is useful for displaying suggestions directly in an editor. (optional, defaultfalse)
Returns Promise<Object> A promise that resolves with the response from tsserver containing
suggestion diagnostics. The response is typically an array of diagnostic
objects. Each diagnostic object includes:
- start: The starting position of the diagnostic message.
- length: The length of the diagnostic message.
- text: The text of the diagnostic message.
If includeLinePosition is true, the diagnostic object also includes:
- startLocation: An object with line and character position of the start.
- endLocation: An object with line and character position of the end.Example usage: getSuggestionDiagnosticsSync('path/to/file.ts', true).then(response => {
console.log('Suggestion diagnostics:', response);
});This function is particularly useful for tools and editors integrating TypeScript support,
providing an opportunity to present potential code improvements or best practices to the developer.
Sends a 'navbar' request to the TypeScript Server. This command is used to obtain the navigation bar structure of a TypeScript file. The navigation bar typically includes a hierarchical outline of the file's structure, including classes, interfaces, functions, variables, and other code constructs.
-
filePathstring The path to the TypeScript file for which the navigation bar information is requested. The path should be absolute or relative to the TypeScript server's current working directory.
Returns Promise<Object> A promise that resolves with the response from tsserver containing
the navigation bar information. The response is typically an array
of items representing the various code constructs in the file. Each item
includes:
- text: The name of the code construct (e.g., class name, function name).
- kind: The kind of code construct (e.g., 'class', 'function').
- kindModifiers: Modifiers applied to the code construct (e.g., 'public', 'static').
- spans: An array of span objects indicating the location of the construct in the file.
- childItems: An array of child items, following the same structure, representing nested constructs.Example usage: getNavBar('path/to/file.ts').then(response => {
console.log('Navigation bar structure:', response);
});This function is particularly useful for tools and editors integrating TypeScript support,
providing an opportunity to present a structured outline or overview of a code file to the developer.
Sends a 'navto' request to the TypeScript Server. This command is used for searching named symbols in the project or in a particular file, with options to limit the results and scope the search to a specific project.
-
searchValuestring The search term to navigate to from the current location. The term can be '.*' or an identifier prefix. -
filestring? Optional file path to restrict the search to a specific file. -
currentFileOnlyboolean When true, limits search to the current file. (optional, defaultfalse) -
maxResultCountnumber? Optional limit on the number of items to return. -
projectFileNamestring? Optional name of the project file (absolute pathname required).
Returns Promise<Array<Object>> A promise that resolves with an array of navigation items.
Sends a 'navtree' request to the TypeScript Server to obtain the navigation tree of a TypeScript file. The navigation tree provides a hierarchical outline of the file's contents, detailing classes, interfaces, functions, variables, and other top-level constructs. This structured information is useful for understanding the organization of code and for quick navigation within IDEs or editors.
-
filePathstring The absolute path to the TypeScript file. This path is required to locate the file within the project or file system. -
projectFileNamestring? Optional. The absolute path to the project file (usually 'tsconfig.json'). Providing this path helps the TypeScript server correctly resolve the file's context within a specific project, especially useful in workspaces with multiple TypeScript projects.
Returns Promise<Object> A promise that resolves with the navigation tree from the TypeScript server.
The tree is a hierarchical object with nodes representing various code constructs.
Each node typically includes:
- text: The name of the construct (e.g., class or function name).
- kind: The kind of construct (e.g., 'class', 'function').
- spans: Array of location spans indicating where the construct appears in the file.
- childItems: Array of child nodes for nested constructs (following the same structure).Example usage: getNavTree('path/to/file.ts', 'path/to/project.tsconfig.json').then(navTree => {
console.log('Navigation tree:', navTree);
});The returned navigation tree is especially valuable in development environments where a visual outline
or structure of the code file is beneficial for navigation and code comprehension.
Sends a 'navtree-full' request to the TypeScript Server. This command obtains a comprehensive navigation tree of a TypeScript file, which provides a detailed outline of the file's structure. The response includes an extensive hierarchy of all symbols and their nested scopes within the file, such as classes, interfaces, functions, variables, and other code constructs.
This detailed navigation tree is particularly useful for applications that require an in-depth understanding of the file's structure, such as advanced IDE features for code navigation and analysis.
-
filePathstring The absolute path to the TypeScript file for which the full navigation tree is requested. This path is essential for the TypeScript server to locate and analyze the file.
Returns Promise<Object> A promise that resolves with the full navigation tree from the TypeScript server.
The tree is represented as an object with a hierarchical structure. Each node in the tree
includes:
- text: The name of the item (e.g., a class or function name).
- kind: The kind of item (e.g., 'class', 'function').
- spans: An array of span objects indicating the location of the item in the file.
- childItems: An array of child nodes representing nested declarations and structures.
Each child node follows the same structure.Example usage: getNavTreeFull('path/to/file.ts').then(navTreeFull => {
console.log('Full navigation tree:', navTreeFull);
});
Sends a 'documentHighlights' request to the TypeScript Server. This command is used to obtain highlights of all occurrences of a symbol within a specified set of files, optionally within the context of a specific project. It is useful for identifying and navigating to instances of a variable, function name, or other identifiers across multiple files.
-
filePathstring The path to the TypeScript file where the symbol occurs. -
linenumber The line number where the symbol is located. -
offsetnumber The character offset (position) in the line where the symbol is located. -
filesToSearchArray<string> The list of file paths to search for document highlights. -
projectFileNamestring? Optional. The name of the project file (absolute pathname required) that contains the TypeScript file. Providing this helps to accurately resolve symbols in the context of the given project. (optional, default"")
Returns Promise<Array<Object>> A promise that resolves with an array of document highlight objects.
Each object represents a file with highlight instances and includes:* file: The file in which the highlight occurs.
-
highlightSpans: An array of objects representing the highlight locations. Each object includes:-
start: The starting position of the highlight (line and character). -
end: The ending position of the highlight (line and character). -
kind: The kind of highlight (e.g., 'writtenReference', 'reference', 'definition').Example usage: documentHighlights('path/to/file.ts', 10, 5, ['path/to/file1.ts', 'path/to/file2.ts'], 'path/to/project.tsconfig.json') .then(highlights => { console.log('Document highlights:', highlights); });This function is essential for features like symbol search in development environments, where highlighting symbol occurrences enhances code understanding and navigation.
-
- See: exitServer - Sends an 'exit' command to the TypeScript Server for a graceful shutdown.
Terminates the TypeScript Server process. Warning: Use this function with caution. Prefer using the exitServer function for a graceful shutdown.