@interlace/eslint-devkit 1.9.0 → 1.11.0

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.
Files changed (46) hide show
  1. package/README.md +1 -1
  2. package/package.json +2 -2
  3. package/src/aria-definitions.js +1 -990
  4. package/src/ast/ast-utils.js +1 -133
  5. package/src/ast/index.js +1 -17
  6. package/src/ast-node-types.js +1 -174
  7. package/src/index.js +1 -43
  8. package/src/messaging/config.js +1 -98
  9. package/src/messaging/constants.js +1 -678
  10. package/src/messaging/formatters-ai.js +2 -176
  11. package/src/messaging/formatters-v2.js +10 -212
  12. package/src/messaging/formatters.js +3 -186
  13. package/src/messaging/index.js +1 -21
  14. package/src/messaging/types-v2.js +1 -2
  15. package/src/messaging/types.js +1 -2
  16. package/src/node/fs.js +1 -104
  17. package/src/node/index.js +1 -19
  18. package/src/node/os.js +1 -52
  19. package/src/node/path.js +1 -143
  20. package/src/resolver/dependency-analysis.js +1 -740
  21. package/src/resolver/index.js +1 -20
  22. package/src/resolver/resolver-adapter.js +1 -92
  23. package/src/resolver/resolver-detection.js +1 -189
  24. package/src/resolver/resolver.js +1 -206
  25. package/src/resolver.js +1 -17
  26. package/src/rule-creation/browser-escape-hatch-rule.js +1 -100
  27. package/src/rule-creation/hardcoded-credentials-rule.js +1 -143
  28. package/src/rule-creation/index.d.ts +2 -0
  29. package/src/rule-creation/index.js +1 -26
  30. package/src/rule-creation/mass-assignment-rule.js +1 -121
  31. package/src/rule-creation/message-source.d.ts +95 -0
  32. package/src/rule-creation/message-source.js +1 -0
  33. package/src/rule-creation/mock-context.js +1 -39
  34. package/src/rule-creation/raw-identifier-rule.js +1 -140
  35. package/src/rule-creation/require-tls-rule.js +1 -190
  36. package/src/rule-creation/rule-creator.js +1 -70
  37. package/src/rule-creation/sdk-api-key-rule.js +1 -121
  38. package/src/rule-creation/sql-injection-rule.js +1 -207
  39. package/src/rule-creation/system-prompt-injection-rule.d.ts +78 -0
  40. package/src/rule-creation/system-prompt-injection-rule.js +1 -0
  41. package/src/rule-creation/unscoped-mutation-rule.js +1 -234
  42. package/src/security/index.js +1 -17
  43. package/src/security/security-utils.js +1 -461
  44. package/src/types/index.js +1 -18
  45. package/src/types/meta-augmentation.js +1 -2
  46. package/src/types/type-utils.js +1 -222
