Repository navigation
Expand file tree
/
Copy pathLSPClient.js
More file actions
1234 lines (1161 loc) · 61.8 KB
/
Copy pathLSPClient.js
File metadata and controls
1234 lines (1161 loc) · 61.8 KB
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://opensource.org/licenses/AGPL-3.0.
*
*/
/**
* LSPClient - browser-side Language Server Protocol client (desktop only).
*
* This is the thin, modern replacement for the legacy `LanguageClientWrapper` + NodeDomain
* transport. It owns a single shared `ph-lsp` NodeConnector and a multi-server registry
* keyed by `serverId`, and talks to the Node-side `src-node/lsp-client.js`.
*
* Language extensions only call `registerLanguageServer(config)`; this module then:
* - lazily loads the node LSP module on demand (keeps boot fast),
* - spawns + `initialize`s the server,
* - instantiates the standard providers from `DefaultProviders` (completion, signatureHelp,
* definition, references, diagnostics) plus the `HoverProvider`, and registers each with
* its Phoenix manager (CodeHintManager, ParameterHintsManager, JumpToDefManager,
* FindReferencesManager, CodeInspection, QuickViewManager),
* - drives document lifecycle through `DocumentSync`.
*
* Each `LanguageClient` exposes exactly the method surface `DefaultProviders` expects
* (`getServerCapabilities`, `requestHints`, `requestParameterHints`, `gotoDefinition`,
* `findReferences`, plus the new `requestHover`). All translation between Phoenix
* `{line, ch}` / VFS paths and LSP `{line, character}` / `file://` URIs (including the
* `/tauri` virtual-path prefix used by the desktop build) happens here so the providers stay
* transport-agnostic.
*
* @module languageTools/LSPClient
*/
/* eslint max-len: ["error", { "code": 120 }] */
define(function (require, exports, module) {
const NodeConnector = require("NodeConnector"),
NodeUtils = require("utils/NodeUtils"),
ProjectManager = require("project/ProjectManager"),
DocumentManager = require("document/DocumentManager"),
FileUtils = require("file/FileUtils"),
PathConverters = require("languageTools/PathConverters"),
DefaultProviders = require("languageTools/DefaultProviders"),
HoverProvider = require("languageTools/HoverProvider"),
DocumentSync = require("languageTools/DocumentSync"),
DocumentHighlight = require("languageTools/DocumentHighlight"),
LanguageManager = require("language/LanguageManager"),
CodeHintManager = require("editor/CodeHintManager"),
ParameterHintsManager = require("features/ParameterHintsManager"),
JumpToDefManager = require("features/JumpToDefManager"),
FindReferencesManager = require("features/FindReferencesManager"),
QuickViewManager = require("features/QuickViewManager"),
CodeInspection = require("language/CodeInspection"),
EventDispatcher = require("utils/EventDispatcher"),
PreferencesManager = require("preferences/PreferencesManager"),
Strings = require("strings"),
StringUtils = require("utils/StringUtils"),
Metrics = require("utils/Metrics");
EventDispatcher.makeEventDispatcher(exports);
/**
* Fired when a language server has finished (re)starting and is now serving/linting its languages.
* Handler args: `{ serverId, languages }`. Exposed for extensions that want to react to a server
* becoming available - it's loaded lazily, so they can't observe its startup directly.
* @const {string}
*/
const EVENT_LANGUAGE_SERVER_STARTED = "languageServerStarted";
/**
* Fired when a language server's process has stopped. Note a normal project switch does NOT stop
* the server - it is repointed in place via workspace/didChangeWorkspaceFolders. This fires only
* when the process is actually recycled: the restart fallback (for servers that can't change
* workspace folders live) and manual restarts, each followed by EVENT_LANGUAGE_SERVER_STARTED once
* back up. Handler args: `{ serverId, languages }`.
* @const {string}
*/
const EVENT_LANGUAGE_SERVER_STOPPED = "languageServerStopped";
const LSP_CONNECTOR_ID = "ph-lsp";
// Relative path required on the node side (resolved from src-node/utils.js). Lazy-loads the
// node LSP module the first time we connect, so node boot is unaffected.
const NODE_LSP_MODULE = "./lsp-client";
// LSP providers register above the built-in (e.g. Tern) providers so the language server
// wins when it is available, falling back gracefully when it is not.
const DEFAULT_PRIORITY = 1;
let connectorPromise = null;
let connector = null;
const clients = new Map(); // serverId -> LanguageClient
// ------------------------------------------------------------------------------------------
// Path / coordinate translation (VFS <-> real OS path <-> file:// URI)
// ------------------------------------------------------------------------------------------
function _toPlatformPath(vfsPath) {
if (window.fs && window.fs.getTauriPlatformPath) {
const platformPath = window.fs.getTauriPlatformPath(vfsPath);
if (platformPath) {
return platformPath;
}
}
return vfsPath;
}
function _toVirtualPath(platformPath) {
if (window.fs && window.fs.getTauriVirtualPath) {
return window.fs.getTauriVirtualPath(platformPath);
}
return platformPath;
}
/** Convert a Phoenix VFS path to the `file://` URI the server understands (real OS path). */
function pathToServerUri(vfsPath) {
return PathConverters.pathToUri(_toPlatformPath(vfsPath));
}
/** Convert a server `file://` URI (real OS path) back to a VFS-based `file://` URI. */
function serverUriToVfsUri(serverUri) {
let platformPath = PathConverters.uriToPath(serverUri);
// Windows language servers (e.g. tsserver) lowercase the drive letter in URIs
// ("file:///c%3A/..."), but Phoenix VFS mounts use the OS-reported uppercase drive
// ("/tauri/C/..."). The VFS is case-sensitive, so an un-normalized drive letter maps the
// same file to a second path - jump-to-definition would open a duplicate document.
if (brackets.platform === "win" && /^[a-z]:/.test(platformPath)) {
platformPath = platformPath.charAt(0).toUpperCase() + platformPath.substr(1);
}
return PathConverters.pathToUri(_toVirtualPath(platformPath));
}
function _markupToString(documentation) {
if (!documentation) {
return "";
}
if (typeof documentation === "string") {
return documentation;
}
return documentation.value || "";
}
function _paramLabel(signatureLabel, paramLabel) {
if (Array.isArray(paramLabel)) {
// LSP allows [start, end] offsets into the signature label.
return signatureLabel.substring(paramLabel[0], paramLabel[1]);
}
return paramLabel;
}
function _normalizeLocation(loc) {
if (!loc) {
return null;
}
const uri = loc.uri || loc.targetUri;
const range = loc.range || loc.targetSelectionRange || loc.targetRange;
if (!uri || !range) {
return null;
}
return { uri: serverUriToVfsUri(uri), range: range };
}
// ------------------------------------------------------------------------------------------
// Shared connector (lazy)
// ------------------------------------------------------------------------------------------
function getConnector() {
if (!connectorPromise) {
connectorPromise = (async function () {
// Lazy-load the node LSP module on first use so it does not slow node boot.
await NodeUtils._loadNodeExtensionModule(NODE_LSP_MODULE);
connector = NodeConnector.createNodeConnector(LSP_CONNECTOR_ID, {});
connector.on("lspNotification", _onLspNotification);
connector.on("serverExit", _onServerExit);
connector.on("serverError", _onServerError);
return connector;
}());
}
return connectorPromise;
}
function _onLspNotification(_event, data) {
if (!data) {
return;
}
const client = clients.get(data.serverId);
if (!client) {
return;
}
if (client._stopping) {
// The server is shutting down/restarting. Ignore any late messages it emits during the
// teardown window so stale diagnostics from the dying instance don't leak into the fresh
// one that replaces it (both share the same serverId).
return;
}
if (data.method === "textDocument/publishDiagnostics" && client.lintingProvider) {
const params = data.params || {};
// Rewrite the URI to a VFS-based URI so the linting provider keys results by the
// same path CodeInspection uses (editor.document.file._path).
const vfsUri = serverUriToVfsUri(params.uri);
const vfsPath = PathConverters.uriToPath(vfsUri);
const language = LanguageManager.getLanguageForPath(vfsPath);
const langId = language && language.getId();
let diagnostics = params.diagnostics || [];
// Let the language config drop diagnostics that don't make sense for a given file
// (e.g. TypeScript's "needs a declaration file" suggestions in a plain JS file).
const filterFn = client.config && client.config.filterDiagnostics;
if (filterFn && diagnostics.length) {
diagnostics = filterFn(diagnostics, { languageId: langId, filePath: vfsPath });
}
// Severity 4 (Hint) without tags is a refactoring suggestion (e.g. tsserver's "File is
// a CommonJS module; it may be converted to an ES module") - noise in a problems panel,
// so drop it (this also drops its quickfix). Tagged hints stay: tag 1 Unnecessary
// (unused symbol) and tag 2 Deprecated are real signal - they keep their panel row and
// squiggle, and additionally drive the faded/strikethrough text styling.
diagnostics = diagnostics.filter(function (d) {
return d.severity !== 4 || (d.tags && d.tags.length);
});
client.lintingProvider.setInspectionResults({
uri: vfsUri,
diagnostics: diagnostics
});
// Hand the RAW diagnostics (setInspectionResults flattens them, losing range/code/data)
// to the quickfix layer, which idle-fetches textDocument/codeAction fixes for them and
// decorates the cached results - see LintingProvider.updateQuickFixes.
client.lintingProvider.updateQuickFixes(vfsPath, diagnostics);
}
}
const MAX_AUTO_RESTARTS = 3;
function _onServerExit(_event, data) {
const client = data && clients.get(data.serverId);
if (!client) {
return;
}
if (data.pid && client._pid && data.pid !== client._pid) {
// Stale exit from a previous process generation - a restart has already spawned the
// replacement, so this must not clear its state or read as a crash of the new process.
return;
}
client.capabilities = null;
DocumentSync.clearServer(client);
if (client._stopping || client._restarting || _isDisabledByPref(client.serverId)) {
// Intentional stop/restart - do not auto-restart here. The _restarting/pref checks
// also cover the stop's exit event landing after stopServerProcess resolved (and
// reset _stopping), which would otherwise read as a crash, bump _crashCount, and
// schedule an auto-restart that races the restart already in flight (two concurrent
// starts orphan one initialize request, which then times out).
return;
}
// Unexpected crash - log it loudly (with the server's stderr) so failures are never
// silent, then self-heal with a bounded backoff to recover without a reload.
console.error("[LSP] server '" + data.serverId + "' exited unexpectedly (code=" + data.code +
(data.signal ? ", signal=" + data.signal : "") + ")." +
(data.stderr ? "\n--- server stderr ---\n" + data.stderr : ""));
Metrics.countEvent(Metrics.EVENT_TYPE.LSP, "srv", "Crash." + client._metricLabel);
window.logger.leaveTrail("[LSP] " + client.serverId + " crashed, code=" + data.code);
client._crashCount = (client._crashCount || 0) + 1;
if (client._crashCount > MAX_AUTO_RESTARTS) {
console.error("[LSP]", client.serverId, "exited repeatedly; not restarting");
Metrics.countEvent(Metrics.EVENT_TYPE.LSP, "srv", "Gaveup." + client._metricLabel);
window.logger.reportErrorOnce("lspGaveup." + client.serverId,
new Error("code=" + data.code + " signal=" + (data.signal || "none") +
_stderrSnippet(data.stderr)),
"[LSP] server crashed repeatedly, gave up: " + client.serverId);
return;
}
setTimeout(function () {
if (!clients.has(client.serverId) || client.capabilities ||
_isDisabledByPref(client.serverId)) {
return;
}
_startAndInit(client).then(function () {
client._crashCount = 0;
_announceServerStarted(client);
DocumentSync.openSupportedDocuments(client);
}).catch(function (err) {
console.error("[LSP] auto-restart failed", client.serverId, err && (err.message || err));
Metrics.countEvent(Metrics.EVENT_TYPE.LSP, "srv", "RstErr." + client._metricLabel);
});
}, 1000 * client._crashCount);
}
/**
* First non-empty stderr line, truncated, for the crash give-up report. Any user path in
* it is redacted by the loggerSetup message scrubber before the report leaves the app.
* @param {string} stderr
* @return {string} " stderr: <line>" or ""
*/
function _stderrSnippet(stderr) {
const lines = String(stderr || "").split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line) {
return " stderr: " + line.substring(0, 200);
}
}
return "";
}
function _onServerError(_event, data) {
if (data) {
console.error("[LSP] server error", data.serverId, data.error);
Metrics.countEvent(Metrics.EVENT_TYPE.LSP, "srv", "Err." + _srvLabel(data.serverId));
}
}
// ------------------------------------------------------------------------------------------
// LanguageClient - one per server, exposes the provider-facing method surface
// ------------------------------------------------------------------------------------------
/**
* ServerId as a metric name part. Metric names must be short js-var-safe strings (the GA
* event name has a ~30 char budget), and plugin serverIds are unbounded - so sanitize and
* truncate once here; every metric in the LSP stack labels with this.
* @param {string} serverId
* @return {string}
*/
function _srvLabel(serverId) {
const cleaned = String(serverId || "").replace(/[^a-zA-Z0-9]/g, "");
return cleaned.substring(0, 10) || "ukn";
}
// LSP request method -> short metric suffix for per-method latency. Anything unlisted is
// lumped into "Oth" so plugin/custom methods can't explode metric cardinality.
const METRIC_METHOD_GROUPS = {
"textDocument/completion": "Comp",
"textDocument/signatureHelp": "Sig",
"textDocument/hover": "Hover",
"textDocument/definition": "Def",
"textDocument/implementation": "Impl",
"textDocument/references": "Ref",
"textDocument/codeAction": "Fix",
"completionItem/resolve": "Res",
"textDocument/documentHighlight": "Hlt"
};
function LanguageClient(serverId, languages, config) {
this.serverId = serverId;
this.languages = languages;
this.config = config;
this.capabilities = null;
this._metricLabel = _srvLabel(serverId);
}
LanguageClient.prototype.getServerCapabilities = function () {
return this.capabilities;
};
LanguageClient.prototype.uriForPath = function (vfsPath) {
return pathToServerUri(vfsPath);
};
/**
* Whether this client serves the given editor's DOCUMENT. Feature providers are selected by the
* language at the cursor (e.g. "javascript" inside an HTML <script> or a markdown ```js fence),
* so without this check they would claim requests in host documents the server never syncs -
* returning nothing while starving lower-priority providers (Tern) that can actually serve them.
* @param {Editor} editor
* @return {boolean}
*/
LanguageClient.prototype.servesDocument = function (editor) {
if (!editor || this.languages.indexOf(editor.document.getLanguage().getId()) === -1) {
return false;
}
// Optional per-file opt-out (config.documentFilter): lets a server decline specific files
// of a language it otherwise serves, so lower-priority specialised providers can win there
// (e.g. the JSON server yields Phoenix preference files to PrefsCodeHints).
if (this.config && typeof this.config.documentFilter === "function" &&
!this.config.documentFilter(editor.document.file.fullPath)) {
return false;
}
return true;
};
LanguageClient.prototype._request = function (method, params) {
const serverId = this.serverId;
const metricLabel = this._metricLabel;
const startTime = Date.now();
return getConnector().then(function (conn) {
return conn.execPeer("sendRequest", { serverId: serverId, method: method, params: params });
}).then(function (result) {
// Successful requests only - failures include the 120s node-side timeout, which
// would wreck the averages. Failures are counted per feature instead.
Metrics.valueEventBatched(Metrics.EVENT_TYPE.LSP, "time",
(METRIC_METHOD_GROUPS[method] || "Oth") + "." + metricLabel, Date.now() - startTime);
return result;
});
};
LanguageClient.prototype._notify = function (method, params) {
const serverId = this.serverId;
return getConnector().then(function (conn) {
return conn.execPeer("sendNotification", { serverId: serverId, method: method, params: params });
}).catch(function (err) {
// Log AND re-throw: callers must be able to react to a lost notification (DocumentSync
// flags a full resync when a didChange never reached the server - swallowing here would
// leave the server's copy silently divergent). Fire-and-forget callers attach their own
// no-op catch.
console.warn("[LSP] notification '" + method + "' failed:", err && (err.message || err));
throw err;
});
};
/**
* Send an arbitrary LSP notification to this client's server (e.g. a feature module pushing
* `workspace/didChangeConfiguration` after start). Best-effort: failures are logged, never
* thrown.
* @param {string} method - LSP notification method name
* @param {Object} params - notification params
* @return {Promise<void>}
*/
LanguageClient.prototype.sendCustomNotification = function (method, params) {
return this._notify(method, params).catch(function () {
// already logged in _notify; custom notifications are fire-and-forget
});
};
// Document lifecycle notifications used by DocumentSync.
LanguageClient.prototype.notifyDidOpen = function (uri, languageId, version, text) {
return this._notify("textDocument/didOpen", {
textDocument: { uri: uri, languageId: languageId, version: version, text: text }
});
};
// `contentChanges` is the LSP array the caller (DocumentSync) builds: either a single full-text
// entry [{ text }] for full sync, or an ordered list of incremental edits [{ range, text }, ...]
// when the server advertises incremental sync.
LanguageClient.prototype.notifyDidChange = function (uri, version, contentChanges) {
return this._notify("textDocument/didChange", {
textDocument: { uri: uri, version: version },
contentChanges: contentChanges
});
};
LanguageClient.prototype.notifyDidClose = function (uri) {
return this._notify("textDocument/didClose", { textDocument: { uri: uri } }).catch(function () {
// ignorable: if the close never arrived the server is usually gone/restarting anyway,
// and (re)start resyncs documents from scratch
});
};
function _positionOf(cursorPos) {
return { line: cursorPos.line, character: cursorPos.ch };
}
// Describe the completion "context" at a position:
// - key: identifies the word being typed - file, line, and the text on the line before the
// column where that word starts. Stays constant while typing/moving within one word.
// - query: the part of the word already typed before the cursor.
// - anchored: whether the word start sits directly after a trigger-ish non-space character
// (".", "->", "::") rather than after whitespace/line start.
function _completionContext(filePath, pos) {
const doc = DocumentManager.getOpenDocumentForPath(filePath);
if (!doc) {
return null;
}
const lineText = doc.getLine(pos.line) || "";
let start = pos.ch;
while (start > 0 && /[\w$]/.test(lineText.charAt(start - 1))) {
start--;
}
return {
key: filePath + "|" + pos.line + "|" + lineText.substring(0, start),
query: lineText.substring(start, pos.ch),
anchored: start > 0 && /\S/.test(lineText.charAt(start - 1))
};
}
LanguageClient.prototype.requestHints = function (params) {
const self = this;
const deferred = $.Deferred();
(async function () {
try {
// Reuse the cached completion list while typing forward within one word, so every
// keystroke doesn't re-hit the server. Reuse is only sound when the cached list is
// a candidate SUPERSET of what the current query would return, so it needs ALL of:
// - the same context key (same file/line/word-start),
// - the current query extending the query the list was fetched with, and
// - that fetched query being non-empty OR anchored to a trigger char: a member
// list after "." / "->" is a closed set, but what a server answers at a BARE
// position is an arbitrary relevance selection, NOT a superset. intelephense
// answers a blank line with a grab-bag of symbols (marked complete!) which,
// if reused, swallows every later keystroke on that line (e.g. typing is_int
// showed no is_int because a stale blank-line list was being refiltered).
const ctx = _completionContext(params.filePath, params.cursorPos);
const cached = self._completionCache;
if (ctx && cached && cached.key === ctx.key &&
ctx.query.startsWith(cached.query) &&
(cached.query || cached.anchored)) {
deferred.resolve({ items: cached.items });
return;
}
await DocumentSync.flush(self, params.filePath);
const result = await self._request("textDocument/completion", {
textDocument: { uri: self.uriForPath(params.filePath) },
position: _positionOf(params.cursorPos)
});
const isIncomplete = !!(result && !Array.isArray(result) && result.isIncomplete);
const items = (result && (result.items || result)) || [];
items.forEach(function (item) {
// Keep the full server item (its `data` is needed for completionItem/resolve);
// just coerce documentation to a string for inline display.
item.documentation = _markupToString(item.documentation);
});
// Only cache a complete, NON-EMPTY list (an incomplete one must be re-queried as
// the user types; an empty one has nothing to refilter - and some servers answer
// empty at a bare position yet answer fully once a prefix exists). The fetched
// query + anchoring are stored so the reuse check above can prove superset-ness.
self._completionCache = (ctx && !isIncomplete && items.length)
? { key: ctx.key, query: ctx.query, anchored: ctx.anchored, items: items }
: null;
deferred.resolve({ items: items });
} catch (err) {
console.warn("[LSP] request failed:", err && (err.message || err));
deferred.reject(err);
}
}());
return deferred.promise();
};
LanguageClient.prototype.requestParameterHints = function (params) {
const self = this;
const deferred = $.Deferred();
(async function () {
try {
await DocumentSync.flush(self, params.filePath);
const result = await self._request("textDocument/signatureHelp", {
textDocument: { uri: self.uriForPath(params.filePath) },
position: _positionOf(params.cursorPos)
});
if (!result || !result.signatures || !result.signatures.length) {
deferred.reject();
return;
}
const signatures = result.signatures.map(function (sig) {
return {
// Full signature string (e.g. "getTableIndexes(tableName: any): Promise<…>") -
// the provider derives the function name from it for the parameter-hint popup.
label: sig.label,
documentation: _markupToString(sig.documentation) || sig.label,
parameters: (sig.parameters || []).map(function (p) {
return {
label: _paramLabel(sig.label, p.label),
documentation: _markupToString(p.documentation)
};
})
};
});
deferred.resolve({
signatures: signatures,
activeSignature: result.activeSignature,
activeParameter: result.activeParameter
});
} catch (err) {
console.warn("[LSP] request failed:", err && (err.message || err));
deferred.reject(err);
}
}());
return deferred.promise();
};
// Shared by gotoDefinition/gotoImplementation - both are "resolve a position to one or more
// {uri, range} locations" requests that only differ in LSP method name.
function _requestLocations(client, params, method) {
const deferred = $.Deferred();
(async function () {
try {
await DocumentSync.flush(client, params.filePath);
const result = await client._request(method, {
textDocument: { uri: client.uriForPath(params.filePath) },
position: _positionOf(params.cursorPos)
});
if (!result || (Array.isArray(result) && !result.length)) {
deferred.reject();
return;
}
if (Array.isArray(result)) {
const locations = result.map(_normalizeLocation).filter(Boolean);
if (!locations.length) {
deferred.reject();
return;
}
deferred.resolve(locations);
} else {
deferred.resolve(_normalizeLocation(result));
}
} catch (err) {
console.warn("[LSP] request failed:", err && (err.message || err));
deferred.reject(err);
}
}());
return deferred.promise();
}
LanguageClient.prototype.gotoDefinition = function (params) {
return _requestLocations(this, params, "textDocument/definition");
};
// Finds concrete implementations of the symbol at a position. Used as a fallback when
// gotoDefinition resolves to a single canonical declaration (e.g. a base class/interface
// method) for what is actually a polymorphic call site - see DefaultProviders.js doJumpToDef
// and https://github.com/phcode-dev/phoenix/issues/3093.
LanguageClient.prototype.gotoImplementation = function (params) {
return _requestLocations(this, params, "textDocument/implementation");
};
LanguageClient.prototype.findReferences = function (params) {
const self = this;
const deferred = $.Deferred();
(async function () {
try {
await DocumentSync.flush(self, params.filePath);
const result = await self._request("textDocument/references", {
textDocument: { uri: self.uriForPath(params.filePath) },
position: _positionOf(params.cursorPos),
context: { includeDeclaration: true }
});
const locations = Array.isArray(result) ? result.map(_normalizeLocation).filter(Boolean) : [];
deferred.resolve(locations);
} catch (err) {
console.warn("[LSP] request failed:", err && (err.message || err));
deferred.reject(err);
}
}());
return deferred.promise();
};
LanguageClient.prototype.resolveCompletion = function (item) {
const deferred = $.Deferred();
if (!this.capabilities || !this.capabilities.completionProvider ||
!this.capabilities.completionProvider.resolveProvider) {
return deferred.resolve(item).promise(); // server can't enrich items
}
this._request("completionItem/resolve", item).then(function (resolved) {
const out = resolved || item;
out.documentation = _markupToString(out.documentation);
deferred.resolve(out);
}, function () {
deferred.resolve(item); // fall back to the unresolved item
});
return deferred.promise();
};
LanguageClient.prototype.documentHighlight = function (params) {
const self = this;
const deferred = $.Deferred();
(async function () {
try {
await DocumentSync.flush(self, params.filePath);
const result = await self._request("textDocument/documentHighlight", {
textDocument: { uri: self.uriForPath(params.filePath) },
position: _positionOf(params.cursorPos)
});
deferred.resolve(Array.isArray(result) ? result : []);
} catch (err) {
console.warn("[LSP] request failed:", err && (err.message || err));
deferred.reject(err);
}
}());
return deferred.promise();
};
LanguageClient.prototype.requestHover = function (params) {
const self = this;
const deferred = $.Deferred();
(async function () {
try {
await DocumentSync.flush(self, params.filePath);
const result = await self._request("textDocument/hover", {
textDocument: { uri: self.uriForPath(params.filePath) },
position: _positionOf(params.cursorPos)
});
deferred.resolve(result);
} catch (err) {
console.warn("[LSP] request failed:", err && (err.message || err));
deferred.reject(err);
}
}());
return deferred.promise();
};
/**
* Quickfix code actions for the given range's diagnostics (LSP textDocument/codeAction).
* Server-agnostic: gated on the server's codeActionProvider capability (boolean or object).
* @param {{filePath:string, range:Object, diagnostics:Array<Object>}} params - `range` is an LSP
* range ({start:{line,character}, end:{...}}) and `diagnostics` the raw LSP diagnostics to
* pass as context (servers key their fixes off these).
* @return {jQuery.Promise} resolves the server's (CodeAction|Command)[] or []
*/
LanguageClient.prototype.requestCodeActions = function (params) {
const self = this;
const deferred = $.Deferred();
if (!this.capabilities || !this.capabilities.codeActionProvider) {
return deferred.resolve([]).promise(); // server offers no code actions
}
(async function () {
try {
await DocumentSync.flush(self, params.filePath);
const result = await self._request("textDocument/codeAction", {
textDocument: { uri: self.uriForPath(params.filePath) },
range: params.range,
context: {
diagnostics: params.diagnostics || [],
only: ["quickfix"]
}
});
deferred.resolve(Array.isArray(result) ? result : []);
} catch (err) {
console.warn("[LSP] request failed:", err && (err.message || err));
deferred.reject(err);
}
}());
return deferred.promise();
};
/**
* Fill in a CodeAction's deferred properties (typically `edit`) via codeAction/resolve. We don't
* advertise resolveSupport, so conformant servers inline edits and this is never needed - it
* exists for servers that defer anyway, gated on their codeActionProvider.resolveProvider.
* Mirrors resolveCompletion: always resolves, falling back to the unresolved action.
* @param {Object} action - the CodeAction as returned by requestCodeActions
* @return {jQuery.Promise}
*/
LanguageClient.prototype.resolveCodeAction = function (action) {
const deferred = $.Deferred();
const provider = this.capabilities && this.capabilities.codeActionProvider;
if (!provider || !provider.resolveProvider) {
return deferred.resolve(action).promise();
}
this._request("codeAction/resolve", action).then(function (resolved) {
deferred.resolve(resolved || action);
}, function () {
deferred.resolve(action);
});
return deferred.promise();
};
// ------------------------------------------------------------------------------------------
// Server lifecycle + provider registration
// ------------------------------------------------------------------------------------------
function _projectRootPath() {
const root = ProjectManager.getProjectRoot();
return root ? root.fullPath : null;
}
function _clientCapabilities(config) {
return {
textDocument: {
synchronization: {
dynamicRegistration: false,
didSave: true,
willSave: false,
willSaveWaitUntil: false
},
completion: {
dynamicRegistration: false,
completionItem: {
// Off by default: our hint insertion is plain text. A server config can opt
// in (completionSnippetSupport) when the server refuses to offer completion
// without it - vscode-json-language-server does - and the CodeHintsProvider
// strips snippet placeholders on insert for such items.
snippetSupport: !!(config && config.completionSnippetSupport),
documentationFormat: ["markdown", "plaintext"],
// LSP 3.16: servers only lazily fill (via completionItem/resolve) the
// properties the client declares here - intelephense returns empty
// completion docs without it. We resolve the highlighted item for the
// docs popup, so declare exactly what that popup consumes.
resolveSupport: { properties: ["documentation", "detail"] },
// We render labelDetails.detail/description (e.g. the source module of an
// auto-import) so otherwise-identical labels are distinguishable - see the
// CodeHintsProvider renderer.
labelDetailsSupport: true
}
},
hover: { dynamicRegistration: false, contentFormat: ["markdown", "plaintext"] },
signatureHelp: {
dynamicRegistration: false,
signatureInformation: { documentationFormat: ["markdown", "plaintext"] }
},
definition: { dynamicRegistration: false },
references: { dynamicRegistration: false },
publishDiagnostics: { relatedInformation: false },
codeAction: {
dynamicRegistration: false,
// Literal CodeAction support (title/kind/edit) - without this servers degrade to
// bare Commands, which carry no WorkspaceEdit we could apply. resolveSupport is
// deliberately NOT advertised: conformant servers then inline `edit` in the
// codeAction response, sparing a codeAction/resolve round-trip per fix.
codeActionLiteralSupport: {
codeActionKind: { valueSet: ["quickfix"] }
}
}
},
workspace: { workspaceFolders: true, configuration: false }
};
}
// The UI language the user has Phoenix set to (e.g. "en", "fr", "ja"), forwarded to the
// server so it can localize its messages. Falls back to English when unavailable.
function _uiLocale() {
return (typeof brackets !== "undefined" && brackets.getLocale && brackets.getLocale()) || "en";
}
async function _startAndInit(client) {
const startTime = Date.now();
const config = client.config;
const conn = await getConnector();
const rootVfsPath = (config.rootUriProvider && config.rootUriProvider()) || _projectRootPath();
const rootUri = rootVfsPath ? pathToServerUri(rootVfsPath) : null;
const rootName = rootVfsPath ? FileUtils.getBaseName(rootVfsPath) : "root";
// Remember the active workspace folder so a later project switch can hand the server the
// delta (removed old, added new) via workspace/didChangeWorkspaceFolders - see
// changeWorkspaceRoot - instead of a full restart.
client.rootUri = rootUri;
client.rootName = rootName;
const startResult = await conn.execPeer("startServer", {
serverId: client.serverId,
command: config.command,
args: config.args || ["--stdio"],
rootUri: rootUri,
workspaceConfiguration: config.workspaceConfiguration,
suppressStderrPattern: config.suppressStderrPattern
});
// Process-generation marker: lets _onServerExit tell a stale exit event (a previous
// process, delivered after its replacement already spawned) from a crash of this one.
client._pid = (startResult && startResult.pid) || null;
const initResult = await conn.execPeer("sendRequest", {
serverId: client.serverId,
method: "initialize",
params: {
processId: null,
// LSP InitializeParams.locale - the UI language to localize server messages
// (diagnostics, hover/quick-info) in. vtsls forwards this to tsserver, which ships
// localized messages for many locales and falls back to English for unknown ones.
locale: _uiLocale(),
rootUri: rootUri,
workspaceFolders: rootUri ? [{ uri: rootUri, name: rootName }] : null,
capabilities: _clientCapabilities(config),
initializationOptions: config.initializationOptions || {}
}
});
client.capabilities = (initResult && initResult.capabilities) || {};
await conn.execPeer("sendNotification", {
serverId: client.serverId,
method: "initialized",
params: {}
});
// Spawn + initialize handshake time - rare enough to send unbatched.
Metrics.valueEvent(Metrics.EVENT_TYPE.LSP, "time", "Init." + client._metricLabel,
Date.now() - startTime);
}
function _registerProviders(client) {
const langs = client.languages;
client.codeHints = new DefaultProviders.CodeHintsProvider(client);
client.parameterHints = new DefaultProviders.ParameterHintsProvider(client);
client.jumpToDef = new DefaultProviders.JumpToDefProvider(client);
client.references = new DefaultProviders.ReferencesProvider(client);
client.lintingProvider = new DefaultProviders.LintingProvider();
client.lintingProvider._validateOnType = true;
// recorded so the provider can tell whether it is still a participating inspector before nudging a
// re-run on async diagnostics.
client.lintingProvider._inspectionProviderName = client.serverId;
// The quickfix layer requests textDocument/codeAction through this client (capability-gated
// inside requestCodeActions), keeping the provider itself transport-agnostic.
client.lintingProvider._quickFixClient = client;
client.hover = new HoverProvider.HoverProvider(client);
CodeHintManager.registerHintProvider(client.codeHints, langs, DEFAULT_PRIORITY);
ParameterHintsManager.registerHintProvider(client.parameterHints, langs, DEFAULT_PRIORITY);
JumpToDefManager.registerJumpToDefProvider(client.jumpToDef, langs, DEFAULT_PRIORITY);
FindReferencesManager.registerFindReferencesProvider(client.references, langs, DEFAULT_PRIORITY);
QuickViewManager.registerQuickViewProvider(client.hover, langs);
langs.forEach(function (lang) {
CodeInspection.register(lang, {
name: client.lintingProvider._inspectionProviderName,
scanFileAsync: function (text, fullPath) {
// Diagnostics are pushed asynchronously by the server (publishDiagnostics),
// so never block the scan waiting for them - return whatever is cached now and
// let setInspectionResults() trigger a re-scan when fresh diagnostics arrive.
// (Blocking here would surface CodeInspection's 10s "timed out" error.)
const cached = client.lintingProvider.getInspectionResults(text, fullPath);
return $.Deferred().resolve(cached || { errors: [] }).promise();
}
});
});
}
/**
* Announce that `client`'s server has (re)started and is now serving its languages: notify
* listeners (EVENT_LANGUAGE_SERVER_STARTED) and re-run inspection so any linter that defers to a
* language server (e.g. JSHint -> the TS service) drops its now-redundant results - even on a
* clean file, where the server's empty publishDiagnostics wouldn't trigger a re-run. Called from
* every path that brings a server up: initial registration, restart, and crash auto-restart.
*/
function _announceServerStarted(client) {
Metrics.countEvent(Metrics.EVENT_TYPE.LSP, "srv", "Start." + client._metricLabel);
exports.trigger(EVENT_LANGUAGE_SERVER_STARTED, {
serverId: client.serverId,
languages: client.languages
});
CodeInspection.requestRun();
}
/**
* Every registered server gets a `codeIntelligence.<serverId>` boolean preference (defined by
* its extension, or auto-defined here for plugin-supplied servers) - the durable off-switch
* for the whole server: hints, parameter hints, jump-to-def, references, hover, diagnostics.
* @param {string} serverId
* @return {string} the preference key
*/
function _codeIntelPrefKey(serverId) {
return "codeIntelligence." + serverId;
}
function _isDisabledByPref(serverId) {
return PreferencesManager.get(_codeIntelPrefKey(serverId)) === false;
}
// serverIds whose codeIntelligence pref already has a change listener attached - the pref
// outlives the client entry (registration can be retried), so listeners attach only once.
const _prefWatchedServers = new Set();
/**
* Live-toggle a registered server from its `codeIntelligence.<serverId>` pref: off stops the
* server process (providers go dormant without capabilities, and inspection re-runs so a
* fallback linter can take over); on restarts it in place.
*/
function _watchServerPref(serverId) {
if (_prefWatchedServers.has(serverId)) {
return;
}
_prefWatchedServers.add(serverId);
// Change events also fire without the value flipping (e.g. pref scopes reloading on a
// project switch). Only a real flip may act - reacting to a same-value event would
// needlessly restart a running server (and miscount the opt-out metric).
let lastDisabled = _isDisabledByPref(serverId);
PreferencesManager.on("change", _codeIntelPrefKey(serverId), function () {
const disabledNow = _isDisabledByPref(serverId);
if (disabledNow === lastDisabled) {
return;
}
lastDisabled = disabledNow;
const client = clients.get(serverId);
if (!client) {
return;
}
if (disabledNow) {
// The opt-out signal: users actively turning code intelligence off. Only the
// non-default (off) state is logged - flips back to the default would just be
// noise.
Metrics.countEvent(Metrics.EVENT_TYPE.LSP, "srv", "PrefOff." + client._metricLabel);
if (client.capabilities) {
stopServerProcess(client).then(function () {
CodeInspection.requestRun();
});
}
} else {
restartLanguageServer(serverId);
}
});
}
/**
* Register and start a language server, wiring all providers into the editor.
*
* @param {Object} config
* @param {string} config.serverId - unique id for the server (e.g. "typescript")
* @param {string} config.command - server binary (resolved from node_modules/.bin then PATH)
* @param {string[]} [config.args=["--stdio"]] - server arguments
* @param {string[]} config.languages - Phoenix language ids this server handles
* @param {Object} [config.initializationOptions] - LSP initializationOptions for the server
* @param {Object} [config.languageIdMap] - map of Phoenix langId -> LSP languageId
* @param {function(string, Editor):boolean} [config.shouldAutoTrigger] - decides whether a
* typed character should implicitly open the hint list. Receives (implicitChar, editor).
* When omitted, a generic default is used (identifier chars + the server's non-whitespace
* triggerCharacters). Explicit invocation (Ctrl-Space) always shows hints regardless.
* @param {function():string} [config.rootUriProvider] - returns the workspace root VFS path
* @param {function(string):boolean} [config.documentFilter] - per-file opt-out: given a file's
* full path, return false to make this server decline the file even though its language
* matches (e.g. the JSON server yields Phoenix pref files to PrefsCodeHints).
* @param {boolean} [config.completionSnippetSupport] - advertise snippet support in the client