This commit is contained in:
2026-11-02 12:42:04 +00:00
commit e4e28174bf
5498 changed files with 1735888 additions and 0 deletions

19
node_modules/file-entry-cache/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,19 @@
MIT License & © Jared Wray
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

634
node_modules/file-entry-cache/README.md generated vendored Normal file
View File

@@ -0,0 +1,634 @@
[<img align="center" src="https://cacheable.org/symbol.svg" alt="Cacheable" />](https://github.com/jaredwray/cacheable)
# file-entry-cache
> A lightweight cache for file metadata, ideal for processes that work on a specific set of files and only need to reprocess files that have changed since the last run
[![codecov](https://codecov.io/gh/jaredwray/cacheable/branch/main/graph/badge.svg?token=lWZ9OBQ7GM)](https://codecov.io/gh/jaredwray/cacheable)
[![tests](https://github.com/jaredwray/cacheable/actions/workflows/tests.yml/badge.svg)](https://github.com/jaredwray/cacheable/actions/workflows/tests.yml)
[![npm](https://img.shields.io/npm/dm/file-entry-cache.svg)](https://www.npmjs.com/package/file-entry-cache)
[![npm](https://img.shields.io/npm/v/file-entry-cache)](https://www.npmjs.com/package/file-entry-cache)
[![license](https://img.shields.io/github/license/jaredwray/cacheable)](https://github.com/jaredwray/cacheable/blob/main/LICENSE)
# Features
- Lightweight cache for file metadata
- Ideal for processes that work on a specific set of files
- Persists cache to Disk via `reconcile()` or `persistInterval` on `cache` options.
- Uses `checksum` to determine if a file has changed
- Supports `relative` and `absolute` paths with configurable current working directory
- Portable cache files when using relative paths
- ESM and CommonJS support with Typescript
# Table of Contents
- [Installation](#installation)
- [Getting Started](#getting-started)
- [Changes from v10 to v11](#changes-from-v10-to-v11)
- [Changes from v9 to v10](#changes-from-v9-to-v10)
- [Global Default Functions](#global-default-functions)
- [FileEntryCache Options (FileEntryCacheOptions)](#fileentrycache-options-fileentrycacheoptions)
- [API](#api)
- [Get File Descriptor](#get-file-descriptor)
- [Path Handling and Current Working Directory](#path-handling-and-current-working-directory)
- [Cache Portability](#cache-portability)
- [Maximum Portability with Checksums](#maximum-portability-with-checksums)
- [Handling Project Relocations](#handling-project-relocations)
- [Path Security and Traversal Prevention](#path-security-and-traversal-prevention)
- [Using Checksums to Determine if a File has Changed (useCheckSum)](#using-checksums-to-determine-if-a-file-has-changed-usechecksum)
- [Setting Additional Meta Data](#setting-additional-meta-data)
- [Logger Support](#logger-support)
- [Logger Interface](#logger-interface)
- [Using Pino Logger](#using-pino-logger)
- [Log Levels](#log-levels)
- [Example with Custom Log Levels](#example-with-custom-log-levels)
- [Debugging Cache Operations](#debugging-cache-operations)
- [How to Contribute](#how-to-contribute)
- [License and Copyright](#license-and-copyright)
# Installation
```bash
npm install file-entry-cache
```
# Getting Started
```javascript
import fileEntryCache from 'file-entry-cache';
const cache = fileEntryCache.create('cache1');
// Using relative paths
let fileDescriptor = cache.getFileDescriptor('./src/file.txt');
console.log(fileDescriptor.changed); // true as it is the first time
console.log(fileDescriptor.key); // './src/file.txt' (stored as provided)
// Repeated calls keep reporting `changed: true` until you persist the state
// with reconcile(); only then does the file become the cached baseline.
cache.reconcile();
fileDescriptor = cache.getFileDescriptor('./src/file.txt');
console.log(fileDescriptor.changed); // false as it has not changed since reconcile()
// do something to change the file
fs.writeFileSync('./src/file.txt', 'new data foo bar');
// check if the file has changed
fileDescriptor = cache.getFileDescriptor('./src/file.txt');
console.log(fileDescriptor.changed); // true
```
Using `create()` with options for more control:
```javascript
import fileEntryCache from 'file-entry-cache';
// Create cache with options
const cache = fileEntryCache.create('myCache', './.cache', {
useCheckSum: true, // Use checksums for more reliable change detection
cwd: '/path/to/project', // Custom working directory
restrictAccessToCwd: false, // Allow access outside cwd (use with caution)
useAbsolutePathAsKey: false // Store relative paths in cache
});
let fileDescriptor = cache.getFileDescriptor('./src/file.txt');
console.log(fileDescriptor.changed); // true
console.log(fileDescriptor.meta.hash); // checksum hash
```
Save it to Disk and Reconcile files that are no longer found
```javascript
import fileEntryCache from 'file-entry-cache';
const cache = fileEntryCache.create('cache1');
let fileDescriptor = cache.getFileDescriptor('./src/file.txt');
console.log(fileDescriptor.changed); // true as it is the first time
cache.reconcile(); // save the cache to disk and remove files that are no longer found
```
Load the cache from a file:
```javascript
import fileEntryCache from 'file-entry-cache';
// Basic usage
const cache = fileEntryCache.createFromFile('/path/to/cache/file');
let fileDescriptor = cache.getFileDescriptor('./src/file.txt');
console.log(fileDescriptor.changed); // false as it has not changed from the saved cache.
// With options
const cache2 = fileEntryCache.createFromFile('/path/to/cache/file', {
useCheckSum: true,
cwd: '/path/to/project'
});
```
# Changes from v10 to v11
**BREAKING CHANGES:**
- **`create()` and `createFromFile()` now use `CreateOptions` object** - The function signatures have changed to accept an options object instead of individual parameters for better extensibility and clarity.
**Old API (v10):**
```javascript
// v10 - positional parameters
const cache = fileEntryCache.create(cacheId, cacheDirectory, useCheckSum, cwd);
const cache2 = fileEntryCache.createFromFile(filePath, useCheckSum, cwd);
```
**New API (v11):**
```javascript
// v11 - options object
const cache = fileEntryCache.create(cacheId, cacheDirectory, {
useCheckSum: true,
cwd: '/path/to/project',
restrictAccessToCwd: false
});
const cache2 = fileEntryCache.createFromFile(filePath, {
useCheckSum: true,
cwd: '/path/to/project',
restrictAccessToCwd: false
});
```
- **Renamed `strictPaths` to `restrictAccessToCwd`** - For better clarity and self-documentation, the option that restricts file access to the current working directory has been renamed.
**Migration:**
```javascript
// Old
const cache = new FileEntryCache({ strictPaths: true });
cache.strictPaths = false;
// New
const cache = new FileEntryCache({ restrictAccessToCwd: true });
cache.restrictAccessToCwd = false;
```
- **Renamed `currentWorkingDirectory` to `cwd`** - For consistency with common conventions and brevity, the property has been renamed to `cwd`.
**Migration:**
```javascript
// Old
const cache = new FileEntryCache({ currentWorkingDirectory: '/path/to/project' });
cache.currentWorkingDirectory = '/new/path';
// New
const cache = new FileEntryCache({ cwd: '/path/to/project' });
cache.cwd = '/new/path';
```
**NEW FEATURES:**
- **Added `cwd` option** - You can now specify a custom current working directory for resolving relative paths
- **Added `restrictAccessToCwd` option** - Provides protection against path traversal attacks (disabled by default for backwards compatibility)
- **Added `useAbsolutePathAsKey` option** - When `true`, cache keys use absolute paths instead of the provided paths. Default is `false` for better cache portability with relative paths
- **Added `logger` option** - Support for Pino-compatible logger instances to enable debugging and monitoring of cache operations. See [Logger Support](#logger-support) section for details
- **Improved cache portability** - When using relative paths with the same `cwd`, cache files are portable across different environments
# Changes from v9 to v10
There have been many features added and changes made to the `file-entry-cache` class. Here are the main changes:
- Added `cache` object to the options to allow for more control over the cache
- Added `hashAlgorithm` to the options to allow for different checksum algorithms. Note that if you load from file it most likely will break if the value was something before.
- Migrated to Typescript with ESM and CommonJS support. This allows for better type checking and support for both ESM and CommonJS.
- Once options are passed in they get assigned as properties such as `hashAlgorithm`. For the Cache options they are assigned to `cache` such as `cache.ttl` and `cache.lruSize`.
- Added `cache.persistInterval` to allow for saving the cache to disk at a specific interval. This will save the cache to disk at the interval specified instead of calling `reconsile()` to save. (`off` by default)
- Added `getFileDescriptorsByPath(filePath: string): FileEntryDescriptor[]` to get all the file descriptors that start with the path specified. This is useful when you want to get all the files in a directory or a specific path.
- Using `flat-cache` v6 which is a major update. This allows for better performance and more control over the cache.
- On `FileEntryDescriptor.meta` if using typescript you need to use the `meta.data` to set additional information. This is to allow for better type checking and to avoid conflicts with the `meta` object which was `any`.
# Global Default Functions
- `create(cacheId: string, cacheDirectory?: string, options?: CreateOptions)` - Creates a new instance of the `FileEntryCache` class
- `createFromFile(filePath: string, options?: CreateOptions)` - Creates a new instance of the `FileEntryCache` class and loads the cache from a file.
## CreateOptions Type
All options from `FileEntryCacheOptions` except `cache`:
- `useCheckSum?` - If `true` it will use a checksum to determine if the file has changed. Default is `false`
- `hashAlgorithm?` - The algorithm to use for the checksum. Default is `md5`
- `cwd?` - The current working directory for resolving relative paths. Default is `process.cwd()`
- `restrictAccessToCwd?` - If `true` restricts file access to within `cwd` boundaries. Default is `false`
- `useAbsolutePathAsKey?` - If `true` uses absolute paths as cache keys. Default is `false`
- `logger?` - A logger instance for debugging. Default is `undefined`
# FileEntryCache Options (FileEntryCacheOptions)
- `useModifiedTime?` - If `true` it will use the modified time to determine if the file has changed. Default is `true`
- `useCheckSum?` - If `true` it will use a checksum to determine if the file has changed. Default is `false`
- `hashAlgorithm?` - The algorithm to use for the checksum. Default is `md5` but can be any algorithm supported by `crypto.createHash`
- `cwd?` - The current working directory for resolving relative paths. Default is `process.cwd()`
- `restrictAccessToCwd?` - If `true` restricts file access to within `cwd` boundaries, preventing path traversal attacks. Default is `true`
- `logger?` - A logger instance compatible with Pino logger interface for debugging and monitoring. Default is `undefined`
- `cache.ttl?` - The time to live for the cache in milliseconds. Default is `0` which means no expiration
- `cache.lruSize?` - The number of items to keep in the cache. Default is `0` which means no limit
- `cache.useClone?` - If `true` it will clone the data before returning it. Default is `false`
- `cache.expirationInterval?` - The interval to check for expired items in the cache. Default is `0` which means no expiration
- `cache.persistInterval?` - The interval to save the data to disk. Default is `0` which means no persistence
- `cache.cacheDir?` - The directory to save the cache files. Default is `./cache`
- `cache.cacheId?` - The id of the cache. Default is `cache1`
- `cache.parse?` - The function to parse the data. Default is `flatted.parse`
- `cache.stringify?` - The function to stringify the data. Default is `flatted.stringify`
# API
- `constructor(options?: FileEntryCacheOptions)` - Creates a new instance of the `FileEntryCache` class
- `useCheckSum: boolean` - If `true` it will use a checksum to determine if the file has changed. Default is `false`
- `hashAlgorithm: string` - The algorithm to use for the checksum. Default is `md5` but can be any algorithm supported by `crypto.createHash`
- `getHash(buffer: Buffer): string` - Gets the hash of a buffer used for checksums
- `cwd: string` - The current working directory for resolving relative paths. Default is `process.cwd()`
- `restrictAccessToCwd: boolean` - If `true` restricts file access to within `cwd` boundaries. Default is `true`
- `useAbsolutePathAsKey: boolean` - If `true` uses absolute paths as cache keys. Default is `false` to maintain better cache portability
- `logger: ILogger | undefined` - A logger instance for debugging and monitoring cache operations
- `createFileKey(filePath: string): string` - Returns the cache key for the file path (returns the path exactly as provided when `useAbsolutePathAsKey` is `false`, otherwise returns the absolute path).
- `deleteCacheFile(): boolean` - Deletes the cache file from disk
- `destroy(): void` - Destroys the cache. This will clear the cache in memory. If using cache persistence it will stop the interval.
- `removeEntry(filePath: string): void` - Removes an entry from the cache.
- `reconcile(): void` - Saves the cache to disk and removes any files that are no longer found.
- `hasFileChanged(filePath: string): boolean` - Checks if the file has changed. This will return `true` if the file has changed.
- `getFileDescriptor(filePath: string, options?: { useModifiedTime?: boolean, useCheckSum?: boolean }): FileEntryDescriptor` - Gets the file descriptor for the file. Please refer to the entire section on `Get File Descriptor` for more information.
- `normalizeEntries(files?: string[]): FileDescriptor[]` - Normalizes the entries. If no files are provided, it will return all cached entries.
- `analyzeFiles(files: string[])` will return `AnalyzedFiles` object with `changedFiles`, `notFoundFiles`, and `notChangedFiles` as FileDescriptor arrays.
- `getUpdatedFiles(files: string[])` will return an array of `FileEntryDescriptor` objects that have changed.
- `getFileDescriptorsByPath(filePath: string): FileEntryDescriptor[]` will return an array of `FileEntryDescriptor` objects that starts with the path prefix specified.
- `getAbsolutePath(filePath: string): string` - Resolves a relative path to absolute using the configured `cwd`. Returns absolute paths unchanged. When `restrictAccessToCwd` is enabled, throws an error if the path resolves outside `cwd`.
- `getAbsolutePathWithCwd(filePath: string, cwd: string): string` - Resolves a relative path to absolute using a custom working directory. When `restrictAccessToCwd` is enabled, throws an error if the path resolves outside the provided `cwd`.
# Get File Descriptor
The `getFileDescriptor(filePath: string, options?: { useCheckSum?: boolean, useModifiedTime?: boolean }): FileEntryDescriptor` function is used to get the file descriptor for the file. This function will return a `FileEntryDescriptor` object that has the following properties:
- `key: string` - The cache key for the file. This is exactly the path that was provided (relative or absolute).
- `changed: boolean` - If the file has changed since the last time it was analyzed.
- `notFound: boolean` - If the file was not found.
- `meta: FileEntryMeta` - The meta data for the file. This has the following properties: `size`, `mtime`, `hash`, `data`. Note that `data` is an object that can be used to store additional information.
- `err` - If there was an error analyzing the file.
## Path Handling and Current Working Directory
The cache stores paths exactly as they are provided (relative or absolute). When checking if files have changed, relative paths are resolved using the configured `cwd` (current working directory):
```javascript
// Default: uses process.cwd()
const cache1 = fileEntryCache.create('cache1');
// Custom working directory using options object
const cache2 = fileEntryCache.create('cache2', './cache', {
cwd: '/project/root'
});
// Or using the class constructor directly
const cache3 = new FileEntryCache({ cwd: '/project/root' });
// The cache key is always the provided path
const descriptor = cache2.getFileDescriptor('./src/file.txt');
console.log(descriptor.key); // './src/file.txt'
// But file operations resolve from: '/project/root/src/file.txt'
```
### Cache Portability
Using relative paths with a consistent `cwd` (defaults to `process.cwd()`) makes cache files portable across different machines and environments. This is especially useful for CI/CD pipelines and team development.
```javascript
// On machine A (project at /home/user/project)
const cacheA = fileEntryCache.create('build-cache', './cache', {
cwd: '/home/user/project'
});
cacheA.getFileDescriptor('./src/index.js'); // Resolves to /home/user/project/src/index.js
cacheA.reconcile();
// On machine B (project at /workspace/project)
const cacheB = fileEntryCache.create('build-cache', './cache', {
cwd: '/workspace/project'
});
cacheB.getFileDescriptor('./src/index.js'); // Resolves to /workspace/project/src/index.js
// Cache hit! File hasn't changed since machine A
```
### Maximum Portability with Checksums
For maximum cache portability across different environments, use checksums (`useCheckSum: true`) along with relative paths and `cwd` which defaults to `process.cwd()`. This ensures that cache validity is determined by file content rather than modification times, which can vary across systems:
```javascript
// Development machine
const devCache = fileEntryCache.create('.buildcache', './cache', {
useCheckSum: true // Use checksums for content-based comparison
});
// Process files using relative paths
const descriptor = devCache.getFileDescriptor('./src/index.js');
if (descriptor.changed) {
console.log('Building ./src/index.js...');
// Build process here
}
devCache.reconcile(); // Save cache
// CI/CD Pipeline or another developer's machine
const ciCache = fileEntryCache.create('.buildcache', './node_modules/.cache', {
useCheckSum: true, // Same checksum setting
cwd: process.cwd() // Different absolute path, same relative structure
});
// Same relative path works across environments
const descriptor2 = ciCache.getFileDescriptor('./src/index.js');
if (!descriptor2.changed) {
console.log('Using cached result for ./src/index.js');
// Skip rebuild - file content unchanged
}
```
### Handling Project Relocations
Cache remains valid even when projects are moved or renamed:
```javascript
// Original location: /projects/my-app
const cache1 = fileEntryCache.create('.cache', './cache', {
useCheckSum: true,
cwd: '/projects/my-app'
});
cache1.getFileDescriptor('./src/app.js');
cache1.reconcile();
// After moving project to: /archived/2024/my-app
const cache2 = fileEntryCache.create('.cache', './cache', {
useCheckSum: true,
cwd: '/archived/2024/my-app'
});
cache2.getFileDescriptor('./src/app.js'); // Still finds cached entry!
// Cache valid as long as relative structure unchanged
```
If there is an error when trying to get the file descriptor it will return a `notFound` and `err` property with the error.
```javascript
const fileEntryCache = new FileEntryCache();
const fileDescriptor = fileEntryCache.getFileDescriptor('no-file');
if (fileDescriptor.err) {
console.error(fileDescriptor.err);
}
if (fileDescriptor.notFound) {
console.error('File not found');
}
```
# Path Security and Traversal Prevention
The `restrictAccessToCwd` option provides security against path traversal attacks by restricting file access to within the configured `cwd` boundaries. **This is enabled by default (since v11)** to ensure secure defaults when processing untrusted input or when running in security-sensitive environments.
## Basic Usage
```javascript
// restrictAccessToCwd is enabled by default for security
const cache = new FileEntryCache({
cwd: '/project/root'
});
// This will work - file is within cwd
const descriptor = cache.getFileDescriptor('./src/index.js');
// This will throw an error - attempts to access parent directory
try {
cache.getFileDescriptor('../../../etc/passwd');
} catch (error) {
console.error(error); // Path traversal attempt blocked
}
// To allow parent directory access (not recommended for untrusted input)
const unsafeCache = new FileEntryCache({
cwd: '/project/root',
restrictAccessToCwd: false // Explicitly disable protection
});
```
## Security Features
When `restrictAccessToCwd` is enabled:
- **Path Traversal Prevention**: Blocks attempts to access files outside the working directory using `../` sequences
- **Null Byte Protection**: Automatically removes null bytes from paths to prevent injection attacks
- **Path Normalization**: Cleans and normalizes paths to prevent bypass attempts
## Use Cases
### Build Tools with Untrusted Input
```javascript
// Secure build tool configuration
const cache = fileEntryCache.create('.buildcache', './cache', {
useCheckSum: true,
cwd: process.cwd(),
restrictAccessToCwd: true // Enable strict path checking for security
});
// Process user-provided file paths safely
function processUserFile(userProvidedPath) {
try {
const descriptor = cache.getFileDescriptor(userProvidedPath);
// Safe to process - file is within boundaries
return descriptor;
} catch (error) {
if (error.message.includes('Path traversal attempt blocked')) {
console.warn('Security: Blocked access to:', userProvidedPath);
return null;
}
throw error;
}
}
```
### CI/CD Environments
```javascript
// Strict security for CI/CD pipelines
const cache = new FileEntryCache({
cwd: process.env.GITHUB_WORKSPACE || process.cwd(),
restrictAccessToCwd: true, // Prevent access outside workspace
useCheckSum: true // Content-based validation
});
// All file operations are now restricted to the workspace
cache.getFileDescriptor('./src/app.js'); // ✓ Allowed
cache.getFileDescriptor('/etc/passwd'); // ✗ Blocked (absolute path outside cwd)
cache.getFileDescriptor('../../../root'); // ✗ Blocked (path traversal)
```
### Dynamic Security Control
```javascript
const cache = new FileEntryCache({ cwd: '/safe/directory' });
// Start with relaxed mode for trusted operations
cache.restrictAccessToCwd = false;
processInternalFiles();
// Enable strict mode for untrusted input
cache.restrictAccessToCwd = true;
processUserUploadedPaths();
// Return to relaxed mode if needed
cache.restrictAccessToCwd = false;
```
## Default Behavior
**As of v11, `restrictAccessToCwd` is enabled by default** to provide secure defaults. This means:
- Path traversal attempts using `../` are blocked
- File access is restricted to within the configured `cwd`
- Null bytes in paths are automatically sanitized
### Migrating from v10 or Earlier
If you're upgrading from v10 or earlier and need to maintain the previous behavior (for example, if your code legitimately accesses parent directories), you can explicitly disable strict paths:
```javascript
const cache = new FileEntryCache({
cwd: process.cwd(),
restrictAccessToCwd: false // Restore v10 behavior
});
```
However, we strongly recommend keeping `restrictAccessToCwd: true` and adjusting your code to work within the security boundaries, especially when processing any untrusted input.
# Using Checksums to Determine if a File has Changed (useCheckSum)
By default the `useCheckSum` is `false`. This means that the `FileEntryCache` will use the `mtime` and `ctime` to determine if the file has changed. If you set `useCheckSum` to `true` it will use a checksum to determine if the file has changed. This is useful when you want to make sure that the file has not changed at all.
```javascript
const fileEntryCache = new FileEntryCache();
const fileDescriptor = fileEntryCache.getFileDescriptor('file.txt', { useCheckSum: true });
```
You can pass `useCheckSum` in the FileEntryCache options, as a property `.useCheckSum` to make it default for all files, or in the `getFileDescriptor` function. Here is an example where you set it globally but then override it for a specific file:
```javascript
const fileEntryCache = new FileEntryCache({ useCheckSum: true });
const fileDescriptor = fileEntryCache.getFileDescriptor('file.txt', { useCheckSum: false });
```
# Setting Additional Meta Data
In the past we have seen people do random values on the `meta` object. This can cause issues with the `meta` object. To avoid this we have `data` which can be anything.
```javascript
const fileEntryCache = new FileEntryCache();
const fileDescriptor = fileEntryCache.getFileDescriptor('file.txt');
fileDescriptor.meta.data = { myData: 'myData' }; //anything you want
```
# Logger Support
The `FileEntryCache` supports logging through a Pino-compatible logger interface. This is useful for debugging and monitoring cache operations in production environments.
## Logger Interface
The logger must implement the following interface:
```typescript
interface ILogger {
level?: string;
trace: (message: string | object, ...args: unknown[]) => void;
debug: (message: string | object, ...args: unknown[]) => void;
info: (message: string | object, ...args: unknown[]) => void;
warn: (message: string | object, ...args: unknown[]) => void;
error: (message: string | object, ...args: unknown[]) => void;
fatal: (message: string | object, ...args: unknown[]) => void;
}
```
## Using Pino Logger
You can pass a Pino logger instance to the `FileEntryCache` constructor or set it via the `logger` property:
```javascript
import pino from 'pino';
import fileEntryCache from 'file-entry-cache';
// Create a Pino logger
const logger = pino({
level: 'debug',
transport: {
target: 'pino-pretty',
options: {
colorize: true
}
}
});
// Pass logger in constructor
const cache = new fileEntryCache.FileEntryCache({
logger,
cacheId: 'my-cache'
});
// Or set it after creation
cache.logger = logger;
// Now all cache operations will be logged
const descriptor = cache.getFileDescriptor('./src/file.txt');
```
## Log Levels
The logger will output different levels of information:
- **trace**: Detailed internal operations (key creation, cached meta lookup, file stats)
- **debug**: Method entry, checksum settings, change detection, file status
- **info**: Important state changes (file has changed)
- **error**: File read errors and exceptions
## Example with Custom Log Levels
```javascript
import pino from 'pino';
import { FileEntryCache } from 'file-entry-cache';
// Create logger with specific level
const logger = pino({ level: 'info' });
const cache = new FileEntryCache({
logger,
useCheckSum: true
});
// This will log at info level when files change
const files = ['./src/index.js', './src/utils.js'];
files.forEach(file => {
const descriptor = cache.getFileDescriptor(file);
if (descriptor.changed) {
console.log(`Processing changed file: ${file}`);
}
});
cache.reconcile();
```
## Debugging Cache Operations
For detailed debugging, set the logger level to `debug` or `trace`:
```javascript
import pino from 'pino';
import { FileEntryCache } from 'file-entry-cache';
const logger = pino({
level: 'trace',
transport: {
target: 'pino-pretty'
}
});
const cache = new FileEntryCache({
logger,
useCheckSum: true,
cwd: '/project/root'
});
// Will log detailed information about:
// - File path resolution
// - Cache key creation
// - Cached metadata lookup
// - File stats reading
// - Hash calculation (if using checksums)
// - Change detection logic
const descriptor = cache.getFileDescriptor('./src/app.js');
```
# How to Contribute
You can contribute by forking the repo and submitting a pull request. Please make sure to add tests and update the documentation. To learn more about how to contribute go to our main README [https://github.com/jaredwray/cacheable](https://github.com/jaredwray/cacheable). This will talk about how to `Open a Pull Request`, `Ask a Question`, or `Post an Issue`.
# License and Copyright
[MIT © Jared Wray](./LICENSE)

551
node_modules/file-entry-cache/dist/index.cjs generated vendored Normal file
View File

@@ -0,0 +1,551 @@
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
//#region \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
let node_crypto = require("node:crypto");
node_crypto = __toESM(node_crypto, 1);
let node_fs = require("node:fs");
node_fs = __toESM(node_fs, 1);
let node_path = require("node:path");
node_path = __toESM(node_path, 1);
let flat_cache = require("flat-cache");
//#region src/index.ts
/**
* Create a new FileEntryCache instance from a file path
* @param filePath - The path to the cache file
* @param options - create options such as useChecksum, cwd, and more
* @returns A new FileEntryCache instance
*/
function createFromFile(filePath, options) {
return create(node_path.default.basename(filePath), node_path.default.dirname(filePath), options);
}
/**
* Create a new FileEntryCache instance
* @param cacheId - The cache file name
* @param cacheDirectory - The directory to store the cache file (default: undefined, cache won't be persisted)
* @param options - Whether to use checksum to detect file changes (default: false)
* @returns A new FileEntryCache instance
*/
function create(cacheId, cacheDirectory, options) {
const opts = {
...options,
cache: {
cacheId,
cacheDir: cacheDirectory
}
};
const fileEntryCache = new FileEntryCache(opts);
if (cacheDirectory) {
const cachePath = `${cacheDirectory}/${cacheId}`;
if (node_fs.default.existsSync(cachePath)) try {
fileEntryCache.cache = (0, flat_cache.createFromFile)(cachePath, opts.cache);
} catch (error) {
if (error instanceof SyntaxError || error instanceof TypeError) fileEntryCache.cache = new flat_cache.FlatCache(opts.cache);
else throw error;
}
}
return fileEntryCache;
}
var FileEntryDefault = class {
static create = create;
static createFromFile = createFromFile;
};
var FileEntryCache = class {
_cache = new flat_cache.FlatCache({ useClone: false });
_useCheckSum = false;
_hashAlgorithm = "md5";
_cwd = process.cwd();
_restrictAccessToCwd = false;
_logger;
_useAbsolutePathAsKey = false;
_useModifiedTime = true;
/**
* Snapshot of the persisted meta for each key as of the last load/reconcile.
* Change detection compares against this baseline (not the working cache) so
* that repeated `getFileDescriptor()` calls keep reporting a file as changed
* until the cache is reconciled. The set of keys also tracks which files were
* visited during the current session so that `reconcile()` only updates those.
*/
_originalMeta = /* @__PURE__ */ new Map();
/**
* Create a new FileEntryCache instance
* @param options - The options for the FileEntryCache (all properties are optional with defaults)
*/
constructor(options) {
if (options?.cache) this._cache = new flat_cache.FlatCache(options.cache);
if (options?.useCheckSum) this._useCheckSum = options.useCheckSum;
if (options?.hashAlgorithm) this._hashAlgorithm = options.hashAlgorithm;
if (options?.cwd) this._cwd = options.cwd;
if (options?.useModifiedTime !== void 0) this._useModifiedTime = options.useModifiedTime;
if (options?.restrictAccessToCwd !== void 0) this._restrictAccessToCwd = options.restrictAccessToCwd;
if (options?.useAbsolutePathAsKey !== void 0) this._useAbsolutePathAsKey = options.useAbsolutePathAsKey;
if (options?.logger) this._logger = options.logger;
}
/**
* Get the cache
* @returns {FlatCache} The cache
*/
get cache() {
return this._cache;
}
/**
* Set the cache
* @param {FlatCache} cache - The cache to set
*/
set cache(cache) {
this._cache = cache;
this._originalMeta = /* @__PURE__ */ new Map();
}
/**
* Get the logger
* @returns {ILogger | undefined} The logger instance
*/
get logger() {
return this._logger;
}
/**
* Set the logger
* @param {ILogger | undefined} logger - The logger to set
*/
set logger(logger) {
this._logger = logger;
}
/**
* Use the hash to check if the file has changed
* @returns {boolean} if the hash is used to check if the file has changed (default: false)
*/
get useCheckSum() {
return this._useCheckSum;
}
/**
* Set the useCheckSum value
* @param {boolean} value - The value to set
*/
set useCheckSum(value) {
this._useCheckSum = value;
}
/**
* Get the hash algorithm
* @returns {string} The hash algorithm (default: 'md5')
*/
get hashAlgorithm() {
return this._hashAlgorithm;
}
/**
* Set the hash algorithm
* @param {string} value - The value to set
*/
set hashAlgorithm(value) {
this._hashAlgorithm = value;
}
/**
* Get the current working directory
* @returns {string} The current working directory (default: process.cwd())
*/
get cwd() {
return this._cwd;
}
/**
* Set the current working directory
*
* Note: when relative paths are used as cache keys (the default), `cwd` must
* stay stable across a `getFileDescriptor()` / `reconcile()` cycle. Relative
* keys are resolved against the *current* `cwd` each time, so changing it
* mid-run can cause `reconcile()` to resolve a key to a different (missing)
* path and drop the entry. Use absolute keys (`useAbsolutePathAsKey: true`)
* if `cwd` must change during a run.
* @param {string} value - The value to set
*/
set cwd(value) {
this._cwd = value;
}
/**
* Get whether to use modified time for change detection
* @returns {boolean} Whether modified time (mtime) is used for change detection (default: true)
*/
get useModifiedTime() {
return this._useModifiedTime;
}
/**
* Set whether to use modified time for change detection
* @param {boolean} value - The value to set
*/
set useModifiedTime(value) {
this._useModifiedTime = value;
}
/**
* Get whether to restrict paths to cwd boundaries
* @returns {boolean} Whether strict path checking is enabled (default: true)
*/
get restrictAccessToCwd() {
return this._restrictAccessToCwd;
}
/**
* Set whether to restrict paths to cwd boundaries
* @param {boolean} value - The value to set
*/
set restrictAccessToCwd(value) {
this._restrictAccessToCwd = value;
}
/**
* Get whether to use absolute path as cache key
* @returns {boolean} Whether cache keys use absolute paths (default: false)
*/
get useAbsolutePathAsKey() {
return this._useAbsolutePathAsKey;
}
/**
* Set whether to use absolute path as cache key
* @param {boolean} value - The value to set
*/
set useAbsolutePathAsKey(value) {
this._useAbsolutePathAsKey = value;
}
/**
* Given a buffer, calculate md5 hash of its content.
* @method getHash
* @param {Buffer} buffer buffer to calculate hash on
* @return {String} content hash digest
*/
getHash(buffer) {
return node_crypto.default.createHash(this._hashAlgorithm).update(buffer).digest("hex");
}
/**
* Create the key for the file path used for caching.
* @method createFileKey
* @param {String} filePath
* @return {String}
*/
createFileKey(filePath) {
let result = filePath;
if (this._useAbsolutePathAsKey && this.isRelativePath(filePath)) result = this.getAbsolutePathWithCwd(filePath, this._cwd);
return result;
}
/**
* Check if the file path is a relative path
* @method isRelativePath
* @param filePath - The file path to check
* @returns {boolean} if the file path is a relative path, false otherwise
*/
isRelativePath(filePath) {
return !node_path.default.isAbsolute(filePath);
}
/**
* Delete the cache file from the disk
* @method deleteCacheFile
* @return {boolean} true if the file was deleted, false otherwise
*/
deleteCacheFile() {
return this._cache.removeCacheFile();
}
/**
* Remove the cache from the file and clear the memory cache
* @method destroy
*/
destroy() {
this._cache.destroy();
this._originalMeta = /* @__PURE__ */ new Map();
}
/**
* Remove and Entry From the Cache
* @method removeEntry
* @param filePath - The file path to remove from the cache
*/
removeEntry(filePath) {
const key = this.createFileKey(filePath);
this._cache.removeKey(key);
this._originalMeta.delete(key);
}
/**
* Reconcile the cache
* @method reconcile
*/
reconcile() {
for (const key of [...this._cache.keys()]) try {
node_fs.default.statSync(this.getAbsolutePath(key));
} catch (error) {
if (error.code === "ENOENT") {
this._cache.removeKey(key);
this._originalMeta.delete(key);
} else this._logger?.error({
key,
error
}, "reconcile: unable to stat file; keeping cached entry");
}
for (const key of [...this._originalMeta.keys()]) {
const meta = this._cache.getKey(key);
if (meta) this._originalMeta.set(key, { ...meta });
else this._originalMeta.delete(key);
}
this._cache.save();
}
/**
* Check if the file has changed
* @method hasFileChanged
* @param filePath - The file path to check
* @returns {boolean} if the file has changed, false otherwise
*/
hasFileChanged(filePath) {
let result = false;
const fileDescriptor = this.getFileDescriptor(filePath);
if ((!fileDescriptor.err || !fileDescriptor.notFound) && fileDescriptor.changed) result = true;
return result;
}
/**
* Get the file descriptor for the file path
* @method getFileDescriptor
* @param filePath - The file path to get the file descriptor for
* @param options - The options for getting the file descriptor
* @returns The file descriptor
*/
getFileDescriptor(filePath, options) {
this._logger?.debug({
filePath,
options
}, "Getting file descriptor");
let fstat;
const result = {
key: this.createFileKey(filePath),
changed: false,
meta: {}
};
this._logger?.trace({ key: result.key }, "Created file key");
const metaCache = this._cache.getKey(result.key);
if (metaCache) this._logger?.trace({ metaCache }, "Found cached meta");
else this._logger?.trace("No cached meta found");
result.meta = metaCache ? { ...metaCache } : {};
const absolutePath = this.getAbsolutePath(filePath);
this._logger?.trace({ absolutePath }, "Resolved absolute path");
const useCheckSumValue = options?.useCheckSum ?? this._useCheckSum;
this._logger?.debug({ useCheckSum: useCheckSumValue }, "Using checksum setting");
const useModifiedTimeValue = options?.useModifiedTime ?? this.useModifiedTime;
this._logger?.debug({ useModifiedTime: useModifiedTimeValue }, "Using modified time (mtime) setting");
try {
fstat = node_fs.default.statSync(absolutePath);
result.meta.size = fstat.size;
result.meta.mtime = fstat.mtime.getTime();
this._logger?.trace({
size: result.meta.size,
mtime: result.meta.mtime
}, "Read file stats");
if (useCheckSumValue) {
const buffer = node_fs.default.readFileSync(absolutePath);
result.meta.hash = this.getHash(buffer);
this._logger?.trace({ hash: result.meta.hash }, "Calculated file hash");
}
} catch (error) {
this._logger?.error({
filePath,
error
}, "Error reading file");
this.removeEntry(filePath);
let notFound = false;
if (error.message.includes("ENOENT")) {
notFound = true;
this._logger?.debug({ filePath }, "File not found");
}
return {
key: result.key,
err: error,
notFound,
meta: {}
};
}
if (!this._originalMeta.has(result.key)) this._originalMeta.set(result.key, metaCache ? { ...metaCache } : void 0);
const baseline = this._originalMeta.get(result.key);
if (baseline === void 0) {
result.changed = true;
this._cache.setKey(result.key, result.meta);
this._logger?.debug({ filePath }, "File not in cache, marked as changed");
return result;
}
if (useModifiedTimeValue && baseline.mtime !== result.meta?.mtime) {
result.changed = true;
this._logger?.debug({
filePath,
oldMtime: baseline.mtime,
newMtime: result.meta.mtime
}, "File changed: mtime differs");
}
if (baseline.size !== result.meta?.size) {
result.changed = true;
this._logger?.debug({
filePath,
oldSize: baseline.size,
newSize: result.meta.size
}, "File changed: size differs");
}
if (useCheckSumValue && baseline.hash !== result.meta?.hash) {
result.changed = true;
this._logger?.debug({
filePath,
oldHash: baseline.hash,
newHash: result.meta.hash
}, "File changed: hash differs");
}
this._cache.setKey(result.key, result.meta);
if (result.changed) this._logger?.info({ filePath }, "File has changed");
else this._logger?.debug({ filePath }, "File unchanged");
return result;
}
/**
* Get the file descriptors for the files
* @method normalizeEntries
* @param files?: string[] - The files to get the file descriptors for
* @returns The file descriptors
*/
normalizeEntries(files) {
const result = [];
if (files) {
for (const file of files) {
const fileDescriptor = this.getFileDescriptor(file);
result.push(fileDescriptor);
}
return result;
}
const keys = this.cache.keys();
for (const key of keys) {
const fileDescriptor = this.getFileDescriptor(key);
if (!fileDescriptor.notFound && !fileDescriptor.err) result.push(fileDescriptor);
}
return result;
}
/**
* Analyze the files
* @method analyzeFiles
* @param files - The files to analyze
* @returns {AnalyzedFiles} The analysis of the files
*/
analyzeFiles(files) {
const result = {
changedFiles: [],
notFoundFiles: [],
notChangedFiles: []
};
const fileDescriptors = this.normalizeEntries(files);
for (const fileDescriptor of fileDescriptors) if (fileDescriptor.notFound) result.notFoundFiles.push(fileDescriptor.key);
else if (fileDescriptor.changed) result.changedFiles.push(fileDescriptor.key);
else result.notChangedFiles.push(fileDescriptor.key);
return result;
}
/**
* Get the updated files
* @method getUpdatedFiles
* @param files - The files to get the updated files for
* @returns {string[]} The updated files
*/
getUpdatedFiles(files) {
const result = [];
const fileDescriptors = this.normalizeEntries(files);
for (const fileDescriptor of fileDescriptors) if (fileDescriptor.changed) result.push(fileDescriptor.key);
return result;
}
/**
* Get the file descriptors by path prefix
* @method getFileDescriptorsByPath
* @param filePath - the path prefix to match
* @returns {FileDescriptor[]} The file descriptors
*/
getFileDescriptorsByPath(filePath) {
const result = [];
const keys = this._cache.keys();
for (const key of keys)
/* v8 ignore next -- @preserve */
if (key.startsWith(filePath)) {
const fileDescriptor = this.getFileDescriptor(key);
result.push(fileDescriptor);
}
return result;
}
/**
* Get the Absolute Path. If it is already absolute it will return the path as is.
* When restrictAccessToCwd is enabled, ensures the resolved path stays within cwd boundaries.
* @method getAbsolutePath
* @param filePath - The file path to get the absolute path for
* @returns {string}
* @throws {Error} When restrictAccessToCwd is true and path would resolve outside cwd
*/
getAbsolutePath(filePath) {
if (this.isRelativePath(filePath)) {
const sanitizedPath = filePath.replace(/\0/g, "");
const resolved = node_path.default.resolve(this._cwd, sanitizedPath);
if (this._restrictAccessToCwd) {
const normalizedResolved = node_path.default.normalize(resolved);
const normalizedCwd = node_path.default.normalize(this._cwd);
if (!(normalizedResolved === normalizedCwd || normalizedResolved.startsWith(normalizedCwd + node_path.default.sep))) throw new Error(`Path traversal attempt blocked: "${filePath}" resolves outside of working directory "${this._cwd}"`);
}
return resolved;
}
return filePath;
}
/**
* Get the Absolute Path with a custom working directory. If it is already absolute it will return the path as is.
* When restrictAccessToCwd is enabled, ensures the resolved path stays within the provided cwd boundaries.
* @method getAbsolutePathWithCwd
* @param filePath - The file path to get the absolute path for
* @param cwd - The custom working directory to resolve relative paths from
* @returns {string}
* @throws {Error} When restrictAccessToCwd is true and path would resolve outside the provided cwd
*/
getAbsolutePathWithCwd(filePath, cwd) {
if (this.isRelativePath(filePath)) {
const sanitizedPath = filePath.replace(/\0/g, "");
const resolved = node_path.default.resolve(cwd, sanitizedPath);
if (this._restrictAccessToCwd) {
const normalizedResolved = node_path.default.normalize(resolved);
const normalizedCwd = node_path.default.normalize(cwd);
if (!(normalizedResolved === normalizedCwd || normalizedResolved.startsWith(normalizedCwd + node_path.default.sep))) throw new Error(`Path traversal attempt blocked: "${filePath}" resolves outside of working directory "${cwd}"`);
}
return resolved;
}
return filePath;
}
/**
* Rename cache keys that start with a given path prefix.
* @method renameCacheKeys
* @param oldPath - The old path prefix to rename
* @param newPath - The new path prefix to rename to
*/
renameCacheKeys(oldPath, newPath) {
const keys = this._cache.keys();
for (const key of keys)
/* v8 ignore next -- @preserve */
if (key.startsWith(oldPath)) {
const newKey = key.replace(oldPath, newPath);
const meta = this._cache.getKey(key);
this._cache.removeKey(key);
this._cache.setKey(newKey, meta);
if (this._originalMeta.has(key)) {
this._originalMeta.set(newKey, this._originalMeta.get(key));
this._originalMeta.delete(key);
}
}
}
};
//#endregion
exports.FileEntryCache = FileEntryCache;
exports.create = create;
exports.createFromFile = createFromFile;
exports.default = FileEntryDefault;

290
node_modules/file-entry-cache/dist/index.d.cts generated vendored Normal file
View File

@@ -0,0 +1,290 @@
import { Buffer } from "node:buffer";
import { FlatCache, FlatCacheOptions } from "flat-cache";
//#region src/index.d.ts
type ILogger = {
/** Current log level */level?: string; /** Trace level logging */
trace: (message: string | object, ...args: unknown[]) => void; /** Debug level logging */
debug: (message: string | object, ...args: unknown[]) => void; /** Info level logging */
info: (message: string | object, ...args: unknown[]) => void; /** Warning level logging */
warn: (message: string | object, ...args: unknown[]) => void; /** Error level logging */
error: (message: string | object, ...args: unknown[]) => void; /** Fatal level logging */
fatal: (message: string | object, ...args: unknown[]) => void;
};
type FileEntryCacheOptions = {
/** Whether to use file modified time for change detection (default: true) */useModifiedTime?: boolean; /** Whether to use checksum for change detection (default: false) */
useCheckSum?: boolean; /** Hash algorithm to use for checksum (default: 'md5') */
hashAlgorithm?: string; /** Current working directory for resolving relative paths (default: process.cwd()) */
cwd?: string; /** Restrict file access to within cwd boundaries (default: true) */
restrictAccessToCwd?: boolean; /** Whether to use absolute path as cache key (default: false) */
useAbsolutePathAsKey?: boolean; /** Logger instance for logging (default: undefined) */
logger?: ILogger; /** Options for the underlying flat cache */
cache?: FlatCacheOptions;
};
type GetFileDescriptorOptions = {
/** Whether to use checksum for this specific file check instead of modified time (mtime) (overrides instance setting) */useCheckSum?: boolean; /** Whether to use file modified time for change detection (default: true) */
useModifiedTime?: boolean;
};
type FileDescriptor = {
/** The cache key for this file (typically the file path) */key: string; /** Whether the file has changed since last cache check */
changed?: boolean; /** Metadata about the file */
meta: FileDescriptorMeta; /** Whether the file was not found */
notFound?: boolean; /** Error encountered when accessing the file */
err?: Error;
};
type FileDescriptorMeta = {
/** File size in bytes */size?: number; /** File modification time (timestamp in milliseconds) */
mtime?: number; /** File content hash (when useCheckSum is enabled) */
hash?: string; /** Custom data associated with the file (e.g., lint results, metadata) */
data?: unknown; /** Allow any additional custom properties */
[key: string]: unknown;
};
type AnalyzedFiles = {
/** Array of file paths that have changed since last cache */changedFiles: string[]; /** Array of file paths that were not found */
notFoundFiles: string[]; /** Array of file paths that have not changed since last cache */
notChangedFiles: string[];
};
/**
* Create a new FileEntryCache instance from a file path
* @param filePath - The path to the cache file
* @param options - create options such as useChecksum, cwd, and more
* @returns A new FileEntryCache instance
*/
declare function createFromFile(filePath: string, options?: CreateOptions): FileEntryCache;
type CreateOptions = Omit<FileEntryCacheOptions, "cache">;
/**
* Create a new FileEntryCache instance
* @param cacheId - The cache file name
* @param cacheDirectory - The directory to store the cache file (default: undefined, cache won't be persisted)
* @param options - Whether to use checksum to detect file changes (default: false)
* @returns A new FileEntryCache instance
*/
declare function create(cacheId: string, cacheDirectory?: string, options?: CreateOptions): FileEntryCache;
declare class FileEntryDefault {
static create: typeof create;
static createFromFile: typeof createFromFile;
}
declare class FileEntryCache {
private _cache;
private _useCheckSum;
private _hashAlgorithm;
private _cwd;
private _restrictAccessToCwd;
private _logger?;
private _useAbsolutePathAsKey;
private _useModifiedTime;
/**
* Snapshot of the persisted meta for each key as of the last load/reconcile.
* Change detection compares against this baseline (not the working cache) so
* that repeated `getFileDescriptor()` calls keep reporting a file as changed
* until the cache is reconciled. The set of keys also tracks which files were
* visited during the current session so that `reconcile()` only updates those.
*/
private _originalMeta;
/**
* Create a new FileEntryCache instance
* @param options - The options for the FileEntryCache (all properties are optional with defaults)
*/
constructor(options?: FileEntryCacheOptions);
/**
* Get the cache
* @returns {FlatCache} The cache
*/
get cache(): FlatCache;
/**
* Set the cache
* @param {FlatCache} cache - The cache to set
*/
set cache(cache: FlatCache);
/**
* Get the logger
* @returns {ILogger | undefined} The logger instance
*/
get logger(): ILogger | undefined;
/**
* Set the logger
* @param {ILogger | undefined} logger - The logger to set
*/
set logger(logger: ILogger | undefined);
/**
* Use the hash to check if the file has changed
* @returns {boolean} if the hash is used to check if the file has changed (default: false)
*/
get useCheckSum(): boolean;
/**
* Set the useCheckSum value
* @param {boolean} value - The value to set
*/
set useCheckSum(value: boolean);
/**
* Get the hash algorithm
* @returns {string} The hash algorithm (default: 'md5')
*/
get hashAlgorithm(): string;
/**
* Set the hash algorithm
* @param {string} value - The value to set
*/
set hashAlgorithm(value: string);
/**
* Get the current working directory
* @returns {string} The current working directory (default: process.cwd())
*/
get cwd(): string;
/**
* Set the current working directory
*
* Note: when relative paths are used as cache keys (the default), `cwd` must
* stay stable across a `getFileDescriptor()` / `reconcile()` cycle. Relative
* keys are resolved against the *current* `cwd` each time, so changing it
* mid-run can cause `reconcile()` to resolve a key to a different (missing)
* path and drop the entry. Use absolute keys (`useAbsolutePathAsKey: true`)
* if `cwd` must change during a run.
* @param {string} value - The value to set
*/
set cwd(value: string);
/**
* Get whether to use modified time for change detection
* @returns {boolean} Whether modified time (mtime) is used for change detection (default: true)
*/
get useModifiedTime(): boolean;
/**
* Set whether to use modified time for change detection
* @param {boolean} value - The value to set
*/
set useModifiedTime(value: boolean);
/**
* Get whether to restrict paths to cwd boundaries
* @returns {boolean} Whether strict path checking is enabled (default: true)
*/
get restrictAccessToCwd(): boolean;
/**
* Set whether to restrict paths to cwd boundaries
* @param {boolean} value - The value to set
*/
set restrictAccessToCwd(value: boolean);
/**
* Get whether to use absolute path as cache key
* @returns {boolean} Whether cache keys use absolute paths (default: false)
*/
get useAbsolutePathAsKey(): boolean;
/**
* Set whether to use absolute path as cache key
* @param {boolean} value - The value to set
*/
set useAbsolutePathAsKey(value: boolean);
/**
* Given a buffer, calculate md5 hash of its content.
* @method getHash
* @param {Buffer} buffer buffer to calculate hash on
* @return {String} content hash digest
*/
getHash(buffer: Buffer): string;
/**
* Create the key for the file path used for caching.
* @method createFileKey
* @param {String} filePath
* @return {String}
*/
createFileKey(filePath: string): string;
/**
* Check if the file path is a relative path
* @method isRelativePath
* @param filePath - The file path to check
* @returns {boolean} if the file path is a relative path, false otherwise
*/
isRelativePath(filePath: string): boolean;
/**
* Delete the cache file from the disk
* @method deleteCacheFile
* @return {boolean} true if the file was deleted, false otherwise
*/
deleteCacheFile(): boolean;
/**
* Remove the cache from the file and clear the memory cache
* @method destroy
*/
destroy(): void;
/**
* Remove and Entry From the Cache
* @method removeEntry
* @param filePath - The file path to remove from the cache
*/
removeEntry(filePath: string): void;
/**
* Reconcile the cache
* @method reconcile
*/
reconcile(): void;
/**
* Check if the file has changed
* @method hasFileChanged
* @param filePath - The file path to check
* @returns {boolean} if the file has changed, false otherwise
*/
hasFileChanged(filePath: string): boolean;
/**
* Get the file descriptor for the file path
* @method getFileDescriptor
* @param filePath - The file path to get the file descriptor for
* @param options - The options for getting the file descriptor
* @returns The file descriptor
*/
getFileDescriptor(filePath: string, options?: GetFileDescriptorOptions): FileDescriptor;
/**
* Get the file descriptors for the files
* @method normalizeEntries
* @param files?: string[] - The files to get the file descriptors for
* @returns The file descriptors
*/
normalizeEntries(files?: string[]): FileDescriptor[];
/**
* Analyze the files
* @method analyzeFiles
* @param files - The files to analyze
* @returns {AnalyzedFiles} The analysis of the files
*/
analyzeFiles(files: string[]): AnalyzedFiles;
/**
* Get the updated files
* @method getUpdatedFiles
* @param files - The files to get the updated files for
* @returns {string[]} The updated files
*/
getUpdatedFiles(files: string[]): string[];
/**
* Get the file descriptors by path prefix
* @method getFileDescriptorsByPath
* @param filePath - the path prefix to match
* @returns {FileDescriptor[]} The file descriptors
*/
getFileDescriptorsByPath(filePath: string): FileDescriptor[];
/**
* Get the Absolute Path. If it is already absolute it will return the path as is.
* When restrictAccessToCwd is enabled, ensures the resolved path stays within cwd boundaries.
* @method getAbsolutePath
* @param filePath - The file path to get the absolute path for
* @returns {string}
* @throws {Error} When restrictAccessToCwd is true and path would resolve outside cwd
*/
getAbsolutePath(filePath: string): string;
/**
* Get the Absolute Path with a custom working directory. If it is already absolute it will return the path as is.
* When restrictAccessToCwd is enabled, ensures the resolved path stays within the provided cwd boundaries.
* @method getAbsolutePathWithCwd
* @param filePath - The file path to get the absolute path for
* @param cwd - The custom working directory to resolve relative paths from
* @returns {string}
* @throws {Error} When restrictAccessToCwd is true and path would resolve outside the provided cwd
*/
getAbsolutePathWithCwd(filePath: string, cwd: string): string;
/**
* Rename cache keys that start with a given path prefix.
* @method renameCacheKeys
* @param oldPath - The old path prefix to rename
* @param newPath - The new path prefix to rename to
*/
renameCacheKeys(oldPath: string, newPath: string): void;
}
//#endregion
export { AnalyzedFiles, CreateOptions, FileDescriptor, FileDescriptorMeta, FileEntryCache, FileEntryCacheOptions, GetFileDescriptorOptions, ILogger, create, createFromFile, FileEntryDefault as default };

290
node_modules/file-entry-cache/dist/index.d.mts generated vendored Normal file
View File

@@ -0,0 +1,290 @@
import { FlatCache, FlatCacheOptions } from "flat-cache";
import { Buffer } from "node:buffer";
//#region src/index.d.ts
type ILogger = {
/** Current log level */level?: string; /** Trace level logging */
trace: (message: string | object, ...args: unknown[]) => void; /** Debug level logging */
debug: (message: string | object, ...args: unknown[]) => void; /** Info level logging */
info: (message: string | object, ...args: unknown[]) => void; /** Warning level logging */
warn: (message: string | object, ...args: unknown[]) => void; /** Error level logging */
error: (message: string | object, ...args: unknown[]) => void; /** Fatal level logging */
fatal: (message: string | object, ...args: unknown[]) => void;
};
type FileEntryCacheOptions = {
/** Whether to use file modified time for change detection (default: true) */useModifiedTime?: boolean; /** Whether to use checksum for change detection (default: false) */
useCheckSum?: boolean; /** Hash algorithm to use for checksum (default: 'md5') */
hashAlgorithm?: string; /** Current working directory for resolving relative paths (default: process.cwd()) */
cwd?: string; /** Restrict file access to within cwd boundaries (default: true) */
restrictAccessToCwd?: boolean; /** Whether to use absolute path as cache key (default: false) */
useAbsolutePathAsKey?: boolean; /** Logger instance for logging (default: undefined) */
logger?: ILogger; /** Options for the underlying flat cache */
cache?: FlatCacheOptions;
};
type GetFileDescriptorOptions = {
/** Whether to use checksum for this specific file check instead of modified time (mtime) (overrides instance setting) */useCheckSum?: boolean; /** Whether to use file modified time for change detection (default: true) */
useModifiedTime?: boolean;
};
type FileDescriptor = {
/** The cache key for this file (typically the file path) */key: string; /** Whether the file has changed since last cache check */
changed?: boolean; /** Metadata about the file */
meta: FileDescriptorMeta; /** Whether the file was not found */
notFound?: boolean; /** Error encountered when accessing the file */
err?: Error;
};
type FileDescriptorMeta = {
/** File size in bytes */size?: number; /** File modification time (timestamp in milliseconds) */
mtime?: number; /** File content hash (when useCheckSum is enabled) */
hash?: string; /** Custom data associated with the file (e.g., lint results, metadata) */
data?: unknown; /** Allow any additional custom properties */
[key: string]: unknown;
};
type AnalyzedFiles = {
/** Array of file paths that have changed since last cache */changedFiles: string[]; /** Array of file paths that were not found */
notFoundFiles: string[]; /** Array of file paths that have not changed since last cache */
notChangedFiles: string[];
};
/**
* Create a new FileEntryCache instance from a file path
* @param filePath - The path to the cache file
* @param options - create options such as useChecksum, cwd, and more
* @returns A new FileEntryCache instance
*/
declare function createFromFile(filePath: string, options?: CreateOptions): FileEntryCache;
type CreateOptions = Omit<FileEntryCacheOptions, "cache">;
/**
* Create a new FileEntryCache instance
* @param cacheId - The cache file name
* @param cacheDirectory - The directory to store the cache file (default: undefined, cache won't be persisted)
* @param options - Whether to use checksum to detect file changes (default: false)
* @returns A new FileEntryCache instance
*/
declare function create(cacheId: string, cacheDirectory?: string, options?: CreateOptions): FileEntryCache;
declare class FileEntryDefault {
static create: typeof create;
static createFromFile: typeof createFromFile;
}
declare class FileEntryCache {
private _cache;
private _useCheckSum;
private _hashAlgorithm;
private _cwd;
private _restrictAccessToCwd;
private _logger?;
private _useAbsolutePathAsKey;
private _useModifiedTime;
/**
* Snapshot of the persisted meta for each key as of the last load/reconcile.
* Change detection compares against this baseline (not the working cache) so
* that repeated `getFileDescriptor()` calls keep reporting a file as changed
* until the cache is reconciled. The set of keys also tracks which files were
* visited during the current session so that `reconcile()` only updates those.
*/
private _originalMeta;
/**
* Create a new FileEntryCache instance
* @param options - The options for the FileEntryCache (all properties are optional with defaults)
*/
constructor(options?: FileEntryCacheOptions);
/**
* Get the cache
* @returns {FlatCache} The cache
*/
get cache(): FlatCache;
/**
* Set the cache
* @param {FlatCache} cache - The cache to set
*/
set cache(cache: FlatCache);
/**
* Get the logger
* @returns {ILogger | undefined} The logger instance
*/
get logger(): ILogger | undefined;
/**
* Set the logger
* @param {ILogger | undefined} logger - The logger to set
*/
set logger(logger: ILogger | undefined);
/**
* Use the hash to check if the file has changed
* @returns {boolean} if the hash is used to check if the file has changed (default: false)
*/
get useCheckSum(): boolean;
/**
* Set the useCheckSum value
* @param {boolean} value - The value to set
*/
set useCheckSum(value: boolean);
/**
* Get the hash algorithm
* @returns {string} The hash algorithm (default: 'md5')
*/
get hashAlgorithm(): string;
/**
* Set the hash algorithm
* @param {string} value - The value to set
*/
set hashAlgorithm(value: string);
/**
* Get the current working directory
* @returns {string} The current working directory (default: process.cwd())
*/
get cwd(): string;
/**
* Set the current working directory
*
* Note: when relative paths are used as cache keys (the default), `cwd` must
* stay stable across a `getFileDescriptor()` / `reconcile()` cycle. Relative
* keys are resolved against the *current* `cwd` each time, so changing it
* mid-run can cause `reconcile()` to resolve a key to a different (missing)
* path and drop the entry. Use absolute keys (`useAbsolutePathAsKey: true`)
* if `cwd` must change during a run.
* @param {string} value - The value to set
*/
set cwd(value: string);
/**
* Get whether to use modified time for change detection
* @returns {boolean} Whether modified time (mtime) is used for change detection (default: true)
*/
get useModifiedTime(): boolean;
/**
* Set whether to use modified time for change detection
* @param {boolean} value - The value to set
*/
set useModifiedTime(value: boolean);
/**
* Get whether to restrict paths to cwd boundaries
* @returns {boolean} Whether strict path checking is enabled (default: true)
*/
get restrictAccessToCwd(): boolean;
/**
* Set whether to restrict paths to cwd boundaries
* @param {boolean} value - The value to set
*/
set restrictAccessToCwd(value: boolean);
/**
* Get whether to use absolute path as cache key
* @returns {boolean} Whether cache keys use absolute paths (default: false)
*/
get useAbsolutePathAsKey(): boolean;
/**
* Set whether to use absolute path as cache key
* @param {boolean} value - The value to set
*/
set useAbsolutePathAsKey(value: boolean);
/**
* Given a buffer, calculate md5 hash of its content.
* @method getHash
* @param {Buffer} buffer buffer to calculate hash on
* @return {String} content hash digest
*/
getHash(buffer: Buffer): string;
/**
* Create the key for the file path used for caching.
* @method createFileKey
* @param {String} filePath
* @return {String}
*/
createFileKey(filePath: string): string;
/**
* Check if the file path is a relative path
* @method isRelativePath
* @param filePath - The file path to check
* @returns {boolean} if the file path is a relative path, false otherwise
*/
isRelativePath(filePath: string): boolean;
/**
* Delete the cache file from the disk
* @method deleteCacheFile
* @return {boolean} true if the file was deleted, false otherwise
*/
deleteCacheFile(): boolean;
/**
* Remove the cache from the file and clear the memory cache
* @method destroy
*/
destroy(): void;
/**
* Remove and Entry From the Cache
* @method removeEntry
* @param filePath - The file path to remove from the cache
*/
removeEntry(filePath: string): void;
/**
* Reconcile the cache
* @method reconcile
*/
reconcile(): void;
/**
* Check if the file has changed
* @method hasFileChanged
* @param filePath - The file path to check
* @returns {boolean} if the file has changed, false otherwise
*/
hasFileChanged(filePath: string): boolean;
/**
* Get the file descriptor for the file path
* @method getFileDescriptor
* @param filePath - The file path to get the file descriptor for
* @param options - The options for getting the file descriptor
* @returns The file descriptor
*/
getFileDescriptor(filePath: string, options?: GetFileDescriptorOptions): FileDescriptor;
/**
* Get the file descriptors for the files
* @method normalizeEntries
* @param files?: string[] - The files to get the file descriptors for
* @returns The file descriptors
*/
normalizeEntries(files?: string[]): FileDescriptor[];
/**
* Analyze the files
* @method analyzeFiles
* @param files - The files to analyze
* @returns {AnalyzedFiles} The analysis of the files
*/
analyzeFiles(files: string[]): AnalyzedFiles;
/**
* Get the updated files
* @method getUpdatedFiles
* @param files - The files to get the updated files for
* @returns {string[]} The updated files
*/
getUpdatedFiles(files: string[]): string[];
/**
* Get the file descriptors by path prefix
* @method getFileDescriptorsByPath
* @param filePath - the path prefix to match
* @returns {FileDescriptor[]} The file descriptors
*/
getFileDescriptorsByPath(filePath: string): FileDescriptor[];
/**
* Get the Absolute Path. If it is already absolute it will return the path as is.
* When restrictAccessToCwd is enabled, ensures the resolved path stays within cwd boundaries.
* @method getAbsolutePath
* @param filePath - The file path to get the absolute path for
* @returns {string}
* @throws {Error} When restrictAccessToCwd is true and path would resolve outside cwd
*/
getAbsolutePath(filePath: string): string;
/**
* Get the Absolute Path with a custom working directory. If it is already absolute it will return the path as is.
* When restrictAccessToCwd is enabled, ensures the resolved path stays within the provided cwd boundaries.
* @method getAbsolutePathWithCwd
* @param filePath - The file path to get the absolute path for
* @param cwd - The custom working directory to resolve relative paths from
* @returns {string}
* @throws {Error} When restrictAccessToCwd is true and path would resolve outside the provided cwd
*/
getAbsolutePathWithCwd(filePath: string, cwd: string): string;
/**
* Rename cache keys that start with a given path prefix.
* @method renameCacheKeys
* @param oldPath - The old path prefix to rename
* @param newPath - The new path prefix to rename to
*/
renameCacheKeys(oldPath: string, newPath: string): void;
}
//#endregion
export { AnalyzedFiles, CreateOptions, FileDescriptor, FileDescriptorMeta, FileEntryCache, FileEntryCacheOptions, GetFileDescriptorOptions, ILogger, create, createFromFile, FileEntryDefault as default };

519
node_modules/file-entry-cache/dist/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,519 @@
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { FlatCache, createFromFile as createFromFile$1 } from "flat-cache";
//#region src/index.ts
/**
* Create a new FileEntryCache instance from a file path
* @param filePath - The path to the cache file
* @param options - create options such as useChecksum, cwd, and more
* @returns A new FileEntryCache instance
*/
function createFromFile(filePath, options) {
return create(path.basename(filePath), path.dirname(filePath), options);
}
/**
* Create a new FileEntryCache instance
* @param cacheId - The cache file name
* @param cacheDirectory - The directory to store the cache file (default: undefined, cache won't be persisted)
* @param options - Whether to use checksum to detect file changes (default: false)
* @returns A new FileEntryCache instance
*/
function create(cacheId, cacheDirectory, options) {
const opts = {
...options,
cache: {
cacheId,
cacheDir: cacheDirectory
}
};
const fileEntryCache = new FileEntryCache(opts);
if (cacheDirectory) {
const cachePath = `${cacheDirectory}/${cacheId}`;
if (fs.existsSync(cachePath)) try {
fileEntryCache.cache = createFromFile$1(cachePath, opts.cache);
} catch (error) {
if (error instanceof SyntaxError || error instanceof TypeError) fileEntryCache.cache = new FlatCache(opts.cache);
else throw error;
}
}
return fileEntryCache;
}
var FileEntryDefault = class {
static create = create;
static createFromFile = createFromFile;
};
var FileEntryCache = class {
_cache = new FlatCache({ useClone: false });
_useCheckSum = false;
_hashAlgorithm = "md5";
_cwd = process.cwd();
_restrictAccessToCwd = false;
_logger;
_useAbsolutePathAsKey = false;
_useModifiedTime = true;
/**
* Snapshot of the persisted meta for each key as of the last load/reconcile.
* Change detection compares against this baseline (not the working cache) so
* that repeated `getFileDescriptor()` calls keep reporting a file as changed
* until the cache is reconciled. The set of keys also tracks which files were
* visited during the current session so that `reconcile()` only updates those.
*/
_originalMeta = /* @__PURE__ */ new Map();
/**
* Create a new FileEntryCache instance
* @param options - The options for the FileEntryCache (all properties are optional with defaults)
*/
constructor(options) {
if (options?.cache) this._cache = new FlatCache(options.cache);
if (options?.useCheckSum) this._useCheckSum = options.useCheckSum;
if (options?.hashAlgorithm) this._hashAlgorithm = options.hashAlgorithm;
if (options?.cwd) this._cwd = options.cwd;
if (options?.useModifiedTime !== void 0) this._useModifiedTime = options.useModifiedTime;
if (options?.restrictAccessToCwd !== void 0) this._restrictAccessToCwd = options.restrictAccessToCwd;
if (options?.useAbsolutePathAsKey !== void 0) this._useAbsolutePathAsKey = options.useAbsolutePathAsKey;
if (options?.logger) this._logger = options.logger;
}
/**
* Get the cache
* @returns {FlatCache} The cache
*/
get cache() {
return this._cache;
}
/**
* Set the cache
* @param {FlatCache} cache - The cache to set
*/
set cache(cache) {
this._cache = cache;
this._originalMeta = /* @__PURE__ */ new Map();
}
/**
* Get the logger
* @returns {ILogger | undefined} The logger instance
*/
get logger() {
return this._logger;
}
/**
* Set the logger
* @param {ILogger | undefined} logger - The logger to set
*/
set logger(logger) {
this._logger = logger;
}
/**
* Use the hash to check if the file has changed
* @returns {boolean} if the hash is used to check if the file has changed (default: false)
*/
get useCheckSum() {
return this._useCheckSum;
}
/**
* Set the useCheckSum value
* @param {boolean} value - The value to set
*/
set useCheckSum(value) {
this._useCheckSum = value;
}
/**
* Get the hash algorithm
* @returns {string} The hash algorithm (default: 'md5')
*/
get hashAlgorithm() {
return this._hashAlgorithm;
}
/**
* Set the hash algorithm
* @param {string} value - The value to set
*/
set hashAlgorithm(value) {
this._hashAlgorithm = value;
}
/**
* Get the current working directory
* @returns {string} The current working directory (default: process.cwd())
*/
get cwd() {
return this._cwd;
}
/**
* Set the current working directory
*
* Note: when relative paths are used as cache keys (the default), `cwd` must
* stay stable across a `getFileDescriptor()` / `reconcile()` cycle. Relative
* keys are resolved against the *current* `cwd` each time, so changing it
* mid-run can cause `reconcile()` to resolve a key to a different (missing)
* path and drop the entry. Use absolute keys (`useAbsolutePathAsKey: true`)
* if `cwd` must change during a run.
* @param {string} value - The value to set
*/
set cwd(value) {
this._cwd = value;
}
/**
* Get whether to use modified time for change detection
* @returns {boolean} Whether modified time (mtime) is used for change detection (default: true)
*/
get useModifiedTime() {
return this._useModifiedTime;
}
/**
* Set whether to use modified time for change detection
* @param {boolean} value - The value to set
*/
set useModifiedTime(value) {
this._useModifiedTime = value;
}
/**
* Get whether to restrict paths to cwd boundaries
* @returns {boolean} Whether strict path checking is enabled (default: true)
*/
get restrictAccessToCwd() {
return this._restrictAccessToCwd;
}
/**
* Set whether to restrict paths to cwd boundaries
* @param {boolean} value - The value to set
*/
set restrictAccessToCwd(value) {
this._restrictAccessToCwd = value;
}
/**
* Get whether to use absolute path as cache key
* @returns {boolean} Whether cache keys use absolute paths (default: false)
*/
get useAbsolutePathAsKey() {
return this._useAbsolutePathAsKey;
}
/**
* Set whether to use absolute path as cache key
* @param {boolean} value - The value to set
*/
set useAbsolutePathAsKey(value) {
this._useAbsolutePathAsKey = value;
}
/**
* Given a buffer, calculate md5 hash of its content.
* @method getHash
* @param {Buffer} buffer buffer to calculate hash on
* @return {String} content hash digest
*/
getHash(buffer) {
return crypto.createHash(this._hashAlgorithm).update(buffer).digest("hex");
}
/**
* Create the key for the file path used for caching.
* @method createFileKey
* @param {String} filePath
* @return {String}
*/
createFileKey(filePath) {
let result = filePath;
if (this._useAbsolutePathAsKey && this.isRelativePath(filePath)) result = this.getAbsolutePathWithCwd(filePath, this._cwd);
return result;
}
/**
* Check if the file path is a relative path
* @method isRelativePath
* @param filePath - The file path to check
* @returns {boolean} if the file path is a relative path, false otherwise
*/
isRelativePath(filePath) {
return !path.isAbsolute(filePath);
}
/**
* Delete the cache file from the disk
* @method deleteCacheFile
* @return {boolean} true if the file was deleted, false otherwise
*/
deleteCacheFile() {
return this._cache.removeCacheFile();
}
/**
* Remove the cache from the file and clear the memory cache
* @method destroy
*/
destroy() {
this._cache.destroy();
this._originalMeta = /* @__PURE__ */ new Map();
}
/**
* Remove and Entry From the Cache
* @method removeEntry
* @param filePath - The file path to remove from the cache
*/
removeEntry(filePath) {
const key = this.createFileKey(filePath);
this._cache.removeKey(key);
this._originalMeta.delete(key);
}
/**
* Reconcile the cache
* @method reconcile
*/
reconcile() {
for (const key of [...this._cache.keys()]) try {
fs.statSync(this.getAbsolutePath(key));
} catch (error) {
if (error.code === "ENOENT") {
this._cache.removeKey(key);
this._originalMeta.delete(key);
} else this._logger?.error({
key,
error
}, "reconcile: unable to stat file; keeping cached entry");
}
for (const key of [...this._originalMeta.keys()]) {
const meta = this._cache.getKey(key);
if (meta) this._originalMeta.set(key, { ...meta });
else this._originalMeta.delete(key);
}
this._cache.save();
}
/**
* Check if the file has changed
* @method hasFileChanged
* @param filePath - The file path to check
* @returns {boolean} if the file has changed, false otherwise
*/
hasFileChanged(filePath) {
let result = false;
const fileDescriptor = this.getFileDescriptor(filePath);
if ((!fileDescriptor.err || !fileDescriptor.notFound) && fileDescriptor.changed) result = true;
return result;
}
/**
* Get the file descriptor for the file path
* @method getFileDescriptor
* @param filePath - The file path to get the file descriptor for
* @param options - The options for getting the file descriptor
* @returns The file descriptor
*/
getFileDescriptor(filePath, options) {
this._logger?.debug({
filePath,
options
}, "Getting file descriptor");
let fstat;
const result = {
key: this.createFileKey(filePath),
changed: false,
meta: {}
};
this._logger?.trace({ key: result.key }, "Created file key");
const metaCache = this._cache.getKey(result.key);
if (metaCache) this._logger?.trace({ metaCache }, "Found cached meta");
else this._logger?.trace("No cached meta found");
result.meta = metaCache ? { ...metaCache } : {};
const absolutePath = this.getAbsolutePath(filePath);
this._logger?.trace({ absolutePath }, "Resolved absolute path");
const useCheckSumValue = options?.useCheckSum ?? this._useCheckSum;
this._logger?.debug({ useCheckSum: useCheckSumValue }, "Using checksum setting");
const useModifiedTimeValue = options?.useModifiedTime ?? this.useModifiedTime;
this._logger?.debug({ useModifiedTime: useModifiedTimeValue }, "Using modified time (mtime) setting");
try {
fstat = fs.statSync(absolutePath);
result.meta.size = fstat.size;
result.meta.mtime = fstat.mtime.getTime();
this._logger?.trace({
size: result.meta.size,
mtime: result.meta.mtime
}, "Read file stats");
if (useCheckSumValue) {
const buffer = fs.readFileSync(absolutePath);
result.meta.hash = this.getHash(buffer);
this._logger?.trace({ hash: result.meta.hash }, "Calculated file hash");
}
} catch (error) {
this._logger?.error({
filePath,
error
}, "Error reading file");
this.removeEntry(filePath);
let notFound = false;
if (error.message.includes("ENOENT")) {
notFound = true;
this._logger?.debug({ filePath }, "File not found");
}
return {
key: result.key,
err: error,
notFound,
meta: {}
};
}
if (!this._originalMeta.has(result.key)) this._originalMeta.set(result.key, metaCache ? { ...metaCache } : void 0);
const baseline = this._originalMeta.get(result.key);
if (baseline === void 0) {
result.changed = true;
this._cache.setKey(result.key, result.meta);
this._logger?.debug({ filePath }, "File not in cache, marked as changed");
return result;
}
if (useModifiedTimeValue && baseline.mtime !== result.meta?.mtime) {
result.changed = true;
this._logger?.debug({
filePath,
oldMtime: baseline.mtime,
newMtime: result.meta.mtime
}, "File changed: mtime differs");
}
if (baseline.size !== result.meta?.size) {
result.changed = true;
this._logger?.debug({
filePath,
oldSize: baseline.size,
newSize: result.meta.size
}, "File changed: size differs");
}
if (useCheckSumValue && baseline.hash !== result.meta?.hash) {
result.changed = true;
this._logger?.debug({
filePath,
oldHash: baseline.hash,
newHash: result.meta.hash
}, "File changed: hash differs");
}
this._cache.setKey(result.key, result.meta);
if (result.changed) this._logger?.info({ filePath }, "File has changed");
else this._logger?.debug({ filePath }, "File unchanged");
return result;
}
/**
* Get the file descriptors for the files
* @method normalizeEntries
* @param files?: string[] - The files to get the file descriptors for
* @returns The file descriptors
*/
normalizeEntries(files) {
const result = [];
if (files) {
for (const file of files) {
const fileDescriptor = this.getFileDescriptor(file);
result.push(fileDescriptor);
}
return result;
}
const keys = this.cache.keys();
for (const key of keys) {
const fileDescriptor = this.getFileDescriptor(key);
if (!fileDescriptor.notFound && !fileDescriptor.err) result.push(fileDescriptor);
}
return result;
}
/**
* Analyze the files
* @method analyzeFiles
* @param files - The files to analyze
* @returns {AnalyzedFiles} The analysis of the files
*/
analyzeFiles(files) {
const result = {
changedFiles: [],
notFoundFiles: [],
notChangedFiles: []
};
const fileDescriptors = this.normalizeEntries(files);
for (const fileDescriptor of fileDescriptors) if (fileDescriptor.notFound) result.notFoundFiles.push(fileDescriptor.key);
else if (fileDescriptor.changed) result.changedFiles.push(fileDescriptor.key);
else result.notChangedFiles.push(fileDescriptor.key);
return result;
}
/**
* Get the updated files
* @method getUpdatedFiles
* @param files - The files to get the updated files for
* @returns {string[]} The updated files
*/
getUpdatedFiles(files) {
const result = [];
const fileDescriptors = this.normalizeEntries(files);
for (const fileDescriptor of fileDescriptors) if (fileDescriptor.changed) result.push(fileDescriptor.key);
return result;
}
/**
* Get the file descriptors by path prefix
* @method getFileDescriptorsByPath
* @param filePath - the path prefix to match
* @returns {FileDescriptor[]} The file descriptors
*/
getFileDescriptorsByPath(filePath) {
const result = [];
const keys = this._cache.keys();
for (const key of keys)
/* v8 ignore next -- @preserve */
if (key.startsWith(filePath)) {
const fileDescriptor = this.getFileDescriptor(key);
result.push(fileDescriptor);
}
return result;
}
/**
* Get the Absolute Path. If it is already absolute it will return the path as is.
* When restrictAccessToCwd is enabled, ensures the resolved path stays within cwd boundaries.
* @method getAbsolutePath
* @param filePath - The file path to get the absolute path for
* @returns {string}
* @throws {Error} When restrictAccessToCwd is true and path would resolve outside cwd
*/
getAbsolutePath(filePath) {
if (this.isRelativePath(filePath)) {
const sanitizedPath = filePath.replace(/\0/g, "");
const resolved = path.resolve(this._cwd, sanitizedPath);
if (this._restrictAccessToCwd) {
const normalizedResolved = path.normalize(resolved);
const normalizedCwd = path.normalize(this._cwd);
if (!(normalizedResolved === normalizedCwd || normalizedResolved.startsWith(normalizedCwd + path.sep))) throw new Error(`Path traversal attempt blocked: "${filePath}" resolves outside of working directory "${this._cwd}"`);
}
return resolved;
}
return filePath;
}
/**
* Get the Absolute Path with a custom working directory. If it is already absolute it will return the path as is.
* When restrictAccessToCwd is enabled, ensures the resolved path stays within the provided cwd boundaries.
* @method getAbsolutePathWithCwd
* @param filePath - The file path to get the absolute path for
* @param cwd - The custom working directory to resolve relative paths from
* @returns {string}
* @throws {Error} When restrictAccessToCwd is true and path would resolve outside the provided cwd
*/
getAbsolutePathWithCwd(filePath, cwd) {
if (this.isRelativePath(filePath)) {
const sanitizedPath = filePath.replace(/\0/g, "");
const resolved = path.resolve(cwd, sanitizedPath);
if (this._restrictAccessToCwd) {
const normalizedResolved = path.normalize(resolved);
const normalizedCwd = path.normalize(cwd);
if (!(normalizedResolved === normalizedCwd || normalizedResolved.startsWith(normalizedCwd + path.sep))) throw new Error(`Path traversal attempt blocked: "${filePath}" resolves outside of working directory "${cwd}"`);
}
return resolved;
}
return filePath;
}
/**
* Rename cache keys that start with a given path prefix.
* @method renameCacheKeys
* @param oldPath - The old path prefix to rename
* @param newPath - The new path prefix to rename to
*/
renameCacheKeys(oldPath, newPath) {
const keys = this._cache.keys();
for (const key of keys)
/* v8 ignore next -- @preserve */
if (key.startsWith(oldPath)) {
const newKey = key.replace(oldPath, newPath);
const meta = this._cache.getKey(key);
this._cache.removeKey(key);
this._cache.setKey(newKey, meta);
if (this._originalMeta.has(key)) {
this._originalMeta.set(newKey, this._originalMeta.get(key));
this._originalMeta.delete(key);
}
}
}
};
//#endregion
export { FileEntryCache, create, createFromFile, FileEntryDefault as default };

56
node_modules/file-entry-cache/package.json generated vendored Normal file
View File

@@ -0,0 +1,56 @@
{
"name": "file-entry-cache",
"version": "11.1.5",
"description": "A lightweight cache for file metadata, ideal for processes that work on a specific set of files and only need to reprocess files that have changed since the last run",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.mts",
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
},
"repository": {
"type": "git",
"url": "git+https://github.com/jaredwray/cacheable.git",
"directory": "packages/file-entry-cache"
},
"author": "Jared Wray <me@jaredwray.com>",
"license": "MIT",
"private": false,
"keywords": [
"file cache",
"task cache files",
"file cache",
"key par",
"key value",
"cache"
],
"devDependencies": {
"pino": "^10.3.1",
"tsdown": "^0.22.0",
"typescript": "^5.9.3"
},
"dependencies": {
"flat-cache": "^6.1.23"
},
"files": [
"dist",
"license"
],
"scripts": {
"build": "rimraf ./dist && tsdown src/index.ts --format cjs,esm --dts --clean",
"lint": "biome check --write --error-on-warnings",
"test": "pnpm lint && vitest run --coverage",
"test:ci": "biome check --error-on-warnings && vitest run --coverage",
"clean": "rimraf ./dist ./coverage ./node_modules"
}
}