-
-
Notifications
You must be signed in to change notification settings - Fork 536
/
index.ts
1685 lines (1522 loc) · 52 KB
/
index.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 { relative, basename, extname, resolve, dirname, join } from 'path';
import sourceMapSupport = require('source-map-support');
import * as ynModule from 'yn';
import { BaseError } from 'make-error';
import * as util from 'util';
import { fileURLToPath } from 'url';
import type * as _ts from 'typescript';
import {
Module,
createRequire as nodeCreateRequire,
createRequireFromPath as nodeCreateRequireFromPath,
} from 'module';
import type _createRequire from 'create-require';
import { Transpiler, TranspilerFactory } from './transpilers/types';
import { getDefaultTsconfigJsonForNodeVersion } from './tsconfigs';
/** @internal */
export const createRequire =
nodeCreateRequire ??
nodeCreateRequireFromPath ??
(require('create-require') as typeof _createRequire);
export { createRepl, CreateReplOptions, ReplService } from './repl';
/**
* Does this version of node obey the package.json "type" field
* and throw ERR_REQUIRE_ESM when attempting to require() an ESM modules.
*/
const engineSupportsPackageTypeField =
parseInt(process.versions.node.split('.')[0], 10) >= 12;
/**
* Assert that script can be loaded as CommonJS when we attempt to require it.
* If it should be loaded as ESM, throw ERR_REQUIRE_ESM like node does.
*
* Loaded conditionally so we don't need to support older node versions
*/
const assertScriptCanLoadAsCJS: (
filename: string
) => void = engineSupportsPackageTypeField
? require('../dist-raw/node-cjs-loader-utils').assertScriptCanLoadAsCJSImpl
: () => {
/* noop */
};
/**
* Registered `ts-node` instance information.
*/
export const REGISTER_INSTANCE = Symbol.for('ts-node.register.instance');
/**
* Expose `REGISTER_INSTANCE` information on node.js `process`.
*/
declare global {
namespace NodeJS {
interface Process {
[REGISTER_INSTANCE]?: Service;
}
}
}
/** @internal */
export const env = process.env as ProcessEnv;
/**
* Declare all env vars, to aid discoverability.
* If an env var affects ts-node's behavior, it should not be buried somewhere in our codebase.
* @internal
*/
export interface ProcessEnv {
TS_NODE_DEBUG?: string;
TS_NODE_CWD?: string;
/** @deprecated */
TS_NODE_DIR?: string;
TS_NODE_EMIT?: string;
/** @deprecated */
TS_NODE_SCOPE?: string;
TS_NODE_FILES?: string;
TS_NODE_PRETTY?: string;
TS_NODE_COMPILER?: string;
TS_NODE_COMPILER_OPTIONS?: string;
TS_NODE_IGNORE?: string;
TS_NODE_PROJECT?: string;
TS_NODE_SKIP_PROJECT?: string;
TS_NODE_SKIP_IGNORE?: string;
TS_NODE_PREFER_TS_EXTS?: string;
TS_NODE_IGNORE_DIAGNOSTICS?: string;
TS_NODE_TRANSPILE_ONLY?: string;
TS_NODE_TYPE_CHECK?: string;
TS_NODE_COMPILER_HOST?: string;
TS_NODE_LOG_ERROR?: string;
TS_NODE_HISTORY?: string;
NODE_NO_READLINE?: string;
}
/**
* @internal
*/
export const INSPECT_CUSTOM = util.inspect.custom || 'inspect';
/**
* Wrapper around yn module that returns `undefined` instead of `null`.
* This is implemented by yn v4, but we're staying on v3 to avoid v4's node 10 requirement.
*/
function yn(value: string | undefined) {
return ynModule(value) ?? undefined;
}
/**
* Debugging `ts-node`.
*/
const shouldDebug = yn(env.TS_NODE_DEBUG);
/** @internal */
export const debug = shouldDebug
? (...args: any) =>
console.log(`[ts-node ${new Date().toISOString()}]`, ...args)
: () => undefined;
const debugFn = shouldDebug
? <T, U>(key: string, fn: (arg: T) => U) => {
let i = 0;
return (x: T) => {
debug(key, x, ++i);
return fn(x);
};
}
: <T, U>(_: string, fn: (arg: T) => U) => fn;
/**
* Common TypeScript interfaces between versions.
*/
export interface TSCommon {
version: typeof _ts.version;
sys: typeof _ts.sys;
ScriptSnapshot: typeof _ts.ScriptSnapshot;
displayPartsToString: typeof _ts.displayPartsToString;
createLanguageService: typeof _ts.createLanguageService;
getDefaultLibFilePath: typeof _ts.getDefaultLibFilePath;
getPreEmitDiagnostics: typeof _ts.getPreEmitDiagnostics;
flattenDiagnosticMessageText: typeof _ts.flattenDiagnosticMessageText;
transpileModule: typeof _ts.transpileModule;
ModuleKind: typeof _ts.ModuleKind;
ScriptTarget: typeof _ts.ScriptTarget;
findConfigFile: typeof _ts.findConfigFile;
readConfigFile: typeof _ts.readConfigFile;
parseJsonConfigFileContent: typeof _ts.parseJsonConfigFileContent;
formatDiagnostics: typeof _ts.formatDiagnostics;
formatDiagnosticsWithColorAndContext: typeof _ts.formatDiagnosticsWithColorAndContext;
createDocumentRegistry: typeof _ts.createDocumentRegistry;
JsxEmit: typeof _ts.JsxEmit;
createModuleResolutionCache: typeof _ts.createModuleResolutionCache;
resolveModuleName: typeof _ts.resolveModuleName;
resolveModuleNameFromCache: typeof _ts.resolveModuleNameFromCache;
resolveTypeReferenceDirective: typeof _ts.resolveTypeReferenceDirective;
createIncrementalCompilerHost: typeof _ts.createIncrementalCompilerHost;
createSourceFile: typeof _ts.createSourceFile;
getDefaultLibFileName: typeof _ts.getDefaultLibFileName;
createIncrementalProgram: typeof _ts.createIncrementalProgram;
createEmitAndSemanticDiagnosticsBuilderProgram: typeof _ts.createEmitAndSemanticDiagnosticsBuilderProgram;
libs?: string[];
}
/**
* Compiler APIs we use that are marked internal and not included in TypeScript's public API declarations
* @internal
*/
export interface TSInternal {
// https://github.com/microsoft/TypeScript/blob/4a34294908bed6701dcba2456ca7ac5eafe0ddff/src/compiler/core.ts#L1906-L1909
createGetCanonicalFileName(
useCaseSensitiveFileNames: boolean
): TSInternal.GetCanonicalFileName;
// https://github.com/microsoft/TypeScript/blob/c117c266e09c80e8a06b24a6e94b9d018f5fae6b/src/compiler/commandLineParser.ts#L2054
convertToTSConfig(
configParseResult: _ts.ParsedCommandLine,
configFileName: string,
host: TSInternal.ConvertToTSConfigHost
): any;
}
/** @internal */
export namespace TSInternal {
// https://github.com/microsoft/TypeScript/blob/4a34294908bed6701dcba2456ca7ac5eafe0ddff/src/compiler/core.ts#L1906
export type GetCanonicalFileName = (fileName: string) => string;
// https://github.com/microsoft/TypeScript/blob/c117c266e09c80e8a06b24a6e94b9d018f5fae6b/src/compiler/commandLineParser.ts#L2041
export interface ConvertToTSConfigHost {
getCurrentDirectory(): string;
useCaseSensitiveFileNames: boolean;
}
}
export interface TSCompilerFactory {
createTypescriptCompiler(options?: any): TSCommon;
}
/**
* Export the current version.
*/
export const VERSION = require('../package.json').version;
/**
* Options for creating a new TypeScript compiler instance.
*/
export interface CreateOptions {
/**
* Behave as if invoked within this working directory. Roughly equivalent to `cd $dir && ts-node ...`
*
* @default process.cwd()
*/
cwd?: string;
/**
* Legacy alias for `cwd`
*
* @deprecated use `projectSearchDir` or `cwd`
*/
dir?: string;
/**
* Emit output files into `.ts-node` directory.
*
* @default false
*/
emit?: boolean;
/**
* Scope compiler to files within `scopeDir`.
*
* @default false
*/
scope?: boolean;
/**
* @default First of: `tsconfig.json` "rootDir" if specified, directory containing `tsconfig.json`, or cwd if no `tsconfig.json` is loaded.
*/
scopeDir?: string;
/**
* Use pretty diagnostic formatter.
*
* @default false
*/
pretty?: boolean;
/**
* Use TypeScript's faster `transpileModule`.
*
* @default false
*/
transpileOnly?: boolean;
/**
* **DEPRECATED** Specify type-check is enabled (e.g. `transpileOnly == false`).
*
* @default true
*/
typeCheck?: boolean;
/**
* Use TypeScript's compiler host API instead of the language service API.
*
* @default false
*/
compilerHost?: boolean;
/**
* Logs TypeScript errors to stderr instead of throwing exceptions.
*
* @default false
*/
logError?: boolean;
/**
* Load "files" and "include" from `tsconfig.json` on startup.
*
* Default is to override `tsconfig.json` "files" and "include" to only include the entrypoint script.
*
* @default false
*/
files?: boolean;
/**
* Specify a custom TypeScript compiler.
*
* @default "typescript"
*/
compiler?: string;
/**
* Specify a custom transpiler for use with transpileOnly
*/
transpiler?: string | [string, object];
/**
* Paths which should not be compiled.
*
* Each string in the array is converted to a regular expression via `new RegExp()` and tested against source paths prior to compilation.
*
* Source paths are normalized to posix-style separators, relative to the directory containing `tsconfig.json` or to cwd if no `tsconfig.json` is loaded.
*
* Default is to ignore all node_modules subdirectories.
*
* @default ["(?:^|/)node_modules/"]
*/
ignore?: string[];
/**
* Path to TypeScript config file or directory containing a `tsconfig.json`.
* Similar to the `tsc --project` flag: https://www.typescriptlang.org/docs/handbook/compiler-options.html
*/
project?: string;
/**
* Search for TypeScript config file (`tsconfig.json`) in this or parent directories.
*/
projectSearchDir?: string;
/**
* Skip project config resolution and loading.
*
* @default false
*/
skipProject?: boolean;
/**
* Skip ignore check, so that compilation will be attempted for all files with matching extensions.
*
* @default false
*/
skipIgnore?: boolean;
/**
* JSON object to merge with TypeScript `compilerOptions`.
*
* @allOf [{"$ref": "https://schemastore.azurewebsites.net/schemas/json/tsconfig.json#definitions/compilerOptionsDefinition/properties/compilerOptions"}]
*/
compilerOptions?: object;
/**
* Ignore TypeScript warnings by diagnostic code.
*/
ignoreDiagnostics?: Array<number | string>;
/**
* Modules to require, like node's `--require` flag.
*
* If specified in `tsconfig.json`, the modules will be resolved relative to the `tsconfig.json` file.
*
* If specified programmatically, each input string should be pre-resolved to an absolute path for
* best results.
*/
require?: Array<string>;
readFile?: (path: string) => string | undefined;
fileExists?: (path: string) => boolean;
transformers?:
| _ts.CustomTransformers
| ((p: _ts.Program) => _ts.CustomTransformers);
/**
* True if require() hooks should interop with experimental ESM loader.
* Enabled explicitly via a flag since it is a breaking change.
* @internal
*/
experimentalEsmLoader?: boolean;
}
/**
* Options for registering a TypeScript compiler instance globally.
*/
export interface RegisterOptions extends CreateOptions {
/**
* Re-order file extensions so that TypeScript imports are preferred.
*
* For example, when both `index.js` and `index.ts` exist, enabling this option causes `require('./index')` to resolve to `index.ts` instead of `index.js`
*
* @default false
*/
preferTsExts?: boolean;
}
/**
* Must be an interface to support `typescript-json-schema`.
*/
export interface TsConfigOptions
extends Omit<
RegisterOptions,
| 'transformers'
| 'readFile'
| 'fileExists'
| 'skipProject'
| 'project'
| 'dir'
| 'cwd'
| 'projectSearchDir'
| 'scope'
| 'scopeDir'
| 'experimentalEsmLoader'
> {}
/**
* Like `Object.assign`, but ignores `undefined` properties.
*/
function assign<T extends object>(initialValue: T, ...sources: Array<T>): T {
for (const source of sources) {
for (const key of Object.keys(source)) {
const value = (source as any)[key];
if (value !== undefined) (initialValue as any)[key] = value;
}
}
return initialValue;
}
/**
* Information retrieved from type info check.
*/
export interface TypeInfo {
name: string;
comment: string;
}
/**
* Default register options, including values specified via environment
* variables.
* @internal
*/
export const DEFAULTS: RegisterOptions = {
cwd: env.TS_NODE_CWD ?? env.TS_NODE_DIR,
emit: yn(env.TS_NODE_EMIT),
scope: yn(env.TS_NODE_SCOPE),
files: yn(env.TS_NODE_FILES),
pretty: yn(env.TS_NODE_PRETTY),
compiler: env.TS_NODE_COMPILER,
compilerOptions: parse(env.TS_NODE_COMPILER_OPTIONS),
ignore: split(env.TS_NODE_IGNORE),
project: env.TS_NODE_PROJECT,
skipProject: yn(env.TS_NODE_SKIP_PROJECT),
skipIgnore: yn(env.TS_NODE_SKIP_IGNORE),
preferTsExts: yn(env.TS_NODE_PREFER_TS_EXTS),
ignoreDiagnostics: split(env.TS_NODE_IGNORE_DIAGNOSTICS),
transpileOnly: yn(env.TS_NODE_TRANSPILE_ONLY),
typeCheck: yn(env.TS_NODE_TYPE_CHECK),
compilerHost: yn(env.TS_NODE_COMPILER_HOST),
logError: yn(env.TS_NODE_LOG_ERROR),
experimentalEsmLoader: false,
};
/**
* TypeScript compiler option values required by `ts-node` which cannot be overridden.
*/
const TS_NODE_COMPILER_OPTIONS = {
sourceMap: true,
inlineSourceMap: false,
inlineSources: true,
declaration: false,
noEmit: false,
outDir: '.ts-node',
};
/**
* Split a string array of values.
* @internal
*/
export function split(value: string | undefined) {
return typeof value === 'string' ? value.split(/ *, */g) : undefined;
}
/**
* Parse a string as JSON.
* @internal
*/
export function parse(value: string | undefined): object | undefined {
return typeof value === 'string' ? JSON.parse(value) : undefined;
}
/**
* Replace backslashes with forward slashes.
* @internal
*/
export function normalizeSlashes(value: string): string {
return value.replace(/\\/g, '/');
}
/**
* TypeScript diagnostics error.
*/
export class TSError extends BaseError {
name = 'TSError';
constructor(public diagnosticText: string, public diagnosticCodes: number[]) {
super(`⨯ Unable to compile TypeScript:\n${diagnosticText}`);
}
/**
* @internal
*/
[INSPECT_CUSTOM]() {
return this.diagnosticText;
}
}
/**
* Primary ts-node service, which wraps the TypeScript API and can compile TypeScript to JavaScript
*/
export interface Service {
ts: TSCommon;
config: _ts.ParsedCommandLine;
options: RegisterOptions;
enabled(enabled?: boolean): boolean;
ignored(fileName: string): boolean;
compile(code: string, fileName: string, lineOffset?: number): string;
getTypeInfo(code: string, fileName: string, position: number): TypeInfo;
/** @internal */
configFilePath: string | undefined;
}
/**
* Re-export of `Service` interface for backwards-compatibility
* @deprecated use `Service` instead
* @see {Service}
*/
export type Register = Service;
/**
* Cached fs operation wrapper.
*/
function cachedLookup<T>(fn: (arg: string) => T): (arg: string) => T {
const cache = new Map<string, T>();
return (arg: string): T => {
if (!cache.has(arg)) {
cache.set(arg, fn(arg));
}
return cache.get(arg)!;
};
}
/** @internal */
export function getExtensions(config: _ts.ParsedCommandLine) {
const tsExtensions = ['.ts'];
const jsExtensions = [];
// Enable additional extensions when JSX or `allowJs` is enabled.
if (config.options.jsx) tsExtensions.push('.tsx');
if (config.options.allowJs) jsExtensions.push('.js');
if (config.options.jsx && config.options.allowJs) jsExtensions.push('.jsx');
return { tsExtensions, jsExtensions };
}
/**
* Register TypeScript compiler instance onto node.js
*/
export function register(opts: RegisterOptions = {}): Service {
const originalJsHandler = require.extensions['.js'];
const service = create(opts);
const { tsExtensions, jsExtensions } = getExtensions(service.config);
const extensions = [...tsExtensions, ...jsExtensions];
// Expose registered instance globally.
process[REGISTER_INSTANCE] = service;
// Register the extensions.
registerExtensions(
service.options.preferTsExts,
extensions,
service,
originalJsHandler
);
// Require specified modules before start-up.
(Module as any)._preloadModules(service.options.require);
return service;
}
/**
* Create TypeScript compiler instance.
*/
export function create(rawOptions: CreateOptions = {}): Service {
const cwd = resolve(
rawOptions.cwd ?? rawOptions.dir ?? DEFAULTS.cwd ?? process.cwd()
);
const compilerName = rawOptions.compiler ?? DEFAULTS.compiler;
/**
* Load the typescript compiler. It is required to load the tsconfig but might
* be changed by the tsconfig, so we have to do this twice.
*/
function loadCompiler(name: string | undefined, relativeToPath: string) {
const compiler = require.resolve(name || 'typescript', {
paths: [relativeToPath, __dirname],
});
const ts: typeof _ts = require(compiler);
return { compiler, ts };
}
// Compute minimum options to read the config file.
let { compiler, ts } = loadCompiler(
compilerName,
rawOptions.projectSearchDir ?? rawOptions.project ?? cwd
);
// Read config file and merge new options between env and CLI options.
const { configFilePath, config, tsNodeOptionsFromTsconfig } = readConfig(
cwd,
ts,
rawOptions
);
const options = assign<RegisterOptions>(
{},
DEFAULTS,
tsNodeOptionsFromTsconfig || {},
rawOptions
);
options.require = [
...(tsNodeOptionsFromTsconfig.require || []),
...(rawOptions.require || []),
];
// Re-load the compiler in case it has changed.
// Compiler is loaded relative to tsconfig.json, so tsconfig discovery may cause us to load a
// different compiler than we did above, even if the name has not changed.
if (configFilePath) {
({ compiler, ts } = loadCompiler(options.compiler, configFilePath));
}
const readFile = options.readFile || ts.sys.readFile;
const fileExists = options.fileExists || ts.sys.fileExists;
// typeCheck can override transpileOnly, useful for CLI flag to override config file
const transpileOnly =
options.transpileOnly === true && options.typeCheck !== true;
const transformers = options.transformers || undefined;
const ignoreDiagnostics = [
6059, // "'rootDir' is expected to contain all source files."
18002, // "The 'files' list in config file is empty."
18003, // "No inputs were found in config file."
...(options.ignoreDiagnostics || []),
].map(Number);
const configDiagnosticList = filterDiagnostics(
config.errors,
ignoreDiagnostics
);
const outputCache = new Map<
string,
{
content: string;
}
>();
const configFileDirname = configFilePath ? dirname(configFilePath) : null;
const scopeDir =
options.scopeDir ?? config.options.rootDir ?? configFileDirname ?? cwd;
const ignoreBaseDir = configFileDirname ?? cwd;
const isScoped = options.scope
? (fileName: string) => relative(scopeDir, fileName).charAt(0) !== '.'
: () => true;
const shouldIgnore = createIgnore(
ignoreBaseDir,
options.skipIgnore
? []
: (options.ignore || ['(?:^|/)node_modules/']).map(
(str) => new RegExp(str)
)
);
const diagnosticHost: _ts.FormatDiagnosticsHost = {
getNewLine: () => ts.sys.newLine,
getCurrentDirectory: () => cwd,
getCanonicalFileName: ts.sys.useCaseSensitiveFileNames
? (x) => x
: (x) => x.toLowerCase(),
};
if (options.transpileOnly && typeof transformers === 'function') {
throw new TypeError(
'Transformers function is unavailable in "--transpile-only"'
);
}
let customTranspiler: Transpiler | undefined = undefined;
if (options.transpiler) {
if (!transpileOnly)
throw new Error(
'Custom transpiler can only be used when transpileOnly is enabled.'
);
const transpilerName =
typeof options.transpiler === 'string'
? options.transpiler
: options.transpiler[0];
const transpilerOptions =
typeof options.transpiler === 'string' ? {} : options.transpiler[1] ?? {};
// TODO mimic fixed resolution logic from loadCompiler master
// TODO refactor into a more generic "resolve dep relative to project" helper
const transpilerPath = require.resolve(transpilerName, {
paths: [cwd, __dirname],
});
const transpilerFactory: TranspilerFactory = require(transpilerPath).create;
customTranspiler = transpilerFactory({
service: { options, config },
...transpilerOptions,
});
}
// Install source map support and read from memory cache.
sourceMapSupport.install({
environment: 'node',
retrieveFile(pathOrUrl: string) {
let path = pathOrUrl;
// If it's a file URL, convert to local path
// Note: fileURLToPath does not exist on early node v10
// I could not find a way to handle non-URLs except to swallow an error
if (options.experimentalEsmLoader && path.startsWith('file://')) {
try {
path = fileURLToPath(path);
} catch (e) {
/* swallow error */
}
}
path = normalizeSlashes(path);
return outputCache.get(path)?.content || '';
},
});
const formatDiagnostics =
process.stdout.isTTY || options.pretty
? ts.formatDiagnosticsWithColorAndContext || ts.formatDiagnostics
: ts.formatDiagnostics;
function createTSError(diagnostics: ReadonlyArray<_ts.Diagnostic>) {
const diagnosticText = formatDiagnostics(diagnostics, diagnosticHost);
const diagnosticCodes = diagnostics.map((x) => x.code);
return new TSError(diagnosticText, diagnosticCodes);
}
function reportTSError(configDiagnosticList: _ts.Diagnostic[]) {
const error = createTSError(configDiagnosticList);
if (options.logError) {
// Print error in red color and continue execution.
console.error('\x1b[31m%s\x1b[0m', error);
} else {
// Throw error and exit the script.
throw error;
}
}
// Render the configuration errors.
if (configDiagnosticList.length) reportTSError(configDiagnosticList);
/**
* Get the extension for a transpiled file.
*/
const getExtension =
config.options.jsx === ts.JsxEmit.Preserve
? (path: string) => (/\.[tj]sx$/.test(path) ? '.jsx' : '.js')
: (_: string) => '.js';
/**
* Create the basic required function using transpile mode.
*/
let getOutput: (code: string, fileName: string) => SourceOutput;
let getTypeInfo: (
_code: string,
_fileName: string,
_position: number
) => TypeInfo;
const getCanonicalFileName = ((ts as unknown) as TSInternal).createGetCanonicalFileName(
ts.sys.useCaseSensitiveFileNames
);
// In a factory because these are shared across both CompilerHost and LanguageService codepaths
function createResolverFunctions(serviceHost: _ts.ModuleResolutionHost) {
const moduleResolutionCache = ts.createModuleResolutionCache(
cwd,
getCanonicalFileName,
config.options
);
const knownInternalFilenames = new Set<string>();
/** "Buckets" (module directories) whose contents should be marked "internal" */
const internalBuckets = new Set<string>();
// Get bucket for a source filename. Bucket is the containing `./node_modules/*/` directory
// For '/project/node_modules/foo/node_modules/bar/lib/index.js' bucket is '/project/node_modules/foo/node_modules/bar/'
// For '/project/node_modules/foo/node_modules/@scope/bar/lib/index.js' bucket is '/project/node_modules/foo/node_modules/@scope/bar/'
const moduleBucketRe = /.*\/node_modules\/(?:@[^\/]+\/)?[^\/]+\//;
function getModuleBucket(filename: string) {
const find = moduleBucketRe.exec(filename);
if (find) return find[0];
return '';
}
// Mark that this file and all siblings in its bucket should be "internal"
function markBucketOfFilenameInternal(filename: string) {
internalBuckets.add(getModuleBucket(filename));
}
function isFileInInternalBucket(filename: string) {
return internalBuckets.has(getModuleBucket(filename));
}
function isFileKnownToBeInternal(filename: string) {
return knownInternalFilenames.has(filename);
}
/**
* If we need to emit JS for a file, force TS to consider it non-external
*/
const fixupResolvedModule = (
resolvedModule: _ts.ResolvedModule | _ts.ResolvedTypeReferenceDirective
) => {
const { resolvedFileName } = resolvedModule;
if (resolvedFileName === undefined) return;
// .ts is always switched to internal
// .js is switched on-demand
if (
resolvedModule.isExternalLibraryImport &&
((resolvedFileName.endsWith('.ts') &&
!resolvedFileName.endsWith('.d.ts')) ||
isFileKnownToBeInternal(resolvedFileName) ||
isFileInInternalBucket(resolvedFileName))
) {
resolvedModule.isExternalLibraryImport = false;
}
if (!resolvedModule.isExternalLibraryImport) {
knownInternalFilenames.add(resolvedFileName);
}
};
/*
* NOTE:
* Older ts versions do not pass `redirectedReference` nor `options`.
* We must pass `redirectedReference` to newer ts versions, but cannot rely on `options`, hence the weird argument name
*/
const resolveModuleNames: _ts.LanguageServiceHost['resolveModuleNames'] = (
moduleNames: string[],
containingFile: string,
reusedNames: string[] | undefined,
redirectedReference: _ts.ResolvedProjectReference | undefined,
optionsOnlyWithNewerTsVersions: _ts.CompilerOptions
): (_ts.ResolvedModule | undefined)[] => {
return moduleNames.map((moduleName) => {
const { resolvedModule } = ts.resolveModuleName(
moduleName,
containingFile,
config.options,
serviceHost,
moduleResolutionCache,
redirectedReference
);
if (resolvedModule) {
fixupResolvedModule(resolvedModule);
}
return resolvedModule;
});
};
// language service never calls this, but TS docs recommend that we implement it
const getResolvedModuleWithFailedLookupLocationsFromCache: _ts.LanguageServiceHost['getResolvedModuleWithFailedLookupLocationsFromCache'] = (
moduleName,
containingFile
): _ts.ResolvedModuleWithFailedLookupLocations | undefined => {
const ret = ts.resolveModuleNameFromCache(
moduleName,
containingFile,
moduleResolutionCache
);
if (ret && ret.resolvedModule) {
fixupResolvedModule(ret.resolvedModule);
}
return ret;
};
const resolveTypeReferenceDirectives: _ts.LanguageServiceHost['resolveTypeReferenceDirectives'] = (
typeDirectiveNames: string[],
containingFile: string,
redirectedReference: _ts.ResolvedProjectReference | undefined,
options: _ts.CompilerOptions
): (_ts.ResolvedTypeReferenceDirective | undefined)[] => {
// Note: seems to be called with empty typeDirectiveNames array for all files.
return typeDirectiveNames.map((typeDirectiveName) => {
const {
resolvedTypeReferenceDirective,
} = ts.resolveTypeReferenceDirective(
typeDirectiveName,
containingFile,
config.options,
serviceHost,
redirectedReference
);
if (resolvedTypeReferenceDirective) {
fixupResolvedModule(resolvedTypeReferenceDirective);
}
return resolvedTypeReferenceDirective;
});
};
return {
resolveModuleNames,
getResolvedModuleWithFailedLookupLocationsFromCache,
resolveTypeReferenceDirectives,
isFileKnownToBeInternal,
markBucketOfFilenameInternal,
};
}
// Use full language services when the fast option is disabled.
if (!transpileOnly) {
const fileContents = new Map<string, string>();
const rootFileNames = new Set(config.fileNames);
const cachedReadFile = cachedLookup(debugFn('readFile', readFile));
// Use language services by default (TODO: invert next major version).
if (!options.compilerHost) {
let projectVersion = 1;
const fileVersions = new Map(
Array.from(rootFileNames).map((fileName) => [fileName, 0])
);
const getCustomTransformers = () => {
if (typeof transformers === 'function') {
const program = service.getProgram();
return program ? transformers(program) : undefined;
}
return transformers;
};
// Create the compiler host for type checking.
const serviceHost: _ts.LanguageServiceHost &
Required<Pick<_ts.LanguageServiceHost, 'fileExists' | 'readFile'>> = {
getProjectVersion: () => String(projectVersion),
getScriptFileNames: () => Array.from(rootFileNames),
getScriptVersion: (fileName: string) => {
const version = fileVersions.get(fileName);
return version ? version.toString() : '';
},
getScriptSnapshot(fileName: string) {
// TODO ordering of this with getScriptVersion? Should they sync up?
let contents = fileContents.get(fileName);
// Read contents into TypeScript memory cache.
if (contents === undefined) {
contents = cachedReadFile(fileName);
if (contents === undefined) return;
fileVersions.set(fileName, 1);
fileContents.set(fileName, contents);
projectVersion++;
}
return ts.ScriptSnapshot.fromString(contents);
},
readFile: cachedReadFile,
readDirectory: ts.sys.readDirectory,
getDirectories: cachedLookup(
debugFn('getDirectories', ts.sys.getDirectories)
),
fileExists: cachedLookup(debugFn('fileExists', fileExists)),
directoryExists: cachedLookup(
debugFn('directoryExists', ts.sys.directoryExists)
),
realpath: ts.sys.realpath
? cachedLookup(debugFn('realpath', ts.sys.realpath))
: undefined,
getNewLine: () => ts.sys.newLine,
useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,
getCurrentDirectory: () => cwd,
getCompilationSettings: () => config.options,
getDefaultLibFileName: () => ts.getDefaultLibFilePath(config.options),
getCustomTransformers: getCustomTransformers,
};
const {
resolveModuleNames,
getResolvedModuleWithFailedLookupLocationsFromCache,
resolveTypeReferenceDirectives,
isFileKnownToBeInternal,
markBucketOfFilenameInternal,
} = createResolverFunctions(serviceHost);
serviceHost.resolveModuleNames = resolveModuleNames;
serviceHost.getResolvedModuleWithFailedLookupLocationsFromCache = getResolvedModuleWithFailedLookupLocationsFromCache;
serviceHost.resolveTypeReferenceDirectives = resolveTypeReferenceDirectives;
const registry = ts.createDocumentRegistry(
ts.sys.useCaseSensitiveFileNames,
cwd
);
const service = ts.createLanguageService(serviceHost, registry);
const updateMemoryCache = (contents: string, fileName: string) => {
// Add to `rootFiles` as necessary, either to make TS include a file it has not seen,
// or to trigger a re-classification of files from external to internal.
if (
!rootFileNames.has(fileName) &&
!isFileKnownToBeInternal(fileName)
) {
markBucketOfFilenameInternal(fileName);
rootFileNames.add(fileName);
// Increment project version for every change to rootFileNames.
projectVersion++;
}
const previousVersion = fileVersions.get(fileName) || 0;
const previousContents = fileContents.get(fileName);
// Avoid incrementing cache when nothing has changed.
if (contents !== previousContents) {
fileVersions.set(fileName, previousVersion + 1);
fileContents.set(fileName, contents);
// Increment project version for every file change.
projectVersion++;
}
};
let previousProgram: _ts.Program | undefined = undefined;
getOutput = (code: string, fileName: string) => {
updateMemoryCache(code, fileName);
const programBefore = service.getProgram();
if (programBefore !== previousProgram) {
debug(
`compiler rebuilt Program instance when getting output for ${fileName}`
);
}