-
Notifications
You must be signed in to change notification settings - Fork 12.6k
/
editorServices.ts
5722 lines (5211 loc) · 263 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
import {
addToSeen,
arrayFrom,
AssertionLevel,
CachedDirectoryStructureHost,
canWatchDirectoryOrFilePath,
cleanExtendedConfigCache,
clearMap,
clearSharedExtendedConfigFileWatcher,
closeFileWatcherOf,
combinePaths,
CommandLineOption,
CompilerOptions,
CompletionInfo,
contains,
containsPath,
convertCompilerOptionsForTelemetry,
convertJsonOption,
createCachedDirectoryStructureHost,
createDocumentRegistryInternal,
createGetCanonicalFileName,
createMultiMap,
Debug,
Diagnostic,
directorySeparator,
DirectoryStructureHost,
DirectoryWatcherCallback,
DocumentPosition,
DocumentPositionMapper,
DocumentRegistry,
DocumentRegistryBucketKeyWithMode,
emptyOptions,
endsWith,
ensureTrailingDirectorySeparator,
equateStringsCaseInsensitive,
equateStringsCaseSensitive,
ExtendedConfigCacheEntry,
FileExtensionInfo,
fileExtensionIs,
FileWatcher,
FileWatcherCallback,
FileWatcherEventKind,
find,
forEach,
forEachAncestorDirectoryStoppingAtGlobalCache,
forEachEntry,
forEachKey,
forEachResolvedProjectReference,
FormatCodeSettings,
getAnyExtensionFromPath,
getBaseFileName,
getDefaultFormatCodeSettings,
getDirectoryPath,
getDocumentPositionMapper,
getFileNamesFromConfigSpecs,
getFileWatcherEventKind,
getNormalizedAbsolutePath,
getPatternFromSpec,
getRegexFromPattern,
getSnapshotText,
getWatchFactory,
handleWatchOptionsConfigDirTemplateSubstitution,
hasExtension,
hasProperty,
hasTSFileExtension,
HostCancellationToken,
identity,
IncompleteCompletionsCache,
IndentStyle,
isArray,
isExternalModuleNameRelative,
isIgnoredFileFromWildCardWatching,
isInsideNodeModules,
isJsonEqual,
isNodeModulesDirectory,
isRootedDiskPath,
isSolutionConfig,
isString,
isSupportedSourceFileName,
JSDocParsingMode,
LanguageServiceMode,
length,
map,
mapDefinedIterator,
matchesExcludeWorker,
memoize,
missingFileModifiedTime,
MultiMap,
noop,
normalizeSlashes,
notImplemented,
optionDeclarations,
optionsForWatch,
orderedRemoveItem,
PackageJsonAutoImportPreference,
ParsedCommandLine,
parseJsonSourceFileConfigFileContent,
parseJsonText,
Path,
PerformanceEvent,
PluginImport,
PollingInterval,
ProgramUpdateLevel,
ProjectPackageJsonInfo,
ProjectReference,
ReadMapFile,
ReadonlyCollection,
removeFileExtension,
removeIgnoredPath,
removeMinAndVersionNumbers,
ResolvedProjectReference,
resolveProjectReferencePath,
returnFalse,
returnNoopFileWatcher,
ScriptKind,
SharedExtendedConfigFileWatcher,
some,
SourceFile,
SourceFileLike,
startsWith,
Ternary,
TextChange,
toFileNameLowerCase,
toPath,
tracing,
tryAddToSet,
tryReadFile,
TsConfigSourceFile,
TypeAcquisition,
typeAcquisitionDeclarations,
unorderedRemoveItem,
updateSharedExtendedConfigFileWatcher,
updateWatchingWildcardDirectories,
UserPreferences,
version,
WatchDirectoryFlags,
WatchFactory,
WatchFactoryHost,
WatchLogLevel,
WatchOptions,
WatchType,
WildcardDirectoryWatcher,
} from "./_namespaces/ts.js";
import {
ActionInvalidate,
ActionSet,
asNormalizedPath,
AutoImportProviderProject,
AuxiliaryProject,
BeginEnablePluginResult,
BeginInstallTypes,
ConfiguredProject,
countEachFileTypes,
createPackageJsonCache,
emptyArray,
EndInstallTypes,
Errors,
ExternalProject,
getBaseConfigFileName,
hasNoTypeScriptSource,
InferredProject,
InvalidateCachedTypings,
isBackgroundProject,
isConfiguredProject,
isDynamicFileName,
isExternalProject,
isInferredProject,
isInferredProjectName,
isProjectDeferredClose,
ITypingsInstaller,
Logger,
LogLevel,
makeAutoImportProviderProjectName,
makeAuxiliaryProjectName,
makeInferredProjectName,
Msg,
NormalizedPath,
normalizedPathToPath,
PackageInstalledResponse,
PackageJsonCache,
Project,
ProjectFilesWithTSDiagnostics,
ProjectKind,
ProjectOptions,
ScriptInfo,
scriptInfoIsContainedByBackgroundProject,
scriptInfoIsContainedByDeferredClosedProject,
ServerHost,
Session,
SetTypings,
ThrottledOperations,
toNormalizedPath,
WatchTypingLocations,
} from "./_namespaces/ts.server.js";
import * as protocol from "./protocol.js";
export const maxProgramSizeForNonTsFiles: number = 20 * 1024 * 1024;
/** @internal */
export const maxFileSize: number = 4 * 1024 * 1024;
export const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground";
export const ProjectLoadingStartEvent = "projectLoadingStart";
export const ProjectLoadingFinishEvent = "projectLoadingFinish";
export const LargeFileReferencedEvent = "largeFileReferenced";
export const ConfigFileDiagEvent = "configFileDiag";
export const ProjectLanguageServiceStateEvent = "projectLanguageServiceState";
export const ProjectInfoTelemetryEvent = "projectInfo";
export const OpenFileInfoTelemetryEvent = "openFileInfo";
export const CreateFileWatcherEvent: protocol.CreateFileWatcherEventName = "createFileWatcher";
export const CreateDirectoryWatcherEvent: protocol.CreateDirectoryWatcherEventName = "createDirectoryWatcher";
export const CloseFileWatcherEvent: protocol.CloseFileWatcherEventName = "closeFileWatcher";
const ensureProjectForOpenFileSchedule = "*ensureProjectForOpenFiles*";
export interface ProjectsUpdatedInBackgroundEvent {
eventName: typeof ProjectsUpdatedInBackgroundEvent;
data: { openFiles: string[]; };
}
export interface ProjectLoadingStartEvent {
eventName: typeof ProjectLoadingStartEvent;
data: { project: Project; reason: string; };
}
export interface ProjectLoadingFinishEvent {
eventName: typeof ProjectLoadingFinishEvent;
data: { project: Project; };
}
export interface LargeFileReferencedEvent {
eventName: typeof LargeFileReferencedEvent;
data: { file: string; fileSize: number; maxFileSize: number; };
}
export interface ConfigFileDiagEvent {
eventName: typeof ConfigFileDiagEvent;
data: { triggerFile: string; configFileName: string; diagnostics: readonly 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;
}
/* __GDPR__
"projectInfo" : {
"${include}": ["${TypeScriptCommonProperties}"],
"projectId": { "classification": "EndUserPseudonymizedInformation", "purpose": "FeatureInsight", "endpoint": "ProjectId" },
"fileStats": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"compilerOptions": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"extends": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"files": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"include": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"exclude": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"compileOnSave": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"typeAcquisition": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"configFileName": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"projectType": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"languageServiceEnabled": { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
"version": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
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;
}
/**
* Info that we may send about a file that was just opened.
* Info about a file will only be sent once per session, even if the file changes in ways that might affect the info.
* Currently this is only sent for '.js' files.
*/
export interface OpenFileInfoTelemetryEvent {
readonly eventName: typeof OpenFileInfoTelemetryEvent;
readonly data: OpenFileInfoTelemetryEventData;
}
export interface OpenFileInfoTelemetryEventData {
readonly info: OpenFileInfo;
}
export interface ProjectInfoTypeAcquisitionData {
readonly enable: boolean | undefined;
// Actual values of include/exclude entries are scrubbed.
readonly include: boolean;
readonly exclude: boolean;
}
export interface FileStats {
readonly js: number;
readonly jsSize?: number;
readonly jsx: number;
readonly jsxSize?: number;
readonly ts: number;
readonly tsSize?: number;
readonly tsx: number;
readonly tsxSize?: number;
readonly dts: number;
readonly dtsSize?: number;
readonly deferred: number;
readonly deferredSize?: number;
}
export interface OpenFileInfo {
readonly checkJs: boolean;
}
export interface CreateFileWatcherEvent {
readonly eventName: protocol.CreateFileWatcherEventName;
readonly data: protocol.CreateFileWatcherEventBody;
}
export interface CreateDirectoryWatcherEvent {
readonly eventName: protocol.CreateDirectoryWatcherEventName;
readonly data: protocol.CreateDirectoryWatcherEventBody;
}
export interface CloseFileWatcherEvent {
readonly eventName: protocol.CloseFileWatcherEventName;
readonly data: protocol.CloseFileWatcherEventBody;
}
export type ProjectServiceEvent =
| LargeFileReferencedEvent
| ProjectsUpdatedInBackgroundEvent
| ProjectLoadingStartEvent
| ProjectLoadingFinishEvent
| ConfigFileDiagEvent
| ProjectLanguageServiceStateEvent
| ProjectInfoTelemetryEvent
| OpenFileInfoTelemetryEvent
| CreateFileWatcherEvent
| CreateDirectoryWatcherEvent
| CloseFileWatcherEvent;
export type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void;
/** @internal */
export type PerformanceEventHandler = (event: PerformanceEvent) => void;
export interface SafeList {
[name: string]: { match: RegExp; exclude?: (string | number)[][]; types?: string[]; };
}
function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions: CommandLineOption[]): Map<string, Map<string, number>> {
const map = new Map<string, Map<string, number>>();
for (const option of commandLineOptions) {
if (typeof option.type === "object") {
const optionMap = option.type as Map<string, number>;
// 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 watchOptionsConverters = prepareConvertersForEnumLikeCompilerOptions(optionsForWatch);
const indentStyle = new Map(Object.entries({
none: IndentStyle.None,
block: IndentStyle.Block,
smart: IndentStyle.Smart,
}));
export interface TypesMapFile {
typesMap: SafeList;
simpleMap: { [libName: string]: string; };
}
/**
* 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(-ui)?)\/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
},
"References": {
match: /^(.*\/_references\.js)$/i,
exclude: [["^", 1, "$"]],
},
};
export function convertFormatOptions(protocolOptions: protocol.FormatCodeSettings): FormatCodeSettings {
if (isString(protocolOptions.indentStyle)) {
protocolOptions.indentStyle = indentStyle.get(protocolOptions.indentStyle.toLowerCase());
Debug.assert(protocolOptions.indentStyle !== undefined);
}
return protocolOptions as any;
}
export function convertCompilerOptions(protocolOptions: protocol.ExternalProjectCompilerOptions): CompilerOptions & protocol.CompileOnSaveMixin {
compilerOptionConverters.forEach((mappedValues, id) => {
const propertyValue = protocolOptions[id];
if (isString(propertyValue)) {
protocolOptions[id] = mappedValues.get(propertyValue.toLowerCase());
}
});
return protocolOptions as any;
}
export function convertWatchOptions(protocolOptions: protocol.ExternalProjectCompilerOptions, currentDirectory?: string): WatchOptionsAndErrors | undefined {
let watchOptions: WatchOptions | undefined;
let errors: Diagnostic[] | undefined;
optionsForWatch.forEach(option => {
const propertyValue = protocolOptions[option.name];
if (propertyValue === undefined) return;
const mappedValues = watchOptionsConverters.get(option.name);
(watchOptions || (watchOptions = {}))[option.name] = mappedValues ?
isString(propertyValue) ? mappedValues.get(propertyValue.toLowerCase()) : propertyValue :
convertJsonOption(option, propertyValue, currentDirectory || "", errors || (errors = []));
});
return watchOptions && { watchOptions, errors };
}
export function convertTypeAcquisition(protocolOptions: protocol.InferredProjectCompilerOptions): TypeAcquisition | undefined {
let result: TypeAcquisition | undefined;
typeAcquisitionDeclarations.forEach(option => {
const propertyValue = protocolOptions[option.name];
if (propertyValue === undefined) return;
(result || (result = {}))[option.name] = propertyValue;
});
return result;
}
export function tryConvertScriptKindName(scriptKindName: protocol.ScriptKindName | ScriptKind): ScriptKind {
return isString(scriptKindName) ? convertScriptKindName(scriptKindName) : scriptKindName;
}
export function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind {
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;
}
}
/** @internal */
export function convertUserPreferences(preferences: protocol.UserPreferences): UserPreferences {
const { lazyConfiguredProjectsFromExternalProject: _, ...userPreferences } = preferences;
return userPreferences;
}
export interface HostConfiguration {
formatCodeOptions: FormatCodeSettings;
preferences: protocol.UserPreferences;
hostInfo: string;
extraFileExtensions?: FileExtensionInfo[];
watchOptions?: WatchOptions;
/** @internal */ beforeSubstitution?: WatchOptions;
}
export interface OpenConfiguredProjectResult {
configFileName?: NormalizedPath;
configFileErrors?: readonly Diagnostic[];
}
interface AssignProjectResult extends OpenConfiguredProjectResult {
retainProjects: ConfigureProjectToLoadKind | undefined;
}
interface FilePropertyReader<T> {
getFileName(f: T): string;
getScriptKind(f: T, extraFileExtensions?: FileExtensionInfo[]): ScriptKind;
hasMixedContent(f: T, extraFileExtensions: FileExtensionInfo[] | undefined): boolean;
}
const fileNamePropertyReader: FilePropertyReader<string> = {
getFileName: x => x,
getScriptKind: (fileName, extraFileExtensions) => {
let result: ScriptKind | undefined;
if (extraFileExtensions) {
const fileExtension = getAnyExtensionFromPath(fileName);
if (fileExtension) {
some(extraFileExtensions, info => {
if (info.extension === fileExtension) {
result = info.scriptKind;
return true;
}
return false;
});
}
}
return result!; // TODO: GH#18217
},
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!), // TODO: GH#18217
hasMixedContent: x => !!x.hasMixedContent,
};
function findProjectByName<T extends Project>(projectName: string, projects: T[]): T | undefined {
for (const proj of projects) {
if (proj.getProjectName() === projectName) {
return proj;
}
}
}
export const nullTypingsInstaller: ITypingsInstaller = {
isKnownTypesPackageName: returnFalse,
// Should never be called because we never provide a types registry.
installPackage: notImplemented,
enqueueInstallTypingsRequest: noop,
attach: noop,
onProjectClosed: noop,
globalTypingsCacheLocation: undefined!, // TODO: GH#18217
};
const noopConfigFileWatcher: FileWatcher = { close: noop };
/** @internal */
export interface ConfigFileExistenceInfo {
/**
* Cached value of existence of config file
* It is true if there is configured project open for this file.
* It can be either true or false if this is the config file that is being watched by inferred project
* to decide when to update the structure so that it knows about updating the project for its files
* (config file may include the inferred project files after the change and hence may be wont need to be in inferred project)
*/
exists: boolean;
/**
* Tracks how many open files are impacted by this config file that are root of inferred project
*/
inferredProjectRoots?: number;
/**
* openFilesImpactedByConfigFiles is a map of open files that would be impacted by this config file
* because these are the paths being looked up for their default configured project location
*/
openFilesImpactedByConfigFile?: Set<Path>;
/**
* The file watcher watching the config file because there is open script info that is root of
* inferred project and will be impacted by change in the status of the config file
* or
* Configured project for this config file is open
* or
* Configured project references this config file
*/
watcher?: FileWatcher;
/**
* Cached parsed command line and other related information like watched directories etc
*/
config?: ParsedConfig;
}
export interface ProjectServiceOptions {
host: ServerHost;
logger: Logger;
cancellationToken: HostCancellationToken;
useSingleInferredProject: boolean;
useInferredProjectPerProjectRoot: boolean;
typingsInstaller?: ITypingsInstaller;
eventHandler?: ProjectServiceEventHandler;
canUseWatchEvents?: boolean;
suppressDiagnosticEvents?: boolean;
throttleWaitMilliseconds?: number;
globalPlugins?: readonly string[];
pluginProbeLocations?: readonly string[];
allowLocalPluginLoads?: boolean;
typesMapLocation?: string;
serverMode?: LanguageServiceMode;
session: Session<unknown> | undefined;
/** @internal */ incrementalVerifier?: (service: ProjectService) => void;
jsDocParsingMode?: JSDocParsingMode;
}
/**
* string if file name,
* false if no config file name
* @internal
*/
export type ConfigFileName = NormalizedPath | false;
/**
* Stores cached config file name for info as well as ancestor so is a map
* Key is false for Open ScriptInfo
* Key is NormalizedPath for Config file name
* @internal
*/
export type ConfigFileMapForOpenFile = Map<ConfigFileName, ConfigFileName>;
/**
* The cache for open script info will have
* ConfigFileName or false if ancestors are not looked up
* Map if ancestors are looked up
* @internal
*/
export type ConfigFileForOpenFile = ConfigFileName | ConfigFileMapForOpenFile;
/** Gets cached value of config file name based on open script info or ancestor script info */
function getConfigFileNameFromCache(info: OpenScriptInfoOrClosedOrConfigFileInfo, cache: Map<Path, ConfigFileForOpenFile> | undefined): ConfigFileName | undefined {
if (!cache) return undefined;
const configFileForOpenFile = cache.get(info.path);
if (configFileForOpenFile === undefined) return undefined;
if (!isAncestorConfigFileInfo(info)) {
return isString(configFileForOpenFile) || !configFileForOpenFile ?
configFileForOpenFile : // direct result
configFileForOpenFile.get(/*key*/ false); // Its a map, use false as the key for the info's config file name
}
else {
return configFileForOpenFile && !isString(configFileForOpenFile) ? // Map with fileName as key
configFileForOpenFile.get(info.fileName) :
undefined; // No result for the config file name
}
}
/** @internal */
export interface OriginalFileInfo {
fileName: NormalizedPath;
path: Path;
}
/** @internal */
export interface AncestorConfigFileInfo {
/** config file name */
fileName: NormalizedPath;
/** path of open file so we can look at correct root */
path: Path;
configFileInfo: true;
isForDefaultProject: boolean;
}
/** @internal */
export type OpenScriptInfoOrClosedFileInfo = ScriptInfo | OriginalFileInfo;
/** @internal */
export type OpenScriptInfoOrClosedOrConfigFileInfo = OpenScriptInfoOrClosedFileInfo | AncestorConfigFileInfo;
function isOpenScriptInfo(infoOrFileNameOrConfig: OpenScriptInfoOrClosedOrConfigFileInfo): infoOrFileNameOrConfig is ScriptInfo {
return !!(infoOrFileNameOrConfig as ScriptInfo).containingProjects;
}
function isAncestorConfigFileInfo(infoOrFileNameOrConfig: OpenScriptInfoOrClosedOrConfigFileInfo): infoOrFileNameOrConfig is AncestorConfigFileInfo {
return !!(infoOrFileNameOrConfig as AncestorConfigFileInfo).configFileInfo;
}
/** @internal */
export enum ConfiguredProjectLoadKind {
FindOptimized,
Find,
CreateReplayOptimized,
CreateReplay,
CreateOptimized,
Create,
ReloadOptimized,
Reload,
}
type ConguredProjectLoadFindCreateOrReload =
| ConfiguredProjectLoadKind.Find
| ConfiguredProjectLoadKind.CreateReplay
| ConfiguredProjectLoadKind.Create
| ConfiguredProjectLoadKind.Reload;
type ConguredProjectLoadFindCreateOrReloadOptimized =
| ConfiguredProjectLoadKind.FindOptimized
| ConfiguredProjectLoadKind.CreateReplayOptimized
| ConfiguredProjectLoadKind.CreateOptimized
| ConfiguredProjectLoadKind.ReloadOptimized;
function toConfiguredProjectLoadOptimized(kind: ConguredProjectLoadFindCreateOrReload): ConguredProjectLoadFindCreateOrReloadOptimized {
return kind - 1;
}
/** @internal */
export type ConfigureProjectToLoadKind = Map<ConfiguredProject, ConfiguredProjectLoadKind>;
/** @internal */
export type ConfiguredProjectToAnyReloadKind = Map<
ConfiguredProject,
| ConfiguredProjectLoadKind.Reload
| ConfiguredProjectLoadKind.ReloadOptimized
>;
/** @internal */
export type DefaultConfiguredProjectResult = ReturnType<ProjectService["tryFindDefaultConfiguredProjectForOpenScriptInfoOrClosedFileInfo"]>;
/** @internal */
export interface FindCreateOrLoadConfiguredProjectResult {
project: ConfiguredProject;
sentConfigFileDiag: boolean;
configFileExistenceInfo: ConfigFileExistenceInfo | undefined;
reason: string | undefined;
}
/**
* Goes through each tsconfig from project till project root of open script info and finds, creates or reloads project per kind
*/
function forEachAncestorProjectLoad<T>(
info: ScriptInfo,
project: ConfiguredProject,
cb: (ancestor: FindCreateOrLoadConfiguredProjectResult) => T | undefined,
kind: ConfiguredProjectLoadKind,
/** Used with ConfiguredProjectLoadKind.Create or ConfiguredProjectLoadKind.Reload for new projects or reload updates */
reason: string,
/** Used with ConfiguredProjectLoadKind.Find to get deferredClosed projects as well */
allowDeferredClosed: boolean | undefined,
/** Used with ConfiguredProjectLoadKind.Reload to check if this project was already reloaded */
reloadedProjects: ConfiguredProjectToAnyReloadKind | undefined,
/** true means we are looking for solution, so we can stop if found project is not composite to go into parent solution */
searchOnlyPotentialSolution: boolean,
/** Used with ConfiguredProjectLoadKind.Reload to specify delay reload, and also a set of configured projects already marked for delay load */
delayReloadedConfiguredProjects?: Set<ConfiguredProject>,
): T | undefined {
// Create configured project till project root
while (true) {
// Skip if project is not composite and we are only looking for solution
if (
project.parsedCommandLine &&
(
(searchOnlyPotentialSolution && !project.parsedCommandLine.options.composite) ||
// Currently disableSolutionSearching is shared for finding solution/project when
// - loading solution for find all references
// - trying to find default project
project.parsedCommandLine.options.disableSolutionSearching
)
) return;
// Get config file name
const configFileName = project.projectService.getConfigFileNameForFile(
{
fileName: project.getConfigFilePath(),
path: info.path,
configFileInfo: true,
isForDefaultProject: !searchOnlyPotentialSolution,
},
kind <= ConfiguredProjectLoadKind.CreateReplay,
);
if (!configFileName) return;
// find or delay load the project
const ancestor = project.projectService.findCreateOrReloadConfiguredProject(
configFileName,
kind,
reason,
allowDeferredClosed,
!searchOnlyPotentialSolution ? info.fileName : undefined, // Config Diag event for project if its for default project
reloadedProjects,
searchOnlyPotentialSolution, // Delay load if we are searching for solution
delayReloadedConfiguredProjects,
);
if (!ancestor) return;
// If this ancestor is new and was delay loaded, then set the project as potential project reference
if (
!ancestor.project.parsedCommandLine &&
project.parsedCommandLine?.options.composite
) {
// Set a potential project reference
ancestor.project.setPotentialProjectReference(project.canonicalConfigFilePath);
}
const result = cb(ancestor);
if (result) return result;
project = ancestor.project;
}
}
/**
* Goes through parentConfig's project references and finds, creates or reloads project per kind
*/
function forEachResolvedProjectReferenceProjectLoad<T>(
project: ConfiguredProject,
parentConfig: ParsedCommandLine,
cb: (
childConfigFileExistenceInfo: ConfigFileExistenceInfo,
childProject: ConfiguredProject | undefined,
childConfigName: NormalizedPath,
reason: string,
project: ConfiguredProject,
childCanonicalConfigPath: NormalizedPath,
) => T | undefined,
kind: ConguredProjectLoadFindCreateOrReloadOptimized,
reason: string,
/** Used with ConfiguredProjectLoadKind.Find to get deferredClosed projects as well */
allowDeferredClosed: boolean | undefined,
/** Used with ConfiguredProjectLoadKind.Reload to check if this project was already reloaded */
reloadedProjects: ConfiguredProjectToAnyReloadKind | undefined,
seenResolvedRefs?: Map<string, ConfiguredProjectLoadKind>,
): T | undefined {
const loadKind = parentConfig.options.disableReferencedProjectLoad ? ConfiguredProjectLoadKind.FindOptimized : kind;
let children: ParsedCommandLine[] | undefined;
return forEach(
parentConfig.projectReferences,
ref => {
const childConfigName = toNormalizedPath(resolveProjectReferencePath(ref));
const childCanonicalConfigPath = asNormalizedPath(project.projectService.toCanonicalFileName(childConfigName));
const seenValue = seenResolvedRefs?.get(childCanonicalConfigPath);
if (seenValue !== undefined && seenValue >= loadKind) return undefined;
// Get the config
const configFileExistenceInfo = project.projectService.configFileExistenceInfoCache.get(childCanonicalConfigPath);
let childConfig = loadKind === ConfiguredProjectLoadKind.FindOptimized ?
configFileExistenceInfo?.exists || project.resolvedChildConfigs?.has(childCanonicalConfigPath) ?
configFileExistenceInfo!.config!.parsedCommandLine : undefined :
project.getParsedCommandLine(childConfigName);
if (childConfig && loadKind !== kind && loadKind > ConfiguredProjectLoadKind.CreateReplayOptimized) {
// If this was found using find: ensure this is uptodate if looking for creating or reloading
childConfig = project.getParsedCommandLine(childConfigName);
}
if (!childConfig) return undefined;
// Find the project
const childProject = project.projectService.findConfiguredProjectByProjectName(childConfigName, allowDeferredClosed);
// Ignore if we couldnt find child project or config file existence info
if (
loadKind === ConfiguredProjectLoadKind.CreateReplayOptimized &&
!configFileExistenceInfo &&
!childProject
) return undefined;
switch (loadKind) {
case ConfiguredProjectLoadKind.ReloadOptimized:
if (childProject) childProject.projectService.reloadConfiguredProjectOptimized(childProject, reason, reloadedProjects!);
// falls through
case ConfiguredProjectLoadKind.CreateOptimized:
(project.resolvedChildConfigs ??= new Set()).add(childCanonicalConfigPath);
// falls through
case ConfiguredProjectLoadKind.CreateReplayOptimized:
case ConfiguredProjectLoadKind.FindOptimized:
if (childProject || loadKind !== ConfiguredProjectLoadKind.FindOptimized) {
const result = cb(
configFileExistenceInfo ?? project.projectService.configFileExistenceInfoCache.get(childCanonicalConfigPath)!,
childProject,
childConfigName,
reason,
project,
childCanonicalConfigPath,
);
if (result) return result;
}
break;
default:
Debug.assertNever(loadKind);
}
(seenResolvedRefs ??= new Map()).set(childCanonicalConfigPath, loadKind);
(children ??= []).push(childConfig);
},
) || forEach(
children,
childConfig =>
childConfig.projectReferences && forEachResolvedProjectReferenceProjectLoad(
project,
childConfig,
cb,
loadKind,
reason,
allowDeferredClosed,
reloadedProjects,
seenResolvedRefs,
),
);
}
function updateProjectFoundUsingFind(
project: ConfiguredProject,
kind: ConfiguredProjectLoadKind,
/** Used with ConfiguredProjectLoadKind.Create to send configFileDiag */
triggerFile?: NormalizedPath | undefined,
/** Used with ConfiguredProjectLoadKind.Reload to for reload reason */
reason?: string,
/** Used with ConfiguredProjectLoadKind.Reload to check if this project was already reloaded */
reloadedProjects?: ConfiguredProjectToAnyReloadKind | undefined,
): FindCreateOrLoadConfiguredProjectResult {
let sentConfigFileDiag = false;
let configFileExistenceInfo: ConfigFileExistenceInfo | undefined;
// This project was found using "Find" instead of the actually specified kind of "Create" or "Reload",
// We need to update or reload this existing project before calling callback
switch (kind) {
case ConfiguredProjectLoadKind.CreateReplayOptimized:
case ConfiguredProjectLoadKind.CreateReplay:
if (useConfigFileExistenceInfoForOptimizedLoading(project)) {
configFileExistenceInfo = project.projectService.configFileExistenceInfoCache.get(project.canonicalConfigFilePath)!;
}
break;
case ConfiguredProjectLoadKind.CreateOptimized:
configFileExistenceInfo = configFileExistenceInfoForOptimizedLoading(project);
if (configFileExistenceInfo) break;
// falls through
case ConfiguredProjectLoadKind.Create:
sentConfigFileDiag = updateConfiguredProject(project, triggerFile);
break;
case ConfiguredProjectLoadKind.ReloadOptimized:
project.projectService.reloadConfiguredProjectOptimized(project, reason!, reloadedProjects!);
configFileExistenceInfo = configFileExistenceInfoForOptimizedLoading(project);
if (configFileExistenceInfo) break;
// falls through
case ConfiguredProjectLoadKind.Reload:
sentConfigFileDiag = project.projectService.reloadConfiguredProjectClearingSemanticCache(
project,
reason!,
reloadedProjects!,
);
break;
case ConfiguredProjectLoadKind.FindOptimized:
case ConfiguredProjectLoadKind.Find:
break;
default:
Debug.assertNever(kind);
}
return { project, sentConfigFileDiag, configFileExistenceInfo, reason };
}
function forEachPotentialProjectReference<T>(
project: ConfiguredProject,
cb: (potentialProjectReference: NormalizedPath) => T | undefined,
): T | undefined {
return project.initialLoadPending ?
(project.potentialProjectReferences && forEachKey(project.potentialProjectReferences, cb)) ??
(project.resolvedChildConfigs && forEachKey(project.resolvedChildConfigs, cb)) :
undefined;
}
function forEachAnyProjectReferenceKind<T>(
project: ConfiguredProject,
cb: (resolvedProjectReference: ResolvedProjectReference) => T | undefined,
cbProjectRef: (projectReference: ProjectReference) => T | undefined,
cbPotentialProjectRef: (potentialProjectReference: NormalizedPath) => T | undefined,
): T | undefined {
return project.getCurrentProgram() ?
project.forEachResolvedProjectReference(cb) :
project.initialLoadPending ?
forEachPotentialProjectReference(project, cbPotentialProjectRef) :
forEach(project.getProjectReferences(), cbProjectRef);
}