@@ -1,740 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.PERFORMANCE_DOCS = void 0;
4
- exports.createLRUCache = createLRUCache;
5
- exports.isDefinitelyExternal = isDefinitelyExternal;
6
- exports.createFileSystemCache = createFileSystemCache;
7
- exports.clearCache = clearCache;
8
- exports.invalidateSCCCache = invalidateSCCCache;
9
- exports.getFileHash = getFileHash;
10
- exports.isCacheValid = isCacheValid;
11
- exports.fileExists = fileExists;
12
- exports.patternToRegexWithCache = patternToRegexWithCache;
13
- exports.shouldIgnoreFileWithCache = shouldIgnoreFileWithCache;
14
- exports.resolveImportPath = resolveImportPath;
15
- exports.getFileImports = getFileImports;
16
- exports.hasOnlyTypeImports = hasOnlyTypeImports;
17
- exports.computeSCCsFromFile = computeSCCsFromFile;
18
- exports.isFileInCycle = isFileInCycle;
19
- exports.findShortestCyclePath = findShortestCyclePath;
20
- exports.getCycleForFile = getCycleForFile;
21
- exports.detectCycleFromImport = detectCycleFromImport;
22
- exports.findAllCircularDependencies = findAllCircularDependencies;
23
- exports.getMinimalCycle = getMinimalCycle;
24
- exports.getCycleHash = getCycleHash;
25
- exports.saveCacheToDisk = saveCacheToDisk;
26
- exports.loadCacheFromDisk = loadCacheFromDisk;
27
- exports.getFilesNeedingReanalysis = getFilesNeedingReanalysis;
28
- exports.isIncrementalAvailable = isIncrementalAvailable;
29
- const resolver_1 = require("./resolver");
30
- const node_fs_1 = require("node:fs");
31
- const fs_1 = require("../node/fs");
32
- const path_1 = require("../node/path");
33
- const LRU_MAX_SIZE = 50_000;
34
- const EXTERNAL_MODULE_PATTERNS = [
35
- /^node:/,
36
- /^[a-z@][^/]*$/,
37
- /node_modules/,
38
- ];
39
- const KNOWN_EXTERNAL_PACKAGES = new Set([
40
- 'react',
41
- 'react-dom',
42
- 'vue',
43
- 'angular',
44
- 'svelte',
45
- 'lodash',
46
- 'underscore',
47
- 'ramda',
48
- 'rxjs',
49
- 'express',
50
- 'koa',
51
- 'fastify',
52
- 'hapi',
53
- 'axios',
54
- 'fetch',
55
- 'node-fetch',
56
- 'got',
57
- 'fs',
58
- 'path',
59
- 'url',
60
- 'http',
61
- 'https',
62
- 'crypto',
63
- 'util',
64
- 'os',
65
- 'child_process',
66
- 'typescript',
67
- 'eslint',
68
- 'prettier',
69
- 'jest',
70
- 'vitest',
71
- 'mocha',
72
- 'webpack',
73
- 'rollup',
74
- 'vite',
75
- 'esbuild',
76
- 'parcel',
77
- ]);
78
- const IMPORT_REGEX = /import\s+(?:[\w*{}\s,]+\s+from\s+)?['"]([^'"]+)['"]/g;
79
- const DYNAMIC_IMPORT_REGEX = /import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
80
- const TYPE_IMPORT_REGEX = /import\s+type\s/;
81
- const EXPORT_FROM_REGEX = /export\s+\{[\s\S]*?\}\s+from\s+['"]([^'"]+)['"]/g;
82
- const DEFAULT_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];
83
- class LRUCache {
84
- cache = new Map();
85
- maxSize;
86
- constructor(maxSize = LRU_MAX_SIZE) {
87
- this.maxSize = maxSize;
88
- }
89
- get(key) {
90
- const value = this.cache.get(key);
91
- if (value !== undefined) {
92
- this.cache.delete(key);
93
- this.cache.set(key, value);
94
- }
95
- return value;
96
- }
97
- set(key, value) {
98
- if (this.cache.has(key)) {
99
- this.cache.delete(key);
100
- }
101
- else if (this.cache.size >= this.maxSize) {
102
- const firstKey = this.cache.keys().next().value;
103
- if (firstKey !== undefined) {
104
- this.cache.delete(firstKey);
105
- }
106
- }
107
- this.cache.set(key, value);
108
- }
109
- has(key) {
110
- return this.cache.has(key);
111
- }
112
- delete(key) {
113
- return this.cache.delete(key);
114
- }
115
- clear() {
116
- this.cache.clear();
117
- }
118
- get size() {
119
- return this.cache.size;
120
- }
121
- }
122
- function createLRUCache(maxSize = LRU_MAX_SIZE) {
123
- return new LRUCache(maxSize);
124
- }
125
- function isDefinitelyExternal(importPath) {
126
- const packageName = importPath.split('/')[0].replace(/^@[^/]+\//, '');
127
- if (KNOWN_EXTERNAL_PACKAGES.has(packageName)) {
128
- return true;
129
- }
130
- return EXTERNAL_MODULE_PATTERNS.some((pattern) => pattern.test(importPath));
131
- }
132
- function createFileSystemCache() {
133
- return {
134
- dependencies: new Map(),
135
- fileExists: new Map(),
136
- fileHashes: new Map(),
137
- compiledPatterns: (0, path_1.createPatternCache)(),
138
- reportedCycles: new Set(),
139
- sccIndex: new Map(),
140
- sccs: [],
141
- sccComputed: false,
142
- graphHash: '',
143
- resolvedPaths: new Map(),
144
- nonCyclicFiles: new Set(),
145
- pendingCycleReports: new Map(),
146
- };
147
- }
148
- function clearCache(cache) {
149
- cache.dependencies.clear();
150
- cache.fileExists.clear();
151
- cache.fileHashes.clear();
152
- cache.compiledPatterns.clear();
153
- cache.reportedCycles.clear();
154
- cache.sccIndex.clear();
155
- cache.sccs = [];
156
- cache.sccComputed = false;
157
- cache.graphHash = '';
158
- cache.resolvedPaths = new Map();
159
- cache.nonCyclicFiles.clear();
160
- cache.pendingCycleReports.clear();
161
- }
162
- function invalidateSCCCache(cache) {
163
- cache.sccIndex.clear();
164
- cache.sccs = [];
165
- cache.sccComputed = false;
166
- cache.nonCyclicFiles.clear();
167
- }
168
- function getFileHash(filePath) {
169
- const stats = (0, fs_1.statSync)(filePath);
170
- if (!stats) {
171
- return null;
172
- }
173
- return `${stats.mtimeMs}-${stats.size}`;
174
- }
175
- function isCacheValid(filePath, cache) {
176
- const cachedHash = cache.fileHashes.get(filePath);
177
- if (!cachedHash)
178
- return false;
179
- const currentHash = getFileHash(filePath);
180
- return cachedHash === currentHash;
181
- }
182
- function fileExists(filePath, cache) {
183
- const cached = cache.fileExists.get(filePath);
184
- if (cached !== undefined) {
185
- return cached;
186
- }
187
- const exists = (0, fs_1.fileExistsSync)(filePath);
188
- cache.fileExists.set(filePath, exists);
189
- return exists;
190
- }
191
- function patternToRegexWithCache(pattern, cache) {
192
- return (0, path_1.patternToRegex)(pattern, cache.compiledPatterns);
193
- }
194
- function shouldIgnoreFileWithCache(file, patterns, cache) {
195
- return (0, path_1.shouldIgnoreFile)(file, patterns, cache.compiledPatterns);
196
- }
197
- function resolveImportPath(importPath, options) {
198
- const fromFile = options.fromFile;
199
- const extensions = options.extensions || DEFAULT_EXTENSIONS;
200
- const cache = options.cache;
201
- const resolverSettings = options.resolverSettings;
202
- if (isDefinitelyExternal(importPath)) {
203
- if (!importPath.startsWith('@')) {
204
- return null;
205
- }
206
- }
207
- const isRelative = importPath.startsWith('.');
208
- if (!isRelative) {
209
- const globalCached = cache.resolvedPaths.get(importPath);
210
- if (globalCached !== undefined) {
211
- return globalCached;
212
- }
213
- }
214
- const cacheKey = isRelative ? `${fromFile}::${importPath}` : importPath;
215
- const cached = cache.resolvedPaths.get(cacheKey);
216
- if (cached !== undefined) {
217
- return cached;
218
- }
219
- let result = (0, resolver_1.resolveModule)(importPath, fromFile, {
220
- extensions,
221
- mainFields: ['module', 'main'],
222
- resolverSettings,
223
- });
224
- if (result && !isRelative && result.includes('node_modules')) {
225
- try {
226
- const realPath = (0, node_fs_1.realpathSync)(result);
227
- if (realPath.includes('node_modules')) {
228
- cache.resolvedPaths.set(cacheKey, null);
229
- return null;
230
- }
231
- result = realPath;
232
- }
233
- catch {
234
- cache.resolvedPaths.set(cacheKey, null);
235
- return null;
236
- }
237
- }
238
- if (!result && isRelative) {
239
- result = (0, path_1.resolvePath)((0, path_1.getDirname)(fromFile), importPath);
240
- }
241
- cache.resolvedPaths.set(cacheKey, result);
242
- return result;
243
- }
244
- function getFileImports(file, options) {
245
- const { workspaceRoot, barrelExports, cache, resolverSettings } = options;
246
- const cached = cache.dependencies.get(file);
247
- if (cached) {
248
- return cached;
249
- }
250
- const imports = [];
251
- try {
252
- if (!fileExists(file, cache)) {
253
- return imports;
254
- }
255
- const content = (0, fs_1.readFileSync)(file, 'utf-8');
256
- if (content === null) {
257
- return imports;
258
- }
259
- const resolveOpts = {
260
- fromFile: file,
261
- workspaceRoot,
262
- barrelExports,
263
- cache,
264
- extensions: DEFAULT_EXTENSIONS,
265
- resolverSettings,
266
- };
267
- IMPORT_REGEX.lastIndex = 0;
268
- DYNAMIC_IMPORT_REGEX.lastIndex = 0;
269
- EXPORT_FROM_REGEX.lastIndex = 0;
270
- let match;
271
- const seen = new Set();
272
- const pushImport = (importPath, dynamic = false, typeOnly = false) => {
273
- const resolved = resolveImportPath(importPath, resolveOpts);
274
- if (resolved && fileExists(resolved, cache) && !seen.has(resolved)) {
275
- seen.add(resolved);
276
- const info = { path: resolved, source: importPath };
277
- if (dynamic)
278
- info.dynamic = true;
279
- if (typeOnly)
280
- info.typeOnly = true;
281
- imports.push(info);
282
- }
283
- };
284
- while ((match = IMPORT_REGEX.exec(content)) !== null) {
285
- const isTypeImport = /^import\s+type[\s{]/.test(match[0]);
286
- pushImport(match[1], false, isTypeImport);
287
- }
288
- while ((match = EXPORT_FROM_REGEX.exec(content)) !== null)
289
- pushImport(match[1]);
290
- while ((match = DYNAMIC_IMPORT_REGEX.exec(content)) !== null)
291
- pushImport(match[1], true);
292
- const hash = getFileHash(file);
293
- if (hash) {
294
- const oldHash = cache.fileHashes.get(file);
295
- if (oldHash !== hash) {
296
- invalidateSCCCache(cache);
297
- }
298
- cache.fileHashes.set(file, hash);
299
- }
300
- }
301
- catch {
302
- }
303
- cache.dependencies.set(file, imports);
304
- return imports;
305
- }
306
- function hasOnlyTypeImports(cycle, cache) {
307
- for (const file of cycle) {
308
- if (!fileExists(file, cache))
309
- continue;
310
- const content = (0, fs_1.readFileSync)(file, 'utf-8');
311
- if (content === null)
312
- return false;
313
- const hasRuntimeImport = !TYPE_IMPORT_REGEX.test(content) && IMPORT_REGEX.test(content);
314
- IMPORT_REGEX.lastIndex = 0;
315
- if (hasRuntimeImport) {
316
- return false;
317
- }
318
- }
319
- return true;
320
- }
321
- function computeSCCsFromFile(startFile, options) {
322
- try {
323
- startFile = (0, node_fs_1.realpathSync)(startFile);
324
- }
325
- catch { }
326
- const { workspaceRoot, barrelExports, cache, resolverSettings } = options;
327
- if (cache.sccComputed && cache.sccs.length > 0 && cache.sccIndex.has(startFile)) {
328
- return cache.sccs;
329
- }
330
- const state = {
331
- index: 0,
332
- stack: [],
333
- onStack: new Set(),
334
- indices: new Map(),
335
- lowlinks: new Map(),
336
- sccs: [],
337
- };
338
- const visited = new Set();
339
- const filesToProcess = [startFile];
340
- while (filesToProcess.length > 0) {
341
- const file = filesToProcess.pop();
342
- if (visited.has(file))
343
- continue;
344
- visited.add(file);
345
- const imports = getFileImports(file, {
346
- workspaceRoot,
347
- barrelExports,
348
- cache,
349
- resolverSettings,
350
- });
351
- for (const imp of imports) {
352
- if (!imp.dynamic && !imp.typeOnly && !visited.has(imp.path)) {
353
- filesToProcess.push(imp.path);
354
- }
355
- }
356
- }
357
- for (const file of visited) {
358
- if (!state.indices.has(file)) {
359
- tarjanStrongConnect(file, state, options, 0);
360
- }
361
- }
362
- const newResults = state.sccs.map((files) => ({
363
- files,
364
- hasCycle: files.length > 1,
365
- }));
366
- const offset = cache.sccs.length;
367
- cache.sccs.push(...newResults);
368
- cache.sccComputed = true;
369
- for (let i = 0; i < newResults.length; i++) {
370
- for (const file of newResults[i].files) {
371
- if (!cache.sccIndex.has(file)) {
372
- cache.sccIndex.set(file, offset + i);
373
- }
374
- }
375
- }
376
- for (const result of newResults) {
377
- if (result.hasCycle) {
378
- for (const file of result.files) {
379
- cache.nonCyclicFiles.delete(file);
380
- }
381
- }
382
- else {
383
- for (const file of result.files) {
384
- cache.nonCyclicFiles.add(file);
385
- }
386
- }
387
- }
388
- return cache.sccs;
389
- }
390
- function tarjanStrongConnect(file, state, options, depth) {
391
- const { maxDepth, workspaceRoot, barrelExports, cache, resolverSettings } = options;
392
- if (depth > maxDepth) {
393
- return;
394
- }
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
- }
433
- continue;
434
- }
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));
451
- }
452
- }
453
- }
454
- function isFileInCycle(file, cache) {
455
- const sccIndex = cache.sccIndex.get(file);
456
- if (sccIndex === undefined)
457
- return false;
458
- const scc = cache.sccs[sccIndex];
459
- return scc && scc.hasCycle;
460
- }
461
- function findShortestCyclePath(sourceFile, targetFile, options) {
462
- const { workspaceRoot, barrelExports, cache, resolverSettings } = options;
463
- const srcSCC = cache.sccIndex.get(sourceFile);
464
- if (srcSCC === undefined)
465
- return null;
466
- const queue = [[targetFile]];
467
- const visited = new Set([targetFile]);
468
- while (queue.length > 0) {
469
- const path = queue.shift();
470
- const current = path[path.length - 1];
471
- const imports = getFileImports(current, {
472
- workspaceRoot,
473
- barrelExports,
474
- cache,
475
- resolverSettings,
476
- });
477
- for (const imp of imports) {
478
- if (imp.dynamic || imp.typeOnly)
479
- continue;
480
- if (imp.path === sourceFile) {
481
- return [...path, sourceFile];
482
- }
483
- if (visited.has(imp.path))
484
- continue;
485
- if (cache.sccIndex.get(imp.path) !== srcSCC)
486
- continue;
487
- visited.add(imp.path);
488
- queue.push([...path, imp.path]);
489
- }
490
- }
491
- return null;
492
- }
493
- function getCycleForFile(file, cache) {
494
- const sccIndex = cache.sccIndex.get(file);
495
- if (sccIndex === undefined)
496
- return null;
497
- const scc = cache.sccs[sccIndex];
498
- if (!scc || !scc.hasCycle)
499
- return null;
500
- return scc.files;
501
- }
502
- function detectCycleFromImport(sourceFile, targetFile, options) {
503
- try {
504
- sourceFile = (0, node_fs_1.realpathSync)(sourceFile);
505
- }
506
- catch { }
507
- try {
508
- targetFile = (0, node_fs_1.realpathSync)(targetFile);
509
- }
510
- catch { }
511
- const { maxDepth, reportAllCycles, workspaceRoot, barrelExports, cache, resolverSettings, } = options;
512
- if (cache.nonCyclicFiles.has(targetFile)) {
513
- return [];
514
- }
515
- const allCycles = [];
516
- const pathStack = [sourceFile];
517
- let depthLimitHit = false;
518
- function dfs(file, depth, visited) {
519
- if (file === sourceFile) {
520
- allCycles.push([...pathStack, file]);
521
- return;
522
- }
523
- if (depth >= maxDepth) {
524
- depthLimitHit = true;
525
- return;
526
- }
527
- if (visited.has(file))
528
- return;
529
- if (cache.nonCyclicFiles.has(file))
530
- return;
531
- visited.add(file);
532
- pathStack.push(file);
533
- const imports = getFileImports(file, {
534
- workspaceRoot,
535
- barrelExports,
536
- cache,
537
- resolverSettings,
538
- });
539
- for (const imp of imports) {
540
- if (imp.dynamic)
541
- continue;
542
- if (!reportAllCycles && allCycles.length > 0)
543
- break;
544
- dfs(imp.path, depth + 1, visited);
545
- }
546
- pathStack.pop();
547
- }
548
- const visited = new Set();
549
- dfs(targetFile, 1, visited);
550
- if (allCycles.length === 0 && !depthLimitHit) {
551
- cache.nonCyclicFiles.add(targetFile);
552
- }
553
- return allCycles;
554
- }
555
- function findAllCircularDependencies(file, options, currentPath = [], depth = 0, visited = new Set()) {
556
- const { maxDepth, reportAllCycles, workspaceRoot, barrelExports, cache, resolverSettings, } = options;
557
- if (depth === 0) {
558
- try {
559
- file = (0, node_fs_1.realpathSync)(file);
560
- }
561
- catch { }
562
- }
563
- if (cache.nonCyclicFiles.has(file)) {
564
- return [];
565
- }
566
- if (depth === 0) {
567
- computeSCCsFromFile(file, {
568
- maxDepth,
569
- workspaceRoot,
570
- barrelExports,
571
- cache,
572
- resolverSettings,
573
- });
574
- if (!isFileInCycle(file, cache)) {
575
- cache.nonCyclicFiles.add(file);
576
- return [];
577
- }
578
- }
579
- if (depth > maxDepth) {
580
- return [];
581
- }
582
- if (currentPath.includes(file)) {
583
- return [[...currentPath, file]];
584
- }
585
- if (visited.has(file)) {
586
- return [];
587
- }
588
- visited.add(file);
589
- const imports = getFileImports(file, {
590
- workspaceRoot,
591
- barrelExports,
592
- cache,
593
- resolverSettings,
594
- });
595
- const newPath = [...currentPath, file];
596
- const allCycles = [];
597
- for (const imp of imports) {
598
- if (imp.dynamic) {
599
- continue;
600
- }
601
- if (!reportAllCycles && allCycles.length > 0) {
602
- break;
603
- }
604
- const cycles = findAllCircularDependencies(imp.path, options, newPath, depth + 1, visited);
605
- allCycles.push(...cycles);
606
- }
607
- if (depth === 0 && allCycles.length === 0) {
608
- cache.nonCyclicFiles.add(file);
609
- }
610
- return allCycles;
611
- }
612
- function getMinimalCycle(cycle) {
613
- if (cycle.length < 2)
614
- return cycle;
615
- const seen = new Map();
616
- for (let i = 0; i < cycle.length; i++) {
617
- const file = cycle[i];
618
- if (seen.has(file)) {
619
- const cycleStart = seen?.get?.(file);
620
- return cycle.slice(cycleStart, i + 1);
621
- }
622
- seen.set(file, i);
623
- }
624
- return cycle;
625
- }
626
- function getCycleHash(cycle) {
627
- const minimalCycle = getMinimalCycle(cycle);
628
- const minIndex = minimalCycle.indexOf(minimalCycle.reduce((min, curr) => (curr < min ? curr : min), minimalCycle[0]));
629
- const normalized = [
630
- ...minimalCycle.slice(minIndex),
631
- ...minimalCycle.slice(0, minIndex),
632
- ];
633
- return normalized.join('->');
634
- }
635
- const CACHE_VERSION = 1;
636
- const DEFAULT_CACHE_FILE = 'node_modules/.cache/forge-eslint/cycles.json';
637
- const DEFAULT_MAX_CACHE_AGE = 24 * 60 * 60 * 1000;
638
- function saveCacheToDisk(cache, options, workspaceRoot) {
639
- if (!options.enabled)
640
- return;
641
- const cacheFile = (0, path_1.resolvePath)(workspaceRoot, options.cacheFile || DEFAULT_CACHE_FILE);
642
- const data = {
643
- version: CACHE_VERSION,
644
- createdAt: Date.now(),
645
- fileHashes: Object.fromEntries(cache.fileHashes),
646
- sccs: cache.sccs,
647
- sccIndex: Object.fromEntries(cache.sccIndex),
648
- nonCyclicFiles: Array.from(cache.nonCyclicFiles),
649
- graphHash: cache.graphHash,
650
- };
651
- const cacheDir = (0, path_1.getDirname)(cacheFile);
652
- if (!(0, fs_1.fileExistsSync)(cacheDir)) {
653
- (0, fs_1.mkdirSync)(cacheDir, { recursive: true });
654
- }
655
- (0, fs_1.writeFileSync)(cacheFile, JSON.stringify(data), 'utf-8');
656
- }
657
- function loadCacheFromDisk(cache, options, workspaceRoot) {
658
- if (!options.enabled)
659
- return false;
660
- const cacheFile = (0, path_1.resolvePath)(workspaceRoot, options.cacheFile || DEFAULT_CACHE_FILE);
661
- if (!(0, fs_1.fileExistsSync)(cacheFile)) {
662
- return false;
663
- }
664
- const content = (0, fs_1.readFileSync)(cacheFile, 'utf-8');
665
- if (content === null) {
666
- return false;
667
- }
668
- try {
669
- const data = JSON.parse(content);
670
- if (data.version !== CACHE_VERSION) {
671
- return false;
672
- }
673
- const maxAge = options.maxCacheAge ?? DEFAULT_MAX_CACHE_AGE;
674
- if (Date.now() - data.createdAt > maxAge) {
675
- return false;
676
- }
677
- cache.fileHashes = new Map(Object.entries(data.fileHashes));
678
- cache.sccs = data.sccs;
679
- cache.sccIndex = new Map(Object.entries(data.sccIndex).map(([k, v]) => [k, v]));
680
- cache.nonCyclicFiles = new Set(data.nonCyclicFiles);
681
- cache.graphHash = data.graphHash;
682
- cache.sccComputed = true;
683
- return true;
684
- }
685
- catch {
686
- return false;
687
- }
688
- }
689
- function getFilesNeedingReanalysis(files, cache, options) {
690
- if (!options.enabled || !cache.sccComputed) {
691
- return files;
692
- }
693
- const changedFiles = [];
694
- for (const file of files) {
695
- const cachedHash = cache.fileHashes.get(file);
696
- const currentHash = getFileHash(file);
697
- if (!cachedHash || cachedHash !== currentHash) {
698
- changedFiles.push(file);
699
- }
700
- }
701
- if (changedFiles.length > 0) {
702
- const affectedSCCIndices = new Set();
703
- for (const file of changedFiles) {
704
- const sccIndex = cache.sccIndex.get(file);
705
- if (sccIndex !== undefined) {
706
- affectedSCCIndices.add(sccIndex);
707
- }
708
- }
709
- const affectedFiles = new Set(changedFiles);
710
- for (const scc of cache.sccs) {
711
- const sccIndex = cache.sccIndex.get(scc.files[0]);
712
- if (sccIndex !== undefined && affectedSCCIndices.has(sccIndex)) {
713
- for (const file of scc.files) {
714
- affectedFiles.add(file);
715
- cache.nonCyclicFiles.delete(file);
716
- }
717
- }
718
- }
719
- for (const [file, imports] of cache.dependencies) {
720
- for (const imp of imports) {
721
- if (changedFiles.includes(imp.path)) {
722
- affectedFiles.add(file);
723
- cache.nonCyclicFiles.delete(file);
724
- break;
725
- }
726
- }
727
- }
728
- return Array.from(affectedFiles);
729
- }
730
- return [];
731
- }
732
- function isIncrementalAvailable(cache, options) {
733
- return Boolean(options?.enabled && cache.sccComputed && cache.sccs.length > 0);
734
- }
735
- exports.PERFORMANCE_DOCS = {
736
- algorithm: 'Tarjan SCC + DFS hybrid',
737
- timeComplexity: 'O(V + E)',
738
- spaceComplexity: 'O(V)',
739
- guaranteedComplete: true,
740
- };
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.PERFORMANCE_DOCS=void 0;exports.createLRUCache=createLRUCache;exports.isDefinitelyExternal=isDefinitelyExternal;exports.createFileSystemCache=createFileSystemCache;exports.clearCache=clearCache;exports.invalidateSCCCache=invalidateSCCCache;exports.getFileHash=getFileHash;exports.isCacheValid=isCacheValid;exports.fileExists=fileExists;exports.patternToRegexWithCache=patternToRegexWithCache;exports.shouldIgnoreFileWithCache=shouldIgnoreFileWithCache;exports.resolveImportPath=resolveImportPath;exports.getFileImports=getFileImports;exports.hasOnlyTypeImports=hasOnlyTypeImports;exports.computeSCCsFromFile=computeSCCsFromFile;exports.isFileInCycle=isFileInCycle;exports.findShortestCyclePath=findShortestCyclePath;exports.getCycleForFile=getCycleForFile;exports.detectCycleFromImport=detectCycleFromImport;exports.findAllCircularDependencies=findAllCircularDependencies;exports.getMinimalCycle=getMinimalCycle;exports.getCycleHash=getCycleHash;exports.saveCacheToDisk=saveCacheToDisk;exports.loadCacheFromDisk=loadCacheFromDisk;exports.getFilesNeedingReanalysis=getFilesNeedingReanalysis;exports.isIncrementalAvailable=isIncrementalAvailable;const resolver_1=require("./resolver");const node_fs_1=require("node:fs");const fs_1=require("../node/fs");const path_1=require("../node/path");const LRU_MAX_SIZE=5e4;const EXTERNAL_MODULE_PATTERNS=[/^node:/,/^[a-z@][^/]*$/,/node_modules/];const KNOWN_EXTERNAL_PACKAGES=new Set(["react","react-dom","vue","angular","svelte","lodash","underscore","ramda","rxjs","express","koa","fastify","hapi","axios","fetch","node-fetch","got","fs","path","url","http","https","crypto","util","os","child_process","typescript","eslint","prettier","jest","vitest","mocha","webpack","rollup","vite","esbuild","parcel"]);const IMPORT_REGEX=/import\s+(?:[\w*{}\s,]+\s+from\s+)?['"]([^'"]+)['"]/g;const DYNAMIC_IMPORT_REGEX=/import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;const TYPE_IMPORT_REGEX=/import\s+type\s/;const EXPORT_FROM_REGEX=/export\s+\{[\s\S]*?\}\s+from\s+['"]([^'"]+)['"]/g;const DEFAULT_EXTENSIONS=[".ts",".tsx",".js",".jsx"];class LRUCache{cache=new Map;maxSize;constructor(maxSize=LRU_MAX_SIZE){this.maxSize=maxSize}get(key){const value=this.cache.get(key);if(value!==void 0){this.cache.delete(key);this.cache.set(key,value)}return value}set(key,value){if(this.cache.has(key)){this.cache.delete(key)}else if(this.cache.size>=this.maxSize){const firstKey=this.cache.keys().next().value;if(firstKey!==void 0){this.cache.delete(firstKey)}}this.cache.set(key,value)}has(key){return this.cache.has(key)}delete(key){return this.cache.delete(key)}clear(){this.cache.clear()}get size(){return this.cache.size}}function createLRUCache(maxSize=LRU_MAX_SIZE){return new LRUCache(maxSize)}function isDefinitelyExternal(importPath){const packageName=importPath.split("/")[0].replace(/^@[^/]+\//,"");if(KNOWN_EXTERNAL_PACKAGES.has(packageName)){return true}return EXTERNAL_MODULE_PATTERNS.some(pattern=>pattern.test(importPath))}function createFileSystemCache(){return{dependencies:new Map,fileExists:new Map,fileHashes:new Map,compiledPatterns:(0,path_1.createPatternCache)(),reportedCycles:new Set,sccIndex:new Map,sccs:[],sccComputed:false,graphHash:"",resolvedPaths:new Map,nonCyclicFiles:new Set,pendingCycleReports:new Map}}function clearCache(cache){cache.dependencies.clear();cache.fileExists.clear();cache.fileHashes.clear();cache.compiledPatterns.clear();cache.reportedCycles.clear();cache.sccIndex.clear();cache.sccs=[];cache.sccComputed=false;cache.graphHash="";cache.resolvedPaths=new Map;cache.nonCyclicFiles.clear();cache.pendingCycleReports.clear()}function invalidateSCCCache(cache){cache.sccIndex.clear();cache.sccs=[];cache.sccComputed=false;cache.nonCyclicFiles.clear()}function getFileHash(filePath){const stats=(0,fs_1.statSync)(filePath);if(!stats){return null}return`${stats.mtimeMs}-${stats.size}`}function isCacheValid(filePath,cache){const cachedHash=cache.fileHashes.get(filePath);if(!cachedHash)return false;const currentHash=getFileHash(filePath);return cachedHash===currentHash}function fileExists(filePath,cache){const cached=cache.fileExists.get(filePath);if(cached!==void 0){return cached}const exists=(0,fs_1.fileExistsSync)(filePath);cache.fileExists.set(filePath,exists);return exists}function patternToRegexWithCache(pattern,cache){return(0,path_1.patternToRegex)(pattern,cache.compiledPatterns)}function shouldIgnoreFileWithCache(file,patterns,cache){return(0,path_1.shouldIgnoreFile)(file,patterns,cache.compiledPatterns)}function resolveImportPath(importPath,options){const fromFile=options.fromFile;const extensions=options.extensions||DEFAULT_EXTENSIONS;const cache=options.cache;const resolverSettings=options.resolverSettings;if(isDefinitelyExternal(importPath)){if(!importPath.startsWith("@")){return null}}const isRelative=importPath.startsWith(".");if(!isRelative){const globalCached=cache.resolvedPaths.get(importPath);if(globalCached!==void 0){return globalCached}}const cacheKey=isRelative?`${fromFile}::${importPath}`:importPath;const cached=cache.resolvedPaths.get(cacheKey);if(cached!==void 0){return cached}let result=(0,resolver_1.resolveModule)(importPath,fromFile,{extensions,mainFields:["module","main"],resolverSettings});if(result&&!isRelative&&result.includes("node_modules")){try{const realPath=(0,node_fs_1.realpathSync)(result);if(realPath.includes("node_modules")){cache.resolvedPaths.set(cacheKey,null);return null}result=realPath}catch{cache.resolvedPaths.set(cacheKey,null);return null}}if(!result&&isRelative){result=(0,path_1.resolvePath)((0,path_1.getDirname)(fromFile),importPath)}cache.resolvedPaths.set(cacheKey,result);return result}function getFileImports(file,options){const{workspaceRoot,barrelExports,cache,resolverSettings}=options;const cached=cache.dependencies.get(file);if(cached){return cached}const imports=[];try{if(!fileExists(file,cache)){return imports}const content=(0,fs_1.readFileSync)(file,"utf-8");if(content===null){return imports}const resolveOpts={fromFile:file,workspaceRoot,barrelExports,cache,extensions:DEFAULT_EXTENSIONS,resolverSettings};IMPORT_REGEX.lastIndex=0;DYNAMIC_IMPORT_REGEX.lastIndex=0;EXPORT_FROM_REGEX.lastIndex=0;let match;const seen=new Set;const pushImport=(importPath,dynamic=false,typeOnly=false)=>{const resolved=resolveImportPath(importPath,resolveOpts);if(resolved&&fileExists(resolved,cache)&&!seen.has(resolved)){seen.add(resolved);const info={path:resolved,source:importPath};if(dynamic)info.dynamic=true;if(typeOnly)info.typeOnly=true;imports.push(info)}};while((match=IMPORT_REGEX.exec(content))!==null){const isTypeImport=/^import\s+type[\s{]/.test(match[0]);pushImport(match[1],false,isTypeImport)}while((match=EXPORT_FROM_REGEX.exec(content))!==null)pushImport(match[1]);while((match=DYNAMIC_IMPORT_REGEX.exec(content))!==null)pushImport(match[1],true);const hash=getFileHash(file);if(hash){const oldHash=cache.fileHashes.get(file);if(oldHash!==hash){invalidateSCCCache(cache)}cache.fileHashes.set(file,hash)}}catch{}cache.dependencies.set(file,imports);return imports}function hasOnlyTypeImports(cycle,cache){for(const file of cycle){if(!fileExists(file,cache))continue;const content=(0,fs_1.readFileSync)(file,"utf-8");if(content===null)return false;const hasRuntimeImport=!TYPE_IMPORT_REGEX.test(content)&&IMPORT_REGEX.test(content);IMPORT_REGEX.lastIndex=0;if(hasRuntimeImport){return false}}return true}function computeSCCsFromFile(startFile,options){try{startFile=(0,node_fs_1.realpathSync)(startFile)}catch{}const{workspaceRoot,barrelExports,cache,resolverSettings}=options;if(cache.sccComputed&&cache.sccs.length>0&&cache.sccIndex.has(startFile)){return cache.sccs}const state={index:0,stack:[],onStack:new Set,indices:new Map,lowlinks:new Map,sccs:[]};const visited=new Set;const filesToProcess=[startFile];while(filesToProcess.length>0){const file=filesToProcess.pop();if(visited.has(file))continue;visited.add(file);const imports=getFileImports(file,{workspaceRoot,barrelExports,cache,resolverSettings});for(const imp of imports){if(!imp.dynamic&&!imp.typeOnly&&!visited.has(imp.path)){filesToProcess.push(imp.path)}}}for(const file of visited){if(!state.indices.has(file)){tarjanStrongConnect(file,state,options,0)}}const newResults=state.sccs.map(files=>({files,hasCycle:files.length>1}));const offset=cache.sccs.length;cache.sccs.push(...newResults);cache.sccComputed=true;for(let i=0;i<newResults.length;i++){for(const file of newResults[i].files){if(!cache.sccIndex.has(file)){cache.sccIndex.set(file,offset+i)}}}for(const result of newResults){if(result.hasCycle){for(const file of result.files){cache.nonCyclicFiles.delete(file)}}else{for(const file of result.files){cache.nonCyclicFiles.add(file)}}}return cache.sccs}function tarjanStrongConnect(file,state,options,depth){const{maxDepth,workspaceRoot,barrelExports,cache,resolverSettings}=options;if(depth>maxDepth){return}const enter=(node,nodeDepth)=>{state.indices.set(node,state.index);state.lowlinks.set(node,state.index);state.index++;state.stack.push(node);state.onStack.add(node);const imports=getFileImports(node,{workspaceRoot,barrelExports,cache,resolverSettings});const successors=[];for(const imp of imports){if(imp.dynamic||imp.typeOnly)continue;successors.push(imp.path)}return{file:node,depth:nodeDepth,successors,next:0}};const relax=(node,candidate)=>{state.lowlinks.set(node,Math.min(state.lowlinks.get(node),candidate))};const frames=[enter(file,depth)];while(frames.length>0){const frame=frames[frames.length-1];if(frame.next<frame.successors.length){const successor=frame.successors[frame.next++];if(!state.indices.has(successor)){if(frame.depth+1>maxDepth){relax(frame.file,0);continue}frames.push(enter(successor,frame.depth+1))}else if(state.onStack.has(successor)){relax(frame.file,state.indices.get(successor))}continue}frames.pop();const lowlink=state.lowlinks.get(frame.file);const index=state.indices.get(frame.file);if(lowlink===index){const scc=[];let w;do{w=state.stack.pop();state.onStack.delete(w);scc.push(w)}while(w!==frame.file);state.sccs.push(scc)}const parent=frames[frames.length-1];if(parent){relax(parent.file,state.lowlinks.get(frame.file))}}}function isFileInCycle(file,cache){const sccIndex=cache.sccIndex.get(file);if(sccIndex===void 0)return false;const scc=cache.sccs[sccIndex];return scc&&scc.hasCycle}function findShortestCyclePath(sourceFile,targetFile,options){const{workspaceRoot,barrelExports,cache,resolverSettings}=options;const srcSCC=cache.sccIndex.get(sourceFile);if(srcSCC===void 0)return null;const queue=[[targetFile]];const visited=new Set([targetFile]);while(queue.length>0){const path=queue.shift();const current=path[path.length-1];const imports=getFileImports(current,{workspaceRoot,barrelExports,cache,resolverSettings});for(const imp of imports){if(imp.dynamic||imp.typeOnly)continue;if(imp.path===sourceFile){return[...path,sourceFile]}if(visited.has(imp.path))continue;if(cache.sccIndex.get(imp.path)!==srcSCC)continue;visited.add(imp.path);queue.push([...path,imp.path])}}return null}function getCycleForFile(file,cache){const sccIndex=cache.sccIndex.get(file);if(sccIndex===void 0)return null;const scc=cache.sccs[sccIndex];if(!scc||!scc.hasCycle)return null;return scc.files}function detectCycleFromImport(sourceFile,targetFile,options){try{sourceFile=(0,node_fs_1.realpathSync)(sourceFile)}catch{}try{targetFile=(0,node_fs_1.realpathSync)(targetFile)}catch{}const{maxDepth,reportAllCycles,workspaceRoot,barrelExports,cache,resolverSettings}=options;if(cache.nonCyclicFiles.has(targetFile)){return[]}const allCycles=[];const pathStack=[sourceFile];let depthLimitHit=false;function dfs(file,depth,visited2){if(file===sourceFile){allCycles.push([...pathStack,file]);return}if(depth>=maxDepth){depthLimitHit=true;return}if(visited2.has(file))return;if(cache.nonCyclicFiles.has(file))return;visited2.add(file);pathStack.push(file);const imports=getFileImports(file,{workspaceRoot,barrelExports,cache,resolverSettings});for(const imp of imports){if(imp.dynamic)continue;if(!reportAllCycles&&allCycles.length>0)break;dfs(imp.path,depth+1,visited2)}pathStack.pop()}const visited=new Set;dfs(targetFile,1,visited);if(allCycles.length===0&&!depthLimitHit){cache.nonCyclicFiles.add(targetFile)}return allCycles}function findAllCircularDependencies(file,options,currentPath=[],depth=0,visited=new Set){const{maxDepth,reportAllCycles,workspaceRoot,barrelExports,cache,resolverSettings}=options;if(depth===0){try{file=(0,node_fs_1.realpathSync)(file)}catch{}}if(cache.nonCyclicFiles.has(file)){return[]}if(depth===0){computeSCCsFromFile(file,{maxDepth,workspaceRoot,barrelExports,cache,resolverSettings});if(!isFileInCycle(file,cache)){cache.nonCyclicFiles.add(file);return[]}}if(depth>maxDepth){return[]}if(currentPath.includes(file)){return[[...currentPath,file]]}if(visited.has(file)){return[]}visited.add(file);const imports=getFileImports(file,{workspaceRoot,barrelExports,cache,resolverSettings});const newPath=[...currentPath,file];const allCycles=[];for(const imp of imports){if(imp.dynamic){continue}if(!reportAllCycles&&allCycles.length>0){break}const cycles=findAllCircularDependencies(imp.path,options,newPath,depth+1,visited);allCycles.push(...cycles)}if(depth===0&&allCycles.length===0){cache.nonCyclicFiles.add(file)}return allCycles}function getMinimalCycle(cycle){if(cycle.length<2)return cycle;const seen=new Map;for(let i=0;i<cycle.length;i++){const file=cycle[i];if(seen.has(file)){const cycleStart=seen?.get?.(file);return cycle.slice(cycleStart,i+1)}seen.set(file,i)}return cycle}function getCycleHash(cycle){const minimalCycle=getMinimalCycle(cycle);const minIndex=minimalCycle.indexOf(minimalCycle.reduce((min,curr)=>curr<min?curr:min,minimalCycle[0]));const normalized=[...minimalCycle.slice(minIndex),...minimalCycle.slice(0,minIndex)];return normalized.join("->")}const CACHE_VERSION=1;const DEFAULT_CACHE_FILE="node_modules/.cache/forge-eslint/cycles.json";const DEFAULT_MAX_CACHE_AGE=24*60*60*1e3;function saveCacheToDisk(cache,options,workspaceRoot){if(!options.enabled)return;const cacheFile=(0,path_1.resolvePath)(workspaceRoot,options.cacheFile||DEFAULT_CACHE_FILE);const data={version:CACHE_VERSION,createdAt:Date.now(),fileHashes:Object.fromEntries(cache.fileHashes),sccs:cache.sccs,sccIndex:Object.fromEntries(cache.sccIndex),nonCyclicFiles:Array.from(cache.nonCyclicFiles),graphHash:cache.graphHash};const cacheDir=(0,path_1.getDirname)(cacheFile);if(!(0,fs_1.fileExistsSync)(cacheDir)){(0,fs_1.mkdirSync)(cacheDir,{recursive:true})}(0,fs_1.writeFileSync)(cacheFile,JSON.stringify(data),"utf-8")}function loadCacheFromDisk(cache,options,workspaceRoot){if(!options.enabled)return false;const cacheFile=(0,path_1.resolvePath)(workspaceRoot,options.cacheFile||DEFAULT_CACHE_FILE);if(!(0,fs_1.fileExistsSync)(cacheFile)){return false}const content=(0,fs_1.readFileSync)(cacheFile,"utf-8");if(content===null){return false}try{const data=JSON.parse(content);if(data.version!==CACHE_VERSION){return false}const maxAge=options.maxCacheAge??DEFAULT_MAX_CACHE_AGE;if(Date.now()-data.createdAt>maxAge){return false}cache.fileHashes=new Map(Object.entries(data.fileHashes));cache.sccs=data.sccs;cache.sccIndex=new Map(Object.entries(data.sccIndex).map(([k,v])=>[k,v]));cache.nonCyclicFiles=new Set(data.nonCyclicFiles);cache.graphHash=data.graphHash;cache.sccComputed=true;return true}catch{return false}}function getFilesNeedingReanalysis(files,cache,options){if(!options.enabled||!cache.sccComputed){return files}const changedFiles=[];for(const file of files){const cachedHash=cache.fileHashes.get(file);const currentHash=getFileHash(file);if(!cachedHash||cachedHash!==currentHash){changedFiles.push(file)}}if(changedFiles.length>0){const affectedSCCIndices=new Set;for(const file of changedFiles){const sccIndex=cache.sccIndex.get(file);if(sccIndex!==void 0){affectedSCCIndices.add(sccIndex)}}const affectedFiles=new Set(changedFiles);for(const scc of cache.sccs){const sccIndex=cache.sccIndex.get(scc.files[0]);if(sccIndex!==void 0&&affectedSCCIndices.has(sccIndex)){for(const file of scc.files){affectedFiles.add(file);cache.nonCyclicFiles.delete(file)}}}for(const[file,imports]of cache.dependencies){for(const imp of imports){if(changedFiles.includes(imp.path)){affectedFiles.add(file);cache.nonCyclicFiles.delete(file);break}}}return Array.from(affectedFiles)}return[]}function isIncrementalAvailable(cache,options){return Boolean(options?.enabled&&cache.sccComputed&&cache.sccs.length>0)}exports.PERFORMANCE_DOCS={algorithm:"Tarjan SCC + DFS hybrid",timeComplexity:"O(V + E)",spaceComplexity:"O(V)",guaranteedComplete:true};