-
Notifications
You must be signed in to change notification settings - Fork 12.5k
/
program.ts
5558 lines (5068 loc) · 283 KB
/
program.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 {
__String,
addInternalEmitFlags,
addRange,
addRelatedInfo,
append,
arrayIsEqualTo,
AsExpression,
BuilderProgram,
CancellationToken,
canHaveDecorators,
canHaveIllegalDecorators,
chainDiagnosticMessages,
changeExtension,
changesAffectingProgramStructure,
changesAffectModuleResolution,
combinePaths,
commandLineOptionOfCustomType,
CommentDirective,
CommentDirectivesMap,
compareDataObjects,
comparePaths,
compareValues,
Comparison,
CompilerHost,
CompilerOptions,
computeLineAndCharacterOfPosition,
concatenate,
contains,
containsIgnoredPath,
containsPath,
convertToRelativePath,
createCommentDirectivesMap,
createCompilerDiagnostic,
createCompilerDiagnosticFromMessageChain,
createDiagnosticCollection,
createDiagnosticForNodeFromMessageChain,
createDiagnosticForNodeInSourceFile,
createDiagnosticForRange,
createFileDiagnostic,
createFileDiagnosticFromMessageChain,
createGetCanonicalFileName,
createModeAwareCache,
createModeAwareCacheKey,
createModuleResolutionCache,
createMultiMap,
CreateProgramOptions,
createSourceFile,
CreateSourceFileOptions,
createSymlinkCache,
createTypeChecker,
createTypeReferenceDirectiveResolutionCache,
CustomTransformers,
Debug,
DeclarationWithTypeParameterChildren,
Diagnostic,
DiagnosticArguments,
DiagnosticCategory,
diagnosticCategoryName,
DiagnosticMessage,
DiagnosticMessageChain,
DiagnosticReporter,
Diagnostics,
DiagnosticWithLocation,
directorySeparator,
DirectoryStructureHost,
emitFiles,
EmitHost,
emitModuleKindIsNonNodeESM,
EmitOnly,
emitResolverSkipsTypeChecking,
EmitResult,
emptyArray,
ensureTrailingDirectorySeparator,
equateStringsCaseInsensitive,
equateStringsCaseSensitive,
exclusivelyPrefixedNodeCoreModules,
explainIfFileIsRedirectAndImpliedFormat,
ExportAssignment,
ExportDeclaration,
Extension,
extensionFromPath,
externalHelpersModuleNameText,
factory,
fileExtensionIs,
fileExtensionIsOneOf,
FileIncludeKind,
FileIncludeReason,
fileIncludeReasonToDiagnostics,
FilePreprocessingDiagnostics,
FilePreprocessingDiagnosticsKind,
FilePreprocessingLibReferenceDiagnostic,
FileReference,
filter,
find,
findIndex,
firstDefinedIterator,
flatMap,
flatten,
forEach,
forEachAncestorDirectory,
forEachChildRecursively,
forEachDynamicImportOrRequireCall,
forEachEmittedFile,
forEachEntry,
forEachKey,
forEachPropertyAssignment,
forEachResolvedProjectReference as ts_forEachResolvedProjectReference,
forEachTsConfigPropArray,
FunctionLikeDeclaration,
getAllowJSCompilerOption,
getAutomaticTypeDirectiveNames,
getBaseFileName,
GetCanonicalFileName,
getCommonSourceDirectory as ts_getCommonSourceDirectory,
getCommonSourceDirectoryOfConfig,
getDeclarationDiagnostics as ts_getDeclarationDiagnostics,
getDefaultLibFileName,
getDirectoryPath,
getEmitDeclarations,
getEmitModuleKind,
getEmitModuleResolutionKind,
getEmitScriptTarget,
getErrorSpanForNode,
getExternalModuleName,
getIsolatedModules,
getJSXImplicitImportBase,
getJSXRuntimeImport,
getLineAndCharacterOfPosition,
getLineStarts,
getMatchedFileSpec,
getMatchedIncludeSpec,
getNameOfScriptTarget,
getNewLineCharacter,
getNormalizedAbsolutePath,
getNormalizedAbsolutePathWithoutRoot,
getNormalizedPathComponents,
getOutputDeclarationFileName,
getPackageScopeForPath,
getPathFromPathComponents,
getPositionOfLineAndCharacter,
getPropertyArrayElementValue,
getResolvedModuleFromResolution,
getResolvedTypeReferenceDirectiveFromResolution,
getResolveJsonModule,
getRootLength,
getSetExternalModuleIndicator,
getSourceFileOfNode,
getSpellingSuggestion,
getStrictOptionValue,
getSupportedExtensions,
getSupportedExtensionsWithJsonIfResolveJsonModule,
getTemporaryModuleResolutionState,
getTextOfIdentifierOrLiteral,
getTransformers,
getTsBuildInfoEmitOutputFilePath,
getTsConfigObjectLiteralExpression,
getTsConfigPropArrayElementValue,
getTypesPackageName,
HasChangedAutomaticTypeDirectiveNames,
hasChangesInResolutions,
hasExtension,
HasInvalidatedLibResolutions,
HasInvalidatedResolutions,
hasJSFileExtension,
hasJsonModuleEmitEnabled,
hasProperty,
hasSyntacticModifier,
hasZeroOrOneAsteriskCharacter,
HeritageClause,
Identifier,
identity,
ImportAttributes,
ImportClause,
ImportDeclaration,
ImportOrExportSpecifier,
importSyntaxAffectsModuleResolution,
InternalEmitFlags,
inverseJsxOptionMap,
isAmbientModule,
isAnyImportOrReExport,
isArray,
isArrayLiteralExpression,
isBuildInfoFile,
isCheckJsEnabledForFile,
isClassDeclaration,
isDeclarationFileName,
isDecorator,
isDefaultModifier,
isExportDeclaration,
isExportModifier,
isExternalModule,
isExternalModuleNameRelative,
isIdentifierText,
isImportCall,
isImportDeclaration,
isImportEqualsDeclaration,
isImportSpecifier,
isImportTypeNode,
isInJSFile,
isJSDocImportTag,
isModifier,
isModuleDeclaration,
isObjectLiteralExpression,
isParameter,
isPlainJsFile,
isRequireCall,
isRootedDiskPath,
isSourceFileJS,
isString,
isStringLiteral,
isStringLiteralLike,
isTraceEnabled,
JSDocImportTag,
JsonSourceFile,
JsxEmit,
length,
libMap,
LibResolution,
libs,
mapDefined,
maybeBind,
memoize,
MethodDeclaration,
ModeAwareCache,
ModeAwareCacheKey,
ModifierFlags,
ModifierLike,
ModuleBlock,
ModuleDeclaration,
ModuleKind,
ModuleResolutionCache,
ModuleResolutionHost,
moduleResolutionIsEqualTo,
ModuleResolutionKind,
moduleResolutionSupportsPackageJsonExportsAndImports,
Mutable,
Node,
NodeArray,
NodeFlags,
nodeModulesPathPart,
NodeWithTypeArguments,
noop,
normalizePath,
notImplementedResolver,
noTransformers,
ObjectLiteralExpression,
OperationCanceledException,
optionsHaveChanges,
PackageId,
packageIdToPackageName,
packageIdToString,
PackageJsonInfoCache,
ParameterDeclaration,
ParseConfigFileHost,
ParsedCommandLine,
parseIsolatedEntityName,
parseJsonSourceFileConfigFileContent,
parseNodeFactory,
Path,
pathContainsNodeModules,
pathIsAbsolute,
pathIsRelative,
Program,
ProgramHost,
ProjectReference,
ProjectReferenceFile,
projectReferenceIsEqualTo,
PropertyAssignment,
PropertyDeclaration,
ReferencedFile,
removeFileExtension,
removePrefix,
removeSuffix,
resolutionExtensionIsTSOrJson,
ResolutionMode,
ResolutionWithFailedLookupLocations,
resolveConfigFileProjectName,
ResolvedConfigFileName,
ResolvedModuleFull,
ResolvedModuleWithFailedLookupLocations,
ResolvedProjectReference,
ResolvedTypeReferenceDirectiveWithFailedLookupLocations,
resolveLibrary,
resolveModuleName,
resolveTypeReferenceDirective,
returnFalse,
returnUndefined,
SatisfiesExpression,
ScriptKind,
ScriptTarget,
setParent,
setParentRecursive,
skipTrivia,
skipTypeChecking,
some,
sortAndDeduplicateDiagnostics,
SortedReadonlyArray,
SourceFile,
sourceFileAffectingCompilerOptions,
sourceFileMayBeEmitted,
SourceOfProjectReferenceRedirect,
startsWith,
Statement,
StringLiteral,
StringLiteralLike,
StructureIsReused,
supportedJSExtensionsFlat,
SymlinkCache,
SyntaxKind,
sys,
System,
toFileNameLowerCase,
tokenToString,
toPath as ts_toPath,
toSorted,
trace,
tracing,
tryCast,
TsConfigSourceFile,
TypeChecker,
typeDirectiveIsEqualTo,
TypeReferenceDirectiveResolutionCache,
unprefixedNodeCoreModules,
VariableDeclaration,
VariableStatement,
Version,
versionMajorMinor,
walkUpParenthesizedExpressions,
WriteFileCallback,
WriteFileCallbackData,
writeFileEnsuringDirectories,
} from "./_namespaces/ts.js";
import * as performance from "./_namespaces/ts.performance.js";
export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName = "tsconfig.json"): string | undefined {
return forEachAncestorDirectory(searchPath, ancestor => {
const fileName = combinePaths(ancestor, configName);
return fileExists(fileName) ? fileName : undefined;
});
}
export function resolveTripleslashReference(moduleName: string, containingFile: string): string {
const basePath = getDirectoryPath(containingFile);
const referencedFileName = isRootedDiskPath(moduleName) ? moduleName : combinePaths(basePath, moduleName);
return normalizePath(referencedFileName);
}
/** @internal */
export function computeCommonSourceDirectoryOfFilenames(fileNames: readonly string[], currentDirectory: string, getCanonicalFileName: GetCanonicalFileName): string {
let commonPathComponents: string[] | undefined;
const failed = forEach(fileNames, sourceFile => {
// Each file contributes into common source file path
const sourcePathComponents = getNormalizedPathComponents(sourceFile, currentDirectory);
sourcePathComponents.pop(); // The base file name is not part of the common directory path
if (!commonPathComponents) {
// first file
commonPathComponents = sourcePathComponents;
return;
}
const n = Math.min(commonPathComponents.length, sourcePathComponents.length);
for (let i = 0; i < n; i++) {
if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
if (i === 0) {
// Failed to find any common path component
return true;
}
// New common path found that is 0 -> i-1
commonPathComponents.length = i;
break;
}
}
// If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
if (sourcePathComponents.length < commonPathComponents.length) {
commonPathComponents.length = sourcePathComponents.length;
}
});
// A common path can not be found when paths span multiple drives on windows, for example
if (failed) {
return "";
}
if (!commonPathComponents) { // Can happen when all input files are .d.ts files
return currentDirectory;
}
return getPathFromPathComponents(commonPathComponents);
}
export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost {
return createCompilerHostWorker(options, setParentNodes);
}
/** @internal */
export function createGetSourceFile(
readFile: ProgramHost<any>["readFile"],
setParentNodes: boolean | undefined,
): CompilerHost["getSourceFile"] {
return (fileName, languageVersionOrOptions, onError) => {
let text: string | undefined;
try {
performance.mark("beforeIORead");
text = readFile(fileName);
performance.mark("afterIORead");
performance.measure("I/O Read", "beforeIORead", "afterIORead");
}
catch (e) {
if (onError) {
onError(e.message);
}
text = "";
}
return text !== undefined ? createSourceFile(fileName, text, languageVersionOrOptions, setParentNodes) : undefined;
};
}
/** @internal */
export function createWriteFileMeasuringIO(
actualWriteFile: (path: string, data: string, writeByteOrderMark: boolean) => void,
createDirectory: (path: string) => void,
directoryExists: (path: string) => boolean,
): CompilerHost["writeFile"] {
return (fileName, data, writeByteOrderMark, onError) => {
try {
performance.mark("beforeIOWrite");
// NOTE: If patchWriteFileEnsuringDirectory has been called,
// the system.writeFile will do its own directory creation and
// the ensureDirectoriesExist call will always be redundant.
writeFileEnsuringDirectories(
fileName,
data,
writeByteOrderMark,
actualWriteFile,
createDirectory,
directoryExists,
);
performance.mark("afterIOWrite");
performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
}
catch (e) {
if (onError) {
onError(e.message);
}
}
};
}
/** @internal */
export function createCompilerHostWorker(
options: CompilerOptions,
setParentNodes?: boolean,
system: System = sys,
): CompilerHost {
const existingDirectories = new Map<string, boolean>();
const getCanonicalFileName = createGetCanonicalFileName(system.useCaseSensitiveFileNames);
function directoryExists(directoryPath: string): boolean {
if (existingDirectories.has(directoryPath)) {
return true;
}
if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) {
existingDirectories.set(directoryPath, true);
return true;
}
return false;
}
function getDefaultLibLocation(): string {
return getDirectoryPath(normalizePath(system.getExecutingFilePath()));
}
const newLine = getNewLineCharacter(options);
const realpath = system.realpath && ((path: string) => system.realpath!(path));
const compilerHost: CompilerHost = {
getSourceFile: createGetSourceFile(fileName => compilerHost.readFile(fileName), setParentNodes),
getDefaultLibLocation,
getDefaultLibFileName: options => combinePaths(getDefaultLibLocation(), getDefaultLibFileName(options)),
writeFile: createWriteFileMeasuringIO(
(path, data, writeByteOrderMark) => system.writeFile(path, data, writeByteOrderMark),
path => (compilerHost.createDirectory || system.createDirectory)(path),
path => directoryExists(path),
),
getCurrentDirectory: memoize(() => system.getCurrentDirectory()),
useCaseSensitiveFileNames: () => system.useCaseSensitiveFileNames,
getCanonicalFileName,
getNewLine: () => newLine,
fileExists: fileName => system.fileExists(fileName),
readFile: fileName => system.readFile(fileName),
trace: (s: string) => system.write(s + newLine),
directoryExists: directoryName => system.directoryExists(directoryName),
getEnvironmentVariable: name => system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : "",
getDirectories: (path: string) => system.getDirectories(path),
realpath,
readDirectory: (path, extensions, include, exclude, depth) => system.readDirectory(path, extensions, include, exclude, depth),
createDirectory: d => system.createDirectory(d),
createHash: maybeBind(system, system.createHash),
};
return compilerHost;
}
/** @internal */
export interface CompilerHostLikeForCache {
fileExists(fileName: string): boolean;
readFile(fileName: string, encoding?: string): string | undefined;
directoryExists?(directory: string): boolean;
createDirectory?(directory: string): void;
writeFile?: WriteFileCallback;
}
/** @internal */
export interface CompilerHostLikeWithCache {
originalReadFile: (fileName: string, encoding?: string) => string | undefined;
originalFileExists: (fileName: string) => boolean;
originalDirectoryExists: ((directory: string) => boolean) | undefined;
originalCreateDirectory: ((directory: string) => void) | undefined;
originalWriteFile: WriteFileCallback | undefined;
getSourceFileWithCache: ((fileName: string, languageVersionOrOptions: ScriptTarget | CreateSourceFileOptions, onError?: (message: string) => void, shouldCreateNewSourceFile?: boolean) => SourceFile | undefined) | undefined;
readFileWithCache: (fileName: string) => string | undefined;
}
/** @internal */
export function changeCompilerHostLikeToUseCache(
host: CompilerHostLikeForCache,
toPath: (fileName: string) => Path,
getSourceFile?: CompilerHost["getSourceFile"],
): CompilerHostLikeWithCache {
const originalReadFile = host.readFile;
const originalFileExists = host.fileExists;
const originalDirectoryExists = host.directoryExists;
const originalCreateDirectory = host.createDirectory;
const originalWriteFile = host.writeFile;
const readFileCache = new Map<Path, string | false>();
const fileExistsCache = new Map<Path, boolean>();
const directoryExistsCache = new Map<Path, boolean>();
const sourceFileCache = new Map<ResolutionMode, Map<Path, SourceFile>>();
const readFileWithCache = (fileName: string): string | undefined => {
const key = toPath(fileName);
const value = readFileCache.get(key);
if (value !== undefined) return value !== false ? value : undefined;
return setReadFileCache(key, fileName);
};
const setReadFileCache = (key: Path, fileName: string) => {
const newValue = originalReadFile.call(host, fileName);
readFileCache.set(key, newValue !== undefined ? newValue : false);
return newValue;
};
host.readFile = fileName => {
const key = toPath(fileName);
const value = readFileCache.get(key);
if (value !== undefined) return value !== false ? value : undefined; // could be .d.ts from output
// Cache json or buildInfo
if (!fileExtensionIs(fileName, Extension.Json) && !isBuildInfoFile(fileName)) {
return originalReadFile.call(host, fileName);
}
return setReadFileCache(key, fileName);
};
const getSourceFileWithCache: CompilerHost["getSourceFile"] | undefined = getSourceFile ? (fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile) => {
const key = toPath(fileName);
const impliedNodeFormat: ResolutionMode = typeof languageVersionOrOptions === "object" ? languageVersionOrOptions.impliedNodeFormat : undefined;
const forImpliedNodeFormat = sourceFileCache.get(impliedNodeFormat);
const value = forImpliedNodeFormat?.get(key);
if (value) return value;
const sourceFile = getSourceFile(fileName, languageVersionOrOptions, onError, shouldCreateNewSourceFile);
if (sourceFile && (isDeclarationFileName(fileName) || fileExtensionIs(fileName, Extension.Json))) {
sourceFileCache.set(impliedNodeFormat, (forImpliedNodeFormat || new Map()).set(key, sourceFile));
}
return sourceFile;
} : undefined;
// fileExists for any kind of extension
host.fileExists = fileName => {
const key = toPath(fileName);
const value = fileExistsCache.get(key);
if (value !== undefined) return value;
const newValue = originalFileExists.call(host, fileName);
fileExistsCache.set(key, !!newValue);
return newValue;
};
if (originalWriteFile) {
host.writeFile = (fileName, data, ...rest) => {
const key = toPath(fileName);
fileExistsCache.delete(key);
const value = readFileCache.get(key);
if (value !== undefined && value !== data) {
readFileCache.delete(key);
sourceFileCache.forEach(map => map.delete(key));
}
else if (getSourceFileWithCache) {
sourceFileCache.forEach(map => {
const sourceFile = map.get(key);
if (sourceFile && sourceFile.text !== data) {
map.delete(key);
}
});
}
originalWriteFile.call(host, fileName, data, ...rest);
};
}
// directoryExists
if (originalDirectoryExists) {
host.directoryExists = directory => {
const key = toPath(directory);
const value = directoryExistsCache.get(key);
if (value !== undefined) return value;
const newValue = originalDirectoryExists.call(host, directory);
directoryExistsCache.set(key, !!newValue);
return newValue;
};
if (originalCreateDirectory) {
host.createDirectory = directory => {
const key = toPath(directory);
directoryExistsCache.delete(key);
originalCreateDirectory.call(host, directory);
};
}
}
return {
originalReadFile,
originalFileExists,
originalDirectoryExists,
originalCreateDirectory,
originalWriteFile,
getSourceFileWithCache,
readFileWithCache,
};
}
export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[];
/** @internal */ export function getPreEmitDiagnostics(program: BuilderProgram, sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[]; // eslint-disable-line @typescript-eslint/unified-signatures
export function getPreEmitDiagnostics(program: Program | BuilderProgram, sourceFile?: SourceFile, cancellationToken?: CancellationToken): readonly Diagnostic[] {
let diagnostics: Diagnostic[] | undefined;
diagnostics = addRange(diagnostics, program.getConfigFileParsingDiagnostics());
diagnostics = addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken));
diagnostics = addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile, cancellationToken));
diagnostics = addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken));
diagnostics = addRange(diagnostics, program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (getEmitDeclarations(program.getCompilerOptions())) {
diagnostics = addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken));
}
return sortAndDeduplicateDiagnostics(diagnostics || emptyArray);
}
export interface FormatDiagnosticsHost {
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
getNewLine(): string;
}
export function formatDiagnostics(diagnostics: readonly Diagnostic[], host: FormatDiagnosticsHost): string {
let output = "";
for (const diagnostic of diagnostics) {
output += formatDiagnostic(diagnostic, host);
}
return output;
}
export function formatDiagnostic(diagnostic: Diagnostic, host: FormatDiagnosticsHost): string {
const errorMessage = `${diagnosticCategoryName(diagnostic)} TS${diagnostic.code}: ${flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine())}${host.getNewLine()}`;
if (diagnostic.file) {
const { line, character } = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start!); // TODO: GH#18217
const fileName = diagnostic.file.fileName;
const relativeFileName = convertToRelativePath(fileName, host.getCurrentDirectory(), fileName => host.getCanonicalFileName(fileName));
return `${relativeFileName}(${line + 1},${character + 1}): ` + errorMessage;
}
return errorMessage;
}
/** @internal */
export enum ForegroundColorEscapeSequences {
Grey = "\u001b[90m",
Red = "\u001b[91m",
Yellow = "\u001b[93m",
Blue = "\u001b[94m",
Cyan = "\u001b[96m",
}
const gutterStyleSequence = "\u001b[7m";
const gutterSeparator = " ";
const resetEscapeSequence = "\u001b[0m";
const ellipsis = "...";
const halfIndent = " ";
const indent = " ";
function getCategoryFormat(category: DiagnosticCategory): ForegroundColorEscapeSequences {
switch (category) {
case DiagnosticCategory.Error:
return ForegroundColorEscapeSequences.Red;
case DiagnosticCategory.Warning:
return ForegroundColorEscapeSequences.Yellow;
case DiagnosticCategory.Suggestion:
return Debug.fail("Should never get an Info diagnostic on the command line.");
case DiagnosticCategory.Message:
return ForegroundColorEscapeSequences.Blue;
}
}
/** @internal */
export function formatColorAndReset(text: string, formatStyle: string): string {
return formatStyle + text + resetEscapeSequence;
}
function formatCodeSpan(file: SourceFile, start: number, length: number, indent: string, squiggleColor: ForegroundColorEscapeSequences, host: FormatDiagnosticsHost) {
const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start);
const { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start + length);
const lastLineInFile = getLineAndCharacterOfPosition(file, file.text.length).line;
const hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
let gutterWidth = (lastLine + 1 + "").length;
if (hasMoreThanFiveLines) {
gutterWidth = Math.max(ellipsis.length, gutterWidth);
}
let context = "";
for (let i = firstLine; i <= lastLine; i++) {
context += host.getNewLine();
// If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
// so we'll skip ahead to the second-to-last line.
if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
context += indent + formatColorAndReset(ellipsis.padStart(gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
i = lastLine - 1;
}
const lineStart = getPositionOfLineAndCharacter(file, i, 0);
const lineEnd = i < lastLineInFile ? getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
let lineContent = file.text.slice(lineStart, lineEnd);
lineContent = lineContent.trimEnd(); // trim from end
lineContent = lineContent.replace(/\t/g, " "); // convert tabs to single spaces
// Output the gutter and the actual contents of the line.
context += indent + formatColorAndReset((i + 1 + "").padStart(gutterWidth), gutterStyleSequence) + gutterSeparator;
context += lineContent + host.getNewLine();
// Output the gutter and the error span for the line using tildes.
context += indent + formatColorAndReset("".padStart(gutterWidth), gutterStyleSequence) + gutterSeparator;
context += squiggleColor;
if (i === firstLine) {
// If we're on the last line, then limit it to the last character of the last line.
// Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
const lastCharForLine = i === lastLine ? lastLineChar : undefined;
context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
}
else if (i === lastLine) {
context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
}
else {
// Squiggle the entire line.
context += lineContent.replace(/./g, "~");
}
context += resetEscapeSequence;
}
return context;
}
/** @internal */
export function formatLocation(file: SourceFile, start: number, host: FormatDiagnosticsHost, color: typeof formatColorAndReset = formatColorAndReset): string {
const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start); // TODO: GH#18217
const relativeFileName = host ? convertToRelativePath(file.fileName, host.getCurrentDirectory(), fileName => host.getCanonicalFileName(fileName)) : file.fileName;
let output = "";
output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan);
output += ":";
output += color(`${firstLine + 1}`, ForegroundColorEscapeSequences.Yellow);
output += ":";
output += color(`${firstLineChar + 1}`, ForegroundColorEscapeSequences.Yellow);
return output;
}
export function formatDiagnosticsWithColorAndContext(diagnostics: readonly Diagnostic[], host: FormatDiagnosticsHost): string {
let output = "";
for (const diagnostic of diagnostics) {
if (diagnostic.file) {
const { file, start } = diagnostic;
output += formatLocation(file, start!, host); // TODO: GH#18217
output += " - ";
}
output += formatColorAndReset(diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
output += formatColorAndReset(` TS${diagnostic.code}: `, ForegroundColorEscapeSequences.Grey);
output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
if (diagnostic.file && diagnostic.code !== Diagnostics.File_appears_to_be_binary.code) {
output += host.getNewLine();
output += formatCodeSpan(diagnostic.file, diagnostic.start!, diagnostic.length!, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217
}
if (diagnostic.relatedInformation) {
output += host.getNewLine();
for (const { file, start, length, messageText } of diagnostic.relatedInformation) {
if (file) {
output += host.getNewLine();
output += halfIndent + formatLocation(file, start!, host); // TODO: GH#18217
output += formatCodeSpan(file, start!, length!, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
}
output += host.getNewLine();
output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
}
}
output += host.getNewLine();
}
return output;
}
export function flattenDiagnosticMessageText(diag: string | DiagnosticMessageChain | undefined, newLine: string, indent = 0): string {
if (isString(diag)) {
return diag;
}
else if (diag === undefined) {
return "";
}
let result = "";
if (indent) {
result += newLine;
for (let i = 0; i < indent; i++) {
result += " ";
}
}
result += diag.messageText;
indent++;
if (diag.next) {
for (const kid of diag.next) {
result += flattenDiagnosticMessageText(kid, newLine, indent);
}
}
return result;
}
/**
* Subset of a SourceFile used to calculate index-based resolutions
* This includes some internal fields, so unless you have very good reason,
* (and are willing to use some less stable internals) you should probably just pass a SourceFile.
*
* @internal
*/
export interface SourceFileImportsList {
imports: SourceFile["imports"];
moduleAugmentations: SourceFile["moduleAugmentations"];
impliedNodeFormat?: ResolutionMode;
fileName: string;
packageJsonScope?: SourceFile["packageJsonScope"];
}
/**
* Calculates the resulting resolution mode for some reference in some file - this is generally the explicitly
* provided resolution mode in the reference, unless one is not present, in which case it is the mode of the containing file.
*/
export function getModeForFileReference(ref: FileReference | string, containingFileMode: ResolutionMode): ResolutionMode {
return (isString(ref) ? containingFileMode : ref.resolutionMode) || containingFileMode;
}
/**
* Use `program.getModeForResolutionAtIndex`, which retrieves the correct `compilerOptions`, instead of this function whenever possible.
* Calculates the final resolution mode for an import at some index within a file's `imports` list. This is the resolution mode
* explicitly provided via import attributes, if present, or the syntax the usage would have if emitted to JavaScript. In
* `--module node16` or `nodenext`, this may depend on the file's `impliedNodeFormat`. In `--module preserve`, it depends only on the
* input syntax of the reference. In other `module` modes, when overriding import attributes are not provided, this function returns
* `undefined`, as the result would have no impact on module resolution, emit, or type checking.
* @param file File to fetch the resolution mode within
* @param index Index into the file's complete resolution list to get the resolution of - this is a concatenation of the file's imports and module augmentations
* @param compilerOptions The compiler options for the program that owns the file. If the file belongs to a referenced project, the compiler options
* should be the options of the referenced project, not the referencing project.
*/
export function getModeForResolutionAtIndex(file: SourceFile, index: number, compilerOptions: CompilerOptions): ResolutionMode;
/** @internal @knipignore */
// eslint-disable-next-line @typescript-eslint/unified-signatures
export function getModeForResolutionAtIndex(file: SourceFileImportsList, index: number, compilerOptions: CompilerOptions): ResolutionMode;
export function getModeForResolutionAtIndex(file: SourceFileImportsList, index: number, compilerOptions?: CompilerOptions): ResolutionMode {
// we ensure all elements of file.imports and file.moduleAugmentations have the relevant parent pointers set during program setup,
// so it's safe to use them even pre-bind
return getModeForUsageLocationWorker(file, getModuleNameStringLiteralAt(file, index), compilerOptions);
}
/** @internal */
export function isExclusivelyTypeOnlyImportOrExport(decl: ImportDeclaration | ExportDeclaration | JSDocImportTag): boolean {
if (isExportDeclaration(decl)) {
return decl.isTypeOnly;
}
if (decl.importClause?.isTypeOnly) {
return true;
}
return false;
}
/**
* Use `program.getModeForUsageLocation`, which retrieves the correct `compilerOptions`, instead of this function whenever possible.
* Calculates the final resolution mode for a given module reference node. This function only returns a result when module resolution
* settings allow differing resolution between ESM imports and CJS requires, or when a mode is explicitly provided via import attributes,
* which cause an `import` or `require` condition to be used during resolution regardless of module resolution settings. In absence of
* overriding attributes, and in modes that support differing resolution, the result indicates the syntax the usage would emit to JavaScript.
* Some examples:
*
* ```ts
* // tsc foo.mts --module nodenext
* import {} from "mod";
* // Result: ESNext - the import emits as ESM due to `impliedNodeFormat` set by .mts file extension
*
* // tsc foo.cts --module nodenext
* import {} from "mod";
* // Result: CommonJS - the import emits as CJS due to `impliedNodeFormat` set by .cts file extension
*
* // tsc foo.ts --module preserve --moduleResolution bundler
* import {} from "mod";
* // Result: ESNext - the import emits as ESM due to `--module preserve` and `--moduleResolution bundler`
* // supports conditional imports/exports
*
* // tsc foo.ts --module preserve --moduleResolution node10
* import {} from "mod";
* // Result: undefined - the import emits as ESM due to `--module preserve`, but `--moduleResolution node10`
* // does not support conditional imports/exports
*
* // tsc foo.ts --module commonjs --moduleResolution node10
* import type {} from "mod" with { "resolution-mode": "import" };
* // Result: ESNext - conditional imports/exports always supported with "resolution-mode" attribute
* ```
*
* @param file The file the import or import-like reference is contained within
* @param usage The module reference string
* @param compilerOptions The compiler options for the program that owns the file. If the file belongs to a referenced project, the compiler options
* should be the options of the referenced project, not the referencing project.
* @returns The final resolution mode of the import
*/
export function getModeForUsageLocation(file: SourceFile, usage: StringLiteralLike, compilerOptions: CompilerOptions): ResolutionMode {
return getModeForUsageLocationWorker(file, usage, compilerOptions);
}
function getModeForUsageLocationWorker(file: Pick<SourceFile, "fileName" | "impliedNodeFormat" | "packageJsonScope">, usage: StringLiteralLike, compilerOptions?: CompilerOptions) {
if (isImportDeclaration(usage.parent) || isExportDeclaration(usage.parent) || isJSDocImportTag(usage.parent)) {
const isTypeOnly = isExclusivelyTypeOnlyImportOrExport(usage.parent);
if (isTypeOnly) {
const override = getResolutionModeOverride(usage.parent.attributes);
if (override) {
return override;
}
}
}
if (usage.parent.parent && isImportTypeNode(usage.parent.parent)) {
const override = getResolutionModeOverride(usage.parent.parent.attributes);
if (override) {
return override;
}
}
if (compilerOptions && importSyntaxAffectsModuleResolution(compilerOptions)) {
return getEmitSyntaxForUsageLocationWorker(file, usage, compilerOptions);
}
}
function getEmitSyntaxForUsageLocationWorker(file: Pick<SourceFile, "fileName" | "impliedNodeFormat" | "packageJsonScope">, usage: StringLiteralLike, compilerOptions?: CompilerOptions): ResolutionMode {
if (!compilerOptions) {
// This should always be provided, but we try to fail somewhat
// gracefully to allow projects like ts-node time to update.
return undefined;
}
const exprParentParent = walkUpParenthesizedExpressions(usage.parent)?.parent;
if (exprParentParent && isImportEqualsDeclaration(exprParentParent) || isRequireCall(usage.parent, /*requireStringLiteralLikeArgument*/ false)) {
return ModuleKind.CommonJS;
}
if (isImportCall(walkUpParenthesizedExpressions(usage.parent))) {
return shouldTransformImportCallWorker(file, compilerOptions) ? ModuleKind.CommonJS : ModuleKind.ESNext;
}
// If we're in --module preserve on an input file, we know that an import
// is an import. But if this is a declaration file, we'd prefer to use the
// impliedNodeFormat. Since we want things to be consistent between the two,
// we need to issue errors when the user writes ESM syntax in a definitely-CJS
// file, until/unless declaration emit can indicate a true ESM import. On the
// other hand, writing CJS syntax in a definitely-ESM file is fine, since declaration
// emit preserves the CJS syntax.
const fileEmitMode = getEmitModuleFormatOfFileWorker(file, compilerOptions);
return fileEmitMode === ModuleKind.CommonJS ? ModuleKind.CommonJS :
emitModuleKindIsNonNodeESM(fileEmitMode) || fileEmitMode === ModuleKind.Preserve ? ModuleKind.ESNext :
undefined;
}
/** @internal */
export function getResolutionModeOverride(node: ImportAttributes | undefined, grammarErrorOnNode?: (node: Node, diagnostic: DiagnosticMessage) => void): ResolutionMode | undefined {
if (!node) return undefined;
if (length(node.elements) !== 1) {
grammarErrorOnNode?.(
node,
node.token === SyntaxKind.WithKeyword
? Diagnostics.Type_import_attributes_should_have_exactly_one_key_resolution_mode_with_value_import_or_require
: Diagnostics.Type_import_assertions_should_have_exactly_one_key_resolution_mode_with_value_import_or_require,