forked from microsoft/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproject.js
1067 lines (984 loc) · 42.9 KB
/
project.js
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
// @ts-check
const path = require("path");
const fs = require("fs");
const gulp = require("./gulp");
const gulpif = require("gulp-if");
const log = require("fancy-log"); // was `require("gulp-util").log (see https://github.com/gulpjs/gulp-util)
const chalk = require("./chalk");
const sourcemaps = require("gulp-sourcemaps");
const merge2 = require("merge2");
const tsc = require("gulp-typescript");
const tsc_oop = require("./gulp-typescript-oop");
const upToDate = require("./upToDate");
const ts = require("../../lib/typescript");
const del = require("del");
const needsUpdate = require("./needsUpdate");
const mkdirp = require("./mkdirp");
const { reportDiagnostics } = require("./diagnostics");
const { CountdownEvent, ManualResetEvent, Semaphore } = require("prex");
const workStartedEvent = new ManualResetEvent();
const countdown = new CountdownEvent(0);
// internal `Gulp` instance for compilation artifacts.
const compilationGulp = new gulp.Gulp();
/** @type {Map<ResolvedProjectSpec, ProjectGraph>} */
const projectGraphCache = new Map();
/** @type {Map<string, { typescript: string, alias: string, paths: ResolvedPathOptions }>} */
const typescriptAliasMap = new Map();
// TODO: allow concurrent outer builds to be run in parallel
const sem = new Semaphore(1);
/**
* @param {string|string[]} taskName
* @param {() => any} [cb]
*/
function start(taskName, cb) {
return sem.wait().then(() => new Promise((resolve, reject) => {
compilationGulp.start(taskName, err => {
if (err) {
reject(err);
}
else if (cb) {
try {
resolve(cb());
}
catch (e) {
reject(err);
}
}
else {
resolve();
}
});
})).then(() => {
sem.release()
}, e => {
sem.release();
throw e;
});
}
/**
* Defines a gulp orchestration for a TypeScript project, returning a callback that can be used to trigger compilation.
* @param {string} projectSpec The path to a tsconfig.json file or its containing directory.
* @param {CompileOptions} [options] Project compilation options.
* @returns {() => Promise<void>}
*/
function createCompiler(projectSpec, options) {
const resolvedOptions = resolveCompileOptions(options);
const resolvedProjectSpec = resolveProjectSpec(projectSpec, resolvedOptions.paths, /*referrer*/ undefined);
const projectGraph = getOrCreateProjectGraph(resolvedProjectSpec, resolvedOptions.paths);
projectGraph.isRoot = true;
const taskName = compileTaskName(ensureCompileTask(projectGraph, resolvedOptions), resolvedOptions.typescript);
return () => start(taskName);
}
exports.createCompiler = createCompiler;
/**
* Defines and executes a gulp orchestration for a TypeScript project.
* @param {string} projectSpec The path to a tsconfig.json file or its containing directory.
* @param {CompileOptions} [options] Project compilation options.
* @returns {Promise<void>}
*
* @typedef CompileOptions
* @property {string} [cwd] The path to use for the current working directory. Defaults to `process.cwd()`.
* @property {string} [base] The path to use as the base for relative paths. Defaults to `cwd`.
* @property {string} [typescript] A module specifier or path (relative to gulpfile.js) to the version of TypeScript to use.
* @property {Hook} [js] Pipeline hook for .js file outputs.
* @property {Hook} [dts] Pipeline hook for .d.ts file outputs.
* @property {boolean} [verbose] Indicates whether verbose logging is enabled.
* @property {boolean} [force] Force recompilation (no up-to-date check).
* @property {boolean} [inProcess] Indicates whether to run gulp-typescript in-process or out-of-process (default).
*
* @typedef {(stream: NodeJS.ReadableStream) => NodeJS.ReadWriteStream} Hook
*/
function compile(projectSpec, options) {
const compiler = createCompiler(projectSpec, options);
return compiler();
}
exports.compile = compile;
/**
* Defines a gulp orchestration to clean the outputs of a TypeScript project, returning a callback that can be used to trigger compilation.
* @param {string} projectSpec The path to a tsconfig.json file or its containing directory.
* @param {PathOptions} [options] Project clean options.
*/
function createCleaner(projectSpec, options) {
const paths = resolvePathOptions(options);
const resolvedProjectSpec = resolveProjectSpec(projectSpec, paths, /*referrer*/ undefined);
const projectGraph = getOrCreateProjectGraph(resolvedProjectSpec, paths);
projectGraph.isRoot = true;
const taskName = cleanTaskName(ensureCleanTask(projectGraph));
return () => start(taskName);
}
exports.createCleaner = createCleaner;
/**
* Defines and executes a gulp orchestration to clean the outputs of a TypeScript project.
* @param {string} projectSpec The path to a tsconfig.json file or its containing directory.
* @param {PathOptions} [options] Project clean options.
*/
function clean(projectSpec, options) {
const cleaner = createCleaner(projectSpec, options);
return cleaner();
}
exports.clean = clean;
/**
* Defines a watcher to execute a gulp orchestration to recompile a TypeScript project.
* @param {string} projectSpec
* @param {WatchCallback | string[] | CompileOptions} [options]
* @param {WatchCallback | string[]} [tasks]
* @param {WatchCallback} [callback]
*/
function watch(projectSpec, options, tasks, callback) {
if (typeof tasks === "function") callback = tasks, tasks = /**@type {string[] | undefined}*/(undefined);
if (typeof options === "function") callback = options, tasks = /**@type {string[] | undefined}*/(undefined), options = /**@type {CompileOptions | undefined}*/(undefined);
if (Array.isArray(options)) tasks = options, options = /**@type {CompileOptions | undefined}*/(undefined);
const resolvedOptions = resolveCompileOptions(options);
resolvedOptions.watch = true;
const resolvedProjectSpec = resolveProjectSpec(projectSpec, resolvedOptions.paths, /*referrer*/ undefined);
const projectGraph = getOrCreateProjectGraph(resolvedProjectSpec, resolvedOptions.paths);
projectGraph.isRoot = true;
ensureWatcher(projectGraph, resolvedOptions, tasks, callback);
}
exports.watch = watch;
/**
* Adds a named alias for a TypeScript language service path
* @param {string} alias An alias for a TypeScript version.
* @param {string} typescript An alias or module specifier for a TypeScript version.
* @param {PathOptions} [options] Options used to resolve the path to `typescript`.
*/
function addTypeScript(alias, typescript, options) {
const paths = resolvePathOptions(options);
typescriptAliasMap.set(alias, { typescript, alias, paths });
}
exports.addTypeScript = addTypeScript;
/**
* Flattens a project with project references into a single project.
* @param {string} projectSpec The path to a tsconfig.json file or its containing directory.
* @param {string} flattenedProjectSpec The output path for the flattened tsconfig.json file.
* @param {FlattenOptions} [options] Options used to flatten a project hierarchy.
*
* @typedef FlattenOptions
* @property {string} [cwd] The path to use for the current working directory. Defaults to `process.cwd()`.
* @property {CompilerOptions} [compilerOptions] Compiler option overrides.
* @property {boolean} [force] Forces creation of the output project.
* @property {string[]} [exclude] Files to exclude (relative to `cwd`)
*/
function flatten(projectSpec, flattenedProjectSpec, options = {}) {
const paths = resolvePathOptions(options);
const files = [];
const resolvedOutputSpec = path.resolve(paths.cwd, flattenedProjectSpec);
const resolvedOutputDirectory = path.dirname(resolvedOutputSpec);
const resolvedProjectSpec = resolveProjectSpec(projectSpec, paths, /*referrer*/ undefined);
const projectGraph = getOrCreateProjectGraph(resolvedProjectSpec, paths);
const skipProjects = /**@type {Set<ProjectGraph>}*/(new Set());
const skipFiles = new Set(options && options.exclude && options.exclude.map(file => path.resolve(paths.cwd, file)));
recur(projectGraph);
if (options.force || needsUpdate(files, resolvedOutputSpec)) {
const config = {
extends: normalizeSlashes(path.relative(resolvedOutputDirectory, resolvedProjectSpec)),
compilerOptions: options.compilerOptions || {},
files: files.map(file => normalizeSlashes(path.relative(resolvedOutputDirectory, file)))
};
mkdirp.sync(resolvedOutputDirectory);
fs.writeFileSync(resolvedOutputSpec, JSON.stringify(config, undefined, 2), "utf8");
}
/**
* @param {ProjectGraph} projectGraph
*/
function recur(projectGraph) {
if (skipProjects.has(projectGraph)) return;
skipProjects.add(projectGraph);
for (const ref of projectGraph.references) {
recur(ref.target);
}
for (let file of projectGraph.project.fileNames) {
file = path.resolve(projectGraph.projectDirectory, file);
if (skipFiles.has(file)) continue;
skipFiles.add(file);
files.push(file);
}
}
}
exports.flatten = flatten;
/**
* Returns a Promise that resolves when all pending build tasks have completed
* @param {import("prex").CancellationToken} [token]
*/
function waitForWorkToComplete(token) {
return countdown.wait(token);
}
exports.waitForWorkToComplete = waitForWorkToComplete;
/**
* Returns a Promise that resolves when all pending build tasks have completed
* @param {import("prex").CancellationToken} [token]
*/
function waitForWorkToStart(token) {
return workStartedEvent.wait(token);
}
exports.waitForWorkToStart = waitForWorkToStart;
function getRemainingWork() {
return countdown.remainingCount > 0;
}
exports.hasRemainingWork = getRemainingWork;
/**
* Resolve a TypeScript specifier into a fully-qualified module specifier and any requisite dependencies.
* @param {string} typescript An unresolved module specifier to a TypeScript version.
* @param {ResolvedPathOptions} paths Paths used to resolve `typescript`.
* @returns {ResolvedTypeScript}
*
* @typedef {string & {_isResolvedTypeScript: never}} ResolvedTypeScriptSpec
*
* @typedef ResolvedTypeScript
* @property {ResolvedTypeScriptSpec} typescript
* @property {string} [alias]
*/
function resolveTypeScript(typescript = "default", paths) {
let alias;
while (typescriptAliasMap.has(typescript)) {
({ typescript, alias, paths } = typescriptAliasMap.get(typescript));
}
if (typescript === "default") {
typescript = require.resolve("../../lib/typescript");
}
else if (isPath(typescript)) {
typescript = path.resolve(paths.cwd, typescript);
}
return { typescript: /**@type {ResolvedTypeScriptSpec}*/(normalizeSlashes(typescript)), alias };
}
/**
* Gets a suffix to append to Gulp task names that vary by TypeScript version.
* @param {ResolvedTypeScript} typescript A resolved module specifier to a TypeScript version.
* @param {ResolvedPathOptions} paths Paths used to resolve a relative reference to `typescript`.
*/
function getTaskNameSuffix(typescript, paths) {
return typescript.typescript === resolveTypeScript("default", paths).typescript ? "" :
typescript.alias ? `@${typescript.alias}` :
isPath(typescript.typescript) ? `@${normalizeSlashes(path.relative(paths.base, typescript.typescript))}` :
`@${typescript}`;
}
/** @type {ResolvedPathOptions} */
const defaultPaths = (() => {
const cwd = /**@type {AbsolutePath}*/(normalizeSlashes(process.cwd()));
return { cwd, base: cwd };
})();
/**
* @param {PathOptions | undefined} options Path options to resolve and normalize.
* @returns {ResolvedPathOptions}
*
* @typedef PathOptions
* @property {string} [cwd] The path to use for the current working directory. Defaults to `process.cwd()`.
* @property {string} [base] The path to use as the base for relative paths. Defaults to `cwd`.
*
* @typedef ResolvedPathOptions
* @property {AbsolutePath} cwd The path to use for the current working directory. Defaults to `process.cwd()`.
* @property {AbsolutePath} base The path to use as the base for relative paths. Defaults to `cwd`.
*/
function resolvePathOptions(options) {
const cwd = options && options.cwd ? resolvePath(defaultPaths.cwd, options.cwd) : defaultPaths.cwd;
const base = options && options.base ? resolvePath(cwd, options.base) : cwd;
return cwd === defaultPaths.cwd && base === defaultPaths.base ? defaultPaths : { cwd, base };
}
/**
* @param {CompileOptions} [options]
* @returns {ResolvedCompileOptions}
*
* @typedef ResolvedCompileOptions
* @property {ResolvedPathOptions} paths
* @property {ResolvedTypeScript} typescript A resolved reference to a TypeScript implementation.
* @property {Hook} [js] Pipeline hook for .js file outputs.
* @property {Hook} [dts] Pipeline hook for .d.ts file outputs.
* @property {boolean} [verbose] Indicates whether verbose logging is enabled.
* @property {boolean} [force] Force recompilation (no up-to-date check).
* @property {boolean} [inProcess] Indicates whether to run gulp-typescript in-process or out-of-process (default).
* @property {boolean} [watch] Indicates the project was created in watch mode
*/
function resolveCompileOptions(options = {}) {
const paths = resolvePathOptions(options);
const typescript = resolveTypeScript(options.typescript, paths);
return {
paths,
typescript,
js: options.js,
dts: options.dts,
verbose: options.verbose || false,
force: options.force || false,
inProcess: options.inProcess || false
};
}
/**
* @param {ResolvedCompileOptions} left
* @param {ResolvedCompileOptions} right
* @returns {ResolvedCompileOptions}
*/
function mergeCompileOptions(left, right) {
if (left.typescript.typescript !== right.typescript.typescript) throw new Error("Cannot merge project options targeting different TypeScript packages");
if (tryReuseCompileOptions(left, right)) return left;
return {
paths: left.paths,
typescript: left.typescript,
js: right.js || left.js,
dts: right.dts || left.dts,
verbose: right.verbose || left.verbose,
force: right.force || left.force,
inProcess: right.inProcess || left.inProcess,
watch: right.watch || left.watch
};
}
/**
* @param {ResolvedCompileOptions} left
* @param {ResolvedCompileOptions} right
*/
function tryReuseCompileOptions(left, right) {
return left === right
|| left.js === (right.js || left.js)
&& left.dts === (right.dts || left.dts)
&& !left.verbose === !(right.verbose || left.verbose)
&& !left.force === !(right.force || left.force)
&& !left.inProcess === !(right.inProcess || left.inProcess);
}
/**
* @param {ResolvedProjectSpec} projectSpec
* @param {ResolvedPathOptions} paths
* @returns {UnqualifiedProjectName}
*
* @typedef {string & {_isUnqualifiedProjectName:never}} UnqualifiedProjectName
*/
function getUnqualifiedProjectName(projectSpec, paths) {
let projectName = path.relative(paths.base, projectSpec);
if (path.basename(projectName) === "tsconfig.json") projectName = path.dirname(projectName);
return /**@type {UnqualifiedProjectName}*/(normalizeSlashes(projectName));
}
/**
* @param {UnqualifiedProjectName} projectName
* @param {ResolvedPathOptions} paths
* @param {ResolvedTypeScript} typescript
* @returns {QualifiedProjectName}
*
* @typedef {string & {_isQualifiedProjectName:never}} QualifiedProjectName
*/
function getQualifiedProjectName(projectName, paths, typescript) {
return /**@type {QualifiedProjectName}*/(projectName + getTaskNameSuffix(typescript, paths));
}
/**
* @typedef {import("../../lib/typescript").ParseConfigFileHost} ParseConfigFileHost
* @type {ParseConfigFileHost}
*/
const parseConfigFileHost = {
useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
fileExists: fileName => ts.sys.fileExists(fileName),
readFile: fileName => ts.sys.readFile(fileName),
getCurrentDirectory: () => process.cwd(),
readDirectory: (rootDir, extensions, exclude, include, depth) => ts.sys.readDirectory(rootDir, extensions, exclude, include, depth),
onUnRecoverableConfigFileDiagnostic: diagnostic => reportDiagnostics([diagnostic])
};
/**
* @param {AbsolutePath} [cwd]
* @returns {ParseConfigFileHost}
*/
function getParseConfigFileHost(cwd) {
if (!cwd || cwd === defaultPaths.cwd) return parseConfigFileHost;
return {
useCaseSensitiveFileNames: parseConfigFileHost.useCaseSensitiveFileNames,
fileExists: parseConfigFileHost.fileExists,
readFile: parseConfigFileHost.readFile,
getCurrentDirectory: () => cwd,
readDirectory: parseConfigFileHost.readDirectory,
onUnRecoverableConfigFileDiagnostic: diagnostic => reportDiagnostics([diagnostic], { cwd })
};
}
/**
* @param {ResolvedProjectSpec} projectSpec
* @param {ResolvedPathOptions} paths
* @returns {ProjectGraph}
*
* @typedef ProjectGraph
* @property {ResolvedPathOptions} paths
* @property {ResolvedProjectSpec} projectSpec The fully qualified path to the tsconfig.json of the project
* @property {UnqualifiedProjectName} projectName The relative project name, excluding any TypeScript suffix.
* @property {AbsolutePath} projectDirectory The fully qualified path to the project directory.
* @property {ParsedCommandLine} project The parsed tsconfig.json file.
* @property {ProjectGraphReference[]} references An array of project references.
* @property {Set<ProjectGraph>} referrers An array of referring projects.
* @property {Set<AbsolutePath>} inputs A set of compilation inputs.
* @property {Set<AbsolutePath>} outputs A set of compilation outputs.
* @property {Map<ResolvedTypeScriptSpec, ProjectGraphConfiguration>} configurations TypeScript-specific configurations for the project.
* @property {boolean} cleanTaskCreated A value indicating whether a `clean:` task has been created for this project (not dependent on TypeScript version).
* @property {boolean} watcherCreated A value indicating whether a watcher has been created for this project.
* @property {boolean} isRoot The project graph is a root project reference.
* @property {Set<Watcher>} [allWatchers] Tasks to execute when the compilation has completed after being triggered by a watcher.
*
* @typedef ProjectGraphReference
* @property {ProjectGraph} source The referring project.
* @property {ProjectGraph} target The referenced project.
*/
function getOrCreateProjectGraph(projectSpec, paths) {
let projectGraph = projectGraphCache.get(projectSpec);
if (!projectGraph) {
const project = parseProject(projectSpec, paths);
const projectDirectory = parentDirectory(projectSpec);
projectGraph = {
paths,
projectSpec,
projectName: getUnqualifiedProjectName(projectSpec, paths),
projectDirectory,
project,
references: [],
referrers: new Set(),
inputs: new Set(project.fileNames.map(file => resolvePath(projectDirectory, file))),
outputs: new Set(ts.getAllProjectOutputs(project).map(file => resolvePath(projectDirectory, file))),
configurations: new Map(),
cleanTaskCreated: false,
watcherCreated: false,
isRoot: false
};
projectGraphCache.set(projectSpec, projectGraph);
if (project.projectReferences) {
for (const projectReference of project.projectReferences) {
const resolvedProjectSpec = resolveProjectSpec(projectReference.path, paths, projectGraph);
const referencedProject = getOrCreateProjectGraph(resolvedProjectSpec, paths);
const reference = { source: projectGraph, target: referencedProject };
projectGraph.references.push(reference);
referencedProject.referrers.add(projectGraph);
}
}
}
return projectGraph;
}
/**
* @param {ResolvedPathOptions} paths
*/
function createParseProject(paths) {
/**
* @param {string} configFilePath
*/
function getProject(configFilePath) {
const projectSpec = resolveProjectSpec(configFilePath, paths, /*referrer*/ undefined);
const projectGraph = getOrCreateProjectGraph(projectSpec, defaultPaths);
return projectGraph && projectGraph.project;
}
return getProject;
}
/**
* @param {ProjectGraph} projectGraph
* @param {ParsedCommandLine} parsedProject
*/
function updateProjectGraph(projectGraph, parsedProject) {
projectGraph.project = parsedProject;
projectGraph.inputs = new Set(projectGraph.project.fileNames.map(file => resolvePath(projectGraph.projectDirectory, file)));
projectGraph.outputs = new Set(ts.getAllProjectOutputs(projectGraph.project).map(file => resolvePath(projectGraph.projectDirectory, file)));
// Update project references.
const oldReferences = new Set(projectGraph.references.map(ref => ref.target));
projectGraph.references = [];
if (projectGraph.project.projectReferences) {
for (const projectReference of projectGraph.project.projectReferences) {
const resolvedProjectSpec = resolveProjectSpec(projectReference.path, projectGraph.paths, projectGraph);
const referencedProject = getOrCreateProjectGraph(resolvedProjectSpec, projectGraph.paths);
const reference = { source: projectGraph, target: referencedProject };
projectGraph.references.push(reference);
referencedProject.referrers.add(projectGraph);
oldReferences.delete(referencedProject);
}
}
// Remove project references that have been removed from the project
for (const referencedProject of oldReferences) {
referencedProject.referrers.delete(projectGraph);
// If there are no more references to this project and the project was not directly requested,
// remove it from the cache.
if (referencedProject.referrers.size === 0 && !referencedProject.isRoot) {
projectGraphCache.delete(referencedProject.projectSpec);
}
}
}
/**
* @param {ResolvedProjectSpec} projectSpec
* @param {ResolvedPathOptions} paths
*/
function parseProject(projectSpec, paths) {
return ts.getParsedCommandLineOfConfigFile(projectSpec, {}, getParseConfigFileHost(paths.cwd));
}
/**
* @param {ProjectGraph} projectGraph
* @param {ResolvedCompileOptions} resolvedOptions
* @returns {ProjectGraphConfiguration}
*
* @typedef ProjectGraphConfiguration
* @property {QualifiedProjectName} projectName
* @property {ResolvedCompileOptions} resolvedOptions
* @property {boolean} compileTaskCreated A value indicating whether a `compile:` task has been created for this project.
* @property {Set<Watcher>} [watchers] Tasks to execute when the compilation has completed after being triggered by a watcher.
*/
function getOrCreateProjectGraphConfiguration(projectGraph, resolvedOptions) {
let projectGraphConfig = projectGraph.configurations.get(resolvedOptions.typescript.typescript);
if (!projectGraphConfig) {
projectGraphConfig = {
projectName: getQualifiedProjectName(projectGraph.projectName, resolvedOptions.paths, resolvedOptions.typescript),
resolvedOptions,
compileTaskCreated: false
};
projectGraph.configurations.set(resolvedOptions.typescript.typescript, projectGraphConfig);
}
return projectGraphConfig;
}
/**
* Resolves a series of path steps as a normalized, canonical, and absolute path.
* @param {AbsolutePath} basePath
* @param {...string} paths
* @returns {AbsolutePath}
*
* @typedef {string & {_isResolvedPath:never}} AbsolutePath
*/
function resolvePath(basePath, ...paths) {
return /**@type {AbsolutePath}*/(normalizeSlashes(path.resolve(basePath, ...paths)));
}
/**
* @param {AbsolutePath} from
* @param {AbsolutePath} to
* @returns {Path}
*
* @typedef {string & {_isRelativePath:never}} RelativePath
* @typedef {RelativePath | AbsolutePath} Path
*/
function relativePath(from, to) {
let relativePath = normalizeSlashes(path.relative(from, to));
if (!relativePath) relativePath = ".";
if (path.isAbsolute(relativePath)) return /**@type {AbsolutePath}*/(relativePath);
if (relativePath.charAt(0) !== ".") relativePath = "./" + relativePath;
return /**@type {RelativePath}*/(relativePath);
}
/**
* @param {AbsolutePath} file
* @returns {AbsolutePath}
*/
function parentDirectory(file) {
const dirname = path.dirname(file);
if (!dirname || dirname === file) return file;
return /**@type {AbsolutePath}*/(normalizeSlashes(dirname));
}
/**
* @param {string} projectSpec
* @param {ResolvedPathOptions} paths
* @param {ProjectGraph | undefined} referrer
* @returns {ResolvedProjectSpec}
*
* @typedef {AbsolutePath & {_isResolvedProjectSpec: never}} ResolvedProjectSpec
*/
function resolveProjectSpec(projectSpec, paths, referrer) {
let projectPath = resolvePath(paths.cwd, referrer && referrer.projectDirectory || "", projectSpec);
if (!ts.sys.fileExists(projectPath)) projectPath = resolvePath(paths.cwd, projectPath, "tsconfig.json");
return /**@type {ResolvedProjectSpec}*/(normalizeSlashes(projectPath));
}
/**
* @param {ProjectGraph} projectGraph
* @param {ResolvedPathOptions} paths
*/
function resolveDestPath(projectGraph, paths) {
/** @type {AbsolutePath} */
let destPath = projectGraph.projectDirectory;
if (projectGraph.project.options.outDir) {
destPath = resolvePath(paths.cwd, destPath, projectGraph.project.options.outDir);
}
else if (projectGraph.project.options.outFile || projectGraph.project.options.out) {
destPath = parentDirectory(resolvePath(paths.cwd, destPath, projectGraph.project.options.outFile || projectGraph.project.options.out));
}
return relativePath(paths.base, destPath);
}
/**
* @param {ProjectGraph} projectGraph
* @param {ResolvedCompileOptions} options
*/
function ensureCompileTask(projectGraph, options) {
const projectGraphConfig = getOrCreateProjectGraphConfiguration(projectGraph, options);
projectGraphConfig.resolvedOptions = mergeCompileOptions(projectGraphConfig.resolvedOptions, options);
const hasCompileTask = projectGraphConfig.compileTaskCreated;
projectGraphConfig.compileTaskCreated = true;
const deps = makeProjectReferenceCompileTasks(projectGraph, projectGraphConfig.resolvedOptions.typescript, projectGraphConfig.resolvedOptions.paths, projectGraphConfig.resolvedOptions.watch);
if (!hasCompileTask) {
compilationGulp.task(compileTaskName(projectGraph, projectGraphConfig.resolvedOptions.typescript), deps, () => {
const destPath = resolveDestPath(projectGraph, projectGraphConfig.resolvedOptions.paths);
const { sourceMap, inlineSourceMap, inlineSources = false, sourceRoot, declarationMap } = projectGraph.project.options;
const configFilePath = projectGraph.project.options.configFilePath;
const sourceMapPath = inlineSourceMap ? undefined : ".";
const sourceMapOptions = { includeContent: inlineSources, sourceRoot, destPath };
const project = projectGraphConfig.resolvedOptions.inProcess
? tsc.createProject(configFilePath, { typescript: require(projectGraphConfig.resolvedOptions.typescript.typescript) })
: tsc_oop.createProject(configFilePath, {}, { typescript: projectGraphConfig.resolvedOptions.typescript.typescript });
const stream = project.src()
.pipe(gulpif(!projectGraphConfig.resolvedOptions.force, upToDate(projectGraph.project, { verbose: projectGraphConfig.resolvedOptions.verbose, parseProject: createParseProject(projectGraphConfig.resolvedOptions.paths) })))
.pipe(gulpif(sourceMap || inlineSourceMap, sourcemaps.init()))
.pipe(project());
if (projectGraphConfig.resolvedOptions.watch) {
stream.on("error", error => {
if (error.message === "TypeScript: Compilation failed") {
stream.emit("end");
stream.js.emit("end");
stream.dts.emit("end");
}
});
}
const additionalJsOutputs = projectGraphConfig.resolvedOptions.js ? projectGraphConfig.resolvedOptions.js(stream.js)
.pipe(gulpif(sourceMap || inlineSourceMap, sourcemaps.write(sourceMapPath, sourceMapOptions))) : undefined;
const additionalDtsOutputs = projectGraphConfig.resolvedOptions.dts ? projectGraphConfig.resolvedOptions.dts(stream.dts)
.pipe(gulpif(declarationMap, sourcemaps.write(sourceMapPath, sourceMapOptions))) : undefined;
const js = stream.js
.pipe(gulpif(sourceMap || inlineSourceMap, sourcemaps.write(sourceMapPath, sourceMapOptions)));
const dts = stream.dts
.pipe(gulpif(declarationMap, sourcemaps.write(sourceMapPath, sourceMapOptions)));
return merge2([js, dts, additionalJsOutputs, additionalDtsOutputs].filter(x => !!x))
.pipe(gulp.dest(destPath));
});
}
return projectGraph;
}
/**
* @param {ProjectGraph} projectGraph
* @param {ResolvedTypeScript} typescript
* @param {ResolvedPathOptions} paths
* @param {boolean} watch
*/
function makeProjectReferenceCompileTasks(projectGraph, typescript, paths, watch) {
return projectGraph.references.map(({target}) => compileTaskName(ensureCompileTask(target, { paths, typescript, watch }), typescript));
}
/**
* @param {ProjectGraph} projectGraph
*/
function ensureCleanTask(projectGraph) {
if (!projectGraph.cleanTaskCreated) {
const deps = makeProjectReferenceCleanTasks(projectGraph);
compilationGulp.task(cleanTaskName(projectGraph), deps, () => {
let outputs = ts.getAllProjectOutputs(projectGraph.project);
if (!projectGraph.project.options.inlineSourceMap) {
if (projectGraph.project.options.sourceMap) {
outputs = outputs.concat(outputs.filter(file => /\.jsx?$/.test(file)).map(file => file + ".map"));
}
if (projectGraph.project.options.declarationMap) {
outputs = outputs.concat(outputs.filter(file => /\.d.ts$/.test(file)).map(file => file + ".map"));
}
}
return del(outputs);
});
projectGraph.cleanTaskCreated = true;
}
return projectGraph;
}
/**
* @param {ProjectGraph} projectGraph
*/
function makeProjectReferenceCleanTasks(projectGraph) {
return projectGraph.references.map(({target}) => cleanTaskName(ensureCleanTask(target)));
}
/**
* @param {ProjectGraph} projectGraph
* @param {ResolvedCompileOptions} options
* @param {string[]} [tasks]
* @param {(err?: any) => void} [callback]
*
* @typedef Watcher
* @property {string[]} [tasks]
* @property {(err?: any) => void} [callback]
*
* @typedef WatcherRegistration
* @property {() => void} end
*/
function ensureWatcher(projectGraph, options, tasks, callback) {
ensureCompileTask(projectGraph, options);
if (!projectGraph.watcherCreated) {
projectGraph.watcherCreated = true;
makeProjectReferenceWatchers(projectGraph, options.typescript, options.paths);
createWatcher(projectGraph, options, () => {
for (const config of projectGraph.configurations.values()) {
const taskName = compileTaskName(projectGraph, config.resolvedOptions.typescript);
const task = compilationGulp.tasks[taskName];
if (!task) continue;
possiblyTriggerRecompilation(config, task);
}
});
}
if ((tasks && tasks.length) || callback) {
const projectGraphConfig = getOrCreateProjectGraphConfiguration(projectGraph, options);
if (!projectGraphConfig.watchers) projectGraphConfig.watchers = new Set();
if (!projectGraph.allWatchers) projectGraph.allWatchers = new Set();
/** @type {Watcher} */
const watcher = { tasks, callback };
projectGraphConfig.watchers.add(watcher);
projectGraph.allWatchers.add(watcher);
/** @type {WatcherRegistration} */
const registration = {
end() {
projectGraphConfig.watchers.delete(watcher);
projectGraph.allWatchers.delete(watcher);
}
};
return registration;
}
}
/**
* @param {ProjectGraphConfiguration} config
* @param {import("orchestrator").Task} task
*/
function possiblyTriggerRecompilation(config, task) {
// if any of the task's dependencies are still running, wait until they are complete.
for (const dep of task.dep) {
if (compilationGulp.tasks[dep].running) {
setTimeout(possiblyTriggerRecompilation, 50, config, task);
return;
}
}
triggerRecompilation(task, config);
}
/**
* @param {import("orchestrator").Task} task
* @param {ProjectGraphConfiguration} config
*/
function triggerRecompilation(task, config) {
compilationGulp._resetTask(task);
if (config.watchers && config.watchers.size) {
start(task.name, () => {
/** @type {Set<string>} */
const taskNames = new Set();
/** @type {((err?: any) => void)[]} */
const callbacks = [];
for (const { tasks, callback } of config.watchers) {
if (tasks) for (const task of tasks) taskNames.add(task);
if (callback) callbacks.push(callback);
}
if (taskNames.size) {
gulp.start([...taskNames], error => {
for (const callback of callbacks) callback(error);
});
}
else {
for (const callback of callbacks) callback();
}
});
}
else {
start(task.name);
}
}
/**
* @param {ProjectGraph} projectGraph
* @param {ResolvedTypeScript} typescript
* @param {ResolvedPathOptions} paths
*/
function makeProjectReferenceWatchers(projectGraph, typescript, paths) {
for (const { target } of projectGraph.references) {
ensureWatcher(target, { paths, typescript });
}
}
/**
* @param {ProjectGraph} projectGraph
* @param {ResolvedCompileOptions} options
* @param {() => void} callback
*/
function createWatcher(projectGraph, options, callback) {
let projectRemoved = false;
let patterns = collectWatcherPatterns(projectGraph.projectSpec, projectGraph.project, projectGraph);
let watcher = /**@type {GulpWatcher}*/ (gulp.watch(patterns, { cwd: projectGraph.projectDirectory }, onWatchEvent));
/**
* @param {WatchEvent} event
*/
function onWatchEvent(event) {
const file = resolvePath(options.paths.cwd, event.path);
if (file === projectGraph.projectSpec) {
onProjectWatchEvent(event);
}
else {
onInputOrOutputChanged(file);
}
}
/**
* @param {WatchEvent} event
*/
function onProjectWatchEvent(event) {
if (event.type === "renamed" || event.type === "deleted") {
onProjectRenamedOrDeleted();
}
else {
onProjectCreatedOrModified();
}
}
function onProjectRenamedOrDeleted() {
// stop listening for file changes and wait for the project to be created again
projectRemoved = true;
watcher.end();
watcher = /**@type {GulpWatcher}*/ (gulp.watch([projectGraph.projectSpec], onWatchEvent));
}
function onProjectCreatedOrModified() {
const newParsedProject = parseProject(projectGraph.projectSpec, options.paths);
const newPatterns = collectWatcherPatterns(projectGraph.projectSpec, newParsedProject, projectGraph);
if (projectRemoved || !sameValues(patterns, newPatterns)) {
projectRemoved = false;
watcher.end();
updateProjectGraph(projectGraph, newParsedProject);
// Ensure we catch up with any added projects
for (const config of projectGraph.configurations.values()) {
if (config.watchers) {
makeProjectReferenceWatchers(projectGraph, config.resolvedOptions.typescript, config.resolvedOptions.paths);
}
}
patterns = newPatterns;
watcher = /**@type {GulpWatcher}*/ (gulp.watch(patterns, onWatchEvent));
}
onProjectInvalidated();
}
function onProjectInvalidated() {
callback();
}
/**
* @param {AbsolutePath} file
*/
function onInputOrOutputChanged(file) {
if (projectGraph.inputs.has(file) ||
projectGraph.references.some(ref => ref.target.outputs.has(file))) {
onProjectInvalidated();
}
}
}
/**
* @param {ResolvedProjectSpec} projectSpec
* @param {ParsedCommandLine} parsedProject
* @param {ProjectGraph} projectGraph
*/
function collectWatcherPatterns(projectSpec, parsedProject, projectGraph) {
const configFileSpecs = parsedProject.configFileSpecs;
// NOTE: we do not currently handle files from `/// <reference />` tags
const patterns = /**@type {string[]} */([]);
// Add the project contents.
if (configFileSpecs) {
addIncludeSpecs(patterns, configFileSpecs.validatedIncludeSpecs);
addExcludeSpecs(patterns, configFileSpecs.validatedExcludeSpecs);
addIncludeSpecs(patterns, configFileSpecs.filesSpecs);
}
else {
addWildcardDirectories(patterns, parsedProject.wildcardDirectories);
addIncludeSpecs(patterns, parsedProject.fileNames);
}
// Add the project itself.
addIncludeSpec(patterns, projectSpec);
// TODO: Add the project base.
// addExtendsSpec(patterns, project.raw && project.raw.extends);
// Add project reference outputs.
addProjectReferences(patterns, parsedProject.projectReferences);
return patterns;
/**
* @param {string[]} patterns
* @param {string | undefined} includeSpec
*/
function addIncludeSpec(patterns, includeSpec) {
if (!includeSpec) return;
patterns.push(includeSpec);
}
/**
* @param {string[]} patterns
* @param {ReadonlyArray<string> | undefined} includeSpecs
*/
function addIncludeSpecs(patterns, includeSpecs) {
if (!includeSpecs) return;
for (const includeSpec of includeSpecs) {
addIncludeSpec(patterns, includeSpec);
}
}
/**
* @param {string[]} patterns
* @param {string | undefined} excludeSpec
*/
function addExcludeSpec(patterns, excludeSpec) {
if (!excludeSpec) return;
patterns.push("!" + excludeSpec);
}
/**
* @param {string[]} patterns
* @param {ReadonlyArray<string> | undefined} excludeSpecs
*/
function addExcludeSpecs(patterns, excludeSpecs) {
if (!excludeSpecs) return;
for (const excludeSpec of excludeSpecs) {
addExcludeSpec(patterns, excludeSpec);
}
}
/**
* @param {string[]} patterns
* @param {ts.MapLike<ts.WatchDirectoryFlags> | undefined} wildcardDirectories
*/
function addWildcardDirectories(patterns, wildcardDirectories) {
if (!wildcardDirectories) return;
for (const dirname of Object.keys(wildcardDirectories)) {
const flags = wildcardDirectories[dirname];
patterns.push(path.join(dirname, flags & ts.WatchDirectoryFlags.Recursive ? "**" : "", "*"));
}
}
// TODO: Add the project base
// /**
// * @param {string[]} patterns
// * @param {string | undefined} base
// */
// function addExtendsSpec(patterns, base) {
// if (!base) return;
// addIncludeSpec(patterns, base);
// }
/**
* @param {string[]} patterns
* @param {ReadonlyArray<ProjectReference>} projectReferences
*/
function addProjectReferences(patterns, projectReferences) {
if (!projectReferences) return;
for (const projectReference of projectReferences) {
const resolvedProjectSpec = resolveProjectSpec(projectReference.path, projectGraph.paths, projectGraph);
const referencedProject = getOrCreateProjectGraph(resolvedProjectSpec, projectGraph.paths);