This repository has been archived by the owner on May 21, 2019. It is now read-only.
/
ShellLanguageServer.ts
308 lines (275 loc) · 10.7 KB
/
ShellLanguageServer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import * as ws from "ws";
import * as http from "http";
import * as url from "url";
import * as net from "net";
import * as express from "express";
import * as fs from "fs";
import * as rpc from "vscode-ws-jsonrpc";
import {xhr, XHRResponse, getErrorStatusDescription} from "request-light";
import Uri from "vscode-uri";
import {MessageReader, MessageWriter} from "vscode-jsonrpc";
import {IConnection, TextDocuments, createConnection} from "vscode-languageserver";
import {
TextDocument, Diagnostic, CompletionList, CompletionItem, Hover,
SymbolInformation, DocumentSymbolParams, TextEdit,
} from "vscode-languageserver-types";
import {TextDocumentPositionParams, DocumentRangeFormattingParams} from "vscode-base-languageclient/lib/protocol";
import {getLanguageService, LanguageService, JSONDocument} from "vscode-json-languageservice";
import { listen, MessageConnection } from "vscode-ws-jsonrpc";
import {
BaseLanguageClient, CloseAction, ErrorAction,
createMonacoServices, createConnection as createClientConnection,
} from "monaco-languageclient";
const ReconnectingWebSocket = require("reconnecting-websocket");
export function start(reader: MessageReader, writer: MessageWriter): ShellLanguageServer {
const connection = createConnection(reader, writer);
const server = new ShellLanguageServer(connection);
server.start();
return server;
}
export class ShellLanguageServer {
protected workspaceRoot: Uri | undefined;
protected readonly documents = new TextDocuments();
protected readonly languageService: LanguageService = getLanguageService({
schemaRequestService: this.resovleSchema.bind(this),
});
protected readonly pendingValidationRequests = new Map<string, number>();
constructor(
protected readonly connection: IConnection,
) {
this.documents.listen(this.connection);
this.documents.onDidChangeContent(change =>
this.validate(change.document),
);
this.documents.onDidClose(event => {
this.cleanPendingValidation(event.document);
this.cleanDiagnostics(event.document);
});
this.connection.onInitialize(params => {
if (params.rootPath) {
this.workspaceRoot = Uri.file(params.rootPath);
} else if (params.rootUri) {
this.workspaceRoot = Uri.parse(params.rootUri);
}
this.connection.console.log("The server is initialized.");
return {
capabilities: {
textDocumentSync: this.documents.syncKind,
completionProvider: {
resolveProvider: true,
triggerCharacters: ['"', ":"],
},
hoverProvider: true,
documentSymbolProvider: true,
documentRangeFormattingProvider: true,
},
};
});
this.connection.onCompletion(params =>
this.completion(params),
);
this.connection.onCompletionResolve(item =>
this.resolveCompletion(item),
);
this.connection.onHover(params =>
this.hover(params),
);
this.connection.onDocumentSymbol(params =>
this.findDocumentSymbols(params),
);
this.connection.onDocumentRangeFormatting(params =>
this.format(params),
);
}
start() {
this.connection.listen();
}
protected format(params: DocumentRangeFormattingParams): TextEdit[] {
const document = this.documents.get(params.textDocument.uri);
return this.languageService.format(document, params.range, params.options);
}
protected findDocumentSymbols(params: DocumentSymbolParams): SymbolInformation[] {
const document = this.documents.get(params.textDocument.uri);
const shellDocument = this.getShellDocument(document);
return this.languageService.findDocumentSymbols(document, shellDocument);
}
protected hover(params: TextDocumentPositionParams): Thenable<Hover> {
const document = this.documents.get(params.textDocument.uri);
const shellDocument = this.getShellDocument(document);
return this.languageService.doHover(document, params.position, shellDocument);
}
protected resovleSchema(url: string): Promise<string> {
const uri = Uri.parse(url);
if (uri.scheme === "file") {
return new Promise<string>((resolve, reject) => {
fs.readFile(uri.fsPath, "UTF-8", (err, result) => {
err ? reject("") : resolve(result.toString());
});
});
}
return xhr({url, followRedirects: 5}).then(response => {
return response.responseText;
}, (error: XHRResponse) => {
return Promise.reject(error.responseText || getErrorStatusDescription(error.status) || error.toString());
});
}
protected resolveCompletion(item: CompletionItem): Thenable<CompletionItem> {
return this.languageService.doResolve(item);
}
protected async completion(_params: TextDocumentPositionParams): Promise<CompletionList> {
const item = {
label: "git",
detail: "SOmethisanfosjfd oijf owaej",
};
const items = [item];
return {
isIncomplete: false,
items: items,
};
// console.log("completing");
// const document = this.documents.get(params.textDocument.uri);
// const shellDocument = this.getShellDocument(document);
// return this.languageService.doComplete(document, params.position, shellDocument);
}
protected validate(_document: TextDocument): void {
// console.log("validating");
// this.cleanPendingValidation(document);
// this.pendingValidationRequests.set(document.uri, setTimeout(() => {
// this.pendingValidationRequests.delete(document.uri);
// this.doValidate(document);
// }));
}
protected cleanPendingValidation(document: TextDocument): void {
const request = this.pendingValidationRequests.get(document.uri);
if (request !== undefined) {
clearTimeout(request);
this.pendingValidationRequests.delete(document.uri);
}
}
protected doValidate(document: TextDocument): void {
if (document.getText().length === 0) {
this.cleanDiagnostics(document);
return;
}
const shellDocument = this.getShellDocument(document);
this.languageService.doValidation(document, shellDocument).then(diagnostics =>
this.sendDiagnostics(document, diagnostics),
);
}
protected cleanDiagnostics(document: TextDocument): void {
this.sendDiagnostics(document, []);
}
protected sendDiagnostics(document: TextDocument, diagnostics: Diagnostic[]): void {
this.connection.sendDiagnostics({
uri: document.uri, diagnostics,
});
}
protected getShellDocument(document: TextDocument): JSONDocument {
return this.languageService.parseJSONDocument(document);
}
}
export function launch(socket: rpc.IWebSocket) {
const reader = new rpc.WebSocketMessageReader(socket);
const writer = new rpc.WebSocketMessageWriter(socket);
start(reader, writer);
}
process.on("uncaughtException", function (err: any) {
console.error("Uncaught Exception: ", err.toString());
if (err.stack) {
console.error(err.stack);
}
});
// create the express application
const app = express();
// server the static content, i.e. index.html
app.use(express.static(__dirname));
// start the server
const server = app.listen(3000, "localhost");
// create the web socket
const wss = new ws.Server({
noServer: true,
perMessageDeflate: false,
});
server.on("upgrade", (request: http.IncomingMessage, socket: net.Socket, head: Buffer) => {
const pathname = request.url ? url.parse(request.url).pathname : undefined;
if (pathname === "//sampleServer") {
wss.handleUpgrade(request, socket, head, webSocket => {
const socket: rpc.IWebSocket = {
send: content => webSocket.send(content, error => {
if (error) {
throw error;
}
}),
onMessage: cb => webSocket.on("message", cb),
onError: cb => webSocket.on("error", cb),
onClose: cb => webSocket.on("close", cb),
dispose: () => {
console.log("disposing");
webSocket.close();
},
};
// launch the server when the web socket is opened
if (webSocket.readyState === webSocket.OPEN) {
launch(socket);
} else {
webSocket.on("open", () => launch(socket));
}
});
}
});
/**
* Client.
*/
// register Monaco languages
monaco.languages.register({
id: "shell",
extensions: [".sh"],
aliases: ["shell"],
mimetypes: ["application/json"],
});
// create the web socket
const serverUrl = "ws://localhost:3000//sampleServer";
const webSocket = createWebSocket(serverUrl);
// listen when the web socket is opened
listen({
webSocket,
onConnection: connection => {
// create and start the language client
const languageClient = createLanguageClient(connection);
const disposable = languageClient.start();
connection.onClose(() => disposable.dispose());
},
});
const monacoServices = createMonacoServices();
function createLanguageClient(connection: MessageConnection): BaseLanguageClient {
return new BaseLanguageClient({
name: "Sample Language Client",
clientOptions: {
// use a language id as a document selector
documentSelector: ["json"],
// disable the default error handler
errorHandler: {
error: () => ErrorAction.Continue,
closed: () => CloseAction.DoNotRestart,
},
},
services: monacoServices,
// create a language client connection from the JSON RPC connection on demand
connectionProvider: {
get: (errorHandler, closeHandler) => {
return Promise.resolve(createClientConnection(connection, errorHandler, closeHandler));
},
},
});
}
function createWebSocket(url: string): WebSocket {
const socketOptions = {
maxReconnectionDelay: 10000,
minReconnectionDelay: 1000,
reconnectionDelayGrowFactor: 1.3,
connectionTimeout: 10000,
maxRetries: Infinity,
debug: false,
};
return new ReconnectingWebSocket(url, undefined, socketOptions);
}