-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
index.ts
1144 lines (1017 loc) · 34.2 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
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {execSync} from 'child_process';
import crypto from 'crypto';
import EventEmitter from 'events';
import fs from 'fs';
import os from 'os';
import path from 'path';
import sane from 'sane';
import invariant from 'invariant';
import {Config} from '@jest/types';
import serializer from 'jest-serializer';
import Worker from 'jest-worker';
import {getSha1, worker} from './worker';
import getMockName from './getMockName';
import getPlatformExtension from './lib/getPlatformExtension';
import H from './constants';
import HasteFS from './HasteFS';
import HasteModuleMap, {
SerializableModuleMap as HasteSerializableModuleMap,
} from './ModuleMap';
import nodeCrawl from './crawlers/node';
import normalizePathSep from './lib/normalizePathSep';
import watchmanCrawl from './crawlers/watchman';
// @ts-ignore: not converted to TypeScript - it's a fork: https://github.com/facebook/jest/pull/5387
import WatchmanWatcher from './lib/WatchmanWatcher';
import FSEventsWatcher from './lib/FSEventsWatcher';
import * as fastPath from './lib/fast_path';
import {
ChangeEvent,
EventsQueue,
FileMetaData,
HasteMap as InternalHasteMapObject,
HasteRegExp,
InternalHasteMap,
Mapper,
MockData,
ModuleMapData,
ModuleMetaData,
WorkerMetadata,
CrawlerOptions,
FileData,
} from './types';
type HType = typeof H;
type Options = {
cacheDirectory?: string;
computeDependencies?: boolean;
computeSha1?: boolean;
console?: Console;
dependencyExtractor?: string;
extensions: Array<string>;
forceNodeFilesystemAPI?: boolean;
hasteImplModulePath?: string;
ignorePattern?: HasteRegExp;
mapper?: Mapper;
maxWorkers: number;
mocksPattern?: string;
name: string;
platforms: Array<string>;
providesModuleNodeModules?: Array<string>;
resetCache?: boolean;
retainAllFiles: boolean;
rootDir: string;
roots: Array<string>;
skipPackageJson?: boolean;
throwOnModuleCollision?: boolean;
useWatchman?: boolean;
watch?: boolean;
};
type InternalOptions = {
cacheDirectory: string;
computeDependencies: boolean;
computeSha1: boolean;
dependencyExtractor?: string;
extensions: Array<string>;
forceNodeFilesystemAPI: boolean;
hasteImplModulePath?: string;
ignorePattern?: HasteRegExp;
mapper?: Mapper;
maxWorkers: number;
mocksPattern: RegExp | null;
name: string;
platforms: Array<string>;
resetCache?: boolean;
retainAllFiles: boolean;
rootDir: string;
roots: Array<string>;
skipPackageJson: boolean;
throwOnModuleCollision: boolean;
useWatchman: boolean;
watch: boolean;
};
type Watcher = {
close(callback: () => void): void;
};
type WorkerInterface = {worker: typeof worker; getSha1: typeof getSha1};
// TODO: Ditch namespace when this module exports ESM
namespace HasteMap {
export type ModuleMap = HasteModuleMap;
export type SerializableModuleMap = HasteSerializableModuleMap;
export type FS = HasteFS;
export type HasteMapObject = InternalHasteMapObject;
export type HasteChangeEvent = ChangeEvent;
}
const CHANGE_INTERVAL = 30;
const MAX_WAIT_TIME = 240000;
const NODE_MODULES = path.sep + 'node_modules' + path.sep;
const PACKAGE_JSON = path.sep + 'package.json';
// TypeScript doesn't like us importing from outside `rootDir`, but it doesn't
// understand `require`.
const {version: VERSION} = require('../package.json');
const canUseWatchman = ((): boolean => {
try {
execSync('watchman --version', {stdio: ['ignore']});
return true;
} catch (e) {}
return false;
})();
const escapePathSeparator = (string: string) =>
path.sep === '\\' ? string.replace(/(\/|\\)/g, '\\\\') : string;
const getWhiteList = (list: Array<string> | undefined): RegExp | null => {
if (list && list.length) {
const newList = list.map(item =>
escapePathSeparator(item.replace(/(\/)/g, path.sep)),
);
return new RegExp(
'(' +
escapePathSeparator(NODE_MODULES) +
'(?:' +
newList.join('|') +
')(?=$|' +
escapePathSeparator(path.sep) +
'))',
'g',
);
}
return null;
};
/**
* HasteMap is a JavaScript implementation of Facebook's haste module system.
*
* This implementation is inspired by https://github.com/facebook/node-haste
* and was built with for high-performance in large code repositories with
* hundreds of thousands of files. This implementation is scalable and provides
* predictable performance.
*
* Because the haste map creation and synchronization is critical to startup
* performance and most tasks are blocked by I/O this class makes heavy use of
* synchronous operations. It uses worker processes for parallelizing file
* access and metadata extraction.
*
* The data structures created by `jest-haste-map` can be used directly from the
* cache without further processing. The metadata objects in the `files` and
* `map` objects contain cross-references: a metadata object from one can look
* up the corresponding metadata object in the other map. Note that in most
* projects, the number of files will be greater than the number of haste
* modules one module can refer to many files based on platform extensions.
*
* type HasteMap = {
* clocks: WatchmanClocks,
* files: {[filepath: string]: FileMetaData},
* map: {[id: string]: ModuleMapItem},
* mocks: {[id: string]: string},
* }
*
* // Watchman clocks are used for query synchronization and file system deltas.
* type WatchmanClocks = {[filepath: string]: string};
*
* type FileMetaData = {
* id: ?string, // used to look up module metadata objects in `map`.
* mtime: number, // check for outdated files.
* size: number, // size of the file in bytes.
* visited: boolean, // whether the file has been parsed or not.
* dependencies: Array<string>, // all relative dependencies of this file.
* sha1: ?string, // SHA-1 of the file, if requested via options.
* };
*
* // Modules can be targeted to a specific platform based on the file name.
* // Example: platform.ios.js and Platform.android.js will both map to the same
* // `Platform` module. The platform should be specified during resolution.
* type ModuleMapItem = {[platform: string]: ModuleMetaData};
*
* //
* type ModuleMetaData = {
* path: string, // the path to look up the file object in `files`.
* type: string, // the module type (either `package` or `module`).
* };
*
* Note that the data structures described above are conceptual only. The actual
* implementation uses arrays and constant keys for metadata storage. Instead of
* `{id: 'flatMap', mtime: 3421, size: 42, visited: true, dependencies: []}` the real
* representation is similar to `['flatMap', 3421, 42, 1, []]` to save storage space
* and reduce parse and write time of a big JSON blob.
*
* The HasteMap is created as follows:
* 1. read data from the cache or create an empty structure.
*
* 2. crawl the file system.
* * empty cache: crawl the entire file system.
* * cache available:
* * if watchman is available: get file system delta changes.
* * if watchman is unavailable: crawl the entire file system.
* * build metadata objects for every file. This builds the `files` part of
* the `HasteMap`.
*
* 3. parse and extract metadata from changed files.
* * this is done in parallel over worker processes to improve performance.
* * the worst case is to parse all files.
* * the best case is no file system access and retrieving all data from
* the cache.
* * the average case is a small number of changed files.
*
* 4. serialize the new `HasteMap` in a cache file.
* Worker processes can directly access the cache through `HasteMap.read()`.
*
*/
/* eslint-disable-next-line no-redeclare */
class HasteMap extends EventEmitter {
private _buildPromise: Promise<InternalHasteMapObject> | null;
private _cachePath: Config.Path;
private _changeInterval?: NodeJS.Timeout;
private _console: Console;
private _options: InternalOptions;
private _watchers: Array<Watcher>;
private _whitelist: RegExp | null;
private _worker: WorkerInterface | null;
constructor(options: Options) {
super();
this._options = {
cacheDirectory: options.cacheDirectory || os.tmpdir(),
computeDependencies:
options.computeDependencies === undefined
? true
: options.computeDependencies,
computeSha1: options.computeSha1 || false,
dependencyExtractor: options.dependencyExtractor,
extensions: options.extensions,
forceNodeFilesystemAPI: !!options.forceNodeFilesystemAPI,
hasteImplModulePath: options.hasteImplModulePath,
ignorePattern: options.ignorePattern,
mapper: options.mapper,
maxWorkers: options.maxWorkers,
mocksPattern: options.mocksPattern
? new RegExp(options.mocksPattern)
: null,
name: options.name,
platforms: options.platforms,
resetCache: options.resetCache,
retainAllFiles: options.retainAllFiles,
rootDir: options.rootDir,
roots: Array.from(new Set(options.roots)),
skipPackageJson: !!options.skipPackageJson,
throwOnModuleCollision: !!options.throwOnModuleCollision,
useWatchman: options.useWatchman == null ? true : options.useWatchman,
watch: !!options.watch,
};
this._console = options.console || global.console;
if (options.ignorePattern && !(options.ignorePattern instanceof RegExp)) {
this._console.warn(
'jest-haste-map: the `ignorePattern` options as a function is being ' +
'deprecated. Provide a RegExp instead. See https://github.com/facebook/jest/pull/4063.',
);
}
const rootDirHash = crypto
.createHash('md5')
.update(options.rootDir)
.digest('hex');
let hasteImplHash = '';
let dependencyExtractorHash = '';
if (options.hasteImplModulePath) {
const hasteImpl = require(options.hasteImplModulePath);
if (hasteImpl.getCacheKey) {
hasteImplHash = String(hasteImpl.getCacheKey());
}
}
if (options.dependencyExtractor) {
const dependencyExtractor = require(options.dependencyExtractor);
if (dependencyExtractor.getCacheKey) {
dependencyExtractorHash = String(dependencyExtractor.getCacheKey());
}
}
this._cachePath = HasteMap.getCacheFilePath(
this._options.cacheDirectory,
`haste-map-${this._options.name}-${rootDirHash}`,
VERSION,
this._options.name,
this._options.roots
.map(root => fastPath.relative(options.rootDir, root))
.join(':'),
this._options.extensions.join(':'),
this._options.platforms.join(':'),
this._options.computeSha1.toString(),
options.mocksPattern || '',
(options.ignorePattern || '').toString(),
hasteImplHash,
dependencyExtractorHash,
);
this._whitelist = getWhiteList(options.providesModuleNodeModules);
this._buildPromise = null;
this._watchers = [];
this._worker = null;
}
static getCacheFilePath(
tmpdir: Config.Path,
name: string,
...extra: Array<string>
): string {
const hash = crypto.createHash('md5').update(extra.join(''));
return path.join(
tmpdir,
name.replace(/\W/g, '-') + '-' + hash.digest('hex'),
);
}
getCacheFilePath(): string {
return this._cachePath;
}
build(): Promise<InternalHasteMapObject> {
if (!this._buildPromise) {
this._buildPromise = (async () => {
const data = await this._buildFileMap();
// Persist when we don't know if files changed (changedFiles undefined)
// or when we know a file was changed or deleted.
let hasteMap: InternalHasteMap;
if (
data.changedFiles === undefined ||
data.changedFiles.size > 0 ||
data.removedFiles.size > 0
) {
hasteMap = await this._buildHasteMap(data);
this._persist(hasteMap);
} else {
hasteMap = data.hasteMap;
}
const rootDir = this._options.rootDir;
const hasteFS = new HasteFS({
files: hasteMap.files,
rootDir,
});
const moduleMap = new HasteModuleMap({
duplicates: hasteMap.duplicates,
map: hasteMap.map,
mocks: hasteMap.mocks,
rootDir,
});
const __hasteMapForTest =
(process.env.NODE_ENV === 'test' && hasteMap) || null;
await this._watch(hasteMap);
return {
__hasteMapForTest,
hasteFS,
moduleMap,
};
})();
}
return this._buildPromise;
}
/**
* 1. read data from the cache or create an empty structure.
*/
read(): InternalHasteMap {
let hasteMap: InternalHasteMap;
try {
hasteMap = serializer.readFileSync(this._cachePath);
} catch (err) {
hasteMap = this._createEmptyMap();
}
return hasteMap;
}
readModuleMap(): HasteModuleMap {
const data = this.read();
return new HasteModuleMap({
duplicates: data.duplicates,
map: data.map,
mocks: data.mocks,
rootDir: this._options.rootDir,
});
}
/**
* 2. crawl the file system.
*/
private async _buildFileMap(): Promise<{
removedFiles: FileData;
changedFiles?: FileData;
hasteMap: InternalHasteMap;
}> {
let hasteMap: InternalHasteMap;
try {
const read = this._options.resetCache ? this._createEmptyMap : this.read;
hasteMap = await read.call(this);
} catch {
hasteMap = this._createEmptyMap();
}
return this._crawl(hasteMap);
}
/**
* 3. parse and extract metadata from changed files.
*/
private _processFile(
hasteMap: InternalHasteMap,
map: ModuleMapData,
mocks: MockData,
filePath: Config.Path,
workerOptions?: {forceInBand: boolean},
): Promise<void> | null {
const rootDir = this._options.rootDir;
const setModule = (id: string, module: ModuleMetaData) => {
let moduleMap = map.get(id);
if (!moduleMap) {
moduleMap = Object.create(null) as {};
map.set(id, moduleMap);
}
const platform =
getPlatformExtension(module[H.PATH], this._options.platforms) ||
H.GENERIC_PLATFORM;
const existingModule = moduleMap[platform];
if (existingModule && existingModule[H.PATH] !== module[H.PATH]) {
const method = this._options.throwOnModuleCollision ? 'error' : 'warn';
this._console[method](
[
'jest-haste-map: Haste module naming collision: ' + id,
' The following files share their name; please adjust your hasteImpl:',
' * <rootDir>' + path.sep + existingModule[H.PATH],
' * <rootDir>' + path.sep + module[H.PATH],
'',
].join('\n'),
);
if (this._options.throwOnModuleCollision) {
throw new DuplicateError(existingModule[H.PATH], module[H.PATH]);
}
// We do NOT want consumers to use a module that is ambiguous.
delete moduleMap[platform];
if (Object.keys(moduleMap).length === 1) {
map.delete(id);
}
let dupsByPlatform = hasteMap.duplicates.get(id);
if (dupsByPlatform == null) {
dupsByPlatform = new Map();
hasteMap.duplicates.set(id, dupsByPlatform);
}
const dups = new Map([
[module[H.PATH], module[H.TYPE]],
[existingModule[H.PATH], existingModule[H.TYPE]],
]);
dupsByPlatform.set(platform, dups);
return;
}
const dupsByPlatform = hasteMap.duplicates.get(id);
if (dupsByPlatform != null) {
const dups = dupsByPlatform.get(platform);
if (dups != null) {
dups.set(module[H.PATH], module[H.TYPE]);
}
return;
}
moduleMap[platform] = module;
};
const relativeFilePath = fastPath.relative(rootDir, filePath);
const fileMetadata = hasteMap.files.get(relativeFilePath);
if (!fileMetadata) {
throw new Error(
'jest-haste-map: File to process was not found in the haste map.',
);
}
const moduleMetadata = hasteMap.map.get(fileMetadata[H.ID]);
const computeSha1 = this._options.computeSha1 && !fileMetadata[H.SHA1];
// Callback called when the response from the worker is successful.
const workerReply = (metadata: WorkerMetadata) => {
// `1` for truthy values instead of `true` to save cache space.
fileMetadata[H.VISITED] = 1;
const metadataId = metadata.id;
const metadataModule = metadata.module;
if (metadataId && metadataModule) {
fileMetadata[H.ID] = metadataId;
setModule(metadataId, metadataModule);
}
fileMetadata[H.DEPENDENCIES] = metadata.dependencies
? metadata.dependencies.join(H.DEPENDENCY_DELIM)
: '';
if (computeSha1) {
fileMetadata[H.SHA1] = metadata.sha1;
}
};
// Callback called when the response from the worker is an error.
const workerError = (error: Error | any) => {
if (typeof error !== 'object' || !error.message || !error.stack) {
error = new Error(error);
error.stack = ''; // Remove stack for stack-less errors.
}
// @ts-ignore: checking error code is OK if error comes from "fs".
if (!['ENOENT', 'EACCES'].includes(error.code)) {
throw error;
}
// If a file cannot be read we remove it from the file list and
// ignore the failure silently.
hasteMap.files.delete(relativeFilePath);
};
// If we retain all files in the virtual HasteFS representation, we avoid
// reading them if they aren't important (node_modules).
if (this._options.retainAllFiles && this._isNodeModulesDir(filePath)) {
if (computeSha1) {
return this._getWorker(workerOptions)
.getSha1({
computeDependencies: this._options.computeDependencies,
computeSha1,
dependencyExtractor: this._options.dependencyExtractor,
filePath,
hasteImplModulePath: this._options.hasteImplModulePath,
rootDir,
})
.then(workerReply, workerError);
}
return null;
}
if (
this._options.mocksPattern &&
this._options.mocksPattern.test(filePath)
) {
const mockPath = getMockName(filePath);
const existingMockPath = mocks.get(mockPath);
if (existingMockPath) {
const secondMockPath = fastPath.relative(rootDir, filePath);
if (existingMockPath !== secondMockPath) {
const method = this._options.throwOnModuleCollision
? 'error'
: 'warn';
this._console[method](
[
'jest-haste-map: duplicate manual mock found: ' + mockPath,
' The following files share their name; please delete one of them:',
' * <rootDir>' + path.sep + existingMockPath,
' * <rootDir>' + path.sep + secondMockPath,
'',
].join('\n'),
);
if (this._options.throwOnModuleCollision) {
throw new DuplicateError(existingMockPath, secondMockPath);
}
}
}
mocks.set(mockPath, relativeFilePath);
}
if (fileMetadata[H.VISITED]) {
if (!fileMetadata[H.ID]) {
return null;
}
if (moduleMetadata != null) {
const platform =
getPlatformExtension(filePath, this._options.platforms) ||
H.GENERIC_PLATFORM;
const module = moduleMetadata[platform];
if (module == null) {
return null;
}
const moduleId = fileMetadata[H.ID];
let modulesByPlatform = map.get(moduleId);
if (!modulesByPlatform) {
modulesByPlatform = Object.create(null) as {};
map.set(moduleId, modulesByPlatform);
}
modulesByPlatform[platform] = module;
return null;
}
}
return this._getWorker(workerOptions)
.worker({
computeDependencies: this._options.computeDependencies,
computeSha1,
dependencyExtractor: this._options.dependencyExtractor,
filePath,
hasteImplModulePath: this._options.hasteImplModulePath,
rootDir,
})
.then(workerReply, workerError);
}
private async _buildHasteMap(data: {
removedFiles: FileData;
changedFiles?: FileData;
hasteMap: InternalHasteMap;
}): Promise<InternalHasteMap> {
const {removedFiles, changedFiles, hasteMap} = data;
// If any files were removed or we did not track what files changed, process
// every file looking for changes. Otherwise, process only changed files.
let map: ModuleMapData;
let mocks: MockData;
let filesToProcess: FileData;
if (changedFiles === undefined || removedFiles.size) {
map = new Map();
mocks = new Map();
filesToProcess = hasteMap.files;
} else {
map = hasteMap.map;
mocks = hasteMap.mocks;
filesToProcess = changedFiles;
}
for (const [relativeFilePath, fileMetadata] of removedFiles) {
this._recoverDuplicates(hasteMap, relativeFilePath, fileMetadata[H.ID]);
}
const promises = [];
for (const relativeFilePath of filesToProcess.keys()) {
if (
this._options.skipPackageJson &&
relativeFilePath.endsWith(PACKAGE_JSON)
) {
continue;
}
// SHA-1, if requested, should already be present thanks to the crawler.
const filePath = fastPath.resolve(
this._options.rootDir,
relativeFilePath,
);
const promise = this._processFile(hasteMap, map, mocks, filePath);
if (promise) {
promises.push(promise);
}
}
try {
await Promise.all(promises);
this._cleanup();
hasteMap.map = map;
hasteMap.mocks = mocks;
return hasteMap;
} catch (error) {
this._cleanup();
throw error;
}
}
private _cleanup() {
const worker = this._worker;
// @ts-ignore
if (worker && typeof worker.end === 'function') {
// @ts-ignore
worker.end();
}
this._worker = null;
}
/**
* 4. serialize the new `HasteMap` in a cache file.
*/
private _persist(hasteMap: InternalHasteMap) {
serializer.writeFileSync(this._cachePath, hasteMap);
}
/**
* Creates workers or parses files and extracts metadata in-process.
*/
private _getWorker(options?: {forceInBand: boolean}): WorkerInterface {
if (!this._worker) {
if ((options && options.forceInBand) || this._options.maxWorkers <= 1) {
this._worker = {getSha1, worker};
} else {
// @ts-ignore: assignment of a worker with custom properties.
this._worker = new Worker(require.resolve('./worker'), {
exposedMethods: ['getSha1', 'worker'],
maxRetries: 3,
numWorkers: this._options.maxWorkers,
}) as WorkerInterface;
}
}
return this._worker;
}
private _crawl(hasteMap: InternalHasteMap) {
const options = this._options;
const ignore = this._ignore.bind(this);
const crawl =
canUseWatchman && this._options.useWatchman ? watchmanCrawl : nodeCrawl;
const crawlerOptions: CrawlerOptions = {
computeSha1: options.computeSha1,
data: hasteMap,
extensions: options.extensions,
forceNodeFilesystemAPI: options.forceNodeFilesystemAPI,
ignore,
mapper: options.mapper,
rootDir: options.rootDir,
roots: options.roots,
};
const retry = (error: Error) => {
if (crawl === watchmanCrawl) {
this._console.warn(
`jest-haste-map: Watchman crawl failed. Retrying once with node ` +
`crawler.\n` +
` Usually this happens when watchman isn't running. Create an ` +
`empty \`.watchmanconfig\` file in your project's root folder or ` +
`initialize a git or hg repository in your project.\n` +
` ` +
error,
);
return nodeCrawl(crawlerOptions).catch(e => {
throw new Error(
`Crawler retry failed:\n` +
` Original error: ${error.message}\n` +
` Retry error: ${e.message}\n`,
);
});
}
throw error;
};
try {
return crawl(crawlerOptions).catch(retry);
} catch (error) {
return retry(error);
}
}
/**
* Watch mode
*/
private _watch(hasteMap: InternalHasteMap): Promise<void> {
if (!this._options.watch) {
return Promise.resolve();
}
// In watch mode, we'll only warn about module collisions and we'll retain
// all files, even changes to node_modules.
this._options.throwOnModuleCollision = false;
this._options.retainAllFiles = true;
// WatchmanWatcher > FSEventsWatcher > sane.NodeWatcher
const Watcher: sane.Watcher =
canUseWatchman && this._options.useWatchman
? WatchmanWatcher
: FSEventsWatcher.isSupported()
? FSEventsWatcher
: sane.NodeWatcher;
const extensions = this._options.extensions;
const ignorePattern = this._options.ignorePattern;
const rootDir = this._options.rootDir;
let changeQueue: Promise<null | void> = Promise.resolve();
let eventsQueue: EventsQueue = [];
// We only need to copy the entire haste map once on every "frame".
let mustCopy = true;
const createWatcher = (root: Config.Path): Promise<Watcher> => {
// @ts-ignore: TODO how? "Cannot use 'new' with an expression whose type lacks a call or construct signature."
const watcher = new Watcher(root, {
dot: false,
glob: extensions.map(extension => '**/*.' + extension),
ignored: ignorePattern,
});
return new Promise((resolve, reject) => {
const rejectTimeout = setTimeout(
() => reject(new Error('Failed to start watch mode.')),
MAX_WAIT_TIME,
);
watcher.once('ready', () => {
clearTimeout(rejectTimeout);
watcher.on('all', onChange);
resolve(watcher);
});
});
};
const emitChange = () => {
if (eventsQueue.length) {
mustCopy = true;
const changeEvent: ChangeEvent = {
eventsQueue,
hasteFS: new HasteFS({
files: hasteMap.files,
rootDir,
}),
moduleMap: new HasteModuleMap({
duplicates: hasteMap.duplicates,
map: hasteMap.map,
mocks: hasteMap.mocks,
rootDir,
}),
};
this.emit('change', changeEvent);
eventsQueue = [];
}
};
const onChange = (
type: string,
filePath: Config.Path,
root: Config.Path,
stat?: fs.Stats,
) => {
filePath = path.join(root, normalizePathSep(filePath));
if (
(stat && stat.isDirectory()) ||
this._ignore(filePath) ||
!extensions.some(extension => filePath.endsWith(extension))
) {
return;
}
changeQueue = changeQueue
.then(() => {
// If we get duplicate events for the same file, ignore them.
if (
eventsQueue.find(
event =>
event.type === type &&
event.filePath === filePath &&
((!event.stat && !stat) ||
(!!event.stat &&
!!stat &&
event.stat.mtime.getTime() === stat.mtime.getTime())),
)
) {
return null;
}
if (mustCopy) {
mustCopy = false;
hasteMap = {
clocks: new Map(hasteMap.clocks),
duplicates: new Map(hasteMap.duplicates),
files: new Map(hasteMap.files),
map: new Map(hasteMap.map),
mocks: new Map(hasteMap.mocks),
};
}
const add = () => {
eventsQueue.push({filePath, stat, type});
return null;
};
const relativeFilePath = fastPath.relative(rootDir, filePath);
const fileMetadata = hasteMap.files.get(relativeFilePath);
// If it's not an addition, delete the file and all its metadata
if (fileMetadata != null) {
const moduleName = fileMetadata[H.ID];
const platform =
getPlatformExtension(filePath, this._options.platforms) ||
H.GENERIC_PLATFORM;
hasteMap.files.delete(relativeFilePath);
let moduleMap = hasteMap.map.get(moduleName);
if (moduleMap != null) {
// We are forced to copy the object because jest-haste-map exposes
// the map as an immutable entity.
moduleMap = copy(moduleMap);
delete moduleMap[platform];
if (Object.keys(moduleMap).length === 0) {
hasteMap.map.delete(moduleName);
} else {
hasteMap.map.set(moduleName, moduleMap);
}
}
if (
this._options.mocksPattern &&
this._options.mocksPattern.test(filePath)
) {
const mockName = getMockName(filePath);
hasteMap.mocks.delete(mockName);
}
this._recoverDuplicates(hasteMap, relativeFilePath, moduleName);
}
// If the file was added or changed,
// parse it and update the haste map.
if (type === 'add' || type === 'change') {
invariant(
stat,
'since the file exists or changed, it should have stats',
);
const fileMetadata: FileMetaData = [
'',
stat ? stat.mtime.getTime() : -1,
stat ? stat.size : 0,
0,
'',
null,
];
hasteMap.files.set(relativeFilePath, fileMetadata);
const promise = this._processFile(
hasteMap,
hasteMap.map,
hasteMap.mocks,
filePath,
{forceInBand: true},
);
// Cleanup
this._cleanup();
if (promise) {
return promise.then(add);
} else {
// If a file in node_modules has changed,
// emit an event regardless.
add();
}
} else {
add();
}
return null;
})
.catch((error: Error) => {
this._console.error(
`jest-haste-map: watch error:\n ${error.stack}\n`,
);
});
};
this._changeInterval = setInterval(emitChange, CHANGE_INTERVAL);
return Promise.all(this._options.roots.map(createWatcher)).then(
watchers => {
this._watchers = watchers;
},
);
}
/**
* This function should be called when the file under `filePath` is removed
* or changed. When that happens, we want to figure out if that file was
* part of a group of files that had the same ID. If it was, we want to
* remove it from the group. Furthermore, if there is only one file
* remaining in the group, then we want to restore that single file as the