-
Notifications
You must be signed in to change notification settings - Fork 544
Expand file tree
/
Copy pathdoctor.ts
More file actions
1440 lines (1319 loc) · 47.9 KB
/
doctor.ts
File metadata and controls
1440 lines (1319 loc) · 47.9 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
/**
* @fileoverview Valdi CLI Doctor Command - Environment Health Diagnostics
*
* This module implements the `valdi doctor` command, which performs comprehensive
* health checks on the Valdi development environment. It validates system requirements,
* tool installations, workspace configuration, and provides actionable feedback
* for resolving issues.
*
* @author rohanjsh
*
* @example
* ```bash
* # Basic health check (dev environment only)
* valdi doctor
*
* # Include project-specific checks
* valdi doctor --project
*
* # Include framework development checks
* valdi doctor --framework
*
* # Detailed diagnostics with verbose output
* valdi doctor --verbose
*
* # Machine-readable JSON output for CI/CD
* valdi doctor --json
*
* # Attempt automatic fixes where possible
* valdi doctor --fix
* ```
* @see {@link https://bazel.build/install} Bazel Installation Guide
* @see {@link https://nodejs.org} Node.js Installation
*/
import * as fs from 'fs';
import * as os from 'os';
import path from 'path';
import type { Argv } from 'yargs';
import { ANSI_COLORS } from '../core/constants';
import { ANDROID_NDK_VERSION, ANDROID_PLATFORM_VERSION } from '../setup/versions';
import type { ArgumentsResolver } from '../utils/ArgumentsResolver';
import { BazelClient } from '../utils/BazelClient';
import { checkCommandExists, runCliCommand } from '../utils/cliUtils';
import { makeCommandHandler } from '../utils/errorUtils';
import { wrapInColor } from '../utils/logUtils';
import { getLinuxPackageManager } from '../setup/linuxSetup';
/** Discord support link for troubleshooting */
const DISCORD_SUPPORT_URL = 'https://discord.gg/uJyNEeYX2U';
/**
* Command line parameters for the doctor command.
*
* @interface CommandParameters
*/
interface CommandParameters {
/** Enable detailed diagnostic information output */
verbose: boolean;
/** Attempt to automatically fix issues where possible */
fix: boolean;
/** Output results in JSON format for machine processing */
json: boolean;
/** Include framework development checks (git-lfs, temurin, etc.) */
framework: boolean;
/** Include project-specific checks (workspace structure, etc.) */
project: boolean;
}
/**
* Represents the result of a single diagnostic check.
*
* @interface DiagnosticResult
*/
interface DiagnosticResult {
/** Human-readable name of the diagnostic check */
name: string;
/** Status of the check: pass (✓), warn (⚠), or fail (✗) */
status: 'pass' | 'warn' | 'fail';
/** Primary message describing the check result */
message: string;
/** Optional detailed information about the check */
details?: string;
/** Whether this issue can potentially be auto-fixed */
fixable?: boolean;
/** Command or instruction to fix the issue */
fixCommand?: string;
/** Category for grouping related checks */
category?: string;
}
/**
* Represents a group of related diagnostic checks with their overall status.
*
* @interface GroupedDiagnosticResult
*/
interface GroupedDiagnosticResult {
/** Category name for the group */
category: string;
/** Overall status of the group (worst status among all checks) */
status: 'pass' | 'warn' | 'fail';
/** Summary message for the group */
message: string;
/** Individual check results within this group */
checks: DiagnosticResult[];
/** Issues found in this group (only checks with warn/fail status) */
issues: DiagnosticResult[];
}
/**
* Main class responsible for performing Valdi environment health diagnostics.
*
* This class orchestrates various system checks to ensure the development environment
* is properly configured for Valdi development. It validates:
* - Node.js version compatibility (≥18.0.0)
* - Bazel build system installation and functionality (with version validation)
* - Java JDK installation (Java 17+ recommended)
* - Platform-specific development tools (Android SDK, Xcode)
* - Required development dependencies (git, npm, watchman, ios-webkit-debug-proxy)
* - Optional project-specific checks (workspace structure)
* - Optional framework development tools (git-lfs, temurin)
*
* @class ValdiDoctor
*/
class ValdiDoctor {
/** Collection of diagnostic check results */
private readonly results: DiagnosticResult[] = [];
/** Whether to show detailed diagnostic information */
private readonly verbose: boolean;
/** Whether to attempt automatic fixes for detected issues */
private readonly autoFix: boolean;
/** Whether to output results in JSON format */
private readonly jsonOutput: boolean;
/** Whether to include framework development checks */
private readonly frameworkMode: boolean;
/** Whether to include project-specific checks */
private readonly projectMode: boolean;
/**
* Creates a new ValdiDoctor instance.
*
* @param verbose - Enable detailed diagnostic output
* @param autoFix - Attempt to automatically fix issues where possible
* @param jsonOutput - Output results in JSON format for machine processing
* @param frameworkMode - Include framework development checks
* @param projectMode - Include project-specific checks
*/
constructor(verbose: boolean, autoFix: boolean, jsonOutput: boolean, frameworkMode: boolean, projectMode: boolean) {
this.verbose = verbose;
this.autoFix = autoFix;
this.jsonOutput = jsonOutput;
this.frameworkMode = frameworkMode;
this.projectMode = projectMode;
}
/**
* Executes diagnostic checks based on the target audience.
*
* **App Development Mode (default):**
* - Essential tools for building Valdi applications
* - Node.js, Bazel (with version validation)
* - Basic Android SDK and Java setup (Java 17+ recommended)
* - Core development tools (git, npm, watchman, ios-webkit-debug-proxy)
*
* **Project Mode (--project flag):**
* - All app development checks plus
* - Workspace structure validation (WORKSPACE file, .bazelrc)
*
* **Framework Development Mode (--framework flag):**
* - All app development checks plus
* - Advanced development tools (git-lfs, temurin)
* - Detailed environment variable validation
* - Platform-specific development packages
*
* @returns Promise that resolves when all diagnostics are complete
*
* @example
* ```typescript
* // App development checks only
* await doctor.runDiagnostics();
*
* // App development + project checks
* await doctor.runDiagnostics(); // with projectMode = true
*
* // App development + framework checks
* await doctor.runDiagnostics(); // with frameworkMode = true
* ```
*/
async runDiagnostics(): Promise<DiagnosticResult['status']> {
if (!this.jsonOutput) {
let mode = 'app development';
if (this.frameworkMode) mode = 'framework development';
if (this.projectMode) mode += ' + project';
console.log(wrapInColor(`Running Valdi environment diagnostics (${mode} mode)...`, ANSI_COLORS.BLUE_COLOR));
console.log();
}
// Core checks for all users
await this.checkNodeVersion();
await this.checkBazelInstallation();
// Project-specific checks (only if requested)
if (this.projectMode) {
this.checkWorkspaceStructure();
}
// Essential platform tools
await this.checkEssentialPlatformTools();
// Java for Android development
await this.checkJavaInstallation();
// Android SDK basics
this.checkAndroidSDKBasics();
// Core development dependencies
await this.checkCoreDependencies();
// Framework-specific checks (only if requested)
if (this.frameworkMode) {
await this.checkFrameworkDependencies();
this.checkAdvancedAndroidSDK();
this.checkEnvironmentVariables();
}
return this.results.some(r => r.status === 'fail') ? 'fail' : 'pass';
}
/**
* Outputs the diagnostic results in the appropriate format.
*
* Depending on the configuration, this method will either:
* - Output structured JSON for machine processing (--json flag)
* - Display formatted, colored output for human consumption
*
*
* @example
* ```typescript
* doctor.printResults(); // Human-readable output
* ```
*/
printResults(): void {
if (this.jsonOutput) {
this.printJsonResults();
} else {
this.printFormattedResults();
}
}
/**
* Adds a diagnostic result to the internal collection.
*
* @param result - The diagnostic result to add
* @private
*/
private addResult(result: DiagnosticResult): void {
this.results.push(result);
}
/**
* Groups diagnostic results by category for more concise output.
*
* @returns Array of grouped diagnostic results
* @private
*/
private groupResultsByCategory(): GroupedDiagnosticResult[] {
const groups = new Map<string, DiagnosticResult[]>();
// Group results by category, with fallback for uncategorized results
for (const result of this.results) {
const category = result.category || result.name;
if (!groups.has(category)) {
groups.set(category, []);
}
const categoryGroup = groups.get(category);
if (categoryGroup) {
categoryGroup.push(result);
}
}
// Convert to grouped results with overall status
const groupedResults: GroupedDiagnosticResult[] = [];
for (const [category, checks] of groups.entries()) {
// Determine overall status (worst status wins)
let overallStatus: 'pass' | 'warn' | 'fail' = 'pass';
for (const check of checks) {
if (check.status === 'fail') {
overallStatus = 'fail';
break;
} else if (check.status === 'warn' && overallStatus === 'pass') {
overallStatus = 'warn';
}
}
// Create summary message
const warnCount = checks.filter(c => c.status === 'warn').length;
const failCount = checks.filter(c => c.status === 'fail').length;
let message: string;
if (overallStatus === 'pass') {
const firstCheck = checks[0];
message = checks.length === 1 && firstCheck ? firstCheck.message : `All ${checks.length} checks passed`;
} else {
const issues = failCount + warnCount;
message = `${issues} issue${issues > 1 ? 's' : ''} found`;
}
groupedResults.push({
category,
status: overallStatus,
message,
checks,
issues: checks.filter(c => c.status !== 'pass'),
});
}
return groupedResults;
}
/**
* Attempts to automatically fix a detected issue.
*
* This method executes the provided fix command and reports the outcome.
* It only runs when auto-fix mode is enabled and provides user feedback
* about the success or failure of the fix attempt.
*
* @param tool - Name of the tool being fixed (for user feedback)
* @param command - Shell command to execute for the fix
* @returns Promise that resolves when the fix attempt is complete
*/
private async attemptAutoFix(tool: string, command: string): Promise<void> {
if (!this.autoFix) {
return;
}
try {
console.log(wrapInColor(`Attempting to fix ${tool}...`, ANSI_COLORS.YELLOW_COLOR));
const { returnCode } = await runCliCommand(command);
if (returnCode === 0) {
console.log(wrapInColor(`✓ Successfully fixed ${tool}`, ANSI_COLORS.GREEN_COLOR));
} else {
console.log(wrapInColor(`✗ Failed to fix ${tool}`, ANSI_COLORS.RED_COLOR));
}
} catch (error) {
console.log(wrapInColor(`✗ Failed to fix ${tool}: ${error instanceof Error ? error.message : 'Unknown error'}`, ANSI_COLORS.RED_COLOR));
}
}
/**
* Validates Node.js installation and version compatibility.
*
* Valdi requires Node.js version 18.0.0 or higher for optimal compatibility.
* This method:
* 1. Checks if Node.js is installed and accessible via PATH
* 2. Validates the version meets minimum requirements (≥18.0.0)
* 3. Optionally attempts to upgrade to Node.js 20 if auto-fix is enabled
* 4. Provides specific installation/upgrade instructions
*
* @returns Promise that resolves when the check is complete
*/
private async checkNodeVersion(): Promise<void> {
try {
const { stdout } = await runCliCommand('node --version');
const version = stdout.trim();
const versionParts = version.replace('v', '').split('.');
const majorVersionStr = versionParts[0];
if (!majorVersionStr) {
throw new Error('Invalid version format');
}
const majorVersion = Number.parseInt(majorVersionStr, 10);
if (majorVersion >= 18) {
this.addResult({
name: 'Node.js version',
status: 'pass',
message: `Node.js ${version} is installed`,
category: 'Node.js installation',
});
// Suggest upgrading to Node.js 20 for better performance
if (this.autoFix && majorVersion < 20) {
await this.attemptAutoFix('node', 'nvm install 20 && nvm use 20');
}
} else {
this.addResult({
name: 'Node.js version',
status: 'fail',
message: `Node.js ${version} is outdated. Valdi requires Node.js 18 or higher`,
fixable: true,
fixCommand: 'nvm install 18 && nvm use 18',
category: 'Node.js installation',
});
if (this.autoFix) {
await this.attemptAutoFix('node', 'nvm install 18 && nvm use 18');
}
}
} catch {
this.addResult({
name: 'Node.js version',
status: 'fail',
message: 'Node.js is not installed or not in PATH',
fixable: true,
fixCommand: 'Install Node.js from https://nodejs.org or use nvm',
category: 'Node.js installation',
});
}
}
/**
* Validates Bazel build system installation and functionality.
*
* Bazel is the core build system for Valdi projects. This method:
* 1. Attempts to create a BazelClient instance
* 2. Executes `bazel version` to verify installation and functionality
* 3. Validates version against .bazelversion file if available
* 4. Provides installation guidance if Bazel is missing or broken
*
* @returns Promise that resolves when the check is complete
* @see {@link https://bazel.build/install} Bazel Installation Guide
*/
private async checkBazelInstallation(): Promise<void> {
try {
const bazel = new BazelClient();
const [returnCode, versionInfo, errorInfo] = await bazel.getVersion();
if (returnCode === 0 && versionInfo) {
const versionLine = versionInfo.split('\n')[0] || 'Unknown version';
// Extract version number for comparison
const versionMatch = versionLine.match(/(\d+\.\d+\.\d+)/);
const installedVersion = versionMatch?.[1];
// Check against .bazelversion file
const bazelVersionFile = path.join(process.cwd(), '.bazelversion');
let expectedVersion: string | undefined;
try {
if (fs.existsSync(bazelVersionFile)) {
expectedVersion = fs.readFileSync(bazelVersionFile, 'utf8').trim();
}
} catch {
// Ignore file read errors
}
if (expectedVersion && installedVersion && installedVersion !== expectedVersion) {
this.addResult({
name: 'Bazel version',
status: 'warn',
message: `Bazel version mismatch: installed ${installedVersion}, expected ${expectedVersion}`,
details: 'Version mismatch may cause build issues. Consider updating Bazel.',
fixable: true,
fixCommand: `Install Bazel ${expectedVersion} or run a trial bazel command to verify compatibility`,
category: 'Bazel installation',
});
} else {
this.addResult({
name: 'Bazel installation',
status: 'pass',
message: `Bazel is installed: ${versionLine}${expectedVersion ? ` (matches expected ${expectedVersion})` : ''}`,
category: 'Bazel installation',
});
}
} else {
this.addResult({
name: 'Bazel installation',
status: 'fail',
message: 'Bazel is installed but not working correctly',
details: errorInfo || versionInfo || 'Unknown error',
category: 'Bazel installation',
});
}
} catch {
this.addResult({
name: 'Bazel installation',
status: 'fail',
message: 'Bazel is not installed or not in PATH',
fixable: true,
fixCommand: 'Install Bazel from https://bazel.build/install',
category: 'Bazel installation',
});
}
}
/**
* Validates Valdi workspace structure and configuration files.
*
* **WORKSPACE File Requirement:**
* Every Valdi application requires a WORKSPACE file at the project root. This file:
* - Defines the Bazel workspace name
* - Imports the Valdi framework as an external dependency
* - Configures build rules and toolchains for Valdi development
* - Is automatically created by `valdi bootstrap` when starting a new project
*
* **Configuration Files:**
* - WORKSPACE file (required for all Valdi apps)
* - .bazelrc file (recommended for build optimization and consistency)
*
* This method checks the current working directory for these essential files
* and provides guidance if they're missing.
*
* @private
*
* @see {@link https://bazel.build/concepts/build-ref#workspace} Bazel Workspace Documentation
*
* @example
* ```typescript
* this.checkWorkspaceStructure();
* // Results in diagnostic output like:
* // ✓ Valid Valdi workspace detected
* // ✗ Not in a Valdi workspace directory
* ```
*/
private checkWorkspaceStructure(): void {
const workspaceFile = path.join(process.cwd(), 'WORKSPACE');
const bazelrcFile = path.join(process.cwd(), '.bazelrc');
if (fs.existsSync(workspaceFile)) {
this.addResult({
name: 'Valdi workspace',
status: 'pass',
message: 'Valid Valdi workspace detected',
category: 'Workspace configuration',
});
} else {
this.addResult({
name: 'Valdi workspace',
status: 'fail',
message: 'Not in a Valdi workspace directory',
details: 'WORKSPACE file is required for all Valdi applications. Run `valdi bootstrap` to create a new project or navigate to an existing Valdi project root.',
fixable: true,
fixCommand: 'valdi bootstrap',
category: 'Workspace configuration',
});
}
if (fs.existsSync(bazelrcFile)) {
this.addResult({
name: 'Bazel configuration',
status: 'pass',
message: '.bazelrc file found',
category: 'Workspace configuration',
});
} else {
this.addResult({
name: 'Bazel configuration',
status: 'warn',
message: '.bazelrc file not found',
details: 'A .bazelrc file provides build optimization and consistency. Consider creating one or use `valdi bootstrap` for new projects.',
fixable: true,
fixCommand: 'Create .bazelrc file with Valdi-specific build configurations',
category: 'Workspace configuration',
});
}
}
/**
* Validates essential platform tools needed for app development.
*
* Focuses on core tools that app developers need:
* - Android SDK (basic check)
* - Xcode (macOS only, for iOS apps)
*
* @returns Promise that resolves when essential platform checks are complete
* @private
*/
private async checkEssentialPlatformTools(): Promise<void> {
// Check Android SDK (essential for mobile app development)
const androidHome = process.env['ANDROID_HOME'] || process.env['ANDROID_SDK_ROOT'];
if (androidHome && fs.existsSync(androidHome)) {
this.addResult({
name: 'Android SDK',
status: 'pass',
message: `Android SDK found at ${androidHome}`,
category: 'Android installation',
});
} else {
this.addResult({
name: 'Android SDK',
status: 'warn',
message: 'Android SDK not found',
details: 'Required for Android app development. Set ANDROID_HOME environment variable.',
fixable: true,
fixCommand: 'Install Android Studio and set ANDROID_HOME',
category: 'Android installation',
});
}
// Check Xcode (macOS only, essential for iOS app development)
if (os.platform() === 'darwin') {
if (checkCommandExists('xcode-select')) {
try {
const { stdout } = await runCliCommand('xcode-select -p');
this.addResult({
name: 'Xcode',
status: 'pass',
message: `Xcode found at ${stdout.trim()}`,
category: 'iOS development',
});
} catch {
this.addResult({
name: 'Xcode',
status: 'warn',
message: 'Xcode not properly configured',
fixable: true,
fixCommand: 'xcode-select --install',
category: 'iOS development',
});
}
} else {
this.addResult({
name: 'Xcode',
status: 'warn',
message: 'Xcode command line tools not installed',
details: 'Required for iOS app development',
fixable: true,
fixCommand: 'Install Xcode from App Store and run: xcode-select --install',
category: 'iOS development',
});
}
}
}
private async getLinuxJavaInstallCommand() {
const pm = await getLinuxPackageManager();
if (pm === 'apt') {
return 'sudo apt install openjdk-17-jdk';
} else if (pm === 'yum') {
return 'sudo yum install java-17-openjdk-devel';
} else if (pm === 'pacman') {
return 'sudo pacman -S jdk17-openjdk && sudo archlinux-java set jdk17-openjdk';
} else {
return 'Please install Java JDK manually';
}
}
/**
* Validates Java JDK installation and configuration as set up by dev_setup.
*
* Checks for Java installation and configuration that dev_setup manages:
* - Java JDK availability and version (Java 17+)
* - JAVA_HOME environment variable
* - Java symlink configuration (macOS)
* - Java runtime availability (Linux)
*
* @returns Promise that resolves when Java checks are complete
* @private
*/
private async checkJavaInstallation(): Promise<void> {
// Check if Java is available
if (checkCommandExists('java')) {
try {
const { stdout, stderr } = await runCliCommand('java -version');
// java -version typically outputs to stderr, but check both
const versionInfo = stderr || stdout || '';
// Try multiple version string formats:
// 1. version "17.0.16" (older format)
// 2. openjdk 17.0.16 (OpenJDK format)
// 3. java version "17.0.16" (alternative format)
let versionMatch = versionInfo.match(/version "([^"]+)"/);
if (!versionMatch) {
versionMatch = versionInfo.match(/openjdk\s+(\d+\.\d+\.\d+)/i);
}
if (!versionMatch) {
versionMatch = versionInfo.match(/java\s+(\d+\.\d+\.\d+)/i);
}
const version = versionMatch?.[1] ?? 'Unknown version';
// Check if Java version is 17 or higher
const majorVersionMatch = version.match(/^(\d+)/);
const majorVersion = majorVersionMatch?.[1] ? Number.parseInt(majorVersionMatch[1], 10) : 0;
if (majorVersion >= 17) {
this.addResult({
name: 'Java Runtime',
status: 'pass',
message: `Java is installed: ${version}`,
category: 'Java installation',
});
} else if (majorVersion > 0) {
this.addResult({
name: 'Java Runtime',
status: 'warn',
message: `Java ${version} is outdated. Java 17+ is recommended`,
details: 'dev_setup now installs Java 17 for better compatibility',
fixable: true,
fixCommand: os.platform() === 'darwin' ? 'brew install openjdk@17' : await this.getLinuxJavaInstallCommand(),
category: 'Java installation',
});
} else {
// Could detect java but not parse version
this.addResult({
name: 'Java Runtime',
status: 'pass',
message: 'Java is installed',
details: `Version info: ${versionInfo.split('\n')[0] || 'Unable to parse version'}`,
category: 'Java installation',
});
}
} catch {
this.addResult({
name: 'Java Runtime',
status: 'pass',
message: 'Java is installed',
category: 'Java installation',
});
}
} else {
this.addResult({
name: 'Java Runtime',
status: 'fail',
message: 'Java not found in PATH',
details: 'dev_setup installs Java JDK for Android development',
fixable: true,
fixCommand: os.platform() === 'darwin' ? 'brew install openjdk@17' : await this.getLinuxJavaInstallCommand(),
category: 'Java installation',
});
}
// Check JAVA_HOME environment variable
const javaHome = process.env['JAVA_HOME'];
if (javaHome && fs.existsSync(javaHome)) {
this.addResult({
name: 'JAVA_HOME',
status: 'pass',
message: `JAVA_HOME set to ${javaHome}`,
category: 'Java installation',
});
} else {
this.addResult({
name: 'JAVA_HOME',
status: 'warn',
message: 'JAVA_HOME not set or invalid',
details: 'dev_setup configures JAVA_HOME for Android development',
fixable: true,
fixCommand: os.platform() === 'darwin' ? 'export JAVA_HOME=`/usr/libexec/java_home -v 17`' : 'Set JAVA_HOME environment variable',
category: 'Java installation',
});
}
// Check Java tools in PATH
const pathEnv = process.env['PATH'] || '';
if (os.platform() === 'darwin') {
if (pathEnv.includes('/opt/homebrew/opt/openjdk@17/bin') || pathEnv.includes('/opt/homebrew/opt/openjdk@11/bin')) {
this.addResult({
name: 'Java PATH',
status: 'pass',
message: 'Java tools in PATH',
category: 'Java installation',
});
} else {
this.addResult({
name: 'Java PATH',
status: 'warn',
message: 'Java tools not in PATH',
details: 'dev_setup adds Java tools to PATH',
fixable: true,
fixCommand: 'export PATH="/opt/homebrew/opt/openjdk@17/bin:$PATH"',
category: 'Java installation',
});
}
}
// macOS-specific Java JDK symlink check
if (os.platform() === 'darwin') {
const jdk17Symlink = '/Library/Java/JavaVirtualMachines/openjdk-17.jdk';
const jdk11Symlink = '/Library/Java/JavaVirtualMachines/openjdk-11.jdk';
if (fs.existsSync(jdk17Symlink)) {
this.addResult({
name: 'Java JDK symlink',
status: 'pass',
message: 'OpenJDK 17 symlink configured',
category: 'Java installation',
});
} else if (fs.existsSync(jdk11Symlink)) {
this.addResult({
name: 'Java JDK symlink',
status: 'warn',
message: 'OpenJDK 11 symlink found, but Java 17+ is recommended',
details: 'dev_setup now installs Java 17 for better compatibility',
fixable: true,
fixCommand: 'sudo ln -sfn /opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-17.jdk',
category: 'Java installation',
});
} else {
this.addResult({
name: 'Java JDK symlink',
status: 'warn',
message: 'OpenJDK symlink not found',
details: 'dev_setup creates symlink for system-wide Java access',
fixable: true,
fixCommand: 'sudo ln -sfn /opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-17.jdk',
category: 'Java installation',
});
}
}
}
/**
* Validates basic Android SDK components needed for app development.
*
* Checks essential Android SDK components without overwhelming users:
* - Android Platform (latest)
* - Build Tools (basic check)
*
* @private
*/
private checkAndroidSDKBasics(): void {
const androidHome = process.env['ANDROID_HOME'] || process.env['ANDROID_SDK_ROOT'];
if (!androidHome || !fs.existsSync(androidHome)) {
this.addResult({
name: 'Android SDK Components',
status: 'warn',
message: 'Cannot check Android SDK components - ANDROID_HOME not set',
details: 'Set ANDROID_HOME environment variable for Android development',
fixable: true,
fixCommand: 'Install Android Studio and set ANDROID_HOME',
category: 'Android installation',
});
return;
}
// Check for any Android Platform (not specific version)
const platformsDir = path.join(androidHome, 'platforms');
if (fs.existsSync(platformsDir)) {
const platforms = fs.readdirSync(platformsDir).filter(dir => dir.startsWith('android-'));
if (platforms.length > 0) {
this.addResult({
name: 'Android Platform',
status: 'pass',
message: `Android Platform installed (${platforms.length} version${platforms.length > 1 ? 's' : ''})`,
category: 'Android installation',
});
} else {
this.addResult({
name: 'Android Platform',
status: 'warn',
message: 'No Android Platform found',
details: 'Install an Android Platform via Android Studio SDK Manager',
fixable: true,
fixCommand: 'Open Android Studio > SDK Manager > Install an Android Platform',
category: 'Android installation',
});
}
} else {
this.addResult({
name: 'Android Platform',
status: 'warn',
message: 'Android platforms directory not found',
fixable: true,
fixCommand: 'Install Android Studio and configure SDK',
category: 'Android installation',
});
}
// Check for any Build Tools (not specific version)
const buildToolsDir = path.join(androidHome, 'build-tools');
if (fs.existsSync(buildToolsDir)) {
const buildTools = fs.readdirSync(buildToolsDir);
if (buildTools.length > 0) {
this.addResult({
name: 'Android Build Tools',
status: 'pass',
message: `Android Build Tools installed (${buildTools.length} version${buildTools.length > 1 ? 's' : ''})`,
category: 'Android installation',
});
} else {
this.addResult({
name: 'Android Build Tools',
status: 'warn',
message: 'No Android Build Tools found',
fixable: true,
fixCommand: 'Install Build Tools via Android Studio SDK Manager',
category: 'Android installation',
});
}
} else {
this.addResult({
name: 'Android Build Tools',
status: 'warn',
message: 'Build tools directory not found',
fixable: true,
fixCommand: 'Install Android Studio and configure SDK',
category: 'Android installation',
});
}
}
/**
* Validates core development dependencies needed for app development.
*
* Focuses on essential tools that app developers need:
* - git: Version control (essential)
* - npm: Package management (essential)
* - watchman: File watching for hot reloader (essential)
* - ios-webkit-debug-proxy: iOS debugging for hot reloader (macOS only, essential)
*
* @returns Promise that resolves when core dependency checks are complete
* @private
*/
private async checkCoreDependencies(): Promise<void> {
const coreDeps = ['git', 'npm', 'watchman'];
for (const dep of coreDeps) {
await this.checkSingleDependency(dep, 'fail'); // Core deps are critical
}
// Platform-specific core dependencies
if (os.platform() === 'darwin') {
await this.checkSingleDependency('ios_webkit_debug_proxy', 'fail'); // Essential for hot reloader
}
}
/**
* Validates framework development dependencies.
*
* Additional tools needed for framework development:
* - git-lfs: Large file storage
* - temurin: Alternative JDK (macOS)
*
* @returns Promise that resolves when framework dependency checks are complete
* @private
*/
private async checkFrameworkDependencies(): Promise<void> {
const frameworkDeps = ['git-lfs'];
for (const dep of frameworkDeps) {
await this.checkSingleDependency(dep, 'warn'); // Framework deps are optional
}
// Platform-specific framework dependencies
if (os.platform() === 'darwin') {
// Check for temurin package
const temurinPath = '/opt/homebrew/opt/temurin';
if (fs.existsSync(temurinPath)) {
this.addResult({
name: 'temurin package',
status: 'pass',
message: 'temurin installed via Homebrew',
category: 'Framework tools',
});
} else {
this.addResult({
name: 'temurin package',
status: 'warn',
message: 'temurin not found',
details: 'Alternative JDK for framework development',
fixable: true,
fixCommand: 'brew install temurin',
category: 'Framework tools',
});
}
}
}
/**
* Validates advanced Android SDK components for framework development.
*
* Detailed Android SDK validation including:
* - Specific platform versions
* - NDK installation
* - Command line tools
*
* @private
*/
private checkAdvancedAndroidSDK(): void {
const androidHome = process.env['ANDROID_HOME'] || process.env['ANDROID_SDK_ROOT'];
if (!androidHome || !fs.existsSync(androidHome)) {
return; // Already checked in basics
}
// Check specific Android Platform version
const platformPath = path.join(androidHome, 'platforms', ANDROID_PLATFORM_VERSION);
if (fs.existsSync(platformPath)) {
this.addResult({
name: `Android Platform ${ANDROID_PLATFORM_VERSION}`,
status: 'pass',
message: `Android Platform ${ANDROID_PLATFORM_VERSION} installed`,
category: 'Android installation',
});
} else {