-
Notifications
You must be signed in to change notification settings - Fork 12.6k
/
editorServices.ts
1810 lines (1588 loc) · 85.7 KB
/
editorServices.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
/// <reference path="..\compiler\commandLineParser.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="utilities.ts" />
/// <reference path="session.ts" />
/// <reference path="scriptVersionCache.ts"/>
/// <reference path="lsHost.ts"/>
/// <reference path="project.ts"/>
/// <reference path="typingsCache.ts"/>
namespace ts.server {
export const maxProgramSizeForNonTsFiles = 20 * 1024 * 1024;
export const ContextEvent = "context";
export const ConfigFileDiagEvent = "configFileDiag";
export const ProjectLanguageServiceStateEvent = "projectLanguageServiceState";
export const ProjectInfoTelemetryEvent = "projectInfo";
export interface ContextEvent {
eventName: typeof ContextEvent;
data: { project: Project; fileName: NormalizedPath };
}
export interface ConfigFileDiagEvent {
eventName: typeof ConfigFileDiagEvent;
data: { triggerFile: string, configFileName: string, diagnostics: ReadonlyArray<Diagnostic> };
}
export interface ProjectLanguageServiceStateEvent {
eventName: typeof ProjectLanguageServiceStateEvent;
data: { project: Project, languageServiceEnabled: boolean };
}
/** This will be converted to the payload of a protocol.TelemetryEvent in session.defaultEventHandler. */
export interface ProjectInfoTelemetryEvent {
readonly eventName: typeof ProjectInfoTelemetryEvent;
readonly data: ProjectInfoTelemetryEventData;
}
export interface ProjectInfoTelemetryEventData {
/** Cryptographically secure hash of project file location. */
readonly projectId: string;
/** Count of file extensions seen in the project. */
readonly fileStats: FileStats;
/**
* Any compiler options that might contain paths will be taken out.
* Enum compiler options will be converted to strings.
*/
readonly compilerOptions: CompilerOptions;
// "extends", "files", "include", or "exclude" will be undefined if an external config is used.
// Otherwise, we will use "true" if the property is present and "false" if it is missing.
readonly extends: boolean | undefined;
readonly files: boolean | undefined;
readonly include: boolean | undefined;
readonly exclude: boolean | undefined;
readonly compileOnSave: boolean;
readonly typeAcquisition: ProjectInfoTypeAcquisitionData;
readonly configFileName: "tsconfig.json" | "jsconfig.json" | "other";
readonly projectType: "external" | "configured";
readonly languageServiceEnabled: boolean;
/** TypeScript version used by the server. */
readonly version: string;
}
export interface ProjectInfoTypeAcquisitionData {
readonly enable: boolean;
// Actual values of include/exclude entries are scrubbed.
readonly include: boolean;
readonly exclude: boolean;
}
export interface FileStats {
readonly js: number;
readonly jsx: number;
readonly ts: number;
readonly tsx: number;
readonly dts: number;
}
export type ProjectServiceEvent = ContextEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent;
export interface ProjectServiceEventHandler {
(event: ProjectServiceEvent): void;
}
export interface SafeList {
[name: string]: { match: RegExp, exclude?: Array<Array<string | number>>, types?: string[] };
}
function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions: CommandLineOption[]): Map<Map<number>> {
const map: Map<Map<number>> = createMap<Map<number>>();
for (const option of commandLineOptions) {
if (typeof option.type === "object") {
const optionMap = <Map<number>>option.type;
// verify that map contains only numbers
optionMap.forEach(value => {
Debug.assert(typeof value === "number");
});
map.set(option.name, optionMap);
}
}
return map;
}
const compilerOptionConverters = prepareConvertersForEnumLikeCompilerOptions(optionDeclarations);
const indentStyle = createMapFromTemplate({
"none": IndentStyle.None,
"block": IndentStyle.Block,
"smart": IndentStyle.Smart
});
/**
* How to understand this block:
* * The 'match' property is a regexp that matches a filename.
* * If 'match' is successful, then:
* * All files from 'exclude' are removed from the project. See below.
* * All 'types' are included in ATA
* * What the heck is 'exclude' ?
* * An array of an array of strings and numbers
* * Each array is:
* * An array of strings and numbers
* * The strings are literals
* * The numbers refer to capture group indices from the 'match' regexp
* * Remember that '1' is the first group
* * These are concatenated together to form a new regexp
* * Filenames matching these regexps are excluded from the project
* This default value is tested in tsserverProjectSystem.ts; add tests there
* if you are changing this so that you can be sure your regexp works!
*/
const defaultTypeSafeList: SafeList = {
"jquery": {
// jquery files can have names like "jquery-1.10.2.min.js" (or "jquery.intellisense.js")
"match": /jquery(-(\.?\d+)+)?(\.intellisense)?(\.min)?\.js$/i,
"types": ["jquery"]
},
"WinJS": {
// e.g. c:/temp/UWApp1/lib/winjs-4.0.1/js/base.js
"match": /^(.*\/winjs-[.\d]+)\/js\/base\.js$/i, // If the winjs/base.js file is found..
"exclude": [["^", 1, "/.*"]], // ..then exclude all files under the winjs folder
"types": ["winjs"] // And fetch the @types package for WinJS
},
"Kendo": {
// e.g. /Kendo3/wwwroot/lib/kendo/kendo.all.min.js
"match": /^(.*\/kendo)\/kendo\.all\.min\.js$/i,
"exclude": [["^", 1, "/.*"]],
"types": ["kendo-ui"]
},
"Office Nuget": {
// e.g. /scripts/Office/1/excel-15.debug.js
"match": /^(.*\/office\/1)\/excel-\d+\.debug\.js$/i, // Office NuGet package is installed under a "1/office" folder
"exclude": [["^", 1, "/.*"]], // Exclude that whole folder if the file indicated above is found in it
"types": ["office"] // @types package to fetch instead
},
"Minified files": {
// e.g. /whatever/blah.min.js
"match": /^(.+\.min\.js)$/i,
"exclude": [["^", 1, "$"]]
}
};
export function convertFormatOptions(protocolOptions: protocol.FormatCodeSettings): FormatCodeSettings {
if (typeof protocolOptions.indentStyle === "string") {
protocolOptions.indentStyle = indentStyle.get(protocolOptions.indentStyle.toLowerCase());
Debug.assert(protocolOptions.indentStyle !== undefined);
}
return <any>protocolOptions;
}
export function convertCompilerOptions(protocolOptions: protocol.ExternalProjectCompilerOptions): CompilerOptions & protocol.CompileOnSaveMixin {
compilerOptionConverters.forEach((mappedValues, id) => {
const propertyValue = protocolOptions[id];
if (typeof propertyValue === "string") {
protocolOptions[id] = mappedValues.get(propertyValue.toLowerCase());
}
});
return <any>protocolOptions;
}
export function tryConvertScriptKindName(scriptKindName: protocol.ScriptKindName | ScriptKind): ScriptKind {
return typeof scriptKindName === "string"
? convertScriptKindName(scriptKindName)
: scriptKindName;
}
export function convertScriptKindName(scriptKindName: protocol.ScriptKindName) {
switch (scriptKindName) {
case "JS":
return ScriptKind.JS;
case "JSX":
return ScriptKind.JSX;
case "TS":
return ScriptKind.TS;
case "TSX":
return ScriptKind.TSX;
default:
return ScriptKind.Unknown;
}
}
/**
* This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project.
*/
export function combineProjectOutput<T>(projects: ReadonlyArray<Project>, action: (project: Project) => ReadonlyArray<T>, comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean) {
const result = flatMap(projects, action).sort(comparer);
return projects.length > 1 ? deduplicate(result, areEqual) : result;
}
export interface HostConfiguration {
formatCodeOptions: FormatCodeSettings;
hostInfo: string;
extraFileExtensions?: JsFileExtensionInfo[];
}
interface ConfigFileConversionResult {
success: boolean;
configFileErrors?: Diagnostic[];
projectOptions?: ProjectOptions;
}
interface OpenConfigFileResult {
success: boolean;
errors?: ReadonlyArray<Diagnostic>;
project?: ConfiguredProject;
}
export interface OpenConfiguredProjectResult {
configFileName?: NormalizedPath;
configFileErrors?: ReadonlyArray<Diagnostic>;
}
interface FilePropertyReader<T> {
getFileName(f: T): string;
getScriptKind(f: T): ScriptKind;
hasMixedContent(f: T, extraFileExtensions: JsFileExtensionInfo[]): boolean;
}
const fileNamePropertyReader: FilePropertyReader<string> = {
getFileName: x => x,
getScriptKind: _ => undefined,
hasMixedContent: (fileName, extraFileExtensions) => some(extraFileExtensions, ext => ext.isMixedContent && fileExtensionIs(fileName, ext.extension)),
};
const externalFilePropertyReader: FilePropertyReader<protocol.ExternalFile> = {
getFileName: x => x.fileName,
getScriptKind: x => tryConvertScriptKindName(x.scriptKind),
hasMixedContent: x => x.hasMixedContent
};
function findProjectByName<T extends Project>(projectName: string, projects: T[]): T {
for (const proj of projects) {
if (proj.getProjectName() === projectName) {
return proj;
}
}
}
function createFileNotFoundDiagnostic(fileName: string) {
return createCompilerDiagnostic(Diagnostics.File_0_not_found, fileName);
}
/**
* TODO: enforce invariants:
* - script info can be never migrate to state - root file in inferred project, this is only a starting point
* - if script info has more that one containing projects - it is not a root file in inferred project because:
* - references in inferred project supercede the root part
* - root/reference in non-inferred project beats root in inferred project
*/
function isRootFileInInferredProject(info: ScriptInfo): boolean {
if (info.containingProjects.length === 0) {
return false;
}
return info.containingProjects[0].projectKind === ProjectKind.Inferred && info.containingProjects[0].isRoot(info);
}
class DirectoryWatchers {
/**
* a path to directory watcher map that detects added tsconfig files
*/
private readonly directoryWatchersForTsconfig: Map<FileWatcher> = createMap<FileWatcher>();
/**
* count of how many projects are using the directory watcher.
* If the number becomes 0 for a watcher, then we should close it.
*/
private readonly directoryWatchersRefCount: Map<number> = createMap<number>();
constructor(private readonly projectService: ProjectService) {
}
stopWatchingDirectory(directory: string) {
// if the ref count for this directory watcher drops to 0, it's time to close it
const refCount = this.directoryWatchersRefCount.get(directory) - 1;
this.directoryWatchersRefCount.set(directory, refCount);
if (refCount === 0) {
this.projectService.logger.info(`Close directory watcher for: ${directory}`);
this.directoryWatchersForTsconfig.get(directory).close();
this.directoryWatchersForTsconfig.delete(directory);
}
}
startWatchingContainingDirectoriesForFile(fileName: string, project: InferredProject, callback: (fileName: string) => void) {
let currentPath = getDirectoryPath(fileName);
let parentPath = getDirectoryPath(currentPath);
while (currentPath !== parentPath) {
if (!this.directoryWatchersForTsconfig.has(currentPath)) {
this.projectService.logger.info(`Add watcher for: ${currentPath}`);
this.directoryWatchersForTsconfig.set(currentPath, this.projectService.host.watchDirectory(currentPath, callback));
this.directoryWatchersRefCount.set(currentPath, 1);
}
else {
this.directoryWatchersRefCount.set(currentPath, this.directoryWatchersRefCount.get(currentPath) + 1);
}
project.directoriesWatchedForTsconfig.push(currentPath);
currentPath = parentPath;
parentPath = getDirectoryPath(parentPath);
}
}
}
export interface ProjectServiceOptions {
host: ServerHost;
logger: Logger;
cancellationToken: HostCancellationToken;
useSingleInferredProject: boolean;
typingsInstaller: ITypingsInstaller;
eventHandler?: ProjectServiceEventHandler;
throttleWaitMilliseconds?: number;
globalPlugins?: ReadonlyArray<string>;
pluginProbeLocations?: ReadonlyArray<string>;
allowLocalPluginLoads?: boolean;
}
export class ProjectService {
public readonly typingsCache: TypingsCache;
private readonly documentRegistry: DocumentRegistry;
/**
* Container of all known scripts
*/
private readonly filenameToScriptInfo = createMap<ScriptInfo>();
/**
* maps external project file name to list of config files that were the part of this project
*/
private readonly externalProjectToConfiguredProjectMap: Map<NormalizedPath[]> = createMap<NormalizedPath[]>();
/**
* external projects (configuration and list of root files is not controlled by tsserver)
*/
readonly externalProjects: ExternalProject[] = [];
/**
* projects built from openFileRoots
*/
readonly inferredProjects: InferredProject[] = [];
/**
* projects specified by a tsconfig.json file
*/
readonly configuredProjects: ConfiguredProject[] = [];
/**
* list of open files
*/
readonly openFiles: ScriptInfo[] = [];
private compilerOptionsForInferredProjects: CompilerOptions;
private compileOnSaveForInferredProjects: boolean;
private readonly projectToSizeMap: Map<number> = createMap<number>();
private readonly directoryWatchers: DirectoryWatchers;
private readonly throttledOperations: ThrottledOperations;
private readonly hostConfiguration: HostConfiguration;
private safelist: SafeList = defaultTypeSafeList;
private changedFiles: ScriptInfo[];
readonly toCanonicalFileName: (f: string) => string;
public lastDeletedFile: ScriptInfo;
public readonly host: ServerHost;
public readonly logger: Logger;
public readonly cancellationToken: HostCancellationToken;
public readonly useSingleInferredProject: boolean;
public readonly typingsInstaller: ITypingsInstaller;
public readonly throttleWaitMilliseconds?: number;
private readonly eventHandler?: ProjectServiceEventHandler;
public readonly globalPlugins: ReadonlyArray<string>;
public readonly pluginProbeLocations: ReadonlyArray<string>;
public readonly allowLocalPluginLoads: boolean;
/** Tracks projects that we have already sent telemetry for. */
private readonly seenProjects = createMap<true>();
constructor(opts: ProjectServiceOptions) {
this.host = opts.host;
this.logger = opts.logger;
this.cancellationToken = opts.cancellationToken;
this.useSingleInferredProject = opts.useSingleInferredProject;
this.typingsInstaller = opts.typingsInstaller || nullTypingsInstaller;
this.throttleWaitMilliseconds = opts.throttleWaitMilliseconds;
this.eventHandler = opts.eventHandler;
this.globalPlugins = opts.globalPlugins || emptyArray;
this.pluginProbeLocations = opts.pluginProbeLocations || emptyArray;
this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads;
Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService");
this.toCanonicalFileName = createGetCanonicalFileName(this.host.useCaseSensitiveFileNames);
this.directoryWatchers = new DirectoryWatchers(this);
this.throttledOperations = new ThrottledOperations(this.host);
this.typingsInstaller.attach(this);
this.typingsCache = new TypingsCache(this.typingsInstaller);
this.hostConfiguration = {
formatCodeOptions: getDefaultFormatCodeSettings(this.host),
hostInfo: "Unknown host",
extraFileExtensions: []
};
this.documentRegistry = createDocumentRegistry(this.host.useCaseSensitiveFileNames, this.host.getCurrentDirectory());
}
/* @internal */
getChangedFiles_TestOnly() {
return this.changedFiles;
}
ensureInferredProjectsUpToDate_TestOnly() {
this.ensureInferredProjectsUpToDate();
}
getCompilerOptionsForInferredProjects() {
return this.compilerOptionsForInferredProjects;
}
onUpdateLanguageServiceStateForProject(project: Project, languageServiceEnabled: boolean) {
if (!this.eventHandler) {
return;
}
this.eventHandler(<ProjectLanguageServiceStateEvent>{
eventName: ProjectLanguageServiceStateEvent,
data: { project, languageServiceEnabled }
});
}
updateTypingsForProject(response: SetTypings | InvalidateCachedTypings): void {
const project = this.findProject(response.projectName);
if (!project) {
return;
}
switch (response.kind) {
case ActionSet:
this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typeAcquisition, response.unresolvedImports, response.typings);
break;
case ActionInvalidate:
this.typingsCache.deleteTypingsForProject(response.projectName);
break;
}
project.updateGraph();
}
setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions): void {
this.compilerOptionsForInferredProjects = convertCompilerOptions(projectCompilerOptions);
// always set 'allowNonTsExtensions' for inferred projects since user cannot configure it from the outside
// previously we did not expose a way for user to change these settings and this option was enabled by default
this.compilerOptionsForInferredProjects.allowNonTsExtensions = true;
this.compileOnSaveForInferredProjects = projectCompilerOptions.compileOnSave;
for (const proj of this.inferredProjects) {
proj.setCompilerOptions(this.compilerOptionsForInferredProjects);
proj.compileOnSaveEnabled = projectCompilerOptions.compileOnSave;
}
this.updateProjectGraphs(this.inferredProjects);
}
stopWatchingDirectory(directory: string) {
this.directoryWatchers.stopWatchingDirectory(directory);
}
findProject(projectName: string): Project {
if (projectName === undefined) {
return undefined;
}
if (isInferredProjectName(projectName)) {
this.ensureInferredProjectsUpToDate();
return findProjectByName(projectName, this.inferredProjects);
}
return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(toNormalizedPath(projectName));
}
getDefaultProjectForFile(fileName: NormalizedPath, refreshInferredProjects: boolean) {
if (refreshInferredProjects) {
this.ensureInferredProjectsUpToDate();
}
const scriptInfo = this.getScriptInfoForNormalizedPath(fileName);
return scriptInfo && scriptInfo.getDefaultProject();
}
private ensureInferredProjectsUpToDate() {
if (this.changedFiles) {
let projectsToUpdate: Project[];
if (this.changedFiles.length === 1) {
// simpliest case - no allocations
projectsToUpdate = this.changedFiles[0].containingProjects;
}
else {
projectsToUpdate = [];
for (const f of this.changedFiles) {
projectsToUpdate = projectsToUpdate.concat(f.containingProjects);
}
}
this.updateProjectGraphs(projectsToUpdate);
this.changedFiles = undefined;
}
}
private findContainingExternalProject(fileName: NormalizedPath): ExternalProject {
for (const proj of this.externalProjects) {
if (proj.containsFile(fileName)) {
return proj;
}
}
return undefined;
}
getFormatCodeOptions(file?: NormalizedPath) {
let formatCodeSettings: FormatCodeSettings;
if (file) {
const info = this.getScriptInfoForNormalizedPath(file);
if (info) {
formatCodeSettings = info.getFormatCodeSettings();
}
}
return formatCodeSettings || this.hostConfiguration.formatCodeOptions;
}
private updateProjectGraphs(projects: Project[]) {
let shouldRefreshInferredProjects = false;
for (const p of projects) {
if (!p.updateGraph()) {
shouldRefreshInferredProjects = true;
}
}
if (shouldRefreshInferredProjects) {
this.refreshInferredProjects();
}
}
private onSourceFileChanged(fileName: NormalizedPath) {
const info = this.getScriptInfoForNormalizedPath(fileName);
if (!info) {
this.logger.info(`Error: got watch notification for unknown file: ${fileName}`);
return;
}
if (!this.host.fileExists(fileName)) {
// File was deleted
this.handleDeletedFile(info);
}
else {
if (info && (!info.isScriptOpen())) {
if (info.containingProjects.length === 0) {
// Orphan script info, remove it as we can always reload it on next open
info.stopWatcher();
this.filenameToScriptInfo.delete(info.path);
}
else {
// file has been changed which might affect the set of referenced files in projects that include
// this file and set of inferred projects
info.reloadFromFile();
this.updateProjectGraphs(info.containingProjects);
}
}
}
}
private handleDeletedFile(info: ScriptInfo) {
this.logger.info(`${info.fileName} deleted`);
info.stopWatcher();
// TODO: handle isOpen = true case
if (!info.isScriptOpen()) {
this.filenameToScriptInfo.delete(info.path);
this.lastDeletedFile = info;
// capture list of projects since detachAllProjects will wipe out original list
const containingProjects = info.containingProjects.slice();
info.detachAllProjects();
// update projects to make sure that set of referenced files is correct
this.updateProjectGraphs(containingProjects);
this.lastDeletedFile = undefined;
if (!this.eventHandler) {
return;
}
for (const openFile of this.openFiles) {
this.eventHandler(<ContextEvent>{
eventName: ContextEvent,
data: { project: openFile.getDefaultProject(), fileName: openFile.fileName }
});
}
}
this.printProjects();
}
private onTypeRootFileChanged(project: ConfiguredProject, fileName: string) {
this.logger.info(`Type root file ${fileName} changed`);
this.throttledOperations.schedule(project.getConfigFilePath() + " * type root", /*delay*/ 250, () => {
project.updateTypes();
this.updateConfiguredProject(project); // TODO: Figure out why this is needed (should be redundant?)
this.refreshInferredProjects();
});
}
/**
* This is the callback function when a watched directory has added or removed source code files.
* @param project the project that associates with this directory watcher
* @param fileName the absolute file name that changed in watched directory
*/
private onSourceFileInDirectoryChangedForConfiguredProject(project: ConfiguredProject, fileName: string) {
// If a change was made inside "folder/file", node will trigger the callback twice:
// one with the fileName being "folder/file", and the other one with "folder".
// We don't respond to the second one.
if (fileName && !isSupportedSourceFileName(fileName, project.getCompilerOptions(), this.hostConfiguration.extraFileExtensions)) {
return;
}
this.logger.info(`Detected source file changes: ${fileName}`);
this.throttledOperations.schedule(
project.getConfigFilePath(),
/*delay*/250,
() => this.handleChangeInSourceFileForConfiguredProject(project, fileName));
}
private handleChangeInSourceFileForConfiguredProject(project: ConfiguredProject, triggerFile: string) {
const { projectOptions, configFileErrors } = this.convertConfigFileContentToProjectOptions(project.getConfigFilePath());
this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors, triggerFile);
const newRootFiles = projectOptions.files.map((f => this.getCanonicalFileName(f)));
const currentRootFiles = project.getRootFiles().map((f => this.getCanonicalFileName(f)));
// We check if the project file list has changed. If so, we update the project.
if (!arrayIsEqualTo(currentRootFiles.sort(), newRootFiles.sort())) {
// For configured projects, the change is made outside the tsconfig file, and
// it is not likely to affect the project for other files opened by the client. We can
// just update the current project.
this.logger.info("Updating configured project");
this.updateConfiguredProject(project);
// Call refreshInferredProjects to clean up inferred projects we may have
// created for the new files
this.refreshInferredProjects();
}
}
private onConfigChangedForConfiguredProject(project: ConfiguredProject) {
const configFileName = project.getConfigFilePath();
this.logger.info(`Config file changed: ${configFileName}`);
const configFileErrors = this.updateConfiguredProject(project);
this.reportConfigFileDiagnostics(configFileName, configFileErrors, /*triggerFile*/ configFileName);
this.refreshInferredProjects();
}
/**
* This is the callback function when a watched directory has an added tsconfig file.
*/
private onConfigFileAddedForInferredProject(fileName: string) {
// TODO: check directory separators
if (getBaseFileName(fileName) !== "tsconfig.json") {
this.logger.info(`${fileName} is not tsconfig.json`);
return;
}
const { configFileErrors } = this.convertConfigFileContentToProjectOptions(fileName);
this.reportConfigFileDiagnostics(fileName, configFileErrors, fileName);
this.logger.info(`Detected newly added tsconfig file: ${fileName}`);
this.reloadProjects();
}
private getCanonicalFileName(fileName: string) {
const name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
return normalizePath(name);
}
private removeProject(project: Project) {
this.logger.info(`remove project: ${project.getRootFiles().toString()}`);
project.close();
switch (project.projectKind) {
case ProjectKind.External:
unorderedRemoveItem(this.externalProjects, <ExternalProject>project);
this.projectToSizeMap.delete((project as ExternalProject).externalProjectName);
break;
case ProjectKind.Configured:
unorderedRemoveItem(this.configuredProjects, <ConfiguredProject>project);
this.projectToSizeMap.delete((project as ConfiguredProject).canonicalConfigFilePath);
break;
case ProjectKind.Inferred:
unorderedRemoveItem(this.inferredProjects, <InferredProject>project);
break;
}
}
private assignScriptInfoToInferredProjectIfNecessary(info: ScriptInfo, addToListOfOpenFiles: boolean): void {
const externalProject = this.findContainingExternalProject(info.fileName);
if (externalProject) {
// file is already included in some external project - do nothing
if (addToListOfOpenFiles) {
this.openFiles.push(info);
}
return;
}
let foundConfiguredProject = false;
for (const p of info.containingProjects) {
// file is the part of configured project
if (p.projectKind === ProjectKind.Configured) {
foundConfiguredProject = true;
if (addToListOfOpenFiles) {
((<ConfiguredProject>p)).addOpenRef();
}
}
}
if (foundConfiguredProject) {
if (addToListOfOpenFiles) {
this.openFiles.push(info);
}
return;
}
if (info.containingProjects.length === 0) {
// create new inferred project p with the newly opened file as root
// or add root to existing inferred project if 'useOneInferredProject' is true
const inferredProject = this.createInferredProjectWithRootFileIfNecessary(info);
if (!this.useSingleInferredProject) {
// if useOneInferredProject is not set then try to fixup ownership of open files
// check 'defaultProject !== inferredProject' is necessary to handle cases
// when creation inferred project for some file has added other open files into this project (i.e. as referenced files)
// we definitely don't want to delete the project that was just created
for (const f of this.openFiles) {
if (f.containingProjects.length === 0 || !inferredProject.containsScriptInfo(f)) {
// this is orphaned file that we have not processed yet - skip it
continue;
}
for (const fContainingProject of f.containingProjects) {
if (fContainingProject.projectKind === ProjectKind.Inferred &&
fContainingProject.isRoot(f) &&
fContainingProject !== inferredProject) {
// open file used to be root in inferred project,
// this inferred project is different from the one we've just created for current file
// and new inferred project references this open file.
// We should delete old inferred project and attach open file to the new one
this.removeProject(fContainingProject);
f.attachToProject(inferredProject);
}
}
}
}
}
if (addToListOfOpenFiles) {
this.openFiles.push(info);
}
}
/**
* Remove this file from the set of open, non-configured files.
* @param info The file that has been closed or newly configured
*/
private closeOpenFile(info: ScriptInfo): void {
// Closing file should trigger re-reading the file content from disk. This is
// because the user may chose to discard the buffer content before saving
// to the disk, and the server's version of the file can be out of sync.
info.close();
unorderedRemoveItem(this.openFiles, info);
// collect all projects that should be removed
let projectsToRemove: Project[];
for (const p of info.containingProjects) {
if (p.projectKind === ProjectKind.Configured) {
if (info.hasMixedContent) {
info.registerFileUpdate();
}
// last open file in configured project - close it
if ((<ConfiguredProject>p).deleteOpenRef() === 0) {
(projectsToRemove || (projectsToRemove = [])).push(p);
}
}
else if (p.projectKind === ProjectKind.Inferred && p.isRoot(info)) {
// open file in inferred project
(projectsToRemove || (projectsToRemove = [])).push(p);
}
if (!p.languageServiceEnabled) {
// if project language service is disabled then we create a program only for open files.
// this means that project should be marked as dirty to force rebuilding of the program
// on the next request
p.markAsDirty();
}
}
if (projectsToRemove) {
for (const project of projectsToRemove) {
this.removeProject(project);
}
let orphanFiles: ScriptInfo[];
// for all open files
for (const f of this.openFiles) {
// collect orphanted files and try to re-add them as newly opened
if (f.containingProjects.length === 0) {
(orphanFiles || (orphanFiles = [])).push(f);
}
}
// treat orphaned files as newly opened
if (orphanFiles) {
for (const f of orphanFiles) {
this.assignScriptInfoToInferredProjectIfNecessary(f, /*addToListOfOpenFiles*/ false);
}
}
// Cleanup script infos that arent part of any project is postponed to
// next file open so that if file from same project is opened we wont end up creating same script infos
}
// If the current info is being just closed - add the watcher file to track changes
// But if file was deleted, handle that part
if (this.host.fileExists(info.fileName)) {
this.watchClosedScriptInfo(info);
}
else {
this.handleDeletedFile(info);
}
}
private deleteOrphanScriptInfoNotInAnyProject() {
this.filenameToScriptInfo.forEach(info => {
if (!info.isScriptOpen() && info.containingProjects.length === 0) {
// if there are not projects that include this script info - delete it
info.stopWatcher();
this.filenameToScriptInfo.delete(info.path);
}
});
}
/**
* This function tries to search for a tsconfig.json for the given file. If we found it,
* we first detect if there is already a configured project created for it: if so, we re-read
* the tsconfig file content and update the project; otherwise we create a new one.
*/
private openOrUpdateConfiguredProjectForFile(fileName: NormalizedPath, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult {
const searchPath = getDirectoryPath(fileName);
this.logger.info(`Search path: ${searchPath}`);
// check if this file is already included in one of external projects
const configFileName = this.findConfigFile(asNormalizedPath(searchPath), projectRootPath);
if (!configFileName) {
this.logger.info("No config files found.");
return {};
}
this.logger.info(`Config file name: ${configFileName}`);
const project = this.findConfiguredProjectByProjectName(configFileName);
if (!project) {
const { success, errors } = this.openConfigFile(configFileName, fileName);
if (!success) {
return { configFileName, configFileErrors: errors };
}
// even if opening config file was successful, it could still
// contain errors that were tolerated.
this.logger.info(`Opened configuration file ${configFileName}`);
if (errors && errors.length > 0) {
return { configFileName, configFileErrors: errors };
}
}
else {
this.updateConfiguredProject(project);
}
return { configFileName };
}
// This is different from the method the compiler uses because
// the compiler can assume it will always start searching in the
// current directory (the directory in which tsc was invoked).
// The server must start searching from the directory containing
// the newly opened file.
private findConfigFile(searchPath: NormalizedPath, projectRootPath?: NormalizedPath): NormalizedPath {
while (!projectRootPath || searchPath.indexOf(projectRootPath) >= 0) {
const tsconfigFileName = asNormalizedPath(combinePaths(searchPath, "tsconfig.json"));
if (this.host.fileExists(tsconfigFileName)) {
return tsconfigFileName;
}
const jsconfigFileName = asNormalizedPath(combinePaths(searchPath, "jsconfig.json"));
if (this.host.fileExists(jsconfigFileName)) {
return jsconfigFileName;
}
const parentPath = asNormalizedPath(getDirectoryPath(searchPath));
if (parentPath === searchPath) {
break;
}
searchPath = parentPath;
}
return undefined;
}
private printProjects() {
if (!this.logger.hasLevel(LogLevel.verbose)) {
return;
}
this.logger.group(info => {
let counter = 0;
counter = printProjects(this.externalProjects, info, counter);
counter = printProjects(this.configuredProjects, info, counter);
printProjects(this.inferredProjects, info, counter);
info("Open files: ");
for (const rootFile of this.openFiles) {
info(`\t${rootFile.fileName}`);
}
});
function printProjects(projects: Project[], info: (msg: string) => void, counter: number): number {
for (const project of projects) {
project.updateGraph();
info(`Project '${project.getProjectName()}' (${ProjectKind[project.projectKind]}) ${counter}`);
info(project.filesToString());
info("-----------------------------------------------");
counter++;
}
return counter;
}
}
private findConfiguredProjectByProjectName(configFileName: NormalizedPath) {
// make sure that casing of config file name is consistent
configFileName = asNormalizedPath(this.toCanonicalFileName(configFileName));
for (const proj of this.configuredProjects) {
if (proj.canonicalConfigFilePath === configFileName) {
return proj;
}
}
}
private findExternalProjectByProjectName(projectFileName: string) {
return findProjectByName(projectFileName, this.externalProjects);
}
private convertConfigFileContentToProjectOptions(configFilename: string): ConfigFileConversionResult {
configFilename = normalizePath(configFilename);
const configFileContent = this.host.readFile(configFilename);
const result = parseJsonText(configFilename, configFileContent);
if (!result.endOfFileToken) {
result.endOfFileToken = <EndOfFileToken>{ kind: SyntaxKind.EndOfFileToken };
}
const errors = result.parseDiagnostics;
const parsedCommandLine = parseJsonSourceFileConfigFileContent(
result,
this.host,
getDirectoryPath(configFilename),
/*existingOptions*/ {},
configFilename,
/*resolutionStack*/[],
this.hostConfiguration.extraFileExtensions);
if (parsedCommandLine.errors.length) {
errors.push(...parsedCommandLine.errors);
}
Debug.assert(!!parsedCommandLine.fileNames);
if (parsedCommandLine.fileNames.length === 0) {
errors.push(createCompilerDiagnostic(Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename));
return { success: false, configFileErrors: errors };
}
const projectOptions: ProjectOptions = {
files: parsedCommandLine.fileNames,