-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
6033 lines (5301 loc) · 211 KB
/
Copy pathcli.js
File metadata and controls
6033 lines (5301 loc) · 211 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
/**
* NeuroLint CLI - Main Entry Point
*
* Copyright (c) 2025 NeuroLint
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const fs = require('fs').promises;
const path = require('path');
const ora = require('./simple-ora');
const { performance } = require('perf_hooks');
const https = require('https');
const { execSync } = require('child_process');
// Import shared core and existing modules
const sharedCore = require('./shared-core');
const fixMaster = require('./fix-master.js');
const TransformationValidator = require('./validator.js');
const BackupManager = require('./backup-manager');
const { ProductionBackupManager } = require('./backup-manager-production');
const {
CVE_2025_55182,
isVulnerableReactVersion,
getPatchedReactVersion,
isVulnerableNextVersion,
getPatchedNextVersion,
formatPatchedVersionsList
} = require('./shared-core/security-constants');
// Backup Manager Factory
function createBackupManager(options = {}) {
const useProduction = options.production ||
process.env.NEUROLINT_PRODUCTION === 'true' ||
process.env.NODE_ENV === 'production';
if (useProduction) {
return new ProductionBackupManager({
backupDir: options.backupDir || '.neurolint-backups',
maxBackups: options.maxBackups || 50,
environment: process.env.NODE_ENV || 'production',
loggerConfig: {
enableConsole: options.verbose || false,
enableFile: true,
logLevel: options.verbose ? 'DEBUG' : 'INFO'
},
...options
});
} else {
return new BackupManager({
backupDir: options.backupDir || '.neurolint-backups',
maxBackups: options.maxBackups || 10,
...options
});
}
}
// Layer configuration
const LAYER_NAMES = {
1: 'config',
2: 'patterns',
3: 'components',
4: 'hydration',
5: 'nextjs',
6: 'testing',
7: 'adaptive',
8: 'security-forensics'
};
// Layer 8: Security Forensics (lazy loaded)
let Layer8SecurityForensics = null;
function getLayer8() {
if (!Layer8SecurityForensics) {
Layer8SecurityForensics = require('./scripts/fix-layer-8-security');
}
return Layer8SecurityForensics;
}
// Smart Layer Selector for analyzing and recommending layers
class SmartLayerSelector {
static analyzeAndRecommend(code, filePath) {
const issues = [];
const ext = path.extname(filePath);
try {
// Use AST-based analysis for more accurate detection
const ASTTransformer = require('./ast-transformer');
const transformer = new ASTTransformer();
const astIssues = transformer.analyzeCode(code, { filename: filePath });
// Convert AST issues to layer recommendations
astIssues.forEach(issue => {
issues.push({
layer: issue.layer,
reason: issue.message,
confidence: 0.9,
location: issue.location
});
});
} catch (error) {
// Fallback to regex-based detection if AST parsing fails
issues.push(...this.fallbackAnalysis(code, filePath));
}
return {
detectedIssues: issues,
recommendedLayers: [...new Set(issues.map(i => i.layer))].sort(),
reasons: issues.map(i => i.reason),
confidence: issues.reduce((acc, i) => acc + i.confidence, 0) / issues.length || 0
};
}
static fallbackAnalysis(code, filePath) {
const issues = [];
const ext = path.extname(filePath);
// Layer 1: Configuration files
if (filePath.endsWith('tsconfig.json') || filePath.endsWith('next.config.js') || filePath.endsWith('package.json')) {
issues.push({
layer: 1,
reason: 'Configuration file detected',
confidence: 0.9
});
}
// Layer 2: Pattern issues
if (code.includes('"') || code.includes('&') || code.includes('console.log(')) {
issues.push({
layer: 2,
reason: 'Common pattern issues detected',
confidence: 0.8
});
}
// Layer 3: Component issues
if ((ext === '.tsx' || ext === '.jsx') && code.includes('function') && code.includes('return (')) {
if (code.includes('.map(') && !code.includes('key={')) {
issues.push({
layer: 3,
reason: 'React component issues detected (missing keys)',
confidence: 0.9
});
}
if (code.includes('<button') && !code.includes('aria-label')) {
issues.push({
layer: 3,
reason: 'React component issues detected (missing aria labels)',
confidence: 0.9
});
}
if (code.includes('<Button') && !code.includes('variant=')) {
issues.push({
layer: 3,
reason: 'React component issues detected (missing Button variant)',
confidence: 0.8
});
}
if (code.includes('<Input') && !code.includes('type=')) {
issues.push({
layer: 3,
reason: 'React component issues detected (missing Input type)',
confidence: 0.8
});
}
if (code.includes('<img') && !code.includes('alt=')) {
issues.push({
layer: 3,
reason: 'React component issues detected (missing image alt)',
confidence: 0.9
});
}
}
// Layer 4: Hydration issues
if ((code.includes('localStorage') || code.includes('window.') || code.includes('document.')) && !code.includes('typeof window')) {
issues.push({
layer: 4,
reason: 'Hydration safety issues detected',
confidence: 0.9
});
}
// Layer 5: Next.js issues
if ((ext === '.tsx' || ext === '.jsx') &&
(code.includes('useState') || code.includes('useEffect')) &&
!code.match(/^['"]use client['"];/)) {
issues.push({
layer: 5,
reason: 'Next.js client component issues detected',
confidence: 0.9
});
}
// Layer 6: Testing issues
if ((ext === '.tsx' || ext === '.jsx') && code.includes('export') && !code.includes('test(')) {
issues.push({
layer: 6,
reason: 'Missing test coverage',
confidence: 0.7
});
}
// Layer 7: Adaptive Pattern Learning
if ((ext === '.tsx' || ext === '.jsx') &&
(code.includes('useState') || code.includes('useEffect') || code.includes('function'))) {
issues.push({
layer: 7,
reason: 'Potential for adaptive pattern learning',
confidence: 0.6
});
}
return issues;
}
}
// Rule Store for Layer 7 adaptive learning
class RuleStore {
constructor() {
this._rules = [];
this.ruleFile = path.join(process.cwd(), '.neurolint', 'learned-rules.json');
}
get rules() {
return this._rules || [];
}
set rules(value) {
this._rules = Array.isArray(value) ? value : [];
}
async load() {
try {
const data = await fs.readFile(this.ruleFile, 'utf8');
const parsed = JSON.parse(data);
// Handle both array format and object with rules property
this.rules = Array.isArray(parsed) ? parsed : (parsed.rules || []);
} catch (error) {
this.rules = [];
}
}
async save() {
const ruleDir = path.dirname(this.ruleFile);
await fs.mkdir(ruleDir, { recursive: true });
await fs.writeFile(this.ruleFile, JSON.stringify(this.rules, null, 2));
}
addRule(pattern, transformation) {
this.rules.push({
pattern,
transformation,
timestamp: new Date().toISOString(),
usageCount: 1
});
}
}
// Community CTA helper - displays GitHub, docs, and support links
const NEUROLINT_GITHUB = 'https://github.com/Alcatecablee/Neurolint';
const NEUROLINT_DOCS = 'https://github.com/Alcatecablee/Neurolint/blob/main/CLI_USAGE.md';
const NEUROLINT_ISSUES = 'https://github.com/Alcatecablee/Neurolint/issues';
function printCommunityCTA(context = 'default') {
const isQuiet = process.argv.includes('--quiet') || process.argv.includes('-q');
if (isQuiet) return;
const separator = '\x1b[2m' + '─'.repeat(60) + '\x1b[0m';
if (context === 'help') {
console.log(`
${separator}
\x1b[1m\x1b[36mJoin the NeuroLint Community\x1b[0m
[STAR] Star us on GitHub: ${NEUROLINT_GITHUB}
[DOCS] Documentation: ${NEUROLINT_DOCS}
[HELP] Report issues: ${NEUROLINT_ISSUES}
${separator}`);
} else if (context === 'version') {
console.log(`\x1b[2m-> Star us: ${NEUROLINT_GITHUB}\x1b[0m`);
} else if (context === 'success') {
console.log(`\n\x1b[2mLove NeuroLint? Star us on GitHub: ${NEUROLINT_GITHUB}\x1b[0m`);
} else if (context === 'first-run') {
console.log(`
\x1b[1m\x1b[32mWelcome to NeuroLint!\x1b[0m
Get started:
-> Run \x1b[1mneurolint --help\x1b[0m to see all commands
-> Run \x1b[1mneurolint analyze .\x1b[0m to analyze your project
Join our community:
[STAR] Star us: ${NEUROLINT_GITHUB}
[DOCS] Docs: ${NEUROLINT_DOCS}
`);
}
}
// File pattern matching utility with performance optimizations
async function getFiles(dir, include = ['**/*.{ts,tsx,js,jsx,json}'], exclude = [
// Build and dependency directories
'**/node_modules/**',
'**/dist/**',
'**/.next/**',
'**/build/**',
'**/.build/**',
'**/out/**',
'**/.out/**',
// Coverage and test artifacts
'**/coverage/**',
'**/.nyc_output/**',
'**/.jest/**',
'**/test-results/**',
// Version control
'**/.git/**',
'**/.svn/**',
'**/.hg/**',
// IDE and editor files
'**/.vscode/**',
'**/.idea/**',
'**/.vs/**',
'**/*.swp',
'**/*.swo',
'**/*~',
'**/.#*',
'**/#*#',
// OS generated files
'**/.DS_Store',
'**/Thumbs.db',
'**/desktop.ini',
'**/*.tmp',
'**/*.temp',
// Log files
'**/*.log',
'**/logs/**',
'**/.log/**',
// Cache directories
'**/.cache/**',
'**/cache/**',
'**/.parcel-cache/**',
'**/.eslintcache',
'**/.stylelintcache',
// Neurolint specific exclusions
'**/.neurolint/**',
'**/states-*.json',
'**/*.backup-*',
'**/*.backup',
// Package manager files
'**/package-lock.json',
'**/yarn.lock',
'**/pnpm-lock.yaml',
'**/.npm/**',
'**/.yarn/**',
// Environment and config files
'**/.env*',
'**/.env.local',
'**/.env.development',
'**/.env.test',
'**/.env.production',
// Documentation and assets
'**/docs/**',
'**/documentation/**',
'**/assets/**',
'**/public/**',
'**/static/**',
'**/images/**',
'**/img/**',
'**/icons/**',
'**/fonts/**',
'**/*.png',
'**/*.jpg',
'**/*.jpeg',
'**/*.gif',
'**/*.svg',
'**/*.ico',
'**/*.woff',
'**/*.woff2',
'**/*.ttf',
'**/*.eot',
'**/*.mp4',
'**/*.webm',
'**/*.mp3',
'**/*.wav',
'**/*.pdf',
'**/*.zip',
'**/*.tar.gz',
'**/*.rar',
// Generated files
'**/*.min.js',
'**/*.min.css',
'**/*.bundle.js',
'**/*.chunk.js',
'**/vendor/**',
// Backup and temporary files
'**/*.bak',
'**/*.backup',
'**/*.old',
'**/*.orig',
'**/*.rej',
'**/*.tmp',
'**/*.temp',
// Lock files and manifests
'**/.lock-wscript',
'**/npm-debug.log*',
'**/yarn-debug.log*',
'**/yarn-error.log*',
'**/.pnp.*',
// TypeScript declaration files (optional - uncomment if needed)
// '**/*.d.ts',
// Test files (optional - uncomment if you want to exclude tests)
// '**/*.test.js',
// '**/*.test.ts',
// '**/*.test.tsx',
// '**/*.spec.js',
// '**/*.spec.ts',
// '**/*.spec.tsx',
// '**/__tests__/**',
// '**/tests/**',
// '**/test/**',
// Storybook files (optional - uncomment if needed)
// '**/*.stories.js',
// '**/*.stories.ts',
// '**/*.stories.tsx',
// '**/.storybook/**',
// Cypress files (optional - uncomment if needed)
// '**/cypress/**',
// '**/cypress.config.*',
// Playwright files (optional - uncomment if needed)
// '**/playwright.config.*',
// '**/tests/**',
// Docker files (optional - uncomment if needed)
// '**/Dockerfile*',
// '**/.dockerignore',
// '**/docker-compose*',
// CI/CD files (optional - uncomment if needed)
// '**/.github/**',
// '**/.gitlab-ci.yml',
// '**/.travis.yml',
// '**/.circleci/**',
// '**/azure-pipelines.yml',
// Database files (optional - uncomment if needed)
// '**/*.sqlite',
// '**/*.db',
// '**/*.sql',
// Configuration files (optional - uncomment if needed)
// '**/.eslintrc*',
// '**/.prettierrc*',
// '**/.babelrc*',
// '**/tsconfig.json',
// '**/next.config.js',
// '**/webpack.config.*',
// '**/rollup.config.*',
// '**/vite.config.*',
// '**/jest.config.*',
// '**/tailwind.config.*',
// '**/postcss.config.*'
]) {
const files = [];
const maxConcurrent = 50; // Increased from 10 for better throughput
const batchSize = 100; // Process files in batches
let activeOperations = 0;
// Pre-compile regex patterns for better performance
const compiledPatterns = {
include: include.map(pattern => ({
pattern,
regex: globToRegex(pattern),
hasBraces: pattern.includes('{') && pattern.includes('}')
})),
exclude: exclude.map(pattern => ({
pattern,
regex: globToRegex(pattern)
}))
};
// Helper function to convert glob pattern to regex (optimized)
function globToRegex(pattern) {
// Cache compiled regex patterns
if (!globToRegex.cache) {
globToRegex.cache = new Map();
}
if (globToRegex.cache.has(pattern)) {
return globToRegex.cache.get(pattern);
}
let regexPattern = pattern
.replace(/\*\*/g, '.*') // ** becomes .*
.replace(/\*/g, '[^/]*') // * becomes [^/]*
.replace(/\./g, '\\.') // . becomes \.
.replace(/\-/g, '\\-'); // - becomes \-
// Handle path separators for cross-platform compatibility
regexPattern = regexPattern.replace(/\//g, '[\\\\/]');
// For patterns like **/*.backup-*, we need to handle the path structure properly
if (pattern.startsWith('**/*')) {
const suffix = pattern.substring(4); // Remove **/* prefix
regexPattern = '.*' + suffix.replace(/\*/g, '[^/]*').replace(/\./g, '\\.').replace(/\-/g, '\\-').replace(/\//g, '[\\\\/]');
}
// For patterns like **/.neurolint/states-*.json, handle the path structure
if (pattern.startsWith('**/')) {
const suffix = pattern.substring(3); // Remove **/ prefix
regexPattern = '.*' + suffix.replace(/\*/g, '[^/]*').replace(/\./g, '\\.').replace(/\-/g, '\\-').replace(/\//g, '[\\\\/]');
}
const regex = new RegExp(regexPattern + '$', 'i'); // Case insensitive
globToRegex.cache.set(pattern, regex);
return regex;
}
// Helper function to check if file matches pattern (optimized)
function matchesPattern(filePath, patternInfo) {
// Handle brace expansion in patterns like **/*.{ts,tsx,js,jsx,json}
if (patternInfo.hasBraces) {
const pattern = patternInfo.pattern;
const braceStart = pattern.indexOf('{');
const braceEnd = pattern.indexOf('}');
const prefix = pattern.substring(0, braceStart);
const suffix = pattern.substring(braceEnd + 1);
const options = pattern.substring(braceStart + 1, braceEnd).split(',');
return options.some(opt => {
const expandedPattern = prefix + opt + suffix;
const expandedRegex = globToRegex(expandedPattern);
return expandedRegex.test(filePath);
});
}
// Use pre-compiled regex
return patternInfo.regex.test(filePath);
}
// Check if target is a single file
try {
const stats = await fs.stat(dir);
if (stats.isFile()) {
// Check if file should be included
const shouldInclude = compiledPatterns.include.some(patternInfo =>
matchesPattern(dir, patternInfo)
);
if (shouldInclude) {
return [dir];
}
return [];
}
} catch (error) {
// Not a file, continue with directory scanning
}
// Use worker threads for large directories
const useWorkers = process.env.NODE_ENV !== 'test' && require('worker_threads').isMainThread;
async function scanDirectory(currentDir) {
try {
// Limit concurrent operations with better queuing
if (activeOperations >= maxConcurrent) {
await new Promise(resolve => {
const checkQueue = () => {
if (activeOperations < maxConcurrent) {
resolve();
} else {
setImmediate(checkQueue);
}
};
checkQueue();
});
}
activeOperations++;
const entries = await fs.readdir(currentDir, { withFileTypes: true });
activeOperations--;
// Process entries in batches for better memory management
const batches = [];
for (let i = 0; i < entries.length; i += batchSize) {
batches.push(entries.slice(i, i + batchSize));
}
for (const batch of batches) {
const batchPromises = batch.map(async entry => {
const fullPath = path.join(currentDir, entry.name);
if (entry.isDirectory()) {
// Check if directory should be excluded
const shouldExclude = compiledPatterns.exclude.some(patternInfo => {
const pattern = patternInfo.pattern;
// Handle common exclusion patterns more efficiently
if (pattern === '**/node_modules/**' && entry.name === 'node_modules') {
return true;
}
if (pattern === '**/dist/**' && entry.name === 'dist') {
return true;
}
if (pattern === '**/.next/**' && entry.name === '.next') {
return true;
}
if (pattern === '**/build/**' && entry.name === 'build') {
return true;
}
if (pattern === '**/coverage/**' && entry.name === 'coverage') {
return true;
}
if (pattern === '**/.git/**' && entry.name === '.git') {
return true;
}
if (pattern === '**/.vscode/**' && entry.name === '.vscode') {
return true;
}
if (pattern === '**/.idea/**' && entry.name === '.idea') {
return true;
}
if (pattern === '**/.cache/**' && entry.name === '.cache') {
return true;
}
// Fallback to regex matching
return patternInfo.regex.test(fullPath);
});
if (!shouldExclude) {
await scanDirectory(fullPath);
}
} else if (entry.isFile()) {
// Check if file should be excluded first
const shouldExclude = compiledPatterns.exclude.some(patternInfo => {
const pattern = patternInfo.pattern;
// Handle common file exclusion patterns more efficiently
if (pattern.includes('*.log') && entry.name.endsWith('.log')) {
return true;
}
if (pattern.includes('*.tmp') && entry.name.endsWith('.tmp')) {
return true;
}
if (pattern.includes('*.backup') && entry.name.includes('.backup')) {
return true;
}
if (pattern.includes('*.min.js') && entry.name.endsWith('.min.js')) {
return true;
}
if (pattern.includes('*.bundle.js') && entry.name.endsWith('.bundle.js')) {
return true;
}
// Fallback to regex matching
return patternInfo.regex.test(fullPath);
});
if (!shouldExclude) {
// Check if file should be included
const shouldInclude = compiledPatterns.include.some(patternInfo =>
matchesPattern(fullPath, patternInfo)
);
if (shouldInclude) {
files.push(fullPath);
}
}
}
});
// Process batch with controlled concurrency
await Promise.all(batchPromises);
}
} catch (error) {
// Handle permission errors gracefully
if (error.code === 'EACCES' || error.code === 'EPERM') {
return; // Skip directories we can't access
}
throw error;
}
}
await scanDirectory(dir);
return files;
}
// Parse command line options
function parseOptions(args) {
const options = {
dryRun: args.includes('--dry-run'),
verbose: args.includes('--verbose'),
production: args.includes('--production'),
backup: !args.includes('--no-backup'),
withOfficialCodemods: args.includes('--with-official-codemods'),
skipOfficialCodemods: args.includes('--skip-official'),
useRecipe: args.includes('--recipe'),
codemodVersion: null,
layers: args.includes('--layers') ? args[args.indexOf('--layers') + 1].split(',').map(Number) : null,
allLayers: args.includes('--all-layers'),
include: args.includes('--include') ? args[args.indexOf('--include') + 1].split(',') : ['**/*.{ts,tsx,js,jsx,json}'],
exclude: args.includes('--exclude') ? args[args.indexOf('--exclude') + 1].split(',') : ['**/node_modules/**', '**/dist/**', '**/.next/**'],
format: 'console',
output: null,
init: args.includes('--init'),
show: args.includes('--show'),
states: args.includes('--states'),
olderThan: undefined,
keepLatest: undefined,
list: args.includes('--list'),
delete: undefined,
reset: args.includes('--reset'),
edit: undefined,
confidence: undefined,
export: undefined,
import: undefined,
yes: args.includes('--yes'),
target: undefined
};
// Parse format and output from args
for (let i = 0; i < args.length; i++) {
if (args[i] === '--format' && i + 1 < args.length) {
options.format = args[i + 1];
} else if (args[i] === '--output' && i + 1 < args.length) {
options.output = args[i + 1];
} else if (args[i] === '--older-than' && i + 1 < args.length) {
options.olderThan = parseInt(args[i + 1]);
} else if (args[i] === '--keep-latest' && i + 1 < args.length) {
options.keepLatest = parseInt(args[i + 1]);
} else if (args[i] === '--delete' && i + 1 < args.length) {
options.delete = args[i + 1];
} else if (args[i] === '--edit' && i + 1 < args.length) {
options.edit = args[i + 1];
} else if (args[i] === '--confidence' && i + 1 < args.length) {
options.confidence = parseFloat(args[i + 1]);
} else if (args[i] === '--export' && i + 1 < args.length) {
options.export = args[i + 1];
} else if (args[i] === '--import' && i + 1 < args.length) {
options.import = args[i + 1];
} else if (args[i] === '--target' && i + 1 < args.length) {
options.target = args[i + 1];
} else if (args[i].startsWith('--format=')) {
options.format = args[i].split('=')[1];
} else if (args[i].startsWith('--output=')) {
options.output = args[i].split('=')[1];
} else if (args[i].startsWith('--older-than=')) {
options.olderThan = parseInt(args[i].split('=')[1]);
} else if (args[i].startsWith('--keep-latest=')) {
options.keepLatest = parseInt(args[i].split('=')[1]);
} else if (args[i].startsWith('--delete=')) {
options.delete = args[i].split('=')[1];
} else if (args[i].startsWith('--edit=')) {
options.edit = args[i].split('=')[1];
} else if (args[i].startsWith('--confidence=')) {
options.confidence = parseFloat(args[i].split('=')[1]);
} else if (args[i].startsWith('--export=')) {
options.export = args[i].split('=')[1];
} else if (args[i].startsWith('--import=')) {
options.import = args[i].split('=')[1];
} else if (args[i].startsWith('--target=')) {
options.target = args[i].split('=')[1];
} else if (args[i] === '--codemod-version' && i + 1 < args.length) {
options.codemodVersion = args[i + 1];
} else if (args[i].startsWith('--codemod-version=')) {
options.codemodVersion = args[i].split('=')[1];
} else if (args[i] === '--json') {
// --json is a shorthand alias for --format json, consistent across all commands
options.format = 'json';
}
}
return options;
}
// Enhanced output functions to replace emoji-based spinners
function logSuccess(message) {
console.log(`[SUCCESS] ${message}`);
}
function logError(message) {
console.error(`[ERROR] ${message}`);
}
function logWarning(message) {
console.warn(`[WARNING] ${message}`);
}
function logInfo(message) {
console.log(`[INFO] ${message}`);
}
function logProgress(message) {
process.stdout.write(`[PROCESSING] ${message}...`);
}
function logComplete(message) {
process.stdout.write(`[COMPLETE] ${message}\n`);
}
// Official codemods configuration
// React codemods use: npx codemod@latest react/19/<transform> --target <path>
// Next.js codemods use: npx @next/codemod@latest <transform> <path>
const OFFICIAL_CODEMODS = {
react19: [
{ name: 'replace-reactdom-render', transform: 'react/19/replace-reactdom-render', description: 'Converts ReactDOM.render() to createRoot().render()' },
{ name: 'replace-string-ref', transform: 'react/19/replace-string-ref', description: 'Converts string refs to callback refs' },
{ name: 'replace-act-import', transform: 'react/19/replace-act-import', description: 'Updates act import from react-dom/test-utils to react' },
{ name: 'replace-use-form-state', transform: 'react/19/replace-use-form-state', description: 'Replaces useFormState with useActionState' }
],
react19Recipe: [
{ name: 'migration-recipe', transform: 'react/19/migration-recipe', description: 'Runs all React 19 codemods at once (recommended)' }
],
nextjs15: [
{ name: 'next-async-request-api', transform: 'next-async-request-api', description: 'Makes cookies(), headers(), params async' },
{ name: 'next-request-geo-ip', transform: 'next-request-geo-ip', description: 'Migrates geo/ip to @vercel/functions' },
{ name: 'app-dir-runtime-config-experimental-edge', transform: 'app-dir-runtime-config-experimental-edge', description: 'Changes experimental-edge to edge runtime' }
],
nextjs16: [
{ name: 'remove-experimental-ppr', transform: 'remove-experimental-ppr', description: 'Removes experimental_ppr Route Segment Config' },
{ name: 'remove-unstable-prefix', transform: 'remove-unstable-prefix', description: 'Removes unstable_ prefix from stabilized APIs' },
{ name: 'middleware-to-proxy', transform: 'middleware-to-proxy', description: 'Migrates middleware convention to proxy' }
]
};
/**
* Capture file hashes for change detection
* @param {string} targetPath - Directory to scan
* @returns {Promise<Map<string, string>>} Map of file paths to content hashes
*/
async function captureFileHashes(targetPath) {
const crypto = require('crypto');
const fileHashes = new Map();
try {
const files = await getFiles(targetPath, ['**/*.{ts,tsx,js,jsx}'], [
'**/node_modules/**', '**/dist/**', '**/.next/**', '**/build/**'
]);
for (const file of files) {
try {
const content = await fs.readFile(file, 'utf8');
const hash = crypto.createHash('sha256').update(content).digest('hex');
fileHashes.set(file, hash);
} catch (e) {
// Skip unreadable files
}
}
} catch (e) {
// Return empty map on error
}
return fileHashes;
}
/**
* Compare file hashes to detect changes
* @param {Map<string, string>} before - Hashes before changes
* @param {Map<string, string>} after - Hashes after changes
* @returns {Object} Changed, added, and removed files
*/
function compareFileHashes(before, after) {
const changed = [];
const added = [];
const removed = [];
// Check for changed and removed files
for (const [file, hash] of before) {
if (!after.has(file)) {
removed.push(file);
} else if (after.get(file) !== hash) {
changed.push(file);
}
}
// Check for added files
for (const file of after.keys()) {
if (!before.has(file)) {
added.push(file);
}
}
return { changed, added, removed };
}
/**
* Run official framework codemods (Phase 1)
* Now with backup support and file change tracking for auditability
* @param {Object} config - Configuration object
* @param {string} config.framework - 'react19', 'react19Recipe', 'nextjs15', or 'nextjs16'
* @param {string} config.targetPath - Path to the project
* @param {boolean} config.dryRun - Whether to skip execution (just report)
* @param {boolean} config.verbose - Whether to show detailed output
* @param {string} [config.codemodVersion] - Optional version to pin codemods (e.g., '1.0.0')
* For React: pins 'codemod' package (e.g., codemod@1.0.0)
* For Next.js: pins '@next/codemod' package (e.g., @next/codemod@15.0.0)
* @param {boolean} [config.enableBackup=true] - Whether to create backups before codemods
* @param {boolean} [config.trackChanges=true] - Whether to track file-level changes
* @returns {Promise<Object>} Results summary with file manifest
*/
async function runOfficialCodemods({ framework, targetPath, dryRun, verbose, codemodVersion, enableBackup = true, trackChanges = true }) {
const codemods = OFFICIAL_CODEMODS[framework];
if (!codemods || codemods.length === 0) {
return { success: 0, skipped: 0, errors: 0, results: [], manifest: { changed: [], added: [], removed: [] } };
}
const isReactFramework = framework.startsWith('react');
const frameworkLabel = isReactFramework ? 'React 19' :
framework === 'nextjs15' ? 'Next.js 15' : 'Next.js 16';
// Determine package version suffix - only for the relevant package type
const reactCodemodPkg = codemodVersion && isReactFramework ? `codemod@${codemodVersion}` : 'codemod@latest';
const nextCodemodPkg = codemodVersion && !isReactFramework ? `@next/codemod@${codemodVersion}` : '@next/codemod@latest';
console.log(`\n[Phase 1] Running official ${frameworkLabel} codemods...`);
if (codemodVersion) {
const pinnedPkg = isReactFramework ? `codemod@${codemodVersion}` : `@next/codemod@${codemodVersion}`;
console.log(` [INFO] Using pinned version: ${pinnedPkg}`);
}
console.log(` [INFO] Target: ${targetPath}`);
console.log(` [INFO] Codemods to run: ${codemods.length}`);
if (dryRun) {
console.log(' [INFO] Dry-run mode - skipping official codemods execution');
console.log(' [INFO] The following codemods would run:');
codemods.forEach((codemod, index) => {
console.log(` ${index + 1}/${codemods.length} ${codemod.name}: ${codemod.description}`);
});
return {
success: 0,
skipped: codemods.length,
errors: 0,
results: codemods.map(c => ({ name: c.name, status: 'skipped', reason: 'dry-run' })),
version: codemodVersion || 'latest',
manifest: { changed: [], added: [], removed: [] }
};
}
// Check if npx is available
try {
execSync('npx --version', { stdio: 'pipe' });
} catch (error) {
console.log(' [WARN] npx not found. Skipping official codemods.');
console.log(' [INFO] Install Node.js 18+ for codemod support.');
console.log(' [INFO] You can run codemods manually later.');
return {
success: 0,
skipped: codemods.length,
errors: 0,
results: codemods.map(c => ({ name: c.name, status: 'skipped', reason: 'npx not found' })),
version: codemodVersion || 'latest',
manifest: { changed: [], added: [], removed: [] }
};
}
// Capture file state before codemods for change tracking
let beforeHashes = new Map();
if (trackChanges) {
console.log(' [INFO] Capturing file state for change tracking...');
beforeHashes = await captureFileHashes(targetPath);
}
// Create backup before running official codemods (for rollback safety)
let backupInfo = null;
if (enableBackup && !dryRun) {
try {
const backupManager = createBackupManager({ verbose });
console.log(' [INFO] Creating backup before official codemods...');
// Backup files that will be affected
const filesToBackup = await getFiles(targetPath, ['**/*.{ts,tsx,js,jsx}'], [
'**/node_modules/**', '**/dist/**', '**/.next/**', '**/build/**'
]);
const backupResults = [];
for (const file of filesToBackup.slice(0, 100)) { // Limit to first 100 files for performance
try {
const result = await backupManager.createBackup(file, `phase1-${framework}`);