Skip to content

Commit

Permalink
feat(test-utils): initial implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
johnsoncodehk committed Dec 9, 2023
1 parent 344dc82 commit 7b08e83
Show file tree
Hide file tree
Showing 7 changed files with 397 additions and 0 deletions.
21 changes: 21 additions & 0 deletions packages/test-utils/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023-present Johnson Chu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
31 changes: 31 additions & 0 deletions packages/test-utils/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# @volar/test-utils

This module provides a simple way to start a language server and interact with it. It exports a function `startLanguageServer` which starts a language server and returns a handle to interact with it.

## Usage

First, import the module and start the language server:

```typescript
import { startLanguageServer } from '@volar/test-utils';

const serverHandle = startLanguageServer('path/to/server/module');
```

The `startLanguageServer` function takes the path to the server module as a string and optionally a current working directory as a string or URL.

The returned server handle provides several methods to interact with the language server:

- `initialize(rootUri: string, initializationOptions: InitializationOptions)`: Initializes the language server.
- `openTextDocument(fileName: string, languageId: string)`: Opens a text document.
- `openUntitledTextDocument(content: string, languageId: string)`: Opens an untitled text document.
- `closeTextDocument(uri: string)`: Closes a text document.
- Various `send*Request` methods: Send language-related requests to the server.

For example, to open a text document and send a completion request:

```typescript
await serverHandle.initialize('file:///path/to/workspace', {});
const document = await serverHandle.openTextDocument('path/to/file', 'typescript');
const completions = await serverHandle.sendCompletionRequest(document.uri, { line: 0, character: 0 });
```
299 changes: 299 additions & 0 deletions packages/test-utils/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,299 @@
import * as _ from '@volar/language-server/node';
import * as assert from 'assert';
import * as cp from 'child_process';
import * as fs from 'fs';
import { TextDocument } from 'vscode-languageserver-textdocument';
import { URI } from 'vscode-uri';

export type LanguageServerHandle = ReturnType<typeof startLanguageServer>;

