index.js 34.8 KB
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports.DuplicateError = void 0;
Object.defineProperty(exports, 'ModuleMap', {
  enumerable: true,
  get: function () {
    return _ModuleMap.default;
  }
});
exports.default = void 0;

function _child_process() {
  const data = require('child_process');

  _child_process = function () {
    return data;
  };

  return data;
}

function _crypto() {
  const data = require('crypto');

  _crypto = function () {
    return data;
  };

  return data;
}

function _events() {
  const data = require('events');

  _events = function () {
    return data;
  };

  return data;
}

function _os() {
  const data = require('os');

  _os = function () {
    return data;
  };

  return data;
}

function path() {
  const data = _interopRequireWildcard(require('path'));

  path = function () {
    return data;
  };

  return data;
}

function _jestRegexUtil() {
  const data = require('jest-regex-util');

  _jestRegexUtil = function () {
    return data;
  };

  return data;
}

function _jestSerializer() {
  const data = _interopRequireDefault(require('jest-serializer'));

  _jestSerializer = function () {
    return data;
  };

  return data;
}

function _jestWorker() {
  const data = require('jest-worker');

  _jestWorker = function () {
    return data;
  };

  return data;
}

var _HasteFS = _interopRequireDefault(require('./HasteFS'));

var _ModuleMap = _interopRequireDefault(require('./ModuleMap'));

var _constants = _interopRequireDefault(require('./constants'));

var _node = _interopRequireDefault(require('./crawlers/node'));

var _watchman = _interopRequireDefault(require('./crawlers/watchman'));

var _getMockName = _interopRequireDefault(require('./getMockName'));

var fastPath = _interopRequireWildcard(require('./lib/fast_path'));

var _getPlatformExtension = _interopRequireDefault(
  require('./lib/getPlatformExtension')
);

var _normalizePathSep = _interopRequireDefault(
  require('./lib/normalizePathSep')
);

var _FSEventsWatcher = _interopRequireDefault(
  require('./watchers/FSEventsWatcher')
);

var _NodeWatcher = _interopRequireDefault(require('./watchers/NodeWatcher'));

var _WatchmanWatcher = _interopRequireDefault(
  require('./watchers/WatchmanWatcher')
);

var _worker = require('./worker');

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : {default: obj};
}

function _getRequireWildcardCache(nodeInterop) {
  if (typeof WeakMap !== 'function') return null;
  var cacheBabelInterop = new WeakMap();
  var cacheNodeInterop = new WeakMap();
  return (_getRequireWildcardCache = function (nodeInterop) {
    return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
  })(nodeInterop);
}

function _interopRequireWildcard(obj, nodeInterop) {
  if (!nodeInterop && obj && obj.__esModule) {
    return obj;
  }
  if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
    return {default: obj};
  }
  var cache = _getRequireWildcardCache(nodeInterop);
  if (cache && cache.has(obj)) {
    return cache.get(obj);
  }
  var newObj = {};
  var hasPropertyDescriptor =
    Object.defineProperty && Object.getOwnPropertyDescriptor;
  for (var key in obj) {
    if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
      var desc = hasPropertyDescriptor
        ? Object.getOwnPropertyDescriptor(obj, key)
        : null;
      if (desc && (desc.get || desc.set)) {
        Object.defineProperty(newObj, key, desc);
      } else {
        newObj[key] = obj[key];
      }
    }
  }
  newObj.default = obj;
  if (cache) {
    cache.set(obj, newObj);
  }
  return newObj;
}

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }
  return obj;
}

// TypeScript doesn't like us importing from outside `rootDir`, but it doesn't
// understand `require`.
const {version: VERSION} = require('../package.json');

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';
const VCS_DIRECTORIES = ['.git', '.hg']
  .map(vcs =>
    (0, _jestRegexUtil().escapePathForRegex)(path().sep + vcs + path().sep)
  )
  .join('|');

const canUseWatchman = (() => {
  try {
    (0, _child_process().execSync)('watchman --version', {
      stdio: ['ignore']
    });
    return true;
  } catch {}

  return false;
})();

function invariant(condition, message) {
  if (!condition) {
    throw new Error(message);
  }
}
/**
 * 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()`.
 *
 */

class HasteMap extends _events().EventEmitter {
  static getStatic(config) {
    if (config.haste.hasteMapModulePath) {
      return require(config.haste.hasteMapModulePath);
    }

    return HasteMap;
  }

