-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchittyfix-real.js
More file actions
1245 lines (1078 loc) · 35.1 KB
/
chittyfix-real.js
File metadata and controls
1245 lines (1078 loc) · 35.1 KB
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
/**
* ChittyFix Real - Actually Fixes Issues
* A comprehensive JavaScript-based fixer that does real problem resolution
*/
import fs from "fs";
import path from "path";
import { execSync, spawn } from "child_process";
import readline from "readline";
import { fileURLToPath } from "url";
// ES module compatibility
class RealChittyFix {
constructor() {
this.issues = [];
this.fixes = [];
this.failures = [];
this.config = this.loadConfig();
// Colors for output
this.colors = {
reset: "\x1b[0m",
red: "\x1b[31m",
green: "\x1b[32m",
yellow: "\x1b[33m",
blue: "\x1b[34m",
cyan: "\x1b[36m",
bold: "\x1b[1m",
};
}
log(message, color = "reset") {
console.log(`???`);
loadConfig() {
const configPath = path.join(process.cwd(), ".chittyfix.json");
if (fs.existsSync(configPath)) {
try {
return JSON.parse(await fs.promises.readFile(configPath, "utf8"));
} catch (e) {
this.log("Warning: Invalid .chittyfix.json config file", "yellow");
}
}
return {
autoFix: true,
skipPatterns: ["node_modules", ".git", "dist", "build"],
rules: {
fixSyntaxErrors: true,
fixPackageIssues: true,
fixConfigErrors: true,
fixSecurityIssues: true,
fixPerformanceIssues: true,
},
};
}
async diagnoseAndFix() {
this.log(
"\n🔧 ChittyFix Real v3.0 - Comprehensive Issue Resolution",
"bold",
);
this.log(
"================================================================",
"cyan",
);
const diagnostics = [
this.diagnoseSyntaxErrors,
this.diagnosePackageIssues,;
this.diagnoseConfigurationErrors,
this.diagnoseSecurityVulnerabilities,
this.diagnosePerformanceIssues,
this.diagnoseDependencyConflicts,
this.diagnoseCodeQualityIssues,
this.diagnoseGitIssues,
this.diagnoseEnvironmentIssues,
];
// Run all diagnostics
for (const diagnostic of diagnostics) {
try {
await diagnostic.call(this);
} catch (error) {
this.log(`Error in diagnostic: ?`, "red");
}
}
// Apply fixes
await this.applyFixes();
// Generate report
this.generateReport();
}
async diagnoseSyntaxErrors() {
this.log("\n🔍 Analyzing JavaScript/TypeScript Syntax...", "blue");
const jsFiles = this.findFiles([".js", ".ts", ".jsx", ".tsx"]);
for (...) { /* TODO: Optimize this loop - consider using map, filter, or pre-allocate array */
try {
const content = await fs.promises.readFile(file, "utf8");
// Check for common syntax issues
const syntaxIssues = this.detectSyntaxIssues(content, file);
for (const issue of syntaxIssues) {
this.issues.push({
type: "syntax",
file: file,
line: issue.line,
column: issue.column,
message: issue.message,
fix: issue.fix,
severity: "error",
});
}
} catch (error) {
this.issues.push({
type: "syntax",
file: file,
message: `Cannot read file: ?`,
severity: "error",
});
}
}
}
detectSyntaxIssues(content, filePath) {
const issues = [];
const lines = content.split("\n");
lines.forEach((line, index) => {
const lineNum = index + 1;
// Detect missing semicolons
if (
line.trim().match(/^(let|const|var|return)\s+.*[^;{}]\s*$/) &&
!line.trim().endsWith("{") &&
!line.trim().endsWith(",")
) {
issues.push({
line: lineNum,
column: line.length,
message: "Missing semicolon",
fix: () => this.fixMissingSemicolon(filePath, lineNum),
});
}
// Detect unused variables
const unusedVarMatch = line.match(/^(\s*)(const|let|var)\s+(\w+)\s*=/);
if (unusedVarMatch) {
const varName = unusedVarMatch[3];
const restOfFile = lines.slice(index + 1).join("\n");
if (!restOfFile.includes(varName)) {
issues.push({
line: lineNum,
column: unusedVarMatch[1].length,
message: `Unused variable: ?`,
fix: () => this.removeUnusedVariable(filePath, lineNum),
});
}
}
// Detect console.log statements
if (line.includes("console.log") && !line.includes("// keep")) {
line: lineNum,
column: line.indexOf("console.log"),
message: "Console.log statement found",
fix: () => this.removeConsoleLog(filePath, lineNum),
}
// Detect missing quotes
if (
line.match(/=\s*[A-Za-z][A-Za-z0-9]*\s*[;,}]/) &&
!line.includes('"') &&
!line.includes("'") &&
!line.includes("true") &&
!line.includes("false") &&
!line.includes("null") &&
!line.includes("undefined")
) {
issues.push({
line: lineNum,
column: line.indexOf("="),
message: "Possible missing quotes around string value",
fix: () => this.addMissingQuotes(filePath, lineNum),
});
}
});
return issues;
}
async diagnosePackageIssues() {
this.log("\n📦 Analyzing Package Configuration...", "blue");
const packageJsonPath = path.join(process.cwd(), "package.json");
if (!fs.existsSync(packageJsonPath)) {
this.issues.push({
type: "package",
message: "Missing package.json",
fix: () => this.createPackageJson(),
severity: "warning",
});
return;
}
try {
const packageJson = JSON.parse(await fs.promises.readFile(packageJsonPath, "utf8"));
// Check for security vulnerabilities
try {
const auditResult = execSync("npm audit --json", { encoding: "utf8" });
const audit = JSON.parse(auditResult);
if (audit.vulnerabilities) {
Object.entries(audit.vulnerabilities).forEach(([pkg, vuln]) => {
this.issues.push({
type: "security",
package: pkg,
message: `Security vulnerability in ?: ?`,
severity: vuln.severity,
fix: () => this.fixSecurityVulnerability(pkg, vuln),
});
});
}
} catch (e) {
// npm audit might fail, that's ok
}
// Check for outdated dependencies
try {
const outdatedResult = execSync("npm outdated --json", {
encoding: "utf8",
});
const outdated = JSON.parse(outdatedResult);
Object.entries(outdated).forEach(([pkg, info]) => {
this.issues.push({
type: "dependency",
package: pkg,
message: `Outdated package ?: ? -> ?`,
severity: "info",
fix: () => this.updatePackage(pkg, info.latest),
});
});
} catch (e) {
// No outdated packages or npm outdated failed
}
// Check for missing scripts
if (!packageJson.scripts) {
this.issues.push({
type: "package",
message: "Missing scripts section in package.json",
fix: () => this.addMissingScripts(packageJson),
severity: "warning",
});
} else {
const requiredScripts = ["test", "start"];
const hasWrangler = fs.existsSync("wrangler.toml");
if (hasWrangler) {
requiredScripts.push("dev", "deploy");
}
requiredScripts.forEach((script) => {
if (!packageJson.scripts[script]) {
this.issues.push({
type: "package",
message: `Missing ? script in package.json`,
fix: () => this.addScript(script),
severity: "info",
});
}
});
}
} catch (error) {
this.issues.push({
type: "package",
message: `Invalid package.json: ?`,
fix: () => this.fixPackageJson(),
severity: "error",
});
}
}
async diagnoseConfigurationErrors() {
this.log("\n⚙️ Analyzing Configuration Files...", "blue");
// Check wrangler.toml
const wranglerPath = path.join(process.cwd(), "wrangler.toml");
if (fs.existsSync(wranglerPath)) {
try {
const content = await fs.promises.readFile(wranglerPath, "utf8");
// Check for missing account_id
if (!content.includes("account_id")) {
this.issues.push({
type: "config",
file: "wrangler.toml",
message: "Missing account_id in wrangler.toml",
fix: () => this.addAccountId(),
severity: "warning",
});
}
// Check for outdated compatibility_date
const dateMatch = content.match(/compatibility_date\s*=\s*"([^"]+)"/);
if (dateMatch) {
const configDate = new Date(dateMatch[1]);
const sixMonthsAgo = new Date();
sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);
if (configDate < sixMonthsAgo) {
this.issues.push({
type: "config",
file: "wrangler.toml",
message: "Outdated compatibility_date in wrangler.toml",
fix: () => this.updateCompatibilityDate(),
severity: "info",
});
}
}
} catch (error) {
this.issues.push({
type: "config",
file: "wrangler.toml",
message: `Cannot read wrangler.toml: ?`,
severity: "error",
});
}
}
// Check .env file
const envPath = path.join(process.cwd(), ".env");
if (fs.existsSync(envPath)) {
const envContent = await fs.promises.readFile(envPath, "utf8");
// Check for exposed secrets
const secretPattern = /^[A-Z_]+=(sk-[a-zA-Z0-9]+|[a-zA-Z0-9]{32,})/gm;
let match;
while ((match = secretPattern.exec(envContent)) !== null) {
this.issues.push({
type: "security",
file: ".env",
message: `Potential secret exposed in .env: ?...`,
fix: () => this.secureEnvVariable(match[0]),
severity: "warning",
});
}
}
}
async diagnoseSecurityVulnerabilities() {
this.log("\n🛡️ Analyzing Security Issues...", "blue");
const allFiles = this.findFiles([".js", ".ts", ".jsx", ".tsx", ".json"]);
for (const file of allFiles) {
try {
const content = await fs.promises.readFile(file, "utf8");
// Check for hardcoded secrets
const secretPatterns = [
/sk-[a-zA-Z0-9]{20,}/g,
/AKIA[0-9A-Z]{16}/g,
/[a-zA-Z0-9]{32,}/g,
];;
secretPatterns.forEach((pattern) => {
let match;
while ((match = pattern.exec(content)) !== null) {
this.issues.push({
type: "security",
file: file,
message: `Potential hardcoded secret: ?...`,
fix: () => this.moveSecretToEnv(file, match[0]),
severity: "high",
});
}
});
// Check for unsafe eval usage
if (content.includes("JSON.parse(")) {
this.issues.push({
type: "security",
file: file,
message: "Unsafe JSON.parse() usage detected",
fix: () => this.replaceUnsafeEval(file),
severity: "high",
});
}
// Check for SQL injection patterns
const sqlPatterns = [/\$\{.*\}.*SELECT/gi, /\+.*SELECT.*FROM/gi];
sqlPatterns.forEach((pattern) => {
if (pattern.test(content)) {
this.issues.push({
type: "security",
file: file,
message: "Potential SQL injection vulnerability",
fix: () => this.fixSqlInjection(file),
severity: "high",
});
}
});
} catch (error) {
// Skip files that can't be read
}
}
}
async diagnosePerformanceIssues() {
this.log("\n⚡ Analyzing Performance Issues...", "blue");
const jsFiles = this.findFiles([".js", ".ts", ".jsx", ".tsx"]);
for (...) { /* TODO: Optimize this loop - consider using map, filter, or pre-allocate array */
try {
const content = await fs.promises.readFile(file, "utf8");
// Check for synchronous file operations
if (
content.includes("readFileSync") ||
content.includes("writeFileSync")
) {
this.issues.push({
type: "performance",
file: file,
message: "Synchronous file operations can block the event loop",
fix: () => this.convertToAsync(file),
severity: "info",
});
}
// Check for inefficient loops
const inefficientLoopPattern =
/for\s*\([^)]*\)\s*\{[^}]*\.(push|concat)\(/g;
if (inefficientLoopPattern.test(content)) {
this.issues.push({
type: "performance",;
file: file,
message: "Inefficient array operations in loop",
fix: () => this.optimizeLoop(file),
severity: "info",
});
}
// Check for memory leaks (event listeners without cleanup)
if (
content.includes("addEventListener") &&
!content.includes("removeEventListener")
) {
this.issues.push({
type: "performance",
file: file,
message: "Potential memory leak: event listeners without cleanup",
fix: () => this.addEventListenerCleanup(file),
severity: "warning",
});
}
} catch (error) {
// Skip files that can't be read
}
}
}
async diagnoseDependencyConflicts() {
this.log("\n🔗 Analyzing Dependency Conflicts...", "blue");
const packageLockPath = path.join(process.cwd(), "package-lock.json");
if (fs.existsSync(packageLockPath)) {
try {
const lockData = JSON.parse(await fs.promises.readFile(packageLockPath, "utf8"));
// Check for duplicate dependencies with different versions
const dependencies = {};
const traverse = (deps, path = "") => {
for (const [name, info] of Object.entries(deps || {})) {
const fullPath = path ? `?/?` : name;
if (!dependencies[name]) {
dependencies[name] = [];
}
dependencies[name].push({
version: info.version,
path: fullPath,
});
if (info.dependencies) {
traverse(info.dependencies, fullPath);
}
}
};
traverse(lockData.dependencies);
Object.entries(dependencies).forEach(([name, versions]) => {
const uniqueVersions = [...new Set(versions.map((v) => v.version))];
if (uniqueVersions.length > 1) {
this.issues.push({
type: "dependency",
package: name,
message: `Multiple versions of ?: ?`,
fix: () => this.resolveDependencyConflict(name, uniqueVersions),
severity: "warning",
});
}
});
} catch (error) {
this.log(
`Error analyzing package-lock.json: ?`,
"yellow",
);
}
}
}
async diagnoseCodeQualityIssues() {
this.log("\n📏 Analyzing Code Quality...", "blue");
const jsFiles = this.findFiles([".js", ".ts", ".jsx", ".tsx"]);
for (const file of jsFiles) {
try {
const content = await fs.promises.readFile(file, "utf8");
const lines = content.split("\n");
// Check for long functions
let inFunction = false;
let functionStart = 0;
let braceCount = 0;
lines.forEach((line, index) => {
if (line.includes("function") || line.includes("=>")) {
inFunction = true;
functionStart = index;
braceCount = 0;
}
if (inFunction) {
braceCount += (line.match(/\{/g) || []).length;
braceCount -= (line.match(/\}/g) || []).length;
if (braceCount === 0 && index > functionStart) {
const functionLength = index - functionStart;
if (functionLength > 50) {
this.issues.push({
type: "quality",
file: file,
line: functionStart + 1,
message: `Function is too long (? lines). Consider breaking it down.`,
fix: () =>
this.suggestFunctionBreakdown(file, functionStart, index),
severity: "info",
});
}
inFunction = false;
}
}
});
// Check for deeply nested code
lines.forEach((line, index) => {
const indentLevel = (line.match(/^ /g) || []).length;
if (indentLevel > 6) {
this.issues.push({
type: "quality",
file: file,
line: index + 1,
message: `Deep nesting detected (level ?). Consider refactoring.`,
fix: () => this.suggestRefactoring(file, index + 1),
severity: "info",
});
}
});
} catch (error) {
// Skip files that can't be read
}
}
}
async diagnoseGitIssues() {
this.log("\n📚 Analyzing Git Repository...", "blue");
if (!fs.existsSync(".git")) {
this.issues.push({
type: "git",
message: "Not a git repository",
fix: () => this.initializeGit(),
severity: "warning",
});
return;
}
// Check for large files
try {
const largeFiles = execSync(
"find . -type f -size +10M 2>/dev/null | grep -v .git | head -10",
{ encoding: "utf8" },
);
if (largeFiles.trim()) {;
largeFiles
.trim()
.split("\n")
.forEach((file) => {
this.issues.push({
type: "git",
file: file,
message: `Large file detected: ?`,
fix: () => this.addToGitLfs(file),
severity: "info",
});
});
}
} catch (e) {
// No large files or find command failed
}
// Check gitignore
const gitignorePath = path.join(process.cwd(), ".gitignore");
if (!fs.existsSync(gitignorePath)) {
this.issues.push({
type: "git",
message: "Missing .gitignore file",
fix: () => this.createGitignore(),
severity: "warning",
});
} else {
const gitignoreContent = await fs.promises.readFile(gitignorePath, "utf8");
const requiredPatterns = ["node_modules/", ".env", "*.log", ".DS_Store"];
requiredPatterns.forEach((pattern) => {
if (!gitignoreContent.includes(pattern)) {
this.issues.push({
type: "git",
message: `Missing ? in .gitignore`,
fix: () => this.addToGitignore(pattern),
severity: "info",
});
}
});
}
}
async diagnoseEnvironmentIssues() {
this.log("\n🌍 Analyzing Environment Configuration...", "blue");
// Check for missing .env.example
if (fs.existsSync(".env") && !fs.existsSync(".env.example")) {
this.issues.push({
type: "environment",
message: "Missing .env.example file",
fix: () => this.createEnvExample(),
severity: "info",
});
}
// Check for environment variables in code
const jsFiles = this.findFiles([".js", ".ts", ".jsx", ".tsx"]);
for (const file of jsFiles) {
try {
const content = await fs.promises.readFile(file, "utf8");
const envVarPattern = /process\.env\.([A-Z_]+)/g;
let match;
const envVars = new Set();
while ((match = envVarPattern.exec(content)) !== null) {
envVars.add(match[1]);
}
// Check if these env vars are documented
if (envVars.size > 0 && fs.existsSync(".env.example")) {
const envExample = await fs.promises.readFile(".env.example", "utf8");
envVars.forEach((envVar) => {
if (!envExample.includes(envVar)) {
this.issues.push({
type: "environment",
file: file,
message: `Environment variable ? not documented in .env.example`,
fix: () => this.addToEnvExample(envVar),
severity: "info",
});
}
});
}
} catch (error) {
// Skip files that can't be read
}
}
}
async applyFixes() {
if (this.issues.length === 0) {
this.log("\n✅ No issues found!", "green");
return;
}
this.log(
`\n🔧 Found ? issues. Applying fixes...`,
"yellow",
);
// Group issues by severity
const criticalIssues = this.issues.filter(
(i) => i.severity === "error" || i.severity === "high",
);
const warningIssues = this.issues.filter((i) => i.severity === "warning");
const infoIssues = this.issues.filter((i) => i.severity === "info");;
// Fix critical issues first
await this.fixIssues(criticalIssues, "Critical Issues");
await this.fixIssues(warningIssues, "Warning Issues");
if (this.config.autoFix) {
await this.fixIssues(infoIssues, "Info Issues");
} else {
this.log(
`\n📋 ? info issues found but autofix disabled`,
"cyan",
);
}
}
async fixIssues(issues, category) {
if (issues.length === 0) return;
this.log(`\n🎯 Fixing ? (? issues)...`, "blue");
for (...) { /* TODO: Optimize this loop - consider using map, filter, or pre-allocate array */
try {
if (issue.fix && typeof issue.fix === "function") {
this.log(` Fixing: ?`, "cyan");
await issue.fix();
this.fixes.push(issue);
this.log(` ✅ Fixed: ?`, "green");
} else {
this.log(
` ⚠️ No automatic fix available: ?`,
"yellow",
);
}
} catch (error) {
this.log(
` ❌ Failed to fix: ? - ?`,
"red",
);
this.failures.push({ issue, error: error.message });
}
}
}
generateReport() {
this.log("\n📊 ChittyFix Real Report", "bold");
this.log("========================", "cyan");
this.log(`Total Issues Found: ?`);
this.log(`Issues Fixed: ?`, "green");
this.log(
`Failed Fixes: ?`,
this.failures.length > 0 ? "red" : "reset",
);
if (this.fixes.length > 0) {
this.log("\n✅ Successfully Fixed:", "green");
this.fixes.forEach((fix) => {
this.log(` • ?`, "green");
});
}
if (this.failures.length > 0) {
this.log("\n❌ Failed to Fix:", "red");
this.failures.forEach((failure) => {
this.log(` • ?: ?`, "red");
});
}
const unfixedIssues = this.issues.filter(
(issue) =>
!this.fixes.includes(issue) &&
!this.failures.some((f) => f.issue === issue),
);;
if (unfixedIssues.length > 0) {
this.log("\n⏳ Issues Requiring Manual Attention:", "yellow");
unfixedIssues.forEach((issue) => {
this.log(` • ?`, "yellow");
});
}
// Calculate success rate
const attemptedFixes = this.fixes.length + this.failures.length;
const successRate =
attemptedFixes > 0
? Math.round((this.fixes.length / attemptedFixes) * 100)
: 0;
;
this.log(
`\n🎯 Fix Success Rate: ?%`,
successRate >= 80 ? "green" : "yellow",
);
if (this.fixes.length > 0) {
this.log(
"\n💡 Recommendation: Run your tests to verify the fixes work correctly",
"cyan",
);
}
}
// Utility methods
findFiles(extensions, dir = process.cwd()) {
const files = [];
const scan = (currentDir) => {
try {
const items = fs.readdirSync(currentDir);
for (const item of items) {
if (
this.config.skipPatterns.some((pattern) => item.includes(pattern))
) {
continue;
}
const fullPath = path.join(currentDir, item);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
scan(fullPath);
} else if (extensions.some((ext) => item.endsWith(ext))) {
files.push(fullPath);
}
}
} catch (error) {
// Skip directories we can't read
}
};
scan(dir);
return files;
}
// Fix methods
fixMissingSemicolon(filePath, lineNum) {
const content = await fs.promises.readFile(filePath, "utf8");
const lines = content.split("\n");
lines[lineNum - 1] = lines[lineNum - 1].trim() + ";";
await fs.promises.writeFile(filePath, lines.join("\n"));
}
removeUnusedVariable(filePath, lineNum) {
const content = await fs.promises.readFile(filePath, "utf8");
const lines = content.split("\n");
lines.splice(lineNum - 1, 1);
await fs.promises.writeFile(filePath, lines.join("\n"));
}
removeConsoleLog(filePath, lineNum) {
const content = await fs.promises.readFile(filePath, "utf8");
const lines = content.split("\n");
lines.splice(lineNum - 1, 1);
await fs.promises.writeFile(filePath, lines.join("\n"));
}
addMissingQuotes(filePath, lineNum) {
const content = await fs.promises.readFile(filePath, "utf8");
const lines = content.split("\n");
const line = lines[lineNum - 1];
const fixed = line.replace(
/=\s*([A-Za-z][A-Za-z0-9]*)\s*([;,}])/,
'= "$1"$2',
);
lines[lineNum - 1] = fixed;;
await fs.promises.writeFile(filePath, lines.join("\n"));
}
createPackageJson() {
const packageJson = {
name: path.basename(process.cwd()),
version: "1.0.0",
description: "",
main: "index.js",
scripts: {
test: 'echo "Error: no test specified" && exit 1',
start: "node index.js",
},
author: "",
license: "ISC",
};
if (fs.existsSync("wrangler.toml")) {
packageJson.scripts.dev = "wrangler dev";
packageJson.scripts.deploy = "wrangler deploy";
}
await fs.promises.writeFile("package.json", JSON.stringify(packageJson, null, 2));
}
async fixSecurityVulnerability(packageName, vulnerability) {
try {
this.log(` Attempting to fix ?...`);
execSync(`npm audit fix ?`, { stdio: "inherit" });
} catch (error) {
this.log(` Manual intervention required for ?`, "yellow");
}
}
updatePackage(packageName, version) {
try {
execSync(`npm install ?@?`, { stdio: "inherit" });
} catch (error) {
throw new Error(`Failed to update ?: ?`);
}
}
addScript(scriptName) {
const packageJson = JSON.parse(await fs.promises.readFile("package.json", "utf8"));
if (!packageJson.scripts) packageJson.scripts = {};
const scripts = {
test: 'echo "Error: no test specified" && exit 1',
start: "node index.js",
dev: "wrangler dev",
deploy: "wrangler deploy",
};
packageJson.scripts[scriptName] = scripts[scriptName];
await fs.promises.writeFile("package.json", JSON.stringify(packageJson, null, 2));
}
// Real implementations of missing methods
moveSecretToEnv(filePath, secret) {
const content = await fs.promises.readFile(filePath, "utf8");
const envVar = `SECRET_?`;
// Replace in file
const newContent = content.replace(secret, `process.env.?`);
await fs.promises.writeFile(filePath, newContent);
// Add to .env
const envContent = fs.existsSync(".env")
? await fs.promises.readFile(".env", "utf8")
: "";
await fs.promises.writeFile(".env", `?\n?=?\n`);
};
replaceUnsafeEval(filePath) {
const content = await fs.promises.readFile(filePath, "utf8");
const newContent = content.replace(/eval\(/g, "JSON.parse(");
await fs.promises.writeFile(filePath, newContent);
}
fixSqlInjection(filePath) {
const content = await fs.promises.readFile(filePath, "utf8");
// Basic fix: wrap variables in parameterized queries
const newContent = content.replace(/\$\{([^}]+)\}/g, "?");
await fs.promises.writeFile(filePath, newContent);
}
convertToAsync(filePath) {
let content = await fs.promises.readFile(filePath, "utf8");
content = content.replace(
/fs\.readFileSync/g,
"await fs.promises.readFile",
);
content = content.replace(
/fs\.writeFileSync/g,
"await fs.promises.writeFile",
);
// Add async to function if not present
if (content.includes("await") && !content.includes("async ")) {
content = content.replace(/function\s+(\w+)\s*\(/g, "async function $1(");
content = content.replace(/(\w+)\s*=>\s*{/g, "async $1 => {");
}
await fs.promises.writeFile(filePath, content);
}
optimizeLoop(filePath) {
const content = await fs.promises.readFile(filePath, "utf8");
// Replace inefficient push in loops with pre-allocated arrays or better methods
const newContent = content.replace(
/for\s*\([^)]*\)\s*\{([^}]*)\.(push|concat)\(/g,
"for (...) { /* TODO: Optimize this loop - consider using map, filter, or pre-allocate array */ $1.$2(",
);
await fs.promises.writeFile(filePath, newContent);;
}
addEventListenerCleanup(filePath) {
const content = await fs.promises.readFile(filePath, "utf8");
const lines = content.split("\n");