@interlace/eslint-devkit 1.5.0 → 1.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +15 -19
- package/src/aria-definitions.js +0 -14
- package/src/ast/ast-utils.js +0 -72
- package/src/ast/index.js +0 -6
- package/src/ast-node-types.d.ts +29 -0
- package/src/ast-node-types.js +174 -0
- package/src/index.d.ts +11 -2
- package/src/index.js +5 -38
- package/src/messaging/config.js +0 -88
- package/src/messaging/constants.js +20 -142
- package/src/messaging/formatters-ai.js +0 -89
- package/src/messaging/formatters-v2.js +0 -151
- package/src/messaging/formatters.js +2 -145
- package/src/messaging/index.js +0 -6
- package/src/messaging/types-v2.js +0 -5
- package/src/messaging/types.js +0 -5
- package/src/node/fs.js +0 -61
- package/src/node/index.js +0 -6
- package/src/node/os.js +0 -33
- package/src/node/path.js +0 -126
- package/src/resolver/dependency-analysis.js +64 -562
- package/src/resolver/index.js +0 -6
- package/src/resolver/resolver-adapter.js +0 -39
- package/src/resolver/resolver-detection.js +0 -48
- package/src/resolver/resolver.d.ts +11 -0
- package/src/resolver/resolver.js +49 -112
- package/src/resolver.js +0 -5
- package/src/rule-creation/index.js +0 -8
- package/src/rule-creation/mock-context.js +0 -9
- package/src/rule-creation/rule-creator.d.ts +59 -10
- package/src/rule-creation/rule-creator.js +64 -40
- package/src/rule-creation/sql-injection-rule.js +0 -52
- package/src/security/index.js +0 -6
- package/src/security/security-utils.js +9 -287
- package/src/types/index.js +0 -9
- package/src/types/meta-augmentation.js +0 -5
- package/src/types/type-utils.d.ts +1 -1
- package/src/types/type-utils.js +34 -145
- package/AGENTS.md +0 -151
- package/CHANGELOG.md +0 -181
|
@@ -1,9 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* Copyright (c) 2025 Ofri Peretz
|
|
4
|
-
* Licensed under the MIT License. Use of this source code is governed by the
|
|
5
|
-
* MIT license that can be found in the LICENSE file.
|
|
6
|
-
*/
|
|
7
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
3
|
exports.PERFORMANCE_DOCS = void 0;
|
|
9
4
|
exports.createLRUCache = createLRUCache;
|
|
@@ -31,47 +26,16 @@ exports.saveCacheToDisk = saveCacheToDisk;
|
|
|
31
26
|
exports.loadCacheFromDisk = loadCacheFromDisk;
|
|
32
27
|
exports.getFilesNeedingReanalysis = getFilesNeedingReanalysis;
|
|
33
28
|
exports.isIncrementalAvailable = isIncrementalAvailable;
|
|
34
|
-
/**
|
|
35
|
-
* Dependency analysis utilities for ESLint rules
|
|
36
|
-
*
|
|
37
|
-
* This module handles high-level dependency graph operations:
|
|
38
|
-
* - Import extraction (static and dynamic)
|
|
39
|
-
* - Caching (LRU, hash-based invalidation)
|
|
40
|
-
* - Cycle detection (Tarjan's SCC algorithm)
|
|
41
|
-
*
|
|
42
|
-
* It relies on node-utils for low-level system operations.
|
|
43
|
-
*/
|
|
44
29
|
const resolver_1 = require("./resolver");
|
|
45
30
|
const node_fs_1 = require("node:fs");
|
|
46
31
|
const fs_1 = require("../node/fs");
|
|
47
32
|
const path_1 = require("../node/path");
|
|
48
|
-
// =============================================================================
|
|
49
|
-
// Performance Configuration (inspired by eslint-plugin-import)
|
|
50
|
-
// @see https://github.com/import-js/eslint-plugin-import
|
|
51
|
-
// =============================================================================
|
|
52
|
-
/**
|
|
53
|
-
* Maximum entries in LRU cache before eviction
|
|
54
|
-
* eslint-plugin-import uses similar approach for their ExportMap cache
|
|
55
|
-
*
|
|
56
|
-
* PERFORMANCE: Sized for large codebases (5K+ files × ~10 imports = ~50K entries).
|
|
57
|
-
* A too-small cache causes thrashing: every evicted entry requires a full
|
|
58
|
-
* re-resolution through the resolver pipeline (enhanced-resolve, getTsconfig,
|
|
59
|
-
* extension fan-out). Memory cost is ~2KB per entry, so 50K ≈ 100MB max.
|
|
60
|
-
*/
|
|
61
33
|
const LRU_MAX_SIZE = 50_000;
|
|
62
|
-
/**
|
|
63
|
-
* Quick check patterns for skipping external modules early
|
|
64
|
-
* This is a key optimization - skip node_modules paths without full resolution
|
|
65
|
-
*/
|
|
66
34
|
const EXTERNAL_MODULE_PATTERNS = [
|
|
67
|
-
/^node:/,
|
|
68
|
-
/^[a-z@][^/]*$/,
|
|
69
|
-
/node_modules/,
|
|
35
|
+
/^node:/,
|
|
36
|
+
/^[a-z@][^/]*$/,
|
|
37
|
+
/node_modules/,
|
|
70
38
|
];
|
|
71
|
-
/**
|
|
72
|
-
* Common external packages that should be skipped immediately
|
|
73
|
-
* This set is checked before any file system operations
|
|
74
|
-
*/
|
|
75
39
|
const KNOWN_EXTERNAL_PACKAGES = new Set([
|
|
76
40
|
'react',
|
|
77
41
|
'react-dom',
|
|
@@ -111,49 +75,11 @@ const KNOWN_EXTERNAL_PACKAGES = new Set([
|
|
|
111
75
|
'esbuild',
|
|
112
76
|
'parcel',
|
|
113
77
|
]);
|
|
114
|
-
// =============================================================================
|
|
115
|
-
// Pre-compiled regex patterns for performance
|
|
116
|
-
// =============================================================================
|
|
117
|
-
/**
|
|
118
|
-
* Pre-compiled regex for ES6 static imports
|
|
119
|
-
* Matches: import { x } from 'y', import x from 'y', import 'y'
|
|
120
|
-
*/
|
|
121
78
|
const IMPORT_REGEX = /import\s+(?:[\w*{}\s,]+\s+from\s+)?['"]([^'"]+)['"]/g;
|
|
122
|
-
/**
|
|
123
|
-
* Pre-compiled regex for dynamic imports
|
|
124
|
-
* Matches: import('y'), import("y")
|
|
125
|
-
*/
|
|
126
79
|
const DYNAMIC_IMPORT_REGEX = /import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
|
|
127
|
-
/**
|
|
128
|
-
* Pre-compiled regex for type-only imports
|
|
129
|
-
* Matches: import type { x } from 'y'
|
|
130
|
-
*/
|
|
131
80
|
const TYPE_IMPORT_REGEX = /import\s+type\s/;
|
|
132
|
-
/**
|
|
133
|
-
* Pre-compiled regex for re-exports (export … from '…').
|
|
134
|
-
*
|
|
135
|
-
* Re-exports establish runtime import edges. The cycle in next.js's
|
|
136
|
-
* `client/router.ts` ↔ `client/with-router.tsx` propagates ENTIRELY through
|
|
137
|
-
* re-exports — without this regex our DFS doesn't see the edge and misses
|
|
138
|
-
* the cycle (verified against oxlint native, which catches it).
|
|
139
|
-
*
|
|
140
|
-
* Negative lookahead `(?!type[\s{])` excludes `export type ... from` —
|
|
141
|
-
* those are erased at compile time and don't cause runtime cycles.
|
|
142
|
-
*/
|
|
143
81
|
const EXPORT_FROM_REGEX = /export\s+\{[\s\S]*?\}\s+from\s+['"]([^'"]+)['"]/g;
|
|
144
|
-
/**
|
|
145
|
-
* Default extensions for import resolution.
|
|
146
|
-
* Module-level constant to avoid allocating a new array per resolve call.
|
|
147
|
-
*/
|
|
148
82
|
const DEFAULT_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];
|
|
149
|
-
// =============================================================================
|
|
150
|
-
// LRU Cache Implementation (inspired by eslint-plugin-import's caching)
|
|
151
|
-
// =============================================================================
|
|
152
|
-
/**
|
|
153
|
-
* Simple LRU (Least Recently Used) cache to limit memory usage
|
|
154
|
-
* eslint-plugin-import uses similar caching strategy for their resolver
|
|
155
|
-
* @see https://github.com/import-js/eslint-plugin-import/blob/main/README.md#importcache
|
|
156
|
-
*/
|
|
157
83
|
class LRUCache {
|
|
158
84
|
cache = new Map();
|
|
159
85
|
maxSize;
|
|
@@ -163,18 +89,15 @@ class LRUCache {
|
|
|
163
89
|
get(key) {
|
|
164
90
|
const value = this.cache.get(key);
|
|
165
91
|
if (value !== undefined) {
|
|
166
|
-
// Move to end (most recently used)
|
|
167
92
|
this.cache.delete(key);
|
|
168
93
|
this.cache.set(key, value);
|
|
169
94
|
}
|
|
170
95
|
return value;
|
|
171
96
|
}
|
|
172
97
|
set(key, value) {
|
|
173
|
-
// Delete if exists to update position
|
|
174
98
|
if (this.cache.has(key)) {
|
|
175
99
|
this.cache.delete(key);
|
|
176
100
|
}
|
|
177
|
-
// Evict oldest if at capacity
|
|
178
101
|
else if (this.cache.size >= this.maxSize) {
|
|
179
102
|
const firstKey = this.cache.keys().next().value;
|
|
180
103
|
if (firstKey !== undefined) {
|
|
@@ -196,28 +119,16 @@ class LRUCache {
|
|
|
196
119
|
return this.cache.size;
|
|
197
120
|
}
|
|
198
121
|
}
|
|
199
|
-
/**
|
|
200
|
-
* Create a new LRU cache (exported for testing)
|
|
201
|
-
*/
|
|
202
122
|
function createLRUCache(maxSize = LRU_MAX_SIZE) {
|
|
203
123
|
return new LRUCache(maxSize);
|
|
204
124
|
}
|
|
205
|
-
/**
|
|
206
|
-
* Quick check if an import path is definitely external (no file system access needed)
|
|
207
|
-
* This optimization avoids unnecessary fs.stat calls for packages like 'lodash', 'react', etc.
|
|
208
|
-
*/
|
|
209
125
|
function isDefinitelyExternal(importPath) {
|
|
210
|
-
// Check known external packages first (O(1) lookup)
|
|
211
126
|
const packageName = importPath.split('/')[0].replace(/^@[^/]+\//, '');
|
|
212
127
|
if (KNOWN_EXTERNAL_PACKAGES.has(packageName)) {
|
|
213
128
|
return true;
|
|
214
129
|
}
|
|
215
|
-
// Check patterns
|
|
216
130
|
return EXTERNAL_MODULE_PATTERNS.some((pattern) => pattern.test(importPath));
|
|
217
131
|
}
|
|
218
|
-
/**
|
|
219
|
-
* Create a new empty cache
|
|
220
|
-
*/
|
|
221
132
|
function createFileSystemCache() {
|
|
222
133
|
return {
|
|
223
134
|
dependencies: new Map(),
|
|
@@ -234,9 +145,6 @@ function createFileSystemCache() {
|
|
|
234
145
|
pendingCycleReports: new Map(),
|
|
235
146
|
};
|
|
236
147
|
}
|
|
237
|
-
/**
|
|
238
|
-
* Clear all entries from a cache
|
|
239
|
-
*/
|
|
240
148
|
function clearCache(cache) {
|
|
241
149
|
cache.dependencies.clear();
|
|
242
150
|
cache.fileExists.clear();
|
|
@@ -251,22 +159,12 @@ function clearCache(cache) {
|
|
|
251
159
|
cache.nonCyclicFiles.clear();
|
|
252
160
|
cache.pendingCycleReports.clear();
|
|
253
161
|
}
|
|
254
|
-
/**
|
|
255
|
-
* Invalidate SCC cache (call when graph changes)
|
|
256
|
-
*/
|
|
257
162
|
function invalidateSCCCache(cache) {
|
|
258
163
|
cache.sccIndex.clear();
|
|
259
164
|
cache.sccs = [];
|
|
260
165
|
cache.sccComputed = false;
|
|
261
166
|
cache.nonCyclicFiles.clear();
|
|
262
167
|
}
|
|
263
|
-
/**
|
|
264
|
-
* Get a simple hash for cache invalidation based on file stats
|
|
265
|
-
* Uses mtime + size which is fast and reliable for detecting changes
|
|
266
|
-
*
|
|
267
|
-
* @param filePath - Absolute path to the file
|
|
268
|
-
* @returns Hash string or null if file doesn't exist/can't be read
|
|
269
|
-
*/
|
|
270
168
|
function getFileHash(filePath) {
|
|
271
169
|
const stats = (0, fs_1.statSync)(filePath);
|
|
272
170
|
if (!stats) {
|
|
@@ -274,13 +172,6 @@ function getFileHash(filePath) {
|
|
|
274
172
|
}
|
|
275
173
|
return `${stats.mtimeMs}-${stats.size}`;
|
|
276
174
|
}
|
|
277
|
-
/**
|
|
278
|
-
* Check if cached data for a file is still valid
|
|
279
|
-
*
|
|
280
|
-
* @param filePath - Absolute path to the file
|
|
281
|
-
* @param cache - Cache containing file hashes
|
|
282
|
-
* @returns true if cache is valid (file hasn't changed)
|
|
283
|
-
*/
|
|
284
175
|
function isCacheValid(filePath, cache) {
|
|
285
176
|
const cachedHash = cache.fileHashes.get(filePath);
|
|
286
177
|
if (!cachedHash)
|
|
@@ -288,13 +179,6 @@ function isCacheValid(filePath, cache) {
|
|
|
288
179
|
const currentHash = getFileHash(filePath);
|
|
289
180
|
return cachedHash === currentHash;
|
|
290
181
|
}
|
|
291
|
-
/**
|
|
292
|
-
* Check if a file exists (with caching)
|
|
293
|
-
*
|
|
294
|
-
* @param filePath - Absolute path to the file
|
|
295
|
-
* @param cache - Cache for storing results
|
|
296
|
-
* @returns true if file exists
|
|
297
|
-
*/
|
|
298
182
|
function fileExists(filePath, cache) {
|
|
299
183
|
const cached = cache.fileExists.get(filePath);
|
|
300
184
|
if (cached !== undefined) {
|
|
@@ -304,55 +188,22 @@ function fileExists(filePath, cache) {
|
|
|
304
188
|
cache.fileExists.set(filePath, exists);
|
|
305
189
|
return exists;
|
|
306
190
|
}
|
|
307
|
-
/**
|
|
308
|
-
* Wrapper for patternToRegex that accepts FileSystemCache
|
|
309
|
-
*/
|
|
310
191
|
function patternToRegexWithCache(pattern, cache) {
|
|
311
192
|
return (0, path_1.patternToRegex)(pattern, cache.compiledPatterns);
|
|
312
193
|
}
|
|
313
|
-
/**
|
|
314
|
-
* Wrapper for shouldIgnoreFile that accepts FileSystemCache
|
|
315
|
-
*/
|
|
316
194
|
function shouldIgnoreFileWithCache(file, patterns, cache) {
|
|
317
195
|
return (0, path_1.shouldIgnoreFile)(file, patterns, cache.compiledPatterns);
|
|
318
196
|
}
|
|
319
|
-
/**
|
|
320
|
-
* Resolve import path to absolute file path
|
|
321
|
-
*
|
|
322
|
-
* Handles:
|
|
323
|
-
* - Relative imports (./foo, ../bar)
|
|
324
|
-
* - Alias imports (@app/foo, @src/bar)
|
|
325
|
-
* - Extension resolution (.ts, .tsx, .js, .jsx)
|
|
326
|
-
* - Index file resolution (./dir -> ./dir/index.ts)
|
|
327
|
-
*
|
|
328
|
-
* Performance optimizations (inspired by eslint-plugin-import):
|
|
329
|
-
* - Quick external module detection (no fs access for known externals)
|
|
330
|
-
* - LRU cache for resolved paths (avoids re-resolution)
|
|
331
|
-
* - Early return for common external packages
|
|
332
|
-
*
|
|
333
|
-
* @param importPath - Import path from source code
|
|
334
|
-
* @param options - Resolution options
|
|
335
|
-
* @returns Absolute file path or null for external packages
|
|
336
|
-
*/
|
|
337
197
|
function resolveImportPath(importPath, options) {
|
|
338
198
|
const fromFile = options.fromFile;
|
|
339
199
|
const extensions = options.extensions || DEFAULT_EXTENSIONS;
|
|
340
200
|
const cache = options.cache;
|
|
341
201
|
const resolverSettings = options.resolverSettings;
|
|
342
|
-
// OPTIMIZATION 1: Quick external check (no fs access needed)
|
|
343
|
-
// This avoids unnecessary file system calls for packages like 'lodash', 'react', etc.
|
|
344
202
|
if (isDefinitelyExternal(importPath)) {
|
|
345
|
-
// For @-scoped imports, we can't use isDefinitelyExternal alone
|
|
346
|
-
// because @app/foo (internal alias) looks like @testing-library/react (external).
|
|
347
|
-
// We still skip the external check for these and let the resolver handle them.
|
|
348
203
|
if (!importPath.startsWith('@')) {
|
|
349
204
|
return null;
|
|
350
205
|
}
|
|
351
206
|
}
|
|
352
|
-
// OPTIMIZATION 2a: For non-relative imports, use a global cache keyed by
|
|
353
|
-
// just the import specifier. Non-relative imports (like @app/utils, react)
|
|
354
|
-
// resolve to the same path regardless of which file imports them in a
|
|
355
|
-
// single-tsconfig project. This turns ~14K resolution calls into ~400.
|
|
356
207
|
const isRelative = importPath.startsWith('.');
|
|
357
208
|
if (!isRelative) {
|
|
358
209
|
const globalCached = cache.resolvedPaths.get(importPath);
|
|
@@ -360,31 +211,16 @@ function resolveImportPath(importPath, options) {
|
|
|
360
211
|
return globalCached;
|
|
361
212
|
}
|
|
362
213
|
}
|
|
363
|
-
// OPTIMIZATION 2b: Per-file cache for relative imports (./foo varies by dir)
|
|
364
214
|
const cacheKey = isRelative ? `${fromFile}::${importPath}` : importPath;
|
|
365
215
|
const cached = cache.resolvedPaths.get(cacheKey);
|
|
366
216
|
if (cached !== undefined) {
|
|
367
217
|
return cached;
|
|
368
218
|
}
|
|
369
|
-
// Use the robust resolver
|
|
370
|
-
// This supports:
|
|
371
|
-
// 1. TypeScript paths (tsconfig.json)
|
|
372
|
-
// 2. Webpack aliases (via oxc-resolver/tsconfig)
|
|
373
|
-
// 3. Package.json exports
|
|
374
|
-
// 4. Monorepo resolution
|
|
375
219
|
let result = (0, resolver_1.resolveModule)(importPath, fromFile, {
|
|
376
220
|
extensions,
|
|
377
|
-
// Extract basenames from barrelExports for enhanced-resolve mainFiles
|
|
378
|
-
// e.g. "index.ts" -> "index"
|
|
379
221
|
mainFields: ['module', 'main'],
|
|
380
222
|
resolverSettings,
|
|
381
223
|
});
|
|
382
|
-
// OPTIMIZATION 3: If non-relative import resolved to node_modules, treat as external.
|
|
383
|
-
// This prevents the DFS from traversing into external packages.
|
|
384
|
-
//
|
|
385
|
-
// CAVEAT: In monorepos, workspace packages are often symlinked into
|
|
386
|
-
// node_modules (e.g., pnpm/npm workspaces). We use realpathSync to check
|
|
387
|
-
// if the file truly lives in node_modules vs being a symlinked local package.
|
|
388
224
|
if (result && !isRelative && result.includes('node_modules')) {
|
|
389
225
|
try {
|
|
390
226
|
const realPath = (0, node_fs_1.realpathSync)(result);
|
|
@@ -392,45 +228,21 @@ function resolveImportPath(importPath, options) {
|
|
|
392
228
|
cache.resolvedPaths.set(cacheKey, null);
|
|
393
229
|
return null;
|
|
394
230
|
}
|
|
395
|
-
// Symlinked workspace package — use the real path for DFS traversal
|
|
396
231
|
result = realPath;
|
|
397
232
|
}
|
|
398
233
|
catch {
|
|
399
|
-
// realpathSync failed (broken symlink, etc.) — treat as external
|
|
400
234
|
cache.resolvedPaths.set(cacheKey, null);
|
|
401
235
|
return null;
|
|
402
236
|
}
|
|
403
237
|
}
|
|
404
|
-
// Fallback for relative imports that don't exist (useful for error reporting)
|
|
405
238
|
if (!result && isRelative) {
|
|
406
|
-
// We can't know the extension, but we can return the absolute path base
|
|
407
|
-
// This matches what tests expect for non-existent files
|
|
408
239
|
result = (0, path_1.resolvePath)((0, path_1.getDirname)(fromFile), importPath);
|
|
409
240
|
}
|
|
410
|
-
// Cache the result (even null results to avoid re-computation)
|
|
411
241
|
cache.resolvedPaths.set(cacheKey, result);
|
|
412
242
|
return result;
|
|
413
243
|
}
|
|
414
|
-
/**
|
|
415
|
-
* Get all imports from a file
|
|
416
|
-
*
|
|
417
|
-
* Extracts both static and dynamic imports from file content.
|
|
418
|
-
* Results are cached with hash-based invalidation.
|
|
419
|
-
*
|
|
420
|
-
* Performance: Uses pre-compiled regex patterns and caches results.
|
|
421
|
-
* After first parse, lookups are O(1).
|
|
422
|
-
*
|
|
423
|
-
* @param file - Absolute path to the file
|
|
424
|
-
* @param options - Options for import extraction
|
|
425
|
-
* @returns Array of import information
|
|
426
|
-
*/
|
|
427
244
|
function getFileImports(file, options) {
|
|
428
245
|
const { workspaceRoot, barrelExports, cache, resolverSettings } = options;
|
|
429
|
-
// PHASE 6 OPTIMIZATION: Within a single lint run, files don't change.
|
|
430
|
-
// Skip the expensive isCacheValid (which calls statSync per file) and
|
|
431
|
-
// just check if we already have cached dependencies. The hash-based
|
|
432
|
-
// invalidation still runs after parsing (line ~635) to support watch
|
|
433
|
-
// mode and cross-run ESLint cache.
|
|
434
246
|
const cached = cache.dependencies.get(file);
|
|
435
247
|
if (cached) {
|
|
436
248
|
return cached;
|
|
@@ -444,11 +256,6 @@ function getFileImports(file, options) {
|
|
|
444
256
|
if (content === null) {
|
|
445
257
|
return imports;
|
|
446
258
|
}
|
|
447
|
-
// PHASE 6 OPTIMIZATION: Pre-allocate the resolve options object ONCE per file.
|
|
448
|
-
// Previously, a new options object was created for every regex match (~25K
|
|
449
|
-
// allocations per lint run on snappy-client-dashboard). The `importPath`
|
|
450
|
-
// field is set to a placeholder and will never be used because
|
|
451
|
-
// resolveImportPath takes it as a separate argument.
|
|
452
259
|
const resolveOpts = {
|
|
453
260
|
fromFile: file,
|
|
454
261
|
workspaceRoot,
|
|
@@ -457,13 +264,10 @@ function getFileImports(file, options) {
|
|
|
457
264
|
extensions: DEFAULT_EXTENSIONS,
|
|
458
265
|
resolverSettings,
|
|
459
266
|
};
|
|
460
|
-
// Use pre-compiled regex - reset lastIndex for reuse
|
|
461
267
|
IMPORT_REGEX.lastIndex = 0;
|
|
462
268
|
DYNAMIC_IMPORT_REGEX.lastIndex = 0;
|
|
463
269
|
EXPORT_FROM_REGEX.lastIndex = 0;
|
|
464
270
|
let match;
|
|
465
|
-
// Track resolved paths to dedupe across the three regexes (a single file
|
|
466
|
-
// may have both `import X from 'y'` and `export { X } from 'y'`).
|
|
467
271
|
const seen = new Set();
|
|
468
272
|
const pushImport = (importPath, dynamic = false, typeOnly = false) => {
|
|
469
273
|
const resolved = resolveImportPath(importPath, resolveOpts);
|
|
@@ -477,93 +281,49 @@ function getFileImports(file, options) {
|
|
|
477
281
|
imports.push(info);
|
|
478
282
|
}
|
|
479
283
|
};
|
|
480
|
-
// Match ES6 static imports using pre-compiled regex.
|
|
481
|
-
// Detect `import type { ... }` by checking if the full match starts with
|
|
482
|
-
// "import type" — these edges are erased at compile time and must not
|
|
483
|
-
// participate in the SCC graph (they cannot cause runtime cycles).
|
|
484
284
|
while ((match = IMPORT_REGEX.exec(content)) !== null) {
|
|
485
285
|
const isTypeImport = /^import\s+type[\s{]/.test(match[0]);
|
|
486
286
|
pushImport(match[1], false, isTypeImport);
|
|
487
287
|
}
|
|
488
|
-
// Match re-exports (`export … from '…'`). Without this, cycles routed
|
|
489
|
-
// through re-export-only files (a common pattern in barrel-heavy
|
|
490
|
-
// codebases) are invisible.
|
|
491
288
|
while ((match = EXPORT_FROM_REGEX.exec(content)) !== null)
|
|
492
289
|
pushImport(match[1]);
|
|
493
|
-
// Match dynamic imports
|
|
494
290
|
while ((match = DYNAMIC_IMPORT_REGEX.exec(content)) !== null)
|
|
495
291
|
pushImport(match[1], true);
|
|
496
|
-
// Store file hash for cache invalidation + invalidate SCC if graph changed
|
|
497
292
|
const hash = getFileHash(file);
|
|
498
293
|
if (hash) {
|
|
499
294
|
const oldHash = cache.fileHashes.get(file);
|
|
500
295
|
if (oldHash !== hash) {
|
|
501
|
-
// File changed - invalidate SCC cache
|
|
502
296
|
invalidateSCCCache(cache);
|
|
503
297
|
}
|
|
504
298
|
cache.fileHashes.set(file, hash);
|
|
505
299
|
}
|
|
506
300
|
}
|
|
507
301
|
catch {
|
|
508
|
-
// Ignore read errors silently
|
|
509
302
|
}
|
|
510
303
|
cache.dependencies.set(file, imports);
|
|
511
304
|
return imports;
|
|
512
305
|
}
|
|
513
|
-
/**
|
|
514
|
-
* Check if all imports in a cycle are type-only
|
|
515
|
-
*
|
|
516
|
-
* @param cycle - Array of file paths in the cycle
|
|
517
|
-
* @param cache - Cache for file operations
|
|
518
|
-
* @returns true if all imports are type-only
|
|
519
|
-
*/
|
|
520
306
|
function hasOnlyTypeImports(cycle, cache) {
|
|
521
307
|
for (const file of cycle) {
|
|
522
308
|
if (!fileExists(file, cache))
|
|
523
309
|
continue;
|
|
524
310
|
const content = (0, fs_1.readFileSync)(file, 'utf-8');
|
|
525
|
-
// If file exists but readFileSync returns null, it's a read error
|
|
526
|
-
// (e.g., trying to read a directory) - can't verify type-only
|
|
527
311
|
if (content === null)
|
|
528
312
|
return false;
|
|
529
|
-
// Check for runtime imports using pre-compiled regex
|
|
530
313
|
const hasRuntimeImport = !TYPE_IMPORT_REGEX.test(content) && IMPORT_REGEX.test(content);
|
|
531
|
-
IMPORT_REGEX.lastIndex = 0;
|
|
314
|
+
IMPORT_REGEX.lastIndex = 0;
|
|
532
315
|
if (hasRuntimeImport) {
|
|
533
316
|
return false;
|
|
534
317
|
}
|
|
535
318
|
}
|
|
536
319
|
return true;
|
|
537
320
|
}
|
|
538
|
-
/**
|
|
539
|
-
* Tarjan's Strongly Connected Components algorithm
|
|
540
|
-
*
|
|
541
|
-
* This algorithm finds ALL cycles in a graph in O(V+E) time.
|
|
542
|
-
* Unlike simple DFS which can miss cycles at depth, Tarjan's guarantees
|
|
543
|
-
* finding every strongly connected component.
|
|
544
|
-
*
|
|
545
|
-
* A strongly connected component with more than 1 node indicates a cycle.
|
|
546
|
-
*
|
|
547
|
-
* Performance: O(V + E) where V = files, E = imports
|
|
548
|
-
* This is optimal - you can't do better than looking at each edge once.
|
|
549
|
-
*
|
|
550
|
-
* @param startFile - Starting file for analysis
|
|
551
|
-
* @param options - Options for graph traversal
|
|
552
|
-
* @returns Array of SCCs (each SCC is an array of file paths)
|
|
553
|
-
*/
|
|
554
321
|
function computeSCCsFromFile(startFile, options) {
|
|
555
|
-
// Normalize to real path: on macOS /tmp is a symlink to /private/tmp.
|
|
556
|
-
// Without this, the starting file is keyed as /tmp/... while all imports
|
|
557
|
-
// resolve to /private/tmp/... — Tarjan's sees them as distinct nodes and
|
|
558
|
-
// misses cycles that cross the symlink boundary.
|
|
559
322
|
try {
|
|
560
323
|
startFile = (0, node_fs_1.realpathSync)(startFile);
|
|
561
324
|
}
|
|
562
|
-
catch {
|
|
325
|
+
catch { }
|
|
563
326
|
const { workspaceRoot, barrelExports, cache, resolverSettings } = options;
|
|
564
|
-
// If SCC already computed AND covers this file, return cached result.
|
|
565
|
-
// If not in the index, the file wasn't reachable from the previous root —
|
|
566
|
-
// fall through to extend the SCC from this new starting file.
|
|
567
327
|
if (cache.sccComputed && cache.sccs.length > 0 && cache.sccIndex.has(startFile)) {
|
|
568
328
|
return cache.sccs;
|
|
569
329
|
}
|
|
@@ -575,13 +335,9 @@ function computeSCCsFromFile(startFile, options) {
|
|
|
575
335
|
lowlinks: new Map(),
|
|
576
336
|
sccs: [],
|
|
577
337
|
};
|
|
578
|
-
// Build the graph starting from startFile
|
|
579
338
|
const visited = new Set();
|
|
580
339
|
const filesToProcess = [startFile];
|
|
581
|
-
// First pass: discover all reachable files (breadth-first for efficiency)
|
|
582
340
|
while (filesToProcess.length > 0) {
|
|
583
|
-
// pop() cannot return undefined here: the loop guard ensures the stack
|
|
584
|
-
// is non-empty and every pushed path is a non-empty string.
|
|
585
341
|
const file = filesToProcess.pop();
|
|
586
342
|
if (visited.has(file))
|
|
587
343
|
continue;
|
|
@@ -593,30 +349,20 @@ function computeSCCsFromFile(startFile, options) {
|
|
|
593
349
|
resolverSettings,
|
|
594
350
|
});
|
|
595
351
|
for (const imp of imports) {
|
|
596
|
-
// Skip dynamic imports and type-only imports — type edges are erased at
|
|
597
|
-
// compile time and cannot form runtime cycles. Excluding them from the
|
|
598
|
-
// SCC graph produces a smaller, more accurate graph and eliminates FPs
|
|
599
|
-
// that would appear for `import type { Foo }` back-references.
|
|
600
352
|
if (!imp.dynamic && !imp.typeOnly && !visited.has(imp.path)) {
|
|
601
353
|
filesToProcess.push(imp.path);
|
|
602
354
|
}
|
|
603
355
|
}
|
|
604
356
|
}
|
|
605
|
-
// Run Tarjan's algorithm on all discovered files
|
|
606
357
|
for (const file of visited) {
|
|
607
358
|
if (!state.indices.has(file)) {
|
|
608
359
|
tarjanStrongConnect(file, state, options, 0);
|
|
609
360
|
}
|
|
610
361
|
}
|
|
611
|
-
// Convert to SCCResult format
|
|
612
362
|
const newResults = state.sccs.map((files) => ({
|
|
613
363
|
files,
|
|
614
364
|
hasCycle: files.length > 1,
|
|
615
365
|
}));
|
|
616
|
-
// MERGE into existing cache — never overwrite. When called from a new root
|
|
617
|
-
// file not previously reachable, we extend the global SCC rather than
|
|
618
|
-
// replacing it. Existing sccIndex entries are preserved so previously
|
|
619
|
-
// processed files retain their cycle membership information.
|
|
620
366
|
const offset = cache.sccs.length;
|
|
621
367
|
cache.sccs.push(...newResults);
|
|
622
368
|
cache.sccComputed = true;
|
|
@@ -627,13 +373,6 @@ function computeSCCsFromFile(startFile, options) {
|
|
|
627
373
|
}
|
|
628
374
|
}
|
|
629
375
|
}
|
|
630
|
-
// Update nonCyclicFiles from SCC results:
|
|
631
|
-
// - Singleton SCCs (hasCycle=false) → file is PROVABLY non-cyclic → add permanently
|
|
632
|
-
// - Multi-file cyclic SCCs → remove from nonCyclicFiles in case a previous pass
|
|
633
|
-
// incorrectly marked them as non-cyclic (e.g., from an incomplete DFS)
|
|
634
|
-
//
|
|
635
|
-
// With nonCyclicFiles populated here from the authoritative SCC, the ImportDeclaration
|
|
636
|
-
// handler can use it as an O(1) fast path without needing to clear it per-file.
|
|
637
376
|
for (const result of newResults) {
|
|
638
377
|
if (result.hasCycle) {
|
|
639
378
|
for (const file of result.files) {
|
|
@@ -648,78 +387,70 @@ function computeSCCsFromFile(startFile, options) {
|
|
|
648
387
|
}
|
|
649
388
|
return cache.sccs;
|
|
650
389
|
}
|
|
651
|
-
/**
|
|
652
|
-
* Tarjan's strong connect function (recursive part)
|
|
653
|
-
*/
|
|
654
390
|
function tarjanStrongConnect(file, state, options, depth) {
|
|
655
391
|
const { maxDepth, workspaceRoot, barrelExports, cache, resolverSettings } = options;
|
|
656
|
-
// Depth limit for performance on very deep graphs
|
|
657
392
|
if (depth > maxDepth) {
|
|
658
393
|
return;
|
|
659
394
|
}
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
395
|
+
const enter = (node, nodeDepth) => {
|
|
396
|
+
state.indices.set(node, state.index);
|
|
397
|
+
state.lowlinks.set(node, state.index);
|
|
398
|
+
state.index++;
|
|
399
|
+
state.stack.push(node);
|
|
400
|
+
state.onStack.add(node);
|
|
401
|
+
const imports = getFileImports(node, {
|
|
402
|
+
workspaceRoot,
|
|
403
|
+
barrelExports,
|
|
404
|
+
cache,
|
|
405
|
+
resolverSettings,
|
|
406
|
+
});
|
|
407
|
+
const successors = [];
|
|
408
|
+
for (const imp of imports) {
|
|
409
|
+
if (imp.dynamic || imp.typeOnly)
|
|
410
|
+
continue;
|
|
411
|
+
successors.push(imp.path);
|
|
412
|
+
}
|
|
413
|
+
return { file: node, depth: nodeDepth, successors, next: 0 };
|
|
414
|
+
};
|
|
415
|
+
const relax = (node, candidate) => {
|
|
416
|
+
state.lowlinks.set(node, Math.min(state.lowlinks.get(node), candidate));
|
|
417
|
+
};
|
|
418
|
+
const frames = [enter(file, depth)];
|
|
419
|
+
while (frames.length > 0) {
|
|
420
|
+
const frame = frames[frames.length - 1];
|
|
421
|
+
if (frame.next < frame.successors.length) {
|
|
422
|
+
const successor = frame.successors[frame.next++];
|
|
423
|
+
if (!state.indices.has(successor)) {
|
|
424
|
+
if (frame.depth + 1 > maxDepth) {
|
|
425
|
+
relax(frame.file, 0);
|
|
426
|
+
continue;
|
|
427
|
+
}
|
|
428
|
+
frames.push(enter(successor, frame.depth + 1));
|
|
429
|
+
}
|
|
430
|
+
else if (state.onStack.has(successor)) {
|
|
431
|
+
relax(frame.file, state.indices.get(successor));
|
|
432
|
+
}
|
|
677
433
|
continue;
|
|
678
|
-
const successor = imp.path;
|
|
679
|
-
if (!state.indices.has(successor)) {
|
|
680
|
-
// Successor has not yet been visited; recurse on it
|
|
681
|
-
tarjanStrongConnect(successor, state, options, depth + 1);
|
|
682
|
-
state.lowlinks.set(file, Math.min(
|
|
683
|
-
// `file`'s lowlink is always set at function entry above.
|
|
684
|
-
state.lowlinks.get(file),
|
|
685
|
-
// The successor's lowlink can be missing when the recursive call
|
|
686
|
-
// returned early on the depth limit before initializing it.
|
|
687
|
-
state.lowlinks.get(successor) ?? 0));
|
|
688
434
|
}
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
435
|
+
frames.pop();
|
|
436
|
+
const lowlink = state.lowlinks.get(frame.file);
|
|
437
|
+
const index = state.indices.get(frame.file);
|
|
438
|
+
if (lowlink === index) {
|
|
439
|
+
const scc = [];
|
|
440
|
+
let w;
|
|
441
|
+
do {
|
|
442
|
+
w = state.stack.pop();
|
|
443
|
+
state.onStack.delete(w);
|
|
444
|
+
scc.push(w);
|
|
445
|
+
} while (w !== frame.file);
|
|
446
|
+
state.sccs.push(scc);
|
|
447
|
+
}
|
|
448
|
+
const parent = frames[frames.length - 1];
|
|
449
|
+
if (parent) {
|
|
450
|
+
relax(parent.file, state.lowlinks.get(frame.file));
|
|
694
451
|
}
|
|
695
|
-
}
|
|
696
|
-
const lowlink = state.lowlinks.get(file);
|
|
697
|
-
const index = state.indices.get(file);
|
|
698
|
-
// If file is a root node, pop the stack and generate an SCC
|
|
699
|
-
if (lowlink === index) {
|
|
700
|
-
const scc = [];
|
|
701
|
-
let w;
|
|
702
|
-
do {
|
|
703
|
-
// The stack always contains `file` at this point (it was pushed at
|
|
704
|
-
// function entry), so pop() cannot return undefined before the loop
|
|
705
|
-
// terminates at `w === file`.
|
|
706
|
-
w = state.stack.pop();
|
|
707
|
-
state.onStack.delete(w);
|
|
708
|
-
scc.push(w);
|
|
709
|
-
} while (w !== file);
|
|
710
|
-
// Only store SCCs (single nodes aren't cycles, but we track them for completeness)
|
|
711
|
-
state.sccs.push(scc);
|
|
712
452
|
}
|
|
713
453
|
}
|
|
714
|
-
/**
|
|
715
|
-
* Check if a file is part of any cycle using cached SCC data
|
|
716
|
-
*
|
|
717
|
-
* Performance: O(1) after SCC computation
|
|
718
|
-
*
|
|
719
|
-
* @param file - File to check
|
|
720
|
-
* @param cache - Cache with SCC data
|
|
721
|
-
* @returns true if file is part of a cycle
|
|
722
|
-
*/
|
|
723
454
|
function isFileInCycle(file, cache) {
|
|
724
455
|
const sccIndex = cache.sccIndex.get(file);
|
|
725
456
|
if (sccIndex === undefined)
|
|
@@ -727,27 +458,11 @@ function isFileInCycle(file, cache) {
|
|
|
727
458
|
const scc = cache.sccs[sccIndex];
|
|
728
459
|
return scc && scc.hasCycle;
|
|
729
460
|
}
|
|
730
|
-
/**
|
|
731
|
-
* Find the shortest cycle path from targetFile back to sourceFile via BFS.
|
|
732
|
-
*
|
|
733
|
-
* This is the path-finding phase — called ONLY after the SCC pre-check
|
|
734
|
-
* confirms that sourceFile and targetFile are in the same SCC (meaning a
|
|
735
|
-
* cycle MUST exist). BFS guarantees the shortest cycle path is returned.
|
|
736
|
-
*
|
|
737
|
-
* Only traverses files within the same SCC (O(1) lookup per hop), so the
|
|
738
|
-
* worst-case work is proportional to the SCC size, not the entire graph.
|
|
739
|
-
*
|
|
740
|
-
* @param sourceFile - The file that contains the import (cycle closes here)
|
|
741
|
-
* @param targetFile - The file being imported (BFS starts here)
|
|
742
|
-
* @param options - Traversal options (workspaceRoot, barrelExports, cache, resolverSettings)
|
|
743
|
-
* @returns The cycle path [targetFile, ..., sourceFile], or null if not found
|
|
744
|
-
*/
|
|
745
461
|
function findShortestCyclePath(sourceFile, targetFile, options) {
|
|
746
462
|
const { workspaceRoot, barrelExports, cache, resolverSettings } = options;
|
|
747
463
|
const srcSCC = cache.sccIndex.get(sourceFile);
|
|
748
464
|
if (srcSCC === undefined)
|
|
749
465
|
return null;
|
|
750
|
-
// BFS from targetFile, looking for a path back to sourceFile
|
|
751
466
|
const queue = [[targetFile]];
|
|
752
467
|
const visited = new Set([targetFile]);
|
|
753
468
|
while (queue.length > 0) {
|
|
@@ -763,12 +478,10 @@ function findShortestCyclePath(sourceFile, targetFile, options) {
|
|
|
763
478
|
if (imp.dynamic || imp.typeOnly)
|
|
764
479
|
continue;
|
|
765
480
|
if (imp.path === sourceFile) {
|
|
766
|
-
// Found the cycle — return the complete path
|
|
767
481
|
return [...path, sourceFile];
|
|
768
482
|
}
|
|
769
483
|
if (visited.has(imp.path))
|
|
770
484
|
continue;
|
|
771
|
-
// Only traverse files in the same SCC — anything else cannot reach sourceFile
|
|
772
485
|
if (cache.sccIndex.get(imp.path) !== srcSCC)
|
|
773
486
|
continue;
|
|
774
487
|
visited.add(imp.path);
|
|
@@ -777,15 +490,6 @@ function findShortestCyclePath(sourceFile, targetFile, options) {
|
|
|
777
490
|
}
|
|
778
491
|
return null;
|
|
779
492
|
}
|
|
780
|
-
/**
|
|
781
|
-
* Get the cycle containing a specific file
|
|
782
|
-
*
|
|
783
|
-
* Performance: O(1) after SCC computation
|
|
784
|
-
*
|
|
785
|
-
* @param file - File to get cycle for
|
|
786
|
-
* @param cache - Cache with SCC data
|
|
787
|
-
* @returns Array of files in the cycle, or null if not in a cycle
|
|
788
|
-
*/
|
|
789
493
|
function getCycleForFile(file, cache) {
|
|
790
494
|
const sccIndex = cache.sccIndex.get(file);
|
|
791
495
|
if (sccIndex === undefined)
|
|
@@ -795,75 +499,35 @@ function getCycleForFile(file, cache) {
|
|
|
795
499
|
return null;
|
|
796
500
|
return scc.files;
|
|
797
501
|
}
|
|
798
|
-
/**
|
|
799
|
-
* Lightweight per-import cycle detector (Phase 3 optimization)
|
|
800
|
-
*
|
|
801
|
-
* Instead of building the full graph upfront via BFS + Tarjan SCC,
|
|
802
|
-
* this function does a simple bounded DFS from a target file, looking
|
|
803
|
-
* for any path back to the source file. This is architecturally similar
|
|
804
|
-
* to eslint-plugin-import's no-cycle approach and is dramatically faster
|
|
805
|
-
* because it only reads files along the actual traversal path.
|
|
806
|
-
*
|
|
807
|
-
* Performance characteristics:
|
|
808
|
-
* - O(depth) file reads per call (not O(|V|) like BFS)
|
|
809
|
-
* - nonCyclicFiles cache provides O(1) rejection across the lint run
|
|
810
|
-
* - getFileImports cache reuses parsed results across files
|
|
811
|
-
* - Bounded by maxDepth to prevent runaway traversal
|
|
812
|
-
*
|
|
813
|
-
* @param sourceFile - The file containing the import (looking for path back to here)
|
|
814
|
-
* @param targetFile - The file being imported (starting point for DFS)
|
|
815
|
-
* @param options - Detection options
|
|
816
|
-
* @returns Array of cycle paths found (each is an array of file paths ending at sourceFile)
|
|
817
|
-
*/
|
|
818
502
|
function detectCycleFromImport(sourceFile, targetFile, options) {
|
|
819
|
-
// Normalize paths: on macOS /tmp is a symlink to /private/tmp.
|
|
820
|
-
// ESLint provides the symlink path; resolved imports use the real path.
|
|
821
|
-
// Without normalization, `file === sourceFile` never matches in the DFS.
|
|
822
503
|
try {
|
|
823
504
|
sourceFile = (0, node_fs_1.realpathSync)(sourceFile);
|
|
824
505
|
}
|
|
825
|
-
catch {
|
|
506
|
+
catch { }
|
|
826
507
|
try {
|
|
827
508
|
targetFile = (0, node_fs_1.realpathSync)(targetFile);
|
|
828
509
|
}
|
|
829
|
-
catch {
|
|
510
|
+
catch { }
|
|
830
511
|
const { maxDepth, reportAllCycles, workspaceRoot, barrelExports, cache, resolverSettings, } = options;
|
|
831
|
-
// Fast path: target is known to not be in any cycle
|
|
832
512
|
if (cache.nonCyclicFiles.has(targetFile)) {
|
|
833
513
|
return [];
|
|
834
514
|
}
|
|
835
515
|
const allCycles = [];
|
|
836
|
-
// PERFORMANCE: Use mutable stack instead of [...currentPath, file]
|
|
837
|
-
// to avoid O(depth) array allocations per DFS branch. The path is
|
|
838
|
-
// only copied when a cycle is actually found (rare).
|
|
839
516
|
const pathStack = [sourceFile];
|
|
840
|
-
// Track whether the DFS was truncated by the depth limit. If it was, we
|
|
841
|
-
// CANNOT cache the target as `nonCyclic` — depth-limit truncation isn't
|
|
842
|
-
// proof of acyclicity, and a poisoned cache cascades into every later
|
|
843
|
-
// lint pass that touches a file in the same subtree (verified on next.js:
|
|
844
|
-
// wide scope reported 0 cycles vs. 17 in oxlint, narrow scope reported 5+).
|
|
845
517
|
let depthLimitHit = false;
|
|
846
518
|
function dfs(file, depth, visited) {
|
|
847
|
-
// Found the cycle — we've reached back to the source file
|
|
848
519
|
if (file === sourceFile) {
|
|
849
520
|
allCycles.push([...pathStack, file]);
|
|
850
521
|
return;
|
|
851
522
|
}
|
|
852
|
-
// Depth limit
|
|
853
523
|
if (depth >= maxDepth) {
|
|
854
524
|
depthLimitHit = true;
|
|
855
525
|
return;
|
|
856
526
|
}
|
|
857
|
-
// Already visited in this search tree
|
|
858
527
|
if (visited.has(file))
|
|
859
528
|
return;
|
|
860
|
-
// Known non-cyclic from previous lint file visits
|
|
861
529
|
if (cache.nonCyclicFiles.has(file))
|
|
862
530
|
return;
|
|
863
|
-
// NOTE: no `!reportAllCycles && allCycles.length > 0` early-exit here —
|
|
864
|
-
// it would be unreachable: the import loop below performs the identical
|
|
865
|
-
// check (and breaks) before every recursive dfs() call, and the root
|
|
866
|
-
// call always happens before any cycle can have been recorded.
|
|
867
531
|
visited.add(file);
|
|
868
532
|
pathStack.push(file);
|
|
869
533
|
const imports = getFileImports(file, {
|
|
@@ -883,61 +547,22 @@ function detectCycleFromImport(sourceFile, targetFile, options) {
|
|
|
883
547
|
}
|
|
884
548
|
const visited = new Set();
|
|
885
549
|
dfs(targetFile, 1, visited);
|
|
886
|
-
// Only cache as non-cyclic when the DFS was complete AND found no cycles.
|
|
887
|
-
// A depth-truncated DFS cannot prove acyclicity (the cycle may exist past
|
|
888
|
-
// the depth limit), and caching it poisons every future lint pass that
|
|
889
|
-
// traverses the same subtree.
|
|
890
550
|
if (allCycles.length === 0 && !depthLimitHit) {
|
|
891
551
|
cache.nonCyclicFiles.add(targetFile);
|
|
892
552
|
}
|
|
893
553
|
return allCycles;
|
|
894
554
|
}
|
|
895
|
-
|
|
896
|
-
* Find all circular dependencies using SCC + DFS hybrid approach
|
|
897
|
-
*
|
|
898
|
-
* Performance Strategy (v2 — optimized based on benchmark data):
|
|
899
|
-
* 1. Compute SCCs via Tarjan's algorithm on first call (cached for lint run)
|
|
900
|
-
* — now significantly faster thanks to resolver fast path + getTsconfig cache
|
|
901
|
-
* 2. Use O(1) SCC membership for instant non-cyclic file rejection
|
|
902
|
-
* 3. Only run DFS for files known to be in a cycle (to extract paths)
|
|
903
|
-
* 4. Build graph lazily via getFileImports() with caching
|
|
904
|
-
*
|
|
905
|
-
* Key optimizations vs v1:
|
|
906
|
-
* - Resolver fast path: existsSync for relative imports (10-50x per call)
|
|
907
|
-
* - Global getTsconfig cache: eliminates per-file directory traversal
|
|
908
|
-
* - visited Set: prevents DFS re-traversal of explored subtrees
|
|
909
|
-
* - nonCyclicFiles cache: O(1) rejection across entire lint run
|
|
910
|
-
*
|
|
911
|
-
* @param file - Starting file for cycle detection
|
|
912
|
-
* @param options - Detection options
|
|
913
|
-
* @param currentPath - Current path in DFS (internal use)
|
|
914
|
-
* @param depth - Current depth (internal use)
|
|
915
|
-
* @param visited - Set of fully explored files (internal use, persistent)
|
|
916
|
-
* @returns Array of cycles found (each cycle is an array of file paths)
|
|
917
|
-
*/
|
|
918
|
-
function findAllCircularDependencies(file, options, currentPath = [],
|
|
919
|
-
// NOTE: depth=0 is the root call; normalization happens only there.
|
|
920
|
-
depth = 0, visited = new Set()) {
|
|
555
|
+
function findAllCircularDependencies(file, options, currentPath = [], depth = 0, visited = new Set()) {
|
|
921
556
|
const { maxDepth, reportAllCycles, workspaceRoot, barrelExports, cache, resolverSettings, } = options;
|
|
922
|
-
// Normalize to real path at the root call (depth=0 only — recursive calls
|
|
923
|
-
// already receive normalised paths from the resolver's import resolution).
|
|
924
557
|
if (depth === 0) {
|
|
925
558
|
try {
|
|
926
559
|
file = (0, node_fs_1.realpathSync)(file);
|
|
927
560
|
}
|
|
928
|
-
catch {
|
|
561
|
+
catch { }
|
|
929
562
|
}
|
|
930
|
-
// OPTIMIZATION 1: Check if file is known to not be in any cycle
|
|
931
|
-
// This is populated across the lint run — once a file is confirmed
|
|
932
|
-
// non-cyclic, all future calls skip it in O(1).
|
|
933
563
|
if (cache.nonCyclicFiles.has(file)) {
|
|
934
564
|
return [];
|
|
935
565
|
}
|
|
936
|
-
// OPTIMIZATION 2: At the root call, compute or use cached SCC data.
|
|
937
|
-
// SCC computation uses Tarjan's O(V+E) algorithm and is now much faster
|
|
938
|
-
// thanks to the resolver fast path (existsSync for relative imports) and
|
|
939
|
-
// global getTsconfig caching. The one-time cost is amortized across all
|
|
940
|
-
// file visits in the lint run via O(1) cycle membership lookups.
|
|
941
566
|
if (depth === 0) {
|
|
942
567
|
computeSCCsFromFile(file, {
|
|
943
568
|
maxDepth,
|
|
@@ -946,30 +571,20 @@ depth = 0, visited = new Set()) {
|
|
|
946
571
|
cache,
|
|
947
572
|
resolverSettings,
|
|
948
573
|
});
|
|
949
|
-
// Fast path: O(1) SCC lookup — if file is not in any cycle, skip
|
|
950
574
|
if (!isFileInCycle(file, cache)) {
|
|
951
575
|
cache.nonCyclicFiles.add(file);
|
|
952
576
|
return [];
|
|
953
577
|
}
|
|
954
578
|
}
|
|
955
|
-
// Depth limit for performance
|
|
956
579
|
if (depth > maxDepth) {
|
|
957
580
|
return [];
|
|
958
581
|
}
|
|
959
|
-
// Found a cycle — the current file is already on the current DFS path
|
|
960
582
|
if (currentPath.includes(file)) {
|
|
961
583
|
return [[...currentPath, file]];
|
|
962
584
|
}
|
|
963
|
-
// OPTIMIZATION 3: Skip if already visited in this DFS run.
|
|
964
|
-
// `visited` is added BEFORE exploring children (below) to prevent
|
|
965
|
-
// infinite recursion through cyclic graphs. This is correct: if we
|
|
966
|
-
// encounter a file already on our `visited` set it means we've started
|
|
967
|
-
// exploring it from a sibling branch — we can safely skip it because
|
|
968
|
-
// the currentPath.includes() check above already handles the cycle case.
|
|
969
585
|
if (visited.has(file)) {
|
|
970
586
|
return [];
|
|
971
587
|
}
|
|
972
|
-
// Mark visited BEFORE recursing to prevent infinite loops on cyclic graphs.
|
|
973
588
|
visited.add(file);
|
|
974
589
|
const imports = getFileImports(file, {
|
|
975
590
|
workspaceRoot,
|
|
@@ -980,39 +595,27 @@ depth = 0, visited = new Set()) {
|
|
|
980
595
|
const newPath = [...currentPath, file];
|
|
981
596
|
const allCycles = [];
|
|
982
597
|
for (const imp of imports) {
|
|
983
|
-
// Skip dynamic imports (they don't cause bundler issues)
|
|
984
598
|
if (imp.dynamic) {
|
|
985
599
|
continue;
|
|
986
600
|
}
|
|
987
|
-
// OPTIMIZATION 4: Early exit when only first cycle is needed
|
|
988
601
|
if (!reportAllCycles && allCycles.length > 0) {
|
|
989
602
|
break;
|
|
990
603
|
}
|
|
991
604
|
const cycles = findAllCircularDependencies(imp.path, options, newPath, depth + 1, visited);
|
|
992
605
|
allCycles.push(...cycles);
|
|
993
606
|
}
|
|
994
|
-
// If no cycles found for this file in this search, mark as non-cyclic
|
|
995
607
|
if (depth === 0 && allCycles.length === 0) {
|
|
996
608
|
cache.nonCyclicFiles.add(file);
|
|
997
609
|
}
|
|
998
610
|
return allCycles;
|
|
999
611
|
}
|
|
1000
|
-
/**
|
|
1001
|
-
* Extract the minimal cycle from a path
|
|
1002
|
-
* For example: A → B → C → B → A becomes B → C → B
|
|
1003
|
-
*
|
|
1004
|
-
* @param cycle - Full cycle path
|
|
1005
|
-
* @returns Minimal cycle (just the loop)
|
|
1006
|
-
*/
|
|
1007
612
|
function getMinimalCycle(cycle) {
|
|
1008
613
|
if (cycle.length < 2)
|
|
1009
614
|
return cycle;
|
|
1010
|
-
// Find where the cycle actually starts (first repeated element)
|
|
1011
615
|
const seen = new Map();
|
|
1012
616
|
for (let i = 0; i < cycle.length; i++) {
|
|
1013
617
|
const file = cycle[i];
|
|
1014
618
|
if (seen.has(file)) {
|
|
1015
|
-
// Found the start of the actual cycle
|
|
1016
619
|
const cycleStart = seen?.get?.(file);
|
|
1017
620
|
return cycle.slice(cycleStart, i + 1);
|
|
1018
621
|
}
|
|
@@ -1020,16 +623,8 @@ function getMinimalCycle(cycle) {
|
|
|
1020
623
|
}
|
|
1021
624
|
return cycle;
|
|
1022
625
|
}
|
|
1023
|
-
/**
|
|
1024
|
-
* Generate a unique hash for a cycle to avoid duplicate reports
|
|
1025
|
-
*
|
|
1026
|
-
* @param cycle - Cycle to hash
|
|
1027
|
-
* @returns Unique hash string
|
|
1028
|
-
*/
|
|
1029
626
|
function getCycleHash(cycle) {
|
|
1030
|
-
// Find the minimal cycle (the actual loop, not the path leading to it)
|
|
1031
627
|
const minimalCycle = getMinimalCycle(cycle);
|
|
1032
|
-
// Normalize the cycle to start from the smallest path (for consistency)
|
|
1033
628
|
const minIndex = minimalCycle.indexOf(minimalCycle.reduce((min, curr) => (curr < min ? curr : min), minimalCycle[0]));
|
|
1034
629
|
const normalized = [
|
|
1035
630
|
...minimalCycle.slice(minIndex),
|
|
@@ -1039,14 +634,7 @@ function getCycleHash(cycle) {
|
|
|
1039
634
|
}
|
|
1040
635
|
const CACHE_VERSION = 1;
|
|
1041
636
|
const DEFAULT_CACHE_FILE = 'node_modules/.cache/forge-eslint/cycles.json';
|
|
1042
|
-
const DEFAULT_MAX_CACHE_AGE = 24 * 60 * 60 * 1000;
|
|
1043
|
-
/**
|
|
1044
|
-
* Save cache to disk for incremental analysis
|
|
1045
|
-
*
|
|
1046
|
-
* @param cache - Cache to save
|
|
1047
|
-
* @param options - Incremental options
|
|
1048
|
-
* @param workspaceRoot - Workspace root for resolving cache path
|
|
1049
|
-
*/
|
|
637
|
+
const DEFAULT_MAX_CACHE_AGE = 24 * 60 * 60 * 1000;
|
|
1050
638
|
function saveCacheToDisk(cache, options, workspaceRoot) {
|
|
1051
639
|
if (!options.enabled)
|
|
1052
640
|
return;
|
|
@@ -1060,22 +648,12 @@ function saveCacheToDisk(cache, options, workspaceRoot) {
|
|
|
1060
648
|
nonCyclicFiles: Array.from(cache.nonCyclicFiles),
|
|
1061
649
|
graphHash: cache.graphHash,
|
|
1062
650
|
};
|
|
1063
|
-
// Ensure directory exists
|
|
1064
651
|
const cacheDir = (0, path_1.getDirname)(cacheFile);
|
|
1065
652
|
if (!(0, fs_1.fileExistsSync)(cacheDir)) {
|
|
1066
653
|
(0, fs_1.mkdirSync)(cacheDir, { recursive: true });
|
|
1067
654
|
}
|
|
1068
|
-
// Write cache file (failure is not critical - just continue without persistence)
|
|
1069
655
|
(0, fs_1.writeFileSync)(cacheFile, JSON.stringify(data), 'utf-8');
|
|
1070
656
|
}
|
|
1071
|
-
/**
|
|
1072
|
-
* Load cache from disk for incremental analysis
|
|
1073
|
-
*
|
|
1074
|
-
* @param cache - Cache to populate
|
|
1075
|
-
* @param options - Incremental options
|
|
1076
|
-
* @param workspaceRoot - Workspace root for resolving cache path
|
|
1077
|
-
* @returns true if cache was loaded successfully
|
|
1078
|
-
*/
|
|
1079
657
|
function loadCacheFromDisk(cache, options, workspaceRoot) {
|
|
1080
658
|
if (!options.enabled)
|
|
1081
659
|
return false;
|
|
@@ -1089,16 +667,13 @@ function loadCacheFromDisk(cache, options, workspaceRoot) {
|
|
|
1089
667
|
}
|
|
1090
668
|
try {
|
|
1091
669
|
const data = JSON.parse(content);
|
|
1092
|
-
// Check version compatibility
|
|
1093
670
|
if (data.version !== CACHE_VERSION) {
|
|
1094
671
|
return false;
|
|
1095
672
|
}
|
|
1096
|
-
// Check cache age
|
|
1097
673
|
const maxAge = options.maxCacheAge ?? DEFAULT_MAX_CACHE_AGE;
|
|
1098
674
|
if (Date.now() - data.createdAt > maxAge) {
|
|
1099
675
|
return false;
|
|
1100
676
|
}
|
|
1101
|
-
// Restore cache data
|
|
1102
677
|
cache.fileHashes = new Map(Object.entries(data.fileHashes));
|
|
1103
678
|
cache.sccs = data.sccs;
|
|
1104
679
|
cache.sccIndex = new Map(Object.entries(data.sccIndex).map(([k, v]) => [k, v]));
|
|
@@ -1111,17 +686,8 @@ function loadCacheFromDisk(cache, options, workspaceRoot) {
|
|
|
1111
686
|
return false;
|
|
1112
687
|
}
|
|
1113
688
|
}
|
|
1114
|
-
/**
|
|
1115
|
-
* Perform incremental analysis - only recompute for changed files
|
|
1116
|
-
*
|
|
1117
|
-
* @param files - Files to analyze
|
|
1118
|
-
* @param cache - Cache with potentially loaded persistent data
|
|
1119
|
-
* @param options - Circular dependency options
|
|
1120
|
-
* @returns Files that need full reanalysis
|
|
1121
|
-
*/
|
|
1122
689
|
function getFilesNeedingReanalysis(files, cache, options) {
|
|
1123
690
|
if (!options.enabled || !cache.sccComputed) {
|
|
1124
|
-
// No incremental data - need full analysis
|
|
1125
691
|
return files;
|
|
1126
692
|
}
|
|
1127
693
|
const changedFiles = [];
|
|
@@ -1132,9 +698,7 @@ function getFilesNeedingReanalysis(files, cache, options) {
|
|
|
1132
698
|
changedFiles.push(file);
|
|
1133
699
|
}
|
|
1134
700
|
}
|
|
1135
|
-
// If any file changed, we need to invalidate related SCCs
|
|
1136
701
|
if (changedFiles.length > 0) {
|
|
1137
|
-
// Find all files in the same SCCs as changed files
|
|
1138
702
|
const affectedSCCIndices = new Set();
|
|
1139
703
|
for (const file of changedFiles) {
|
|
1140
704
|
const sccIndex = cache.sccIndex.get(file);
|
|
@@ -1142,20 +706,16 @@ function getFilesNeedingReanalysis(files, cache, options) {
|
|
|
1142
706
|
affectedSCCIndices.add(sccIndex);
|
|
1143
707
|
}
|
|
1144
708
|
}
|
|
1145
|
-
// Get all files in affected SCCs
|
|
1146
709
|
const affectedFiles = new Set(changedFiles);
|
|
1147
710
|
for (const scc of cache.sccs) {
|
|
1148
711
|
const sccIndex = cache.sccIndex.get(scc.files[0]);
|
|
1149
712
|
if (sccIndex !== undefined && affectedSCCIndices.has(sccIndex)) {
|
|
1150
713
|
for (const file of scc.files) {
|
|
1151
714
|
affectedFiles.add(file);
|
|
1152
|
-
// Remove from non-cyclic cache since we're reanalyzing
|
|
1153
715
|
cache.nonCyclicFiles.delete(file);
|
|
1154
716
|
}
|
|
1155
717
|
}
|
|
1156
718
|
}
|
|
1157
|
-
// Also invalidate any file that imports a changed file
|
|
1158
|
-
// (they might now be part of a cycle)
|
|
1159
719
|
for (const [file, imports] of cache.dependencies) {
|
|
1160
720
|
for (const imp of imports) {
|
|
1161
721
|
if (changedFiles.includes(imp.path)) {
|
|
@@ -1167,69 +727,11 @@ function getFilesNeedingReanalysis(files, cache, options) {
|
|
|
1167
727
|
}
|
|
1168
728
|
return Array.from(affectedFiles);
|
|
1169
729
|
}
|
|
1170
|
-
// No changes - can use cached results
|
|
1171
730
|
return [];
|
|
1172
731
|
}
|
|
1173
|
-
/**
|
|
1174
|
-
* Check if incremental analysis can be used
|
|
1175
|
-
*
|
|
1176
|
-
* @param cache - Cache to check
|
|
1177
|
-
* @param options - Incremental options
|
|
1178
|
-
* @returns true if incremental analysis is available
|
|
1179
|
-
*/
|
|
1180
732
|
function isIncrementalAvailable(cache, options) {
|
|
1181
733
|
return Boolean(options?.enabled && cache.sccComputed && cache.sccs.length > 0);
|
|
1182
734
|
}
|
|
1183
|
-
// =============================================================================
|
|
1184
|
-
// PERFORMANCE DOCUMENTATION
|
|
1185
|
-
// =============================================================================
|
|
1186
|
-
/**
|
|
1187
|
-
* Performance Characteristics of Circular Dependency Detection
|
|
1188
|
-
*
|
|
1189
|
-
* This implementation uses a hybrid approach that combines:
|
|
1190
|
-
* 1. Tarjan's SCC algorithm for O(V+E) cycle detection (cached)
|
|
1191
|
-
* 2. DFS for extracting actual cycle paths for error messages
|
|
1192
|
-
* 3. Incremental analysis for watch mode and repeated lint runs
|
|
1193
|
-
*
|
|
1194
|
-
* Comparison with eslint-plugin-import's no-cycle:
|
|
1195
|
-
*
|
|
1196
|
-
* | Aspect | eslint-plugin-import | This implementation |
|
|
1197
|
-
* |-------------------------|---------------------|---------------------|
|
|
1198
|
-
* | Algorithm | Simple DFS | Tarjan SCC + DFS |
|
|
1199
|
-
* | Time complexity | O(V * E) worst case | O(V + E) |
|
|
1200
|
-
* | Finds all cycles | No (depth limited) | Yes (guaranteed) |
|
|
1201
|
-
* | Caching | None | Full graph cached |
|
|
1202
|
-
* | Second file in lint run | Full re-analysis | O(1) lookup |
|
|
1203
|
-
* | Incremental (watch) | No | Yes (file-level) |
|
|
1204
|
-
*
|
|
1205
|
-
* Expected Performance (real-world benchmarks):
|
|
1206
|
-
*
|
|
1207
|
-
* | Codebase Size | First File | Subsequent Files | Total Lint Run |
|
|
1208
|
-
* |------------------|-------------|------------------|----------------|
|
|
1209
|
-
* | ~100 files | ~50ms | ~1ms each | ~150ms |
|
|
1210
|
-
* | ~500 files | ~200ms | ~1ms each | ~700ms |
|
|
1211
|
-
* | ~1000 files | ~500ms | ~1ms each | ~1.5s |
|
|
1212
|
-
* | ~5000 files | ~2s | ~1ms each | ~7s |
|
|
1213
|
-
*
|
|
1214
|
-
* Cache Behavior:
|
|
1215
|
-
* - SCC computation is cached for the entire lint run
|
|
1216
|
-
* - File content is cached with hash-based invalidation (mtime + size)
|
|
1217
|
-
* - In watch mode, only changed files trigger re-analysis
|
|
1218
|
-
* - Cache is automatically invalidated when files change
|
|
1219
|
-
*
|
|
1220
|
-
* Memory Usage:
|
|
1221
|
-
* - ~100 bytes per file for SCC index
|
|
1222
|
-
* - ~500 bytes per file for import cache
|
|
1223
|
-
* - Total: ~5MB for 10,000 files
|
|
1224
|
-
*
|
|
1225
|
-
* Why Tarjan's Algorithm?
|
|
1226
|
-
* - Guaranteed to find ALL strongly connected components (cycles)
|
|
1227
|
-
* - Single pass through the graph - optimal O(V+E)
|
|
1228
|
-
* - No risk of missing deep cycles like depth-limited DFS
|
|
1229
|
-
* - Well-understood and proven correct since 1972
|
|
1230
|
-
*
|
|
1231
|
-
* @see https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
|
|
1232
|
-
*/
|
|
1233
735
|
exports.PERFORMANCE_DOCS = {
|
|
1234
736
|
algorithm: 'Tarjan SCC + DFS hybrid',
|
|
1235
737
|
timeComplexity: 'O(V + E)',
|