export function startLanguageServer(serverModule: string, cwd?: string | URL) {

const childProcess = cp.fork(
serverModule,
['--node-ipc', `--clientProcessId=${process.pid.toString()}`],
{
execArgv: ['--nolazy'],
env: process.env,
cwd,
}
);
const connection = _.createProtocolConnection(
new _.IPCMessageReader(childProcess),
new _.IPCMessageWriter(childProcess)
);
const openedDocuments = new Map<string, TextDocument>();

let untitledCounter = 0;

connection.listen();
connection.onClose((e) => console.log(e));
connection.onUnhandledNotification((e) => console.log(e));
connection.onError((e) => console.log(e));
connection.onDispose(() => {
childProcess.kill();
});

return {
process: childProcess,
connection,
async initialize(rootUri: string, initializationOptions: _.InitializationOptions) {
const result = await connection.sendRequest(
_.InitializeRequest.type,
{
processId: childProcess.pid ?? null,
rootUri,
capabilities: {},
initializationOptions,
} satisfies _.InitializeParams
);
await connection.sendNotification(_.InitializedNotification.type);
return result;
},
async openTextDocument(fileName: string, languageId: string) {
const uri = URI.file(fileName).toString();
if (!openedDocuments.has(uri)) {
const document = TextDocument.create(uri, languageId, 0, fs.readFileSync(fileName, 'utf-8'));
openedDocuments.set(uri, document);
await connection.sendNotification(
_.DidOpenTextDocumentNotification.type,
{
textDocument: {
uri,
languageId,
version: document.version,
text: document.getText(),
},
} satisfies _.DidOpenTextDocumentParams
);
}
return openedDocuments.get(uri)!;
},
async openUntitledTextDocument(content: string, languageId: string) {
const uri = URI.from({ scheme: 'untitled', path: `Untitled-${untitledCounter++}` }).toString();
const document = TextDocument.create(uri, languageId, 0, content);
openedDocuments.set(uri, document);
await connection.sendNotification(
_.DidOpenTextDocumentNotification.type,
{
textDocument: {
uri,
languageId,
version: document.version,
text: document.getText(),
},
} satisfies _.DidOpenTextDocumentParams
);
return document;
},
closeTextDocument(uri: string) {
assert(openedDocuments.has(uri));
openedDocuments.delete(uri);
return connection.sendNotification(
_.DidCloseTextDocumentNotification.type,
{
textDocument: { uri },
} satisfies _.DidCloseTextDocumentParams
);
},
async sendCompletionRequest(uri: string, position: _.Position) {
const result = await connection.sendRequest(
_.CompletionRequest.type,
{
textDocument: { uri },
position,
} satisfies _.CompletionParams
);
// @volar/language-server only returns CompletionList
assert(!Array.isArray(result));
return result;
},
async sendCompletionResolveRequest(item: _.CompletionItem) {
return connection.sendRequest(
_.CompletionResolveRequest.type,
item satisfies _.CompletionItem
);
},
sendDocumentDiagnosticRequest(uri: string) {
return connection.sendRequest(
_.DocumentDiagnosticRequest.type,
{
textDocument: { uri },
} satisfies _.DocumentDiagnosticParams
);
},
sendHoverRequest(uri: string, position: _.Position) {
return connection.sendRequest(
_.HoverRequest.type,
{
textDocument: { uri },
position,
} satisfies _.HoverParams
);
},
sendDocumentFormattingRequest(uri: string, options: _.FormattingOptions) {
return connection.sendRequest(
_.DocumentFormattingRequest.type,
{
textDocument: { uri },
options,
} satisfies _.DocumentFormattingParams
);
},
sendRenameRequest(uri: string, position: _.Position, newName: string) {
return connection.sendRequest(
_.RenameRequest.type,
{
textDocument: { uri },
position,
newName,
} satisfies _.RenameParams
);
},
sendPrepareRenameRequest(uri: string, position: _.Position) {
return connection.sendRequest(
_.PrepareRenameRequest.type,
{
textDocument: { uri },
position,
} satisfies _.PrepareRenameParams
);
},
sendFoldingRangesRequest(uri: string) {
return connection.sendRequest(
_.FoldingRangeRequest.type,
{
textDocument: { uri },
} satisfies _.FoldingRangeParams
);
},
sendDocumentSymbolRequest(uri: string) {
return connection.sendRequest(
_.DocumentSymbolRequest.type,
{
textDocument: { uri },
} satisfies _.DocumentSymbolParams
);
},
sendDocumentColorRequest(uri: string) {
return connection.sendRequest(
_.DocumentColorRequest.type,
{
textDocument: { uri },
} satisfies _.DocumentColorParams
);
},
sendDefinitionRequest(uri: string, position: _.Position) {
return connection.sendRequest(
_.DefinitionRequest.type,
{
textDocument: { uri },
position,
} satisfies _.DefinitionParams
);
},
sendTypeDefinitionRequest(uri: string, position: _.Position) {
return connection.sendRequest(
_.TypeDefinitionRequest.type,
{
textDocument: { uri },
position,
} satisfies _.TypeDefinitionParams
);
},
sendReferencesRequest(uri: string, position: _.Position, context: _.ReferenceContext) {
return connection.sendRequest(
_.ReferencesRequest.type,
{
textDocument: { uri },
position,
context,
} satisfies _.ReferenceParams
);
},
sendSignatureHelpRequest(uri: string, position: _.Position) {
return connection.sendRequest(
_.SignatureHelpRequest.type,
{
textDocument: { uri },
position,
} satisfies _.SignatureHelpParams
);
},
sendSelectionRangesRequest(uri: string, positions: _.Position[]) {
return connection.sendRequest(
_.SelectionRangeRequest.type,
{
textDocument: { uri },
positions,
} satisfies _.SelectionRangeParams
);
},
sendCodeActionsRequest(uri: string, range: _.Range, context: _.CodeActionContext) {
return connection.sendRequest(
_.CodeActionRequest.type,
{
textDocument: { uri },
range,
context,
} satisfies _.CodeActionParams
);
},
sendCodeActionResolveRequest(codeAction: _.CodeAction) {
return connection.sendRequest(
_.CodeActionResolveRequest.type,
codeAction satisfies _.CodeAction
);
},
sendExecuteCommandRequest(command: string, args?: any[]) {
return connection.sendRequest(
_.ExecuteCommandRequest.type,
{
command,
arguments: args,
} satisfies _.ExecuteCommandParams
);
},
sendSemanticTokensRequest(uri: string) {
return connection.sendRequest(
_.SemanticTokensRequest.type,
{
textDocument: { uri },
} satisfies _.SemanticTokensParams
);
},
sendSemanticTokensRangeRequest(uri: string, range: _.Range) {
return connection.sendRequest(
_.SemanticTokensRangeRequest.type,
{
textDocument: { uri },
range,
} satisfies _.SemanticTokensRangeParams
);
},
sendColorPresentationRequest(uri: string, color: _.Color, range: _.Range) {
return connection.sendRequest(
_.ColorPresentationRequest.type,
{
textDocument: { uri },
color,
range,
} satisfies _.ColorPresentationParams
);
},
sendDocumentLinkRequest(uri: string) {
return connection.sendRequest(
_.DocumentLinkRequest.type,
{
textDocument: { uri },
} satisfies _.DocumentLinkParams
);
},
sendDocumentLinkResolveRequest(link: _.DocumentLink) {
return connection.sendRequest(
_.DocumentLinkResolveRequest.type,
link satisfies _.DocumentLink
);
},
};
}
22 changes: 22 additions & 0 deletions packages/test-utils/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "@volar/test-utils",
"version": "2.0.0-alpha.2",
"license": "MIT",
"files": [
"**/*.js",
"**/*.d.ts"
],
"repository": {
"type": "git",
"url": "https://github.com/volarjs/volar.js.git",
"directory": "packages/test-utils"
},
"devDependencies": {
"@types/node": "latest"
},
"dependencies": {
"@volar/language-server": "2.0.0-alpha.2",
"vscode-languageserver-textdocument": "^1.0.11",
"vscode-uri": "^3.0.8"
}
}
7 changes: 7 additions & 0 deletions packages/test-utils/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.base.json",
"include": [ "*", "lib/**/*" ],
"references": [
{ "path": "../language-server/tsconfig.json" },
],
}
Loading

0 comments on commit 7b08e83

Please sign in to comment.