  static create(options) {
    if (options.hasteMapModulePath) {
      const CustomHasteMap = require(options.hasteMapModulePath);

      return new CustomHasteMap(options);
    }

    return new HasteMap(options);
  }

  constructor(options) {
    super();

    _defineProperty(this, '_buildPromise', void 0);

    _defineProperty(this, '_cachePath', void 0);

    _defineProperty(this, '_changeInterval', void 0);

    _defineProperty(this, '_console', void 0);

    _defineProperty(this, '_options', void 0);

    _defineProperty(this, '_watchers', void 0);

    _defineProperty(this, '_worker', void 0);

    this._options = {
      cacheDirectory: options.cacheDirectory || (0, _os().tmpdir)(),
      computeDependencies:
        options.computeDependencies === undefined
          ? true
          : options.computeDependencies,
      computeSha1: options.computeSha1 || false,
      dependencyExtractor: options.dependencyExtractor || null,
      enableSymlinks: options.enableSymlinks || false,
      extensions: options.extensions,
      forceNodeFilesystemAPI: !!options.forceNodeFilesystemAPI,
      hasteImplModulePath: options.hasteImplModulePath,
      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) {
      if (options.ignorePattern instanceof RegExp) {
        this._options.ignorePattern = new RegExp(
          options.ignorePattern.source.concat('|' + VCS_DIRECTORIES),
          options.ignorePattern.flags
        );
      } else {
        throw new Error(
          'jest-haste-map: the `ignorePattern` option must be a RegExp'
        );
      }
    } else {
      this._options.ignorePattern = new RegExp(VCS_DIRECTORIES);
    }

    if (this._options.enableSymlinks && this._options.useWatchman) {
      throw new Error(
        'jest-haste-map: enableSymlinks config option was set, but ' +
          'is incompatible with watchman.\n' +
          'Set either `enableSymlinks` to false or `useWatchman` to false.'
      );
    }

    const rootDirHash = (0, _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._options.computeDependencies.toString()
    );
    this._buildPromise = null;
    this._watchers = [];
    this._worker = null;
  }

  static getCacheFilePath(tmpdir, name, ...extra) {
    const hash = (0, _crypto().createHash)('md5').update(extra.join(''));
    return path().join(
      tmpdir,
      name.replace(/\W/g, '-') + '-' + hash.digest('hex')
    );
  }

  static getModuleMapFromJSON(json) {
    return _ModuleMap.default.fromJSON(json);
  }

  getCacheFilePath() {
    return this._cachePath;
  }

