-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
1364 lines (1218 loc) · 39.4 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/* eslint-disable unicorn/prefer-json-parse-buffer */
import { execSync, spawn } from 'node:child_process';
import { readdirSync, statSync } from 'node:fs';
import * as fs from 'node:fs/promises';
import path from 'node:path';
import { stdin as input, stdout as output } from 'node:process';
import * as readline from 'node:readline/promises';
import v8 from 'node:v8';
import { parse } from '@babel/parser';
import traverse from '@babel/traverse';
import type { NodePath } from '@babel/traverse';
import type {
ImportDeclaration,
CallExpression,
TSImportType,
TSExternalModuleReference,
} from '@babel/types';
import chalk from 'chalk';
import cliProgress from 'cli-progress';
import CliTable from 'cli-table3';
import { Command } from 'commander';
import { findUp } from 'find-up';
import { globby } from 'globby';
import { isBinaryFileSync } from 'isbinaryfile';
import micromatch from 'micromatch';
import ora from 'ora';
import type { Ora } from 'ora';
import shellEscape from 'shell-escape';
/*
* Essential packages that should never be removed automatically,
* unless the `-a, --aggressive` flag is used.
******************************************************************/
const PROTECTED_PACKAGES = new Set([
'typescript',
'@types/node',
'tslib',
'prettier',
'eslint',
]);
/******************************************************************/
// Common string literals
const CLI_STRINGS = {
PROGRESS_FORMAT:
'Analyzing dependencies |{bar}| {percentage}% | {value}/{total} Files',
BAR_COMPLETE: '\u2588',
BAR_INCOMPLETE: '\u2591',
CLI_NAME: 'depsweep',
CLI_VERSION: '1.0.0',
CLI_DESCRIPTION:
'CLI tool that identifies and removes unused npm dependencies',
EXAMPLE_TEXT: '\nExample:\n $ depsweep --verbose',
} as const;
const FILE_PATTERNS = {
PACKAGE_JSON: 'package.json',
YARN_LOCK: 'yarn.lock',
PNPM_LOCK: 'pnpm-lock.yaml',
NODE_MODULES: 'node_modules',
CONFIG_REGEX: /\.(config|rc)(\.|\b)/,
PACKAGE_NAME_REGEX: /^[\w./@-]+$/,
} as const;
const PACKAGE_MANAGERS = {
NPM: 'npm',
YARN: 'yarn',
PNPM: 'pnpm',
COMMANDS: {
INSTALL: 'install',
UNINSTALL: 'uninstall',
REMOVE: 'remove',
},
} as const;
const DEPENDENCY_PATTERNS = {
TYPES_PREFIX: '@types/',
DYNAMIC_IMPORT_BASE: String.raw`import\s*\(\s*['"]`,
DYNAMIC_IMPORT_END: String.raw`['"]\s*\)`,
} as const;
// Replace existing MESSAGES constant
const MESSAGES = {
title: 'DepSweep 🧹',
noPackageJson: 'No package.json found.',
monorepoDetected: '\nMonorepo detected. Using root package.json.',
monorepoWorkspaceDetected: '\nMonorepo workspace package detected.',
analyzingDependencies: 'Analyzing dependencies...',
fatalError: '\nFatal error:',
noUnusedDependencies: 'No unused dependencies found.',
unusedFound: 'Unused dependencies found:',
noChangesMade: '\nNo changes made',
promptRemove: '\nDo you want to remove these dependencies? (y/N) ',
dependenciesRemoved: 'Dependencies:',
diskSpace: 'Disk Space:',
carbonFootprint: 'Carbon Footprint:',
measuringInstallTime: 'Measuring installation...',
measureComplete: 'Measurement complete',
installTime: 'Total Install Time:',
analysisComplete: 'Analysis complete',
signalCleanup: '\n{0} received. Cleaning up...',
unexpected: '\nUnexpected error:',
} as const;
// Update interface for package.json structure
interface PackageJson {
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
peerDependencies?: Record<string, string>;
optionalDependencies?: Record<string, string>;
workspaces?: string[] | { packages: string[] };
scripts?: Record<string, string>;
}
// Add interface for dependency context
interface DependencyContext {
scripts?: Record<string, string>;
configs?: Record<string, any>;
}
// Add interface for workspace info
interface WorkspaceInfo {
root: string;
packages: string[];
}
const traverseFunction = ((traverse as any).default || traverse) as (
ast: any,
options: any,
) => void;
// Add raw content patterns
const RAW_CONTENT_PATTERNS = new Map([
['webpack', ['webpack.*', 'webpack-*']],
['babel', ['babel.*', '@babel/*']],
['eslint', ['eslint.*', '@eslint/*']],
['jest', ['jest.*', '@jest/*']],
['typescript', ['ts-*', '@typescript-*']],
['rollup', ['rollup.*', 'rollup-*']],
['esbuild', ['esbuild.*', '@esbuild/*']],
['vite', ['vite.*', '@vitejs/*']],
['next', ['next.*', '@next/*']],
['vue', ['vue.*', '@vue/*', '@nuxt/*']],
['react', ['react.*', '@types/react*']],
['svelte', ['svelte.*', '@sveltejs/*']],
]);
// Add workspace detection
async function getWorkspaceInfo(
packageJsonPath: string,
): Promise<WorkspaceInfo | undefined> {
try {
const content = await fs.readFile(packageJsonPath, 'utf8');
const package_ = JSON.parse(content);
if (!package_.workspaces) return undefined;
const patterns = Array.isArray(package_.workspaces)
? package_.workspaces
: package_.workspaces.packages || [];
const packagePaths = await globby(patterns, {
cwd: path.dirname(packageJsonPath),
onlyDirectories: true,
expandDirectories: false,
ignore: ['node_modules'],
});
return {
root: packageJsonPath,
packages: packagePaths,
};
} catch {
return undefined;
}
}
// Enhanced package.json finder with improved monorepo support
async function findClosestPackageJson(startDirectory: string): Promise<string> {
const packageJsonPath = await findUp(FILE_PATTERNS.PACKAGE_JSON, {
cwd: startDirectory,
});
if (!packageJsonPath) {
console.error(chalk.red(MESSAGES.noPackageJson));
process.exit(1);
}
// Check if this is part of a monorepo
let currentDirectory = path.dirname(packageJsonPath);
while (true) {
const parentDirectory = path.dirname(currentDirectory);
if (parentDirectory === currentDirectory) {
break;
}
const potentialRootPackageJson = path.join(
parentDirectory,
FILE_PATTERNS.PACKAGE_JSON,
);
try {
const rootPackageString = await fs.readFile(
potentialRootPackageJson,
'utf8',
);
const rootPackage = JSON.parse(rootPackageString);
if (rootPackage.workspaces) {
console.log(chalk.yellow(MESSAGES.monorepoDetected));
return potentialRootPackageJson;
}
} catch {
// No package.json found at this level
}
const workspaceInfo = await getWorkspaceInfo(potentialRootPackageJson);
if (workspaceInfo) {
const relativePath = path.relative(
path.dirname(workspaceInfo.root),
packageJsonPath,
);
const isWorkspacePackage = workspaceInfo.packages.some(
(p) => relativePath.startsWith(p) || p.startsWith(relativePath),
);
if (isWorkspacePackage) {
console.log(chalk.yellow('\nMonorepo workspace package detected.'));
console.log(chalk.yellow(`Root: ${workspaceInfo.root}`));
return packageJsonPath; // Analyze the workspace package
}
}
currentDirectory = parentDirectory;
}
return packageJsonPath;
}
// Function to read dependencies from package.json
async function getDependencies(packageJsonPath: string): Promise<string[]> {
const packageJsonString =
(await fs.readFile(packageJsonPath, 'utf8')) || '{}';
const packageJson = JSON.parse(packageJsonString);
const dependencies = packageJson.dependencies
? Object.keys(packageJson.dependencies)
: [];
const devDependencies = packageJson.devDependencies
? Object.keys(packageJson.devDependencies)
: [];
const peerDependencies = packageJson.peerDependencies
? Object.keys(packageJson.peerDependencies)
: [];
const optionalDependencies = packageJson.optionalDependencies
? Object.keys(packageJson.optionalDependencies)
: [];
return [
...dependencies,
...devDependencies,
...peerDependencies,
...optionalDependencies,
];
}
// Add these helper functions
function isConfigFile(filePath: string): boolean {
const filename = path.basename(filePath).toLowerCase();
return (
filename.includes('config') ||
filename.startsWith('.') ||
filename === FILE_PATTERNS.PACKAGE_JSON ||
FILE_PATTERNS.CONFIG_REGEX.test(filename)
);
}
async function parseConfigFile(filePath: string): Promise<unknown> {
const extension = path.extname(filePath).toLowerCase();
const content = await fs.readFile(filePath, 'utf8');
try {
switch (extension) {
case '.json': {
return JSON.parse(content);
}
case '.yaml':
case '.yml': {
const yaml = await import('yaml').catch(() => null);
return yaml ? yaml.parse(content) : content;
}
case '.js':
case '.cjs':
case '.mjs': {
// For JS files, return the raw content as we can't safely eval
return content;
}
default: {
// For unknown extensions, try JSON parse first, then return raw content
try {
return JSON.parse(content);
} catch {
return content;
}
}
}
} catch {
// If parsing fails, return the raw content
return content;
}
}
// Update getSourceFiles function
async function getSourceFiles(
projectDirectory: string,
ignorePatterns: string[] = [],
): Promise<string[]> {
const files = await globby(['**/*'], {
cwd: projectDirectory,
gitignore: true,
ignore: [
FILE_PATTERNS.NODE_MODULES,
'dist',
'coverage',
'build',
'.git',
'*.log',
'*.lock',
...ignorePatterns,
],
absolute: true,
});
// Filter out binary files and return
return files.filter((file) => !isBinaryFileSync(file));
}
// Update getPackageContext function
async function getPackageContext(
packageJsonPath: string,
): Promise<DependencyContext> {
const projectDirectory = path.dirname(packageJsonPath);
const configs: Record<string, any> = {};
// Read all files in the project
const allFiles = await getSourceFiles(projectDirectory);
// Process config files
for (const file of allFiles) {
if (isConfigFile(file)) {
const relativePath = path.relative(projectDirectory, file);
try {
configs[relativePath] = await parseConfigFile(file);
} catch {
// Ignore parse errors
}
}
}
// Get package.json content
const packageJsonString =
(await fs.readFile(packageJsonPath, 'utf8')) || '{}';
const packageJson = JSON.parse(packageJsonString) as PackageJson & {
eslintConfig?: { extends?: string | string[] };
prettier?: unknown;
stylelint?: { extends?: string | string[] };
};
return {
scripts: packageJson.scripts,
configs: {
'package.json': packageJson,
...configs,
},
};
}
// Add a helper function to check if a type package corresponds to an installed package
async function isTypePackageUsed(
dependency: string,
installedPackages: string[],
unusedDependencies: string[],
context: DependencyContext,
sourceFiles: string[],
): Promise<{ isUsed: boolean; supportedPackage?: string }> {
if (!dependency.startsWith(DEPENDENCY_PATTERNS.TYPES_PREFIX)) {
return { isUsed: false };
}
// Handle special case for @types/babel__* packages etc
const correspondingPackage = dependency
.replace(/^@types\//, '')
.replaceAll('__', '/');
// For scoped packages, add the @ prefix back
const normalizedPackage = correspondingPackage.includes('/')
? `@${correspondingPackage}`
: correspondingPackage;
const supportedPackage = installedPackages.find(
(package_) => package_ === normalizedPackage,
);
if (supportedPackage) {
// Check if the corresponding package is used in the source files
for (const file of sourceFiles) {
if (await isDependencyUsedInFile(supportedPackage, file, context)) {
return { isUsed: true, supportedPackage };
}
}
}
// Check if any installed package has this type package as a peer dependency
for (const package_ of installedPackages) {
try {
const packageJsonPath = require.resolve(`${package_}/package.json`, {
paths: [process.cwd()],
});
const packageJsonBuffer = await fs.readFile(packageJsonPath, 'utf8');
const packageJson = JSON.parse(packageJsonBuffer);
if (packageJson.peerDependencies?.[dependency]) {
return { isUsed: true, supportedPackage: package_ };
}
} catch {
// Ignore errors
}
}
return { isUsed: false };
}
// Add helper function to recursively scan objects for dependency usage
// Add dependency pattern helpers
interface DependencyPattern {
type: 'exact' | 'prefix' | 'suffix' | 'combined' | 'regex';
match: string | RegExp;
variations?: string[];
}
const COMMON_PATTERNS: DependencyPattern[] = [
// Direct matches
{ type: 'exact', match: '' }, // Base name
{ type: 'prefix', match: '@' }, // Scoped packages
// Common package organization patterns
{ type: 'prefix', match: '@types/' },
{ type: 'prefix', match: '@storybook/' },
{ type: 'prefix', match: '@testing-library/' },
// Config patterns
{
type: 'suffix',
match: 'config',
variations: ['rc', 'settings', 'configuration', 'setup', 'options'],
},
// Plugin patterns
{
type: 'suffix',
match: 'plugin',
variations: ['plugins', 'extension', 'extensions', 'addon', 'addons'],
},
// Preset patterns
{
type: 'suffix',
match: 'preset',
variations: ['presets', 'recommended', 'standard', 'defaults'],
},
// Tool patterns
{
type: 'combined',
match: '',
variations: ['cli', 'core', 'utils', 'tools', 'helper', 'helpers'],
},
// Framework integration patterns
{
type: 'regex',
match: /[/-](react|vue|svelte|angular|node)$/i,
},
// Common package naming patterns
{
type: 'regex',
match: /[/-](loader|parser|transformer|formatter|linter|compiler)s?$/i,
},
];
function generatePatternMatcher(dependency: string): RegExp[] {
const patterns: RegExp[] = [];
const escapedDep = dependency.replaceAll(
/[$()*+.?[\\\]^{|}]/g,
String.raw`\$&`,
);
for (const pattern of COMMON_PATTERNS) {
switch (pattern.type) {
case 'exact': {
patterns.push(new RegExp(`^${escapedDep}$`));
break;
}
case 'prefix': {
patterns.push(new RegExp(`^${pattern.match}${escapedDep}(/.*)?$`));
break;
}
case 'suffix': {
const suffixes = [pattern.match, ...(pattern.variations || [])];
for (const suffix of suffixes) {
patterns.push(
new RegExp(`^${escapedDep}[-./]${suffix}$`),
new RegExp(`^${escapedDep}[-./]${suffix}s$`),
);
}
break;
}
case 'combined': {
const parts = [pattern.match, ...(pattern.variations || [])];
for (const part of parts) {
patterns.push(
new RegExp(`^${escapedDep}[-./]${part}$`),
new RegExp(`^${part}[-./]${escapedDep}$`),
);
}
break;
}
case 'regex': {
if (pattern.match instanceof RegExp) {
patterns.push(
new RegExp(
`^${escapedDep}${pattern.match.source}`,
pattern.match.flags,
),
);
}
break;
}
}
}
return patterns;
}
// Replace the old scanForDependency function
function scanForDependency(object: unknown, dependency: string): boolean {
if (typeof object === 'string') {
const matchers = generatePatternMatcher(dependency);
return matchers.some((pattern) => pattern.test(object));
}
if (Array.isArray(object)) {
return object.some((item) => scanForDependency(item, dependency));
}
if (object && typeof object === 'object') {
return Object.values(object).some((value) =>
scanForDependency(value, dependency),
);
}
return false;
}
async function isDependencyUsedInFile(
dependency: string,
filePath: string,
context: DependencyContext,
): Promise<boolean> {
// For package.json, do a deep scan of all configurations
if (
path.basename(filePath) === FILE_PATTERNS.PACKAGE_JSON &&
context.configs?.['package.json'] && // Deep scan all of package.json content
scanForDependency(context.configs['package.json'], dependency)
) {
return true;
}
// Check if the file is a config file we've parsed
const configKey = path.relative(path.dirname(filePath), filePath);
const config = context.configs?.[configKey];
if (config) {
if (typeof config === 'string') {
// If the config is a string, treat it as raw content
if (config.includes(dependency)) {
return true;
}
} else if (scanForDependency(config, dependency)) {
return true;
}
}
// Check scripts for exact matches
if (context.scripts) {
for (const script of Object.values(context.scripts)) {
const scriptParts = script.split(' ');
if (scriptParts.includes(dependency)) {
return true;
}
}
}
// Check file imports
try {
if (isBinaryFileSync(filePath)) {
return false;
}
const content = await fs.readFile(filePath, 'utf8');
// Check for dynamic imports in raw content
const dynamicImportRegex = new RegExp(
`${DEPENDENCY_PATTERNS.DYNAMIC_IMPORT_BASE}${dependency.replaceAll(/[/@-]/g, '[/@-]')}${DEPENDENCY_PATTERNS.DYNAMIC_IMPORT_END}`,
'i',
);
if (dynamicImportRegex.test(content)) {
return true;
}
// AST parsing for imports/requires
try {
const ast = parse(content, {
sourceType: 'unambiguous',
plugins: [
'typescript',
'jsx',
'decorators-legacy',
'classProperties',
'dynamicImport',
'exportDefaultFrom',
'exportNamespaceFrom',
'importMeta',
],
});
let isUsed = false;
traverseFunction(ast, {
ImportDeclaration(importPath: NodePath<ImportDeclaration>) {
const importSource = importPath.node.source.value;
if (matchesDependency(importSource, dependency)) {
isUsed = true;
importPath.stop();
}
},
CallExpression(importPath: NodePath<CallExpression>) {
if (
importPath.node.callee.type === 'Identifier' &&
importPath.node.callee.name === 'require' &&
importPath.node.arguments[0]?.type === 'StringLiteral' &&
matchesDependency(importPath.node.arguments[0].value, dependency)
) {
isUsed = true;
importPath.stop();
}
},
// Add handlers for TypeScript type-only imports
TSImportType(importPath: NodePath<TSImportType>) {
const importSource = importPath.node.argument.value;
if (matchesDependency(importSource, dependency)) {
isUsed = true;
importPath.stop();
}
},
TSExternalModuleReference(
importPath: NodePath<TSExternalModuleReference>,
) {
const importSource = importPath.node.expression.value;
if (matchesDependency(importSource, dependency)) {
isUsed = true;
importPath.stop();
}
},
});
if (isUsed) return true;
// Only check raw patterns if not found in imports
for (const [base, patterns] of RAW_CONTENT_PATTERNS.entries()) {
if (
dependency.startsWith(base) &&
patterns.some((pattern) => micromatch.isMatch(dependency, pattern))
) {
const searchPattern = new RegExp(
`\\b${dependency.replaceAll(/[/@-]/g, '[/@-]')}\\b`,
'i',
);
if (searchPattern.test(content)) {
return true;
}
}
}
} catch {
// Ignore parse errors
}
// Only check raw patterns if not found in imports
for (const [base, patterns] of RAW_CONTENT_PATTERNS.entries()) {
if (
dependency.startsWith(base) &&
patterns.some((pattern) => micromatch.isMatch(dependency, pattern))
) {
const searchPattern = new RegExp(
`\\b${dependency.replaceAll(/[/@-]/g, '[/@-]')}\\b`,
'i',
);
if (searchPattern.test(content)) {
return true;
}
}
}
} catch {
// Ignore file read errors
}
return false;
}
// Add a helper function to match dependencies
function matchesDependency(importSource: string, dependency: string): boolean {
const depWithoutScope = dependency.startsWith('@')
? dependency.split('/')[1]
: dependency;
const sourceWithoutScope = importSource.startsWith('@')
? importSource.split('/')[1]
: importSource;
return (
importSource === dependency ||
importSource.startsWith(`${dependency}/`) ||
sourceWithoutScope === depWithoutScope ||
sourceWithoutScope.startsWith(`${depWithoutScope}/`) ||
(dependency.startsWith('@types/') &&
(importSource === dependency.replace(/^@types\//, '') ||
importSource.startsWith(`${dependency.replace(/^@types\//, '')}/`)))
);
}
// Add memory check function
function getMemoryUsage(): { used: number; total: number } {
const heapStats = v8.getHeapStatistics();
return {
used: heapStats.used_heap_size,
total: heapStats.heap_size_limit,
};
}
function processResults(
batchResults: PromiseSettledResult<{
result: string | null;
hasError: boolean;
}>[],
): { validResults: string[]; errors: number } {
const validResults: string[] = [];
let errors = 0;
for (const result of batchResults) {
if (result.status === 'fulfilled') {
if (result.value.hasError) {
errors++;
} else if (result.value.result) {
validResults.push(result.value.result);
}
}
}
return { validResults, errors };
}
// Enhanced parallel processing with memory management
async function processFilesInParallel(
files: string[],
dependency: string,
context: DependencyContext,
onProgress?: (processed: number, total: number) => void,
): Promise<string[]> {
const { total: maxMemory } = getMemoryUsage();
const BATCH_SIZE = Math.min(
100,
Math.max(10, Math.floor(maxMemory / (1024 * 1024 * 50))),
);
const results: string[] = [];
let totalErrors = 0;
const processFile = async (
file: string,
): Promise<{ result: string | null; hasError: boolean }> => {
try {
const used = await isDependencyUsedInFile(dependency, file, context);
return { result: used ? file : null, hasError: false };
} catch (error) {
console.error(
chalk.red(`Error processing ${file}: ${(error as Error).message}`),
);
return { result: null, hasError: true };
}
};
for (let index = 0; index < files.length; index += BATCH_SIZE) {
const batch = files.slice(index, index + BATCH_SIZE);
const batchResults = await Promise.allSettled(
batch.map(async (file) => processFile(file)),
);
const { validResults, errors } = processResults(batchResults);
results.push(...validResults);
totalErrors += errors;
onProgress?.(Math.min(index + BATCH_SIZE, files.length), files.length);
}
if (totalErrors > 0) {
console.warn(
chalk.yellow(`\nWarning: ${totalErrors} files had processing errors`),
);
}
return results;
}
// Add function to detect the package manager
async function detectPackageManager(projectDirectory: string): Promise<string> {
if (
await fs
.access(path.join(projectDirectory, FILE_PATTERNS.YARN_LOCK))
.then(() => true)
.catch(() => false)
) {
return PACKAGE_MANAGERS.YARN;
} else if (
await fs
.access(path.join(projectDirectory, FILE_PATTERNS.PNPM_LOCK))
.then(() => true)
.catch(() => false)
) {
return PACKAGE_MANAGERS.PNPM;
}
return PACKAGE_MANAGERS.NPM;
}
// Add these variables before the main function
let activeSpinner: Ora | null = null;
let activeProgressBar: cliProgress.SingleBar | null = null;
let activeReadline: readline.Interface | null = null;
// Add this function before the main function
function cleanup(): void {
if (activeSpinner) {
activeSpinner.stop();
}
if (activeProgressBar) {
activeProgressBar.stop();
}
if (activeReadline) {
activeReadline.close();
}
// Only exit if not in test environment
if (process.env.NODE_ENV !== 'test') {
process.exit(0);
}
}
// Add a helper function to fetch package size from npm
async function getPackageSizeFromNpm(
packageName: string,
): Promise<number | null> {
try {
// Minimal approach: fetch from npm registry
const response = await fetch(`https://registry.npmjs.org/${packageName}`);
if (!response.ok) {
return null;
}
const data = await response.json();
// Some packages store metadata in "dist.unpackedSize" for the latest version
const versions = (data as { versions: Record<string, any> }).versions || {};
if (typeof data === 'object' && data !== null && 'dist-tags' in data) {
const latest = (data as { 'dist-tags': { latest: string } })['dist-tags']
?.latest;
if (latest && versions[latest]?.dist?.unpackedSize) {
return versions[latest].dist.unpackedSize;
}
}
return null;
} catch {
return null;
}
}
// Measure install time by running a subprocess
async function measureInstallTime(package_: string): Promise<number> {
if (!isValidPackageName(package_)) {
throw new Error(`Invalid package name: ${package_}`);
}
const start = Date.now();
await new Promise<void>((resolve, reject) => {
const child = spawn('npm', ['install', package_], {
stdio: 'ignore',
cwd: process.cwd(),
timeout: 300_000,
});
child.on('error', reject);
child.on('close', (code) => {
if (code === 0) resolve();
else reject(new Error(`Install process exited with code ${code}.`));
});
});
return (Date.now() - start) / 1000;
}
// Add this validation function
function isValidPackageName(name: string): boolean {
return FILE_PATTERNS.PACKAGE_NAME_REGEX.test(name);
}
// Recursively compute dir size for accurate disk usage stats
function getDirectorySize(dir: string): number {
let total = 0;
const files = readdirSync(dir, { withFileTypes: true });
for (const f of files) {
const fullPath = path.join(dir, f.name);
total += f.isDirectory()
? getDirectorySize(fullPath)
: statSync(fullPath).size;
}
return total;
}
// Add a helper function to format bytes into human-readable strings
function formatSize(bytes: number): string {
if (bytes >= 1e9) {
return `${(bytes / 1e9).toFixed(2)} GB`;
} else if (bytes >= 1e6) {
return `${(bytes / 1e6).toFixed(2)} MB`;
} else if (bytes >= 1e3) {
return `${(bytes / 1e3).toFixed(2)} KB`;
}
return `${bytes} Bytes`;
}
// Add this validation at the top with other constants
const VALID_PACKAGE_MANAGERS = new Set(['npm', 'yarn', 'pnpm']);
// Add safe execution wrapper
function safeExecSync(
command: string[],
options: {
cwd: string;
stdio?: 'inherit' | 'ignore';
timeout?: number;
},
): void {
if (!Array.isArray(command) || command.length === 0) {
throw new Error('Invalid command array');
}
const [packageManager, ...arguments_] = command;
if (!VALID_PACKAGE_MANAGERS.has(packageManager)) {
throw new Error(`Invalid package manager: ${packageManager}`);
}
// Validate all arguments
if (
!arguments_.every(
(argument) => typeof argument === 'string' && argument.length > 0,
)
) {
throw new Error('Invalid command arguments');
}
try {
execSync(shellEscape(command), {
stdio: options.stdio || 'inherit',
cwd: options.cwd,
timeout: options.timeout ?? 300_000,
encoding: 'utf8',
});
} catch (error) {
throw new Error(`Command execution failed: ${(error as Error).message}`);
}
}
// Main execution
async function main(): Promise<void> {
try {
// Add signal handlers at the start of main
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
const program = new Command();
// Configure program output and prevent exit
program.configureOutput({
writeOut: (string_) => process.stdout.write(string_),
writeErr: (string_) => process.stdout.write(string_),
});
program.exitOverride();
// Configure the CLI program
program
.name(CLI_STRINGS.CLI_NAME)
.usage('[options]')
.version(CLI_STRINGS.CLI_VERSION)