-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathserver.ts
394 lines (335 loc) · 11.3 KB
/
server.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import {
createConnection,
TextDocuments,
ProposedFeatures,
InitializeParams,
DidChangeConfigurationNotification,
TextDocumentPositionParams,
TextDocumentSyncKind,
InitializeResult,
TextDocumentChangeEvent,
RenameParams,
DocumentSymbolParams,
ExecuteCommandParams,
CompletionParams,
} from 'vscode-languageserver';
import { CodeActionParams } from 'vscode-languageserver-protocol';
import { TextDocument } from 'vscode-languageserver-textdocument';
// We need to import this to include reflect functionality
import 'reflect-metadata';
import {
AURELIA_COMMANDS,
AURELIA_COMMANDS_KEYS,
CodeActionMap,
} from './common/constants';
import { Logger } from './common/logging/logger';
import { MyLodash } from './common/MyLodash';
import { UriUtils } from './common/view/uri-utils';
import { AureliaProjects } from './core/AureliaProjects';
import { AureliaServer } from './core/aureliaServer';
import { globalContainer } from './core/container';
import {
ExtensionSettings,
settingsName,
} from './feature/configuration/DocumentSettings';
import { isViewModelDocument } from './common/documens/TextDocumentUtils';
const logger = new Logger('Server');
// Create a connection for the server. The connection uses Node's IPC as a transport.
// Also include all preview / proposed LSP features.
export const connection = createConnection(ProposedFeatures.all);
// Create a simple text document manager. The text document manager
// supports full document sync only
const documents: TextDocuments<TextDocument> = new TextDocuments(TextDocument);
let hasConfigurationCapability: boolean = false;
let hasWorkspaceFolderCapability: boolean = false;
// let hasDiagnosticRelatedInformationCapability: boolean = false;
let hasServerInitialized = false;
let aureliaServer: AureliaServer;
connection.onInitialize(async (params: InitializeParams) => {
const capabilities = params.capabilities;
// Does the client support the `workspace/configuration` request?
// If not, we will fall back using global settings
hasConfigurationCapability = !!(
capabilities.workspace && Boolean(capabilities.workspace.configuration)
);
hasWorkspaceFolderCapability = !!(
capabilities.workspace && Boolean(capabilities.workspace.workspaceFolders)
);
// hasDiagnosticRelatedInformationCapability = Boolean(
// capabilities.textDocument?.publishDiagnostics?.relatedInformation
// );
const result: InitializeResult = {
capabilities: {
textDocumentSync: TextDocumentSyncKind.Full,
// Tell the client that the server supports code completion
completionProvider: {
resolveProvider: false,
// eslint-disable-next-line @typescript-eslint/quotes
triggerCharacters: [' ', '.', '[', '"', "'", '{', '<', ':', '|', '$'],
},
definitionProvider: true,
// hoverProvider: true,
codeActionProvider: true,
renameProvider: true,
documentSymbolProvider: true,
workspaceSymbolProvider: true,
executeCommandProvider: {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
commands: AURELIA_COMMANDS,
},
},
};
if (hasWorkspaceFolderCapability) {
result.capabilities.workspace = {
workspaceFolders: {
supported: true,
},
};
}
return result;
});
// eslint-disable-next-line @typescript-eslint/no-misused-promises
connection.onInitialized(async () => {
if (hasConfigurationCapability) {
// Register for all configuration changes.
void connection.client.register(
DidChangeConfigurationNotification.type,
undefined
);
await initAurelia();
const should = await shouldInit();
if (!should) return;
hasServerInitialized = true;
}
if (hasWorkspaceFolderCapability) {
connection.workspace.onDidChangeWorkspaceFolders((_event) => {
connection.console.log('Workspace folder change event received.');
});
}
});
// connection.onDidOpenTextDocument(() => {});
// Only keep settings for open documents
// documents.onDidClose((e) => {
// documentSettings.settingsMap.delete(e.document.uri);
// });
connection.onCodeAction(async (codeActionParams: CodeActionParams) => {
if (hasServerInitialized === false) return;
const dontTrigger = await dontTriggerInViewModel(
codeActionParams.textDocument
);
if (dontTrigger) return;
const codeAction = await aureliaServer.onCodeAction(codeActionParams);
if (codeAction) {
return codeAction;
}
});
// This handler provides the initial list of the completion items.
connection.onCompletion(async (completionParams: CompletionParams) => {
const documentUri = completionParams.textDocument.uri;
const document = documents.get(documentUri);
if (!document) {
throw new Error('No document found');
}
const dontTrigger = await dontTriggerInViewModel(document);
if (dontTrigger) return;
const completions = await aureliaServer.onCompletion(
document,
completionParams
);
if (completions != null) {
return completions;
}
});
// This handler resolves additional information for the item selected in
// the completion list.
// connection.onCompletionResolve(
// (item: CompletionItem): CompletionItem => {
// return item;
// }
// );
connection.onDefinition(
async ({ position, textDocument }: TextDocumentPositionParams) => {
const documentUri = textDocument.uri.toString();
const document = documents.get(documentUri); // <
if (!document) return null;
const definition = await aureliaServer.onDefinition(document, position);
if (definition) {
return definition;
}
return null;
}
);
// The content of a text document has changed. This event is emitted
// when the text document first opened or when its content has changed.
documents.onDidChangeContent(
MyLodash.debouncePromise(
async (change: TextDocumentChangeEvent<TextDocument>) => {
if (!hasServerInitialized) return;
// const diagnosticsParams = await aureliaServer.sendDiagnostics(
// change.document
// );
// connection.sendDiagnostics(diagnosticsParams);
await aureliaServer.onConnectionDidChangeContent(change);
},
400
)
);
connection.onDidChangeConfiguration(async () => {
console.log('[server.ts] onDidChangeConfiguration');
if (!hasConfigurationCapability) return;
await initAurelia(true);
});
connection.onDidChangeWatchedFiles((_change) => {
// Monitored files have change in VSCode
connection.console.log('We received an file change event');
});
documents.onDidSave(async (change: TextDocumentChangeEvent<TextDocument>) => {
await aureliaServer.onDidSave(change);
});
connection.onDocumentSymbol(async (params: DocumentSymbolParams) => {
if (hasServerInitialized === false) return;
const dontTrigger = await dontTriggerInViewModel({
uri: params.textDocument.uri,
});
if (dontTrigger) return;
const symbols = await aureliaServer.onDocumentSymbol(params.textDocument.uri);
return symbols;
});
// connection.onWorkspaceSymbol(async (params: WorkspaceSymbolParams) => {
connection.onWorkspaceSymbol(async () => {
if (hasServerInitialized === false) return;
// const workspaceSymbols = aureliaServer.onWorkspaceSymbol(params.query);
try {
const workspaceSymbols = aureliaServer.onWorkspaceSymbol();
return workspaceSymbols;
} catch (error) {
error; /* ? */
}
});
// connection.onHover(
// async ({ position, textDocument }: TextDocumentPositionParams) => {
// const documentUri = textDocument.uri.toString();
// const document = documents.get(documentUri); // <
// if (!document) return null;
// const hovered = await aureliaServer.onHover(
// document.getText(),
// position,
// documentUri,
// );
// return hovered;
// }
// );
connection.onExecuteCommand(
async (executeCommandParams: ExecuteCommandParams) => {
const command = executeCommandParams.command as AURELIA_COMMANDS_KEYS;
switch (command) {
case 'extension.au.reloadExtension': {
await initAurelia(true);
break;
}
case CodeActionMap['refactor.aTag'].command: {
logger.log(
`Command executed: "${CodeActionMap['refactor.aTag'].title}"`
);
break;
}
default: {
// console.log('no command');
}
}
// async () => {
return null;
}
);
connection.onRenameRequest(
async ({ position, textDocument, newName }: RenameParams) => {
const documentUri = textDocument.uri;
const document = documents.get(documentUri);
if (!document) {
throw new Error('No document found');
}
const renamed = await aureliaServer.onRenameRequest(
document,
position,
newName
);
if (renamed) {
return renamed;
}
}
);
// connection.onPrepareRename(async (prepareRename: PrepareRenameParams) => {
// /* prettier-ignore */ console.log('TCL: prepareRename', prepareRename);
// return new ResponseError(0, 'failed');
// });
connection.onRequest('aurelia-get-component-list', () => {
const aureliaProjects = globalContainer.get(AureliaProjects);
// TODO: use .getBy instead of getAll
const { aureliaProgram } = aureliaProjects.getAll()[0];
if (!aureliaProgram) return;
return aureliaProgram.aureliaComponents.getAll().map((cList) => {
const {
componentName,
className,
viewFilePath,
viewModelFilePath,
baseViewModelFileName,
} = cList;
return {
componentName,
className,
viewFilePath,
viewModelFilePath,
baseViewModelFileName,
};
});
});
// Make the text document manager listen on the connection
// for open, change and close text document events
documents.listen(connection);
// Listen on the connection
connection.listen();
async function dontTriggerInViewModel(document: { uri: string }) {
const extensionSettings = (await connection.workspace.getConfiguration({
section: settingsName,
})) as ExtensionSettings;
const dontTrigger = isViewModelDocument(document, extensionSettings);
return dontTrigger;
}
async function initAurelia(forceReinit?: boolean) {
const extensionSettings = (await connection.workspace.getConfiguration({
section: settingsName,
})) as ExtensionSettings;
const rootDirectory = await getRootDirectory(extensionSettings);
extensionSettings.aureliaProject = {
rootDirectory,
};
aureliaServer = new AureliaServer(
globalContainer,
extensionSettings,
documents
);
await aureliaServer.onConnectionInitialized(extensionSettings, forceReinit);
}
async function getRootDirectory(extensionSettings: ExtensionSettings) {
const workspaceFolders = await connection.workspace.getWorkspaceFolders();
if (workspaceFolders === null) return;
const workspaceRootUri = workspaceFolders[0].uri;
let rootDirectory = workspaceRootUri;
const settingRoot = extensionSettings.aureliaProject?.rootDirectory;
if (settingRoot != null && settingRoot !== '') {
rootDirectory = settingRoot;
}
return rootDirectory;
}
async function shouldInit() {
const workspaceFolders = await connection.workspace.getWorkspaceFolders();
if (workspaceFolders === null) return false;
const workspaceRootUri = workspaceFolders[0].uri;
const tsConfigPath = UriUtils.toSysPath(workspaceRootUri);
const aureliaProjects = globalContainer.get(AureliaProjects);
const targetProject = aureliaProjects.getBy(tsConfigPath);
if (!targetProject) return false;
return true;
}