CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jest-haste-map

A module used by Jest to create a fast lookup of files in a project

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

file-system-mapping.mddocs/

File System Mapping

Core file system crawling and mapping functionality for creating fast lookups of project files. Supports parallel processing, intelligent caching, and multiple crawler implementations for optimal performance across different environments.

Capabilities

HasteMap Class

The main class for orchestrating file system mapping, providing factory methods and lifecycle management.

/**
 * Main class for creating and managing haste maps
 * Extends EventEmitter to provide change notifications in watch mode
 */
class HasteMap extends EventEmitter implements IHasteMap {
  /**
   * Factory method to create a HasteMap instance with proper cache setup
   * @param options - Configuration options for the haste map
   * @returns Promise resolving to configured IHasteMap instance
   */
  static create(options: Options): Promise<IHasteMap>;
  
  /**
   * Get static HasteMap implementation, supports custom implementations
   * @param config - Jest project configuration
   * @returns HasteMapStatic implementation
   */
  static getStatic(config: Config.ProjectConfig): HasteMapStatic;
  
  /**
   * Build the complete haste map by crawling files and extracting metadata
   * @returns Promise with hasteFS for file operations and moduleMap for resolution
   */
  build(): Promise<{hasteFS: IHasteFS; moduleMap: IModuleMap}>;
  
  /**
   * Get the cache file path for this haste map instance
   * @returns Absolute path to cache file
   */
  getCacheFilePath(): string;
  
  /**
   * Read existing haste map data from cache
   * @returns Internal haste map data structure
   */
  read(): InternalHasteMap;
  
  /**
   * Read just the module map from cache, faster than full read
   * @returns ModuleMap instance from cached data
   */
  readModuleMap(): HasteModuleMap;
  
  /**
   * Stop file watching and cleanup resources
   * @returns Promise that resolves when cleanup is complete
   */
  end(): Promise<void>;
}

Configuration Options

Comprehensive configuration interface for customizing haste map behavior.

/**
 * Configuration options for HasteMap creation
 */
interface Options {
  /** Unique identifier for caching, typically project name */
  id: string;
  /** File extensions to include in the map */
  extensions: Array<string>;
  /** Maximum number of worker processes for parallel processing */
  maxWorkers: number;
  /** Platform extensions to recognize (e.g., ['ios', 'android']) */
  platforms: Array<string>;
  /** Whether to retain all files in memory, including node_modules */
  retainAllFiles: boolean;
  /** Root directory of the project */
  rootDir: string;
  /** Directories to crawl, subset of rootDir */
  roots: Array<string>;
  
  /** Directory for cache storage, defaults to os.tmpdir() */
  cacheDirectory?: string;
  /** Whether to compute file dependencies, defaults to true */
  computeDependencies?: boolean;
  /** Whether to compute SHA-1 hashes for files, defaults to false */
  computeSha1?: boolean;
  /** Console instance for logging, defaults to global console */
  console?: Console;
  /** Path to custom dependency extractor module */
  dependencyExtractor?: string | null;
  /** Whether to follow symbolic links, defaults to false */
  enableSymlinks?: boolean;
  /** Force Node.js filesystem API instead of native implementations */
  forceNodeFilesystemAPI?: boolean;
  /** Path to custom haste implementation module */
  hasteImplModulePath?: string;
  /** Path to custom haste map implementation module */
  hasteMapModulePath?: string;
  /** Pattern to ignore files and directories */
  ignorePattern?: HasteRegExp;
  /** Pattern to identify mock files */
  mocksPattern?: string;
  /** Whether to clear existing cache before building */
  resetCache?: boolean;
  /** Whether to skip processing package.json files */
  skipPackageJson?: boolean;
  /** Whether to throw errors on module name collisions */
  throwOnModuleCollision?: boolean;
  /** Whether to use Watchman for file system operations, defaults to true */
  useWatchman?: boolean;
  /** Whether to enable file system watching, defaults to false */
  watch?: boolean;
  /** Whether to use worker threads instead of child processes */
  workerThreads?: boolean;
}

Static Utility Methods

Static methods for cache management and module map creation.

/**
 * Generate cache file path with deterministic hashing
 * @param tmpdir - Temporary directory for cache storage
 * @param id - Base identifier for the cache file
 * @param extra - Additional parameters for cache key generation
 * @returns Absolute path to cache file
 */
static getCacheFilePath(
  tmpdir: string,
  id: string,
  ...extra: Array<string>
): string;

/**
 * Create ModuleMap instance from serialized JSON data
 * @param json - Serialized module map data
 * @returns ModuleMap instance
 */
static getModuleMapFromJSON(json: SerializableModuleMap): HasteModuleMap;

Usage Examples:

import HasteMap from "jest-haste-map";
import os from "os";

// Basic project mapping
const hasteMap = await HasteMap.create({
  id: "my-app",
  extensions: ["js", "ts", "jsx", "tsx"],
  maxWorkers: os.availableParallelism(),
  platforms: [],
  roots: ["/src", "/tests"],
  retainAllFiles: false,
  rootDir: "/project/root",
});

// Build the map
const {hasteFS, moduleMap} = await hasteMap.build();

// Advanced configuration with caching and watching
const advancedMap = await HasteMap.create({
  id: "advanced-project",
  extensions: ["js", "ts", "json"],
  maxWorkers: 4,
  platforms: ["ios", "android", "web"],
  roots: ["/src"],
  retainAllFiles: true,
  rootDir: "/project/root",
  cacheDirectory: "/tmp/haste-cache",
  computeDependencies: true,
  computeSha1: true,
  watch: true,
  useWatchman: true,
  ignorePattern: /node_modules|\.git/,
  mocksPattern: "__mocks__",
});

// Handle file changes in watch mode
advancedMap.on('change', (event) => {
  console.log('Files changed:', event.eventsQueue.length);
  // Access updated file system and module map
  const updatedFiles = event.hasteFS.getAllFiles();
});

// Clean up when done
await advancedMap.end();

Internal Data Structures

Core data structures used internally by the haste map system.

/**
 * Internal representation of the complete haste map
 */
interface InternalHasteMap {
  /** Watchman clock specifications for change detection */
  clocks: WatchmanClocks;
  /** Map of duplicate module names to their file paths */
  duplicates: DuplicatesIndex;
  /** Map of file paths to metadata arrays */
  files: FileData;
  /** Map of module names to platform-specific metadata */
  map: ModuleMapData;
  /** Map of mock names to file paths */
  mocks: MockData;
}

/**
 * File metadata stored as array for memory efficiency
 * [id, mtime, size, visited, dependencies, sha1]
 */
type FileMetaData = [
  id: string,
  mtime: number,
  size: number,
  visited: 0 | 1,
  dependencies: string,
  sha1: string | null | undefined,
];

type FileData = Map<string, FileMetaData>;
type ModuleMapData = Map<string, ModuleMapItem>;
type MockData = Map<string, string>;
type WatchmanClocks = Map<string, WatchmanClockSpec>;
type WatchmanClockSpec = string | {scm: {'mergebase-with': string}};

docs

file-system-mapping.md

file-system-watching.md

index.md

module-resolution.md

virtual-file-system.md

tile.json