  build() {
    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;

        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.default({
          files: hasteMap.files,
          rootDir
        });
        const moduleMap = new _ModuleMap.default({
          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() {
    let hasteMap;

    try {
      hasteMap = _jestSerializer().default.readFileSync(this._cachePath);
    } catch {
      hasteMap = this._createEmptyMap();
    }

    return hasteMap;
  }

  readModuleMap() {
    const data = this.read();
    return new _ModuleMap.default({
      duplicates: data.duplicates,
      map: data.map,
      mocks: data.mocks,
      rootDir: this._options.rootDir
    });
  }
  /**
   * 2. crawl the file system.
   */

  async _buildFileMap() {
    let hasteMap;

    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.
   */

  _processFile(hasteMap, map, mocks, filePath, workerOptions) {
    const rootDir = this._options.rootDir;

    const setModule = (id, module) => {
      let moduleMap = map.get(id);

      if (!moduleMap) {
        moduleMap = Object.create(null);
        map.set(id, moduleMap);
      }

      const platform =
        (0, _getPlatformExtension.default)(
          module[_constants.default.PATH],
          this._options.platforms
        ) || _constants.default.GENERIC_PLATFORM;

      const existingModule = moduleMap[platform];

      if (
        existingModule &&
        existingModule[_constants.default.PATH] !==
          module[_constants.default.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[_constants.default.PATH],
            '    * <rootDir>' + path().sep + module[_constants.default.PATH],
            ''
          ].join('\n')
        );

        if (this._options.throwOnModuleCollision) {
          throw new DuplicateError(
            existingModule[_constants.default.PATH],
            module[_constants.default.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[_constants.default.PATH], module[_constants.default.TYPE]],
          [
            existingModule[_constants.default.PATH],
            existingModule[_constants.default.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[_constants.default.PATH],
            module[_constants.default.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[_constants.default.ID]
    );
    const computeSha1 =
      this._options.computeSha1 && !fileMetadata[_constants.default.SHA1]; // Callback called when the response from the worker is successful.

    const workerReply = metadata => {
      // `1` for truthy values instead of `true` to save cache space.
      fileMetadata[_constants.default.VISITED] = 1;
      const metadataId = metadata.id;
      const metadataModule = metadata.module;

      if (metadataId && metadataModule) {
        fileMetadata[_constants.default.ID] = metadataId;
        setModule(metadataId, metadataModule);
      }

      fileMetadata[_constants.default.DEPENDENCIES] = metadata.dependencies
        ? metadata.dependencies.join(_constants.default.DEPENDENCY_DELIM)
        : '';

      if (computeSha1) {
        fileMetadata[_constants.default.SHA1] = metadata.sha1;
      }
    }; // Callback called when the response from the worker is an error.

    const workerError = error => {
      if (typeof error !== 'object' || !error.message || !error.stack) {
        error = new Error(error);
        error.stack = ''; // Remove stack for stack-less errors.
      }

      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 && filePath.includes(NODE_MODULES)) {
      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 = (0, _getMockName.default)(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[_constants.default.VISITED]) {
      if (!fileMetadata[_constants.default.ID]) {
        return null;
      }

      if (moduleMetadata != null) {
        const platform =
          (0, _getPlatformExtension.default)(
            filePath,
            this._options.platforms
          ) || _constants.default.GENERIC_PLATFORM;

        const module = moduleMetadata[platform];

        if (module == null) {
          return null;
        }

        const moduleId = fileMetadata[_constants.default.ID];
        let modulesByPlatform = map.get(moduleId);

        if (!modulesByPlatform) {
          modulesByPlatform = Object.create(null);
          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);
  }

  _buildHasteMap(data) {
    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;
    let mocks;
    let filesToProcess;

    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[_constants.default.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);
      }
    }

    return Promise.all(promises).then(
      () => {
        this._cleanup();

        hasteMap.map = map;
        hasteMap.mocks = mocks;
        return hasteMap;
      },
      error => {
        this._cleanup();

        throw error;
      }
    );
  }

  _cleanup() {
    const worker = this._worker; // @ts-expect-error

    if (worker && typeof worker.end === 'function') {
      // @ts-expect-error
      worker.end();
    }

    this._worker = null;
  }
  /**
   * 4. serialize the new `HasteMap` in a cache file.
   */

  _persist(hasteMap) {
    _jestSerializer().default.writeFileSync(this._cachePath, hasteMap);
  }
  /**
   * Creates workers or parses files and extracts metadata in-process.
   */

  _getWorker(options) {
    if (!this._worker) {
      if ((options && options.forceInBand) || this._options.maxWorkers <= 1) {
        this._worker = {
          getSha1: _worker.getSha1,
          worker: _worker.worker
        };
      } else {
        // @ts-expect-error: assignment of a worker with custom properties.
        this._worker = new (_jestWorker().Worker)(require.resolve('./worker'), {
          exposedMethods: ['getSha1', 'worker'],
          maxRetries: 3,
          numWorkers: this._options.maxWorkers
        });
      }
    }

    return this._worker;
  }

  _crawl(hasteMap) {
    const options = this._options;

    const ignore = this._ignore.bind(this);

    const crawl =
      canUseWatchman && this._options.useWatchman
        ? _watchman.default
        : _node.default;
    const crawlerOptions = {
      computeSha1: options.computeSha1,
      data: hasteMap,
      enableSymlinks: options.enableSymlinks,
      extensions: options.extensions,
      forceNodeFilesystemAPI: options.forceNodeFilesystemAPI,
      ignore,
      rootDir: options.rootDir,
      roots: options.roots
    };

    const retry = error => {
      if (crawl === _watchman.default) {
        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 (0, _node.default)(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
   */

  _watch(hasteMap) {
    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 =
      canUseWatchman && this._options.useWatchman
        ? _WatchmanWatcher.default
        : _FSEventsWatcher.default.isSupported()
        ? _FSEventsWatcher.default
        : _NodeWatcher.default;
    const extensions = this._options.extensions;
    const ignorePattern = this._options.ignorePattern;
    const rootDir = this._options.rootDir;
    let changeQueue = Promise.resolve();
    let eventsQueue = []; // We only need to copy the entire haste map once on every "frame".

    let mustCopy = true;

    const createWatcher = root => {
      const watcher = new Watcher(root, {
        dot: true,
        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 = {
          eventsQueue,
          hasteFS: new _HasteFS.default({
            files: hasteMap.files,
            rootDir
          }),
          moduleMap: new _ModuleMap.default({
            duplicates: hasteMap.duplicates,
            map: hasteMap.map,
            mocks: hasteMap.mocks,
            rootDir
          })
        };
        this.emit('change', changeEvent);
        eventsQueue = [];
      }
    };

    const onChange = (type, filePath, root, stat) => {
      filePath = path().join(root, (0, _normalizePathSep.default)(filePath));

      if (
        (stat && stat.isDirectory()) ||
        this._ignore(filePath) ||
        !extensions.some(extension => filePath.endsWith(extension))
      ) {
        return;
      }

      const relativeFilePath = fastPath.relative(rootDir, filePath);
      const fileMetadata = hasteMap.files.get(relativeFilePath); // The file has been accessed, not modified

      if (
        type === 'change' &&
        fileMetadata &&
        stat &&
        fileMetadata[_constants.default.MTIME] === stat.mtime.getTime()
      ) {
        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 fileMetadata = hasteMap.files.get(relativeFilePath); // If it's not an addition, delete the file and all its metadata

          if (fileMetadata != null) {
            const moduleName = fileMetadata[_constants.default.ID];

            const platform =
              (0, _getPlatformExtension.default)(
                filePath,
                this._options.platforms
              ) || _constants.default.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 = (0, _getMockName.default)(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 = [
              '',
              stat.mtime.getTime(),
              stat.size,
              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 => {
          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
   * correct resolution for its ID, and cleanup the duplicates index.
   */

  _recoverDuplicates(hasteMap, relativeFilePath, moduleName) {
    let dupsByPlatform = hasteMap.duplicates.get(moduleName);

    if (dupsByPlatform == null) {
      return;
    }

    const platform =
      (0, _getPlatformExtension.default)(
        relativeFilePath,
        this._options.platforms
      ) || _constants.default.GENERIC_PLATFORM;

    let dups = dupsByPlatform.get(platform);

    if (dups == null) {
      return;
    }

    dupsByPlatform = copyMap(dupsByPlatform);
    hasteMap.duplicates.set(moduleName, dupsByPlatform);
    dups = copyMap(dups);
    dupsByPlatform.set(platform, dups);
    dups.delete(relativeFilePath);

    if (dups.size !== 1) {
      return;
    }

    const uniqueModule = dups.entries().next().value;

    if (!uniqueModule) {
      return;
    }

    let dedupMap = hasteMap.map.get(moduleName);

    if (dedupMap == null) {
      dedupMap = Object.create(null);
      hasteMap.map.set(moduleName, dedupMap);
    }

    dedupMap[platform] = uniqueModule;
    dupsByPlatform.delete(platform);

    if (dupsByPlatform.size === 0) {
      hasteMap.duplicates.delete(moduleName);
    }
  }

  async end() {
    if (this._changeInterval) {
      clearInterval(this._changeInterval);
    }

    if (!this._watchers.length) {
      return;
    }

    await Promise.all(this._watchers.map(watcher => watcher.close()));
    this._watchers = [];
  }
  /**
   * Helpers
   */

  _ignore(filePath) {
    const ignorePattern = this._options.ignorePattern;
    const ignoreMatched =
      ignorePattern instanceof RegExp
        ? ignorePattern.test(filePath)
        : ignorePattern && ignorePattern(filePath);
    return (
      ignoreMatched ||
      (!this._options.retainAllFiles && filePath.includes(NODE_MODULES))
    );
  }

  _createEmptyMap() {
    return {
      clocks: new Map(),
      duplicates: new Map(),
      files: new Map(),
      map: new Map(),
      mocks: new Map()
    };
  }
}

exports.default = HasteMap;

_defineProperty(HasteMap, 'H', _constants.default);

class DuplicateError extends Error {
  constructor(mockPath1, mockPath2) {
    super('Duplicated files or mocks. Please check the console for more info');

    _defineProperty(this, 'mockPath1', void 0);

    _defineProperty(this, 'mockPath2', void 0);

    this.mockPath1 = mockPath1;
    this.mockPath2 = mockPath2;
  }
}

exports.DuplicateError = DuplicateError;

function copy(object) {
  return Object.assign(Object.create(null), object);
}

function copyMap(input) {
  return new Map(input);
}