-
Notifications
You must be signed in to change notification settings - Fork 342
/
eslintServer.ts
1934 lines (1737 loc) · 61.9 KB
/
eslintServer.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
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
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
'use strict';
import {
createConnection, IConnection,
ResponseError, RequestType, NotificationType, ErrorCodes,
RequestHandler, NotificationHandler,
Diagnostic, DiagnosticSeverity, Range, Files, CancellationToken,
TextDocuments, TextDocumentSyncKind, TextEdit, TextDocumentIdentifier,
Command, WorkspaceChange,
CodeActionRequest, VersionedTextDocumentIdentifier,
ExecuteCommandRequest, DidChangeWatchedFilesNotification, DidChangeConfigurationNotification,
WorkspaceFolder, DidChangeWorkspaceFoldersNotification, CodeAction, CodeActionKind, Position,
DocumentFormattingRequest, DocumentFormattingRegistrationOptions, Disposable, DocumentFilter, TextDocumentEdit
} from 'vscode-languageserver';
import {
TextDocument
} from 'vscode-languageserver-textdocument';
import { URI } from 'vscode-uri';
import * as path from 'path';
import * as fs from 'fs';
import { execSync } from 'child_process';
import { EOL } from 'os';
import { stringDiff } from './diff';
namespace Is {
const toString = Object.prototype.toString;
export function boolean(value: any): value is boolean {
return value === true || value === false;
}
export function nullOrUndefined(value: any): value is null | undefined {
return value === null || value === undefined;
}
export function string(value: any): value is string {
return toString.call(value) === '[object String]';
}
}
namespace CommandIds {
export const applySingleFix: string = 'eslint.applySingleFix';
export const applySuggestion: string = 'eslint.applySuggestion';
export const applySameFixes: string = 'eslint.applySameFixes';
export const applyAllFixes: string = 'eslint.applyAllFixes';
export const applyDisableLine: string = 'eslint.applyDisableLine';
export const applyDisableFile: string = 'eslint.applyDisableFile';
export const openRuleDoc: string = 'eslint.openRuleDoc';
}
interface ESLintError extends Error {
messageTemplate?: string;
messageData?: {
pluginName?: string;
};
}
enum Status {
ok = 1,
warn = 2,
error = 3
}
interface StatusParams {
state: Status;
}
namespace StatusNotification {
export const type = new NotificationType<StatusParams, void>('eslint/status');
}
interface NoConfigParams {
message: string;
document: TextDocumentIdentifier;
}
interface NoConfigResult {
}
namespace NoConfigRequest {
export const type = new RequestType<NoConfigParams, NoConfigResult, void, void>('eslint/noConfig');
}
interface NoESLintLibraryParams {
source: TextDocumentIdentifier;
}
interface NoESLintLibraryResult {
}
namespace NoESLintLibraryRequest {
export const type = new RequestType<NoESLintLibraryParams, NoESLintLibraryResult, void, void>('eslint/noLibrary');
}
interface OpenESLintDocParams {
url: string;
}
interface OpenESLintDocResult {
}
namespace OpenESLintDocRequest {
export const type = new RequestType<OpenESLintDocParams, OpenESLintDocResult, void, void>('eslint/openDoc');
}
interface ProbeFailedParams {
textDocument: TextDocumentIdentifier;
}
namespace ProbleFailedRequest {
export const type = new RequestType<ProbeFailedParams, void, void, void>('eslint/probleFailed');
}
type RunValues = 'onType' | 'onSave';
enum ModeEnum {
auto = 'auto',
location = 'location'
}
namespace ModeEnum {
export function is(value: string): value is ModeEnum {
return value === ModeEnum.auto || value === ModeEnum.location;
}
}
interface ModeItem {
mode: ModeEnum
}
namespace ModeItem {
export function is(item: any): item is ModeItem {
const candidate = item as ModeItem;
return candidate && ModeEnum.is(candidate.mode);
}
}
interface DirectoryItem {
directory: string;
'!cwd'?: boolean;
}
namespace DirectoryItem {
export function is(item: any): item is DirectoryItem {
const candidate = item as DirectoryItem;
return candidate && Is.string(candidate.directory) && (Is.boolean(candidate['!cwd']) || candidate['!cwd'] === undefined);
}
}
interface CodeActionSettings {
disableRuleComment: {
enable: boolean;
location: 'separateLine' | 'sameLine';
};
showDocumentation: {
enable: boolean;
};
}
type PackageManagers = 'npm' | 'yarn' | 'pnpm';
type ESLintOptions = object & { fixTypes?: string[] };
enum Validate {
on = 'on',
off = 'off',
probe = 'probe'
}
enum ESLintSeverity {
off = 'off',
warn = 'warn',
error = 'error'
}
enum CodeActionsOnSaveMode {
all = 'all',
problems = 'problems'
}
interface CodeActionsOnSaveSettings {
enable: boolean;
mode: CodeActionsOnSaveMode
}
interface CommonSettings {
validate: Validate;
packageManager: 'npm' | 'yarn' | 'pnpm';
codeAction: CodeActionSettings;
codeActionOnSave: CodeActionsOnSaveSettings;
format: boolean;
quiet: boolean;
onIgnoredFiles: ESLintSeverity;
options: ESLintOptions | undefined;
run: RunValues;
nodePath: string | null;
workspaceFolder: WorkspaceFolder | undefined;
}
interface ConfigurationSettings extends CommonSettings {
workingDirectory: ModeItem | DirectoryItem | undefined;
}
interface TextDocumentSettings extends CommonSettings {
silent: boolean;
workingDirectory: DirectoryItem | undefined;
library: ESLintModule | undefined;
resolvedGlobalPackageManagerPath: string | undefined;
}
namespace TextDocumentSettings {
export function hasLibrary(settings: TextDocumentSettings): settings is (TextDocumentSettings & { library: ESLintModule }) {
return settings.library !== undefined;
}
}
interface ESLintAutoFixEdit {
range: [number, number];
text: string;
}
interface ESLintSuggestionResult {
desc: string;
fix: ESLintAutoFixEdit;
}
interface ESLintProblem {
line: number;
column: number;
endLine?: number;
endColumn?: number;
severity: number;
ruleId: string;
message: string;
fix?: ESLintAutoFixEdit;
suggestions?: ESLintSuggestionResult[]
}
interface ESLintDocumentReport {
filePath: string;
errorCount: number;
warningCount: number;
messages: ESLintProblem[];
output?: string;
}
interface ESLintReport {
errorCount: number;
warningCount: number;
results: ESLintDocumentReport[];
}
interface CLIOptions {
cwd?: string;
fixTypes?: string[];
fix?: boolean;
}
// { meta: { docs: [Object], schema: [Array] }, create: [Function: create] }
interface RuleData {
meta?: {
docs?: {
url?: string;
};
type?: string;
};
}
namespace RuleData {
export function hasMetaType(value: RuleData | undefined): value is RuleData & { meta: { type: string; }; } {
return value !== undefined && value.meta !== undefined && value.meta.type !== undefined;
}
}
interface ParserOptions {
parser?: string;
}
interface ESLintConfig {
env: Record<string, boolean>;
extends: string | string[];
// globals: Record<string, GlobalConf>;
ignorePatterns: string | string[];
noInlineConfig: boolean;
// overrides: OverrideConfigData[];
parser: string | null;
parserOptions?: ParserOptions;
plugins: string[];
processor: string;
reportUnusedDisableDirectives: boolean | undefined;
root: boolean;
// rules: Record<string, RuleConf>;
settings: object;
}
interface CLIEngine {
executeOnText(content: string, file?: string, warn?: boolean): ESLintReport;
isPathIgnored(path: string): boolean;
// This is only available from v4.15.0 forward
getRules?(): Map<string, RuleData>;
getConfigForFile?(path: string): ESLintConfig;
}
namespace CLIEngine {
export function hasRule(value: CLIEngine): value is CLIEngine & { getRules(): Map<string, RuleData> } {
return value.getRules !== undefined;
}
}
interface CLIEngineConstructor {
new(options: CLIOptions): CLIEngine;
}
interface ESLintModule {
CLIEngine: CLIEngineConstructor;
}
declare const __webpack_require__: typeof require;
declare const __non_webpack_require__: typeof require;
function loadNodeModule<T>(moduleName: string): T | undefined {
const r = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require;
try {
return r(moduleName);
} catch (err) {
connection.console.error(err.stack.toString());
}
return undefined;
}
function makeDiagnostic(problem: ESLintProblem): Diagnostic {
const message = problem.message;
const startLine = Math.max(0, problem.line - 1);
const startChar = Math.max(0, problem.column - 1);
const endLine = Is.nullOrUndefined(problem.endLine) ? startLine : Math.max(0, problem.endLine - 1);
const endChar = Is.nullOrUndefined(problem.endColumn) ? startChar : Math.max(0, problem.endColumn - 1);
const result: Diagnostic = {
message: message,
severity: convertSeverity(problem.severity),
source: 'eslint',
range: {
start: { line: startLine, character: startChar },
end: { line: endLine, character: endChar }
}
};
if (problem.ruleId) {
const url = ruleDocData.urls.get(problem.ruleId);
if (url !== undefined) {
result.code = {
value: problem.ruleId,
target: url
};
} else {
result.code = problem.ruleId;
}
}
return result;
}
interface Problem {
label: string;
documentVersion: number;
ruleId: string;
line: number;
edit?: ESLintAutoFixEdit;
suggestions?: ESLintSuggestionResult[]
}
namespace Problem {
export function isFixable(problem: Problem): problem is FixableProblem {
return problem.edit !== undefined;
}
export function hasSuggestions(problem: Problem): problem is SuggestionsProblem {
return problem.suggestions !== undefined;
}
}
interface FixableProblem extends Problem {
edit: ESLintAutoFixEdit;
}
namespace FixableProblem {
export function createTextEdit(document: TextDocument, editInfo: FixableProblem): TextEdit {
return TextEdit.replace(Range.create(document.positionAt(editInfo.edit.range[0]), document.positionAt(editInfo.edit.range[1])), editInfo.edit.text || '');
}
}
interface SuggestionsProblem extends Problem {
suggestions: ESLintSuggestionResult[];
}
namespace SuggestionsProblem {
export function createTextEdit(document: TextDocument, suggestion: ESLintSuggestionResult): TextEdit {
return TextEdit.replace(Range.create(document.positionAt(suggestion.fix.range[0]), document.positionAt(suggestion.fix.range[1])), suggestion.fix.text || '');
}
}
function computeKey(diagnostic: Diagnostic): string {
const range = diagnostic.range;
return `[${range.start.line},${range.start.character},${range.end.line},${range.end.character}]-${diagnostic.code}`;
}
const codeActions: Map<string, Map<string, Problem>> = new Map<string, Map<string, Problem>>();
function recordCodeAction(document: TextDocument, diagnostic: Diagnostic, problem: ESLintProblem): void {
if (!problem.ruleId) {
return;
}
const uri = document.uri;
let edits: Map<string, Problem> | undefined = codeActions.get(uri);
if (edits === undefined) {
edits = new Map<string, Problem>();
codeActions.set(uri, edits);
}
edits.set(computeKey(diagnostic), { label: `Fix this ${problem.ruleId} problem`, documentVersion: document.version, ruleId: problem.ruleId, edit: problem.fix, suggestions: problem.suggestions, line: problem.line });
}
function convertSeverity(severity: number): DiagnosticSeverity {
switch (severity) {
// Eslint 1 is warning
case 1:
return DiagnosticSeverity.Warning;
case 2:
return DiagnosticSeverity.Error;
default:
return DiagnosticSeverity.Error;
}
}
const enum CharCode {
/**
* The `\` character.
*/
Backslash = 92,
}
/**
* Check if the path follows this pattern: `\\hostname\sharename`.
*
* @see https://msdn.microsoft.com/en-us/library/gg465305.aspx
* @return A boolean indication if the path is a UNC path, on none-windows
* always false.
*/
function isUNC(path: string): boolean {
if (process.platform !== 'win32') {
// UNC is a windows concept
return false;
}
if (!path || path.length < 5) {
// at least \\a\b
return false;
}
let code = path.charCodeAt(0);
if (code !== CharCode.Backslash) {
return false;
}
code = path.charCodeAt(1);
if (code !== CharCode.Backslash) {
return false;
}
let pos = 2;
const start = pos;
for (; pos < path.length; pos++) {
code = path.charCodeAt(pos);
if (code === CharCode.Backslash) {
break;
}
}
if (start === pos) {
return false;
}
code = path.charCodeAt(pos + 1);
if (isNaN(code) || code === CharCode.Backslash) {
return false;
}
return true;
}
function getFileSystemPath(uri: URI): string {
const result = uri.fsPath;
if (process.platform === 'win32' && result.length >= 2 && result[1] === ':') {
// Node by default uses an upper case drive letter and ESLint uses
// === to compare paths which results in the equal check failing
// if the drive letter is lower case in th URI. Ensure upper case.
return result[0].toUpperCase() + result.substr(1);
} else {
return result;
}
}
function getFilePath(documentOrUri: string | TextDocument | URI | undefined): string | undefined {
if (!documentOrUri) {
return undefined;
}
const uri = Is.string(documentOrUri)
? URI.parse(documentOrUri)
: documentOrUri instanceof URI
? documentOrUri
: URI.parse(documentOrUri.uri);
if (uri.scheme !== 'file') {
return undefined;
}
return getFileSystemPath(uri);
}
const exitCalled = new NotificationType<[number, string], void>('eslint/exitCalled');
const nodeExit = process.exit;
process.exit = ((code?: number): void => {
const stack = new Error('stack');
connection.sendNotification(exitCalled, [code ? code : 0, stack.stack]);
setTimeout(() => {
nodeExit(code);
}, 1000);
}) as any;
process.on('uncaughtException', (error: any) => {
let message: string | undefined;
if (error) {
if (typeof error.stack === 'string') {
message = error.stack;
} else if (typeof error.message === 'string') {
message = error.message;
} else if (typeof error === 'string') {
message = error;
}
if (message === undefined || message.length === 0) {
try {
message = JSON.stringify(error, undefined, 4);
} catch (e) {
// Should not happen.
}
}
}
// eslint-disable-next-line no-console
console.error('Uncaught exception received.');
if (message) {
// eslint-disable-next-line no-console
console.error(message);
}
});
const connection = createConnection();
connection.console.info(`ESLint server running in node ${process.version}`);
// Is instantiated in the initalize handle;
let documents!: TextDocuments<TextDocument>;
const _globalPaths: { [key: string]: { cache: string | undefined; get(): string | undefined; } } = {
yarn: {
cache: undefined,
get(): string | undefined {
return Files.resolveGlobalYarnPath(trace);
}
},
npm: {
cache: undefined,
get(): string | undefined {
return Files.resolveGlobalNodePath(trace);
}
},
pnpm: {
cache: undefined,
get(): string {
const pnpmPath = execSync('pnpm root -g').toString().trim();
return pnpmPath;
}
}
};
function globalPathGet(packageManager: PackageManagers): string | undefined {
const pm = _globalPaths[packageManager];
if (pm) {
if (pm.cache === undefined) {
pm.cache = pm.get();
}
return pm.cache;
}
return undefined;
}
const languageId2DefaultExt: Map<string, string> = new Map([
['javascript', 'js'],
['javascriptreact', 'jsx'],
['typescript', 'ts'],
['typescriptreact', 'tsx'],
['html', 'html'],
['vue', 'vue']
]);
const languageId2ParserRegExp: Map<string, RegExp[]> = function createLanguageId2ParserRegExp() {
const result = new Map<string, RegExp[]>();
const typescript = /\/@typescript-eslint\/parser\//;
result.set('typescript', [typescript]);
result.set('typescriptreact', [typescript]);
return result;
}();
const languageId2ParserOptions: Map<string, { regExps: RegExp[]; parsers: Set<string> }> = function createLanguageId2ParserOptionsRegExp() {
const result = new Map<string, { regExps: RegExp[]; parsers: Set<string> }>();
const vue = /vue-eslint-parser\/.*\.js$/;
result.set('typescript', { regExps: [vue], parsers: new Set<string>(['@typescript-eslint/parser'])});
return result;
}();
const languageId2PluginName: Map<string, string> = new Map([
['html', 'html'],
['vue', 'vue'],
['markdown', 'markdown']
]);
const defaultLanguageIds: Set<string> = new Set([
'javascript', 'javascriptreact'
]);
const path2Library: Map<string, ESLintModule> = new Map<string, ESLintModule>();
const document2Settings: Map<string, Promise<TextDocumentSettings>> = new Map<string, Promise<TextDocumentSettings>>();
const projectFolderIndicators: [string, boolean][] = [
[ 'package.json', true ],
[ '.eslintignore', true],
[ '.eslintrc', false ],
[ '.eslintrc.json', false ],
[ '.eslintrc.js', false ],
[ '.eslintrc.yaml', false ],
[ '.eslintrc.yml', false ]
];
function findWorkingDirectory(workspaceFolder: string, file: string | undefined): string | undefined {
if (file === undefined || isUNC(file)) {
return workspaceFolder;
}
// Don't probe for something in node modules folder.
if (file.indexOf(`${path.sep}node_modules${path.sep}`) !== -1) {
return workspaceFolder;
}
let result: string = workspaceFolder;
let directory: string | undefined = path.dirname(file);
outer: while (directory !== undefined && directory.startsWith(workspaceFolder)) {
for (const item of projectFolderIndicators) {
if (fs.existsSync(path.join(directory, item[0]))) {
result = directory;
if (item[1]) {
break outer;
} else {
break;
}
}
}
const parent = path.dirname(directory);
directory = parent !== directory ? parent : undefined;
}
return result;
}
function resolveSettings(document: TextDocument): Promise<TextDocumentSettings> {
const uri = document.uri;
let resultPromise = document2Settings.get(uri);
if (resultPromise) {
return resultPromise;
}
resultPromise = connection.workspace.getConfiguration({ scopeUri: uri, section: '' }).then((configuration: ConfigurationSettings) => {
const settings: TextDocumentSettings = Object.assign(
{},
configuration,
{ silent: false, library: undefined, resolvedGlobalPackageManagerPath: undefined },
{ workingDirectory: undefined}
);
if (settings.validate === Validate.off) {
return settings;
}
settings.resolvedGlobalPackageManagerPath = globalPathGet(settings.packageManager);
const filePath = getFilePath(document);
const workspaceFolderPath = settings.workspaceFolder !== undefined ? getFilePath(settings.workspaceFolder.uri) : undefined;
const hasUserDefinedWorkingDirectories: boolean = configuration.workingDirectory !== undefined;
const workingDirectoryConfig = configuration.workingDirectory ?? { mode: ModeEnum.location };
if (ModeItem.is(workingDirectoryConfig)) {
let candidate: string | undefined;
if (workingDirectoryConfig.mode === ModeEnum.location) {
if (workspaceFolderPath !== undefined) {
candidate = workspaceFolderPath;
} else if (filePath !== undefined && !isUNC(filePath)) {
candidate = path.dirname(filePath);
}
} else if (workingDirectoryConfig.mode === ModeEnum.auto) {
if (workspaceFolderPath !== undefined) {
candidate = findWorkingDirectory(workspaceFolderPath, filePath);
} else if (filePath !== undefined && !isUNC(filePath)) {
candidate = path.dirname(filePath);
}
}
if (candidate !== undefined && fs.existsSync(candidate)) {
settings.workingDirectory = { directory: candidate };
}
} else {
settings.workingDirectory = workingDirectoryConfig;
}
let promise: Promise<string>;
let nodePath: string | undefined;
if (settings.nodePath !== null) {
nodePath = settings.nodePath;
if (!path.isAbsolute(nodePath) && settings.workspaceFolder !== undefined) {
const workspaceFolderPath = getFilePath(settings.workspaceFolder.uri);
if (workspaceFolderPath !== undefined) {
nodePath = path.join(workspaceFolderPath, nodePath);
}
}
}
let moduleResolveWorkingDirectory: string | undefined;
if (!hasUserDefinedWorkingDirectories && filePath !== undefined) {
moduleResolveWorkingDirectory = path.dirname(filePath);
}
if (moduleResolveWorkingDirectory === undefined && settings.workingDirectory !== undefined && !settings.workingDirectory['!cwd']) {
moduleResolveWorkingDirectory = settings.workingDirectory.directory;
}
if (nodePath !== undefined) {
promise = Files.resolve('eslint', nodePath, nodePath, trace).then<string, string>(undefined, () => {
return Files.resolve('eslint', settings.resolvedGlobalPackageManagerPath, moduleResolveWorkingDirectory, trace);
});
} else {
promise = Files.resolve('eslint', settings.resolvedGlobalPackageManagerPath, moduleResolveWorkingDirectory, trace);
}
settings.silent = settings.validate === Validate.probe;
return promise.then((libraryPath) => {
let library = path2Library.get(libraryPath);
if (library === undefined) {
library = loadNodeModule(libraryPath);
if (library === undefined) {
settings.validate = Validate.off;
if (!settings.silent) {
connection.console.error(`Failed to load eslint library from ${libraryPath}. See output panel for more information.`);
}
} else if (library.CLIEngine === undefined) {
settings.validate = Validate.off;
connection.console.error(`The eslint library loaded from ${libraryPath} doesn\'t export a CLIEngine. You need at least [email protected]`);
} else {
connection.console.info(`ESLint library loaded from: ${libraryPath}`);
settings.library = library;
path2Library.set(libraryPath, library);
}
} else {
settings.library = library;
}
if (settings.validate === Validate.probe && TextDocumentSettings.hasLibrary(settings)) {
settings.validate = Validate.off;
const uri: URI = URI.parse(document.uri);
let filePath = getFilePath(document);
if (filePath === undefined && uri.scheme === 'untitled' && settings.workspaceFolder !== undefined) {
const ext = languageId2DefaultExt.get(document.languageId);
const workspacePath = getFilePath(settings.workspaceFolder.uri);
if (workspacePath !== undefined && ext !== undefined) {
filePath = path.join(workspacePath, `test${ext}`);
}
}
if (filePath !== undefined) {
const parserRegExps = languageId2ParserRegExp.get(document.languageId);
const pluginName = languageId2PluginName.get(document.languageId);
const parserOptions = languageId2ParserOptions.get(document.languageId);
if (defaultLanguageIds.has(document.languageId)) {
settings.validate = Validate.on;
} else if (parserRegExps !== undefined || pluginName !== undefined || parserOptions !== undefined) {
const eslintConfig: ESLintConfig | undefined = withCLIEngine((cli) => {
if (typeof cli.getConfigForFile === 'function') {
return cli.getConfigForFile(filePath!);
} else {
return undefined;
}
}, settings);
if (eslintConfig !== undefined) {
const parser: string | undefined = eslintConfig.parser !== null
? (process.platform === 'win32' ? eslintConfig.parser.replace(/\\/g, '/') : eslintConfig.parser)
: undefined;
if (parser !== undefined) {
if (parserRegExps !== undefined) {
for (const regExp of parserRegExps) {
if (regExp.test(parser)) {
settings.validate = Validate.on;
break;
}
}
}
if (settings.validate !== Validate.on && parserOptions !== undefined && typeof eslintConfig.parserOptions?.parser === 'string') {
for (const regExp of parserOptions.regExps) {
if (regExp.test(parser) && parserOptions.parsers.has(eslintConfig.parserOptions.parser)) {
settings.validate = Validate.on;
break;
}
}
}
}
if (settings.validate !== Validate.on && Array.isArray(eslintConfig.plugins) && eslintConfig.plugins.length > 0 && pluginName !== undefined) {
for (const name of eslintConfig.plugins) {
if (name === pluginName) {
settings.validate = Validate.on;
break;
}
}
}
}
}
}
if (settings.validate === Validate.off) {
const params: ProbeFailedParams = { textDocument: { uri: document.uri } };
connection.sendRequest(ProbleFailedRequest.type, params);
}
}
return settings;
}, () => {
settings.validate = Validate.off;
if (!settings.silent) {
connection.sendRequest(NoESLintLibraryRequest.type, { source: { uri: document.uri } });
}
return settings;
});
});
document2Settings.set(uri, resultPromise);
return resultPromise;
}
interface Request<P, R> {
method: string;
params: P;
documentVersion: number | undefined;
resolve: (value: R | Promise<R>) => void | undefined;
reject: (error: any) => void | undefined;
token: CancellationToken;
}
namespace Request {
export function is(value: any): value is Request<any, any> {
const candidate: Request<any, any> = value;
return candidate && candidate.token !== undefined && candidate.resolve !== undefined && candidate.reject !== undefined;
}
}
interface Notification<P> {
method: string;
params: P;
documentVersion: number | undefined;
}
type Message<P, R> = Notification<P> | Request<P, R>;
interface VersionProvider<P> {
(params: P): number | undefined;
}
namespace Thenable {
export function is<T>(value: any): value is Thenable<T> {
const candidate: Thenable<T> = value;
return candidate && typeof candidate.then === 'function';
}
}
class BufferedMessageQueue {
private queue: Message<any, any>[];
private requestHandlers: Map<string, { handler: RequestHandler<any, any, any>, versionProvider?: VersionProvider<any> }>;
private notificationHandlers: Map<string, { handler: NotificationHandler<any>, versionProvider?: VersionProvider<any> }>;
private timer: NodeJS.Immediate | undefined;
constructor(private connection: IConnection) {
this.queue = [];
this.requestHandlers = new Map();
this.notificationHandlers = new Map();
}
public registerRequest<P, R, E, RO>(type: RequestType<P, R, E, RO>, handler: RequestHandler<P, R, E>, versionProvider?: VersionProvider<P>): void {
this.connection.onRequest(type, (params, token) => {
return new Promise<R>((resolve, reject) => {
this.queue.push({
method: type.method,
params: params,
documentVersion: versionProvider ? versionProvider(params) : undefined,
resolve: resolve,
reject: reject,
token: token
});
this.trigger();
});
});
this.requestHandlers.set(type.method, { handler, versionProvider });
}
public registerNotification<P, RO>(type: NotificationType<P, RO>, handler: NotificationHandler<P>, versionProvider?: (params: P) => number): void {
connection.onNotification(type, (params) => {
this.queue.push({
method: type.method,
params: params,
documentVersion: versionProvider ? versionProvider(params) : undefined,
});
this.trigger();
});
this.notificationHandlers.set(type.method, { handler, versionProvider });
}
public addNotificationMessage<P, RO>(type: NotificationType<P, RO>, params: P, version: number) {
this.queue.push({
method: type.method,
params,
documentVersion: version
});
this.trigger();
}
public onNotification<P, RO>(type: NotificationType<P, RO>, handler: NotificationHandler<P>, versionProvider?: (params: P) => number): void {
this.notificationHandlers.set(type.method, { handler, versionProvider });
}
private trigger(): void {
if (this.timer || this.queue.length === 0) {
return;
}
this.timer = setImmediate(() => {
this.timer = undefined;
this.processQueue();
this.trigger();
});
}
private processQueue(): void {
const message = this.queue.shift();
if (!message) {
return;
}
if (Request.is(message)) {
const requestMessage = message;
if (requestMessage.token.isCancellationRequested) {
requestMessage.reject(new ResponseError(ErrorCodes.RequestCancelled, 'Request got cancelled'));
return;
}
const elem = this.requestHandlers.get(requestMessage.method);
if (elem === undefined) {
throw new Error(`No handler registered`);
}
if (elem.versionProvider && requestMessage.documentVersion !== undefined && requestMessage.documentVersion !== elem.versionProvider(requestMessage.params)) {
requestMessage.reject(new ResponseError(ErrorCodes.RequestCancelled, 'Request got cancelled'));
return;
}
const result = elem.handler(requestMessage.params, requestMessage.token);
if (Thenable.is(result)) {
result.then((value) => {
requestMessage.resolve(value);
}, (error) => {
requestMessage.reject(error);
});
} else {
requestMessage.resolve(result);
}
} else {
const notificationMessage = message;
const elem = this.notificationHandlers.get(notificationMessage.method);
if (elem === undefined) {
throw new Error(`No handler registered`);
}
if (elem.versionProvider && notificationMessage.documentVersion !== undefined && notificationMessage.documentVersion !== elem.versionProvider(notificationMessage.params)) {
return;
}
elem.handler(notificationMessage.params);
}
}
}
const messageQueue: BufferedMessageQueue = new BufferedMessageQueue(connection);
const formatterRegistrations: Map<string, Promise<Disposable>> = new Map();
namespace ValidateNotification {
export const type: NotificationType<TextDocument, void> = new NotificationType<TextDocument, void>('eslint/validate');
}
messageQueue.onNotification(ValidateNotification.type, (document) => {
validateSingle(document, true);
}, (document): number => {
return document.version;
});
function setupDocumentsListeners() {
// The documents manager listen for text document create, change
// and close on the connection
documents.listen(connection);
documents.onDidOpen((event) => {
resolveSettings(event.document).then((settings) => {
if (settings.validate !== Validate.on || !TextDocumentSettings.hasLibrary(settings)) {
return;
}
if (settings.format) {
const uri = URI.parse(event.document.uri);
const isFile = uri.scheme === 'file';
const filter: DocumentFilter = isFile
? { scheme: uri.scheme, pattern: uri.fsPath.replace(/\\/g, '/') }
: { scheme: uri.scheme, pattern: uri.path };
const options: DocumentFormattingRegistrationOptions = { documentSelector: [filter] };