@0xobelisk/sui-cli 1.2.0-pre.1 → 1.2.0-pre.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +3 -3
  2. package/dist/dubhe.js +125 -66
  3. package/dist/dubhe.js.map +1 -1
  4. package/package.json +31 -19
  5. package/src/commands/build.ts +47 -16
  6. package/src/commands/call.ts +83 -83
  7. package/src/commands/checkBalance.ts +12 -5
  8. package/src/commands/configStore.ts +12 -4
  9. package/src/commands/convertJson.ts +70 -0
  10. package/src/commands/doctor.ts +1515 -0
  11. package/src/commands/faucet.ts +11 -7
  12. package/src/commands/generateKey.ts +3 -2
  13. package/src/commands/index.ts +16 -7
  14. package/src/commands/info.ts +55 -0
  15. package/src/commands/loadMetadata.ts +57 -0
  16. package/src/commands/localnode.ts +22 -12
  17. package/src/commands/publish.ts +21 -7
  18. package/src/commands/query.ts +101 -101
  19. package/src/commands/schemagen.ts +15 -4
  20. package/src/commands/shell.ts +198 -0
  21. package/src/commands/switchEnv.ts +26 -0
  22. package/src/commands/test.ts +54 -11
  23. package/src/commands/upgrade.ts +11 -4
  24. package/src/commands/wait.ts +333 -22
  25. package/src/commands/watch.ts +2 -1
  26. package/src/dubhe.ts +12 -4
  27. package/src/utils/axios-downloader.ts +116 -0
  28. package/src/utils/callHandler.ts +118 -118
  29. package/src/utils/constants.ts +5 -0
  30. package/src/utils/generateAccount.ts +1 -1
  31. package/src/utils/index.ts +4 -3
  32. package/src/utils/metadataHandler.ts +16 -0
  33. package/src/utils/publishHandler.ts +295 -290
  34. package/src/utils/queryStorage.ts +141 -141
  35. package/src/utils/startNode.ts +165 -108
  36. package/src/utils/storeConfig.ts +6 -12
  37. package/src/utils/upgradeHandler.ts +147 -86
  38. package/src/utils/utils.ts +771 -54
@@ -0,0 +1,1515 @@
1
+ import type { CommandModule } from 'yargs';
2
+ import chalk from 'chalk';
3
+ import { spawn } from 'child_process';
4
+ import Table from 'cli-table3';
5
+ import inquirer from 'inquirer';
6
+ import * as fs from 'fs';
7
+ import * as path from 'path';
8
+ import * as os from 'os';
9
+ import * as net from 'net';
10
+ import axios, { AxiosRequestConfig } from 'axios';
11
+ import packageJson from '../../package.json';
12
+ import { downloadWithAxios } from '../utils/axios-downloader';
13
+ import { handlerExit } from './shell';
14
+
15
+ // Check result type
16
+ interface CheckResult {
17
+ name: string;
18
+ status: 'success' | 'warning' | 'error';
19
+ message: string;
20
+ fixSuggestion?: string;
21
+ }
22
+
23
+ // GitHub Release type
24
+ interface GitHubRelease {
25
+ tag_name: string;
26
+ name: string;
27
+ assets: Array<{
28
+ name: string;
29
+ browser_download_url: string;
30
+ }>;
31
+ published_at: string;
32
+ }
33
+
34
+ // Tool configuration
35
+ interface ToolConfig {
36
+ name: string;
37
+ repo: string;
38
+ binaryName: string;
39
+ installDir: string;
40
+ }
41
+
42
+ // System information
43
+ interface SystemInfo {
44
+ platform: string;
45
+ arch: string;
46
+ platformForAsset: string;
47
+ archForAsset: string;
48
+ }
49
+
50
+ // Get system information
51
+ function getSystemInfo(): SystemInfo {
52
+ const platform = process.platform;
53
+ const arch = process.arch;
54
+
55
+ let platformForAsset: string;
56
+ let archForAsset: string;
57
+
58
+ switch (platform) {
59
+ case 'darwin':
60
+ platformForAsset = 'macos';
61
+ break;
62
+ case 'win32':
63
+ platformForAsset = 'windows';
64
+ break;
65
+ case 'linux':
66
+ platformForAsset = 'ubuntu';
67
+ break;
68
+ default:
69
+ platformForAsset = platform;
70
+ }
71
+
72
+ switch (arch) {
73
+ case 'x64':
74
+ archForAsset = 'x86_64';
75
+ break;
76
+ case 'arm64':
77
+ archForAsset = 'aarch64';
78
+ break;
79
+ default:
80
+ archForAsset = arch;
81
+ }
82
+
83
+ return {
84
+ platform,
85
+ arch,
86
+ platformForAsset,
87
+ archForAsset
88
+ };
89
+ }
90
+
91
+ // Tool configurations
92
+ const TOOL_CONFIGS: Record<string, ToolConfig> = {
93
+ sui: {
94
+ name: 'sui',
95
+ repo: 'MystenLabs/sui',
96
+ binaryName: 'sui',
97
+ installDir: path.join(os.homedir(), '.dubhe', 'bin')
98
+ },
99
+ 'dubhe-indexer': {
100
+ name: 'dubhe-indexer',
101
+ repo: '0xobelisk/dubhe',
102
+ binaryName: 'dubhe-indexer',
103
+ installDir: path.join(os.homedir(), '.dubhe', 'bin')
104
+ }
105
+ };
106
+
107
+ // Execute shell command and return output
108
+ async function execCommand(
109
+ command: string,
110
+ args: string[] = []
111
+ ): Promise<{ code: number; stdout: string; stderr: string }> {
112
+ return new Promise((resolve) => {
113
+ const child = spawn(command, args, { shell: true });
114
+ let stdout = '';
115
+ let stderr = '';
116
+
117
+ child.stdout?.on('data', (data) => {
118
+ stdout += data.toString();
119
+ });
120
+
121
+ child.stderr?.on('data', (data) => {
122
+ stderr += data.toString();
123
+ });
124
+
125
+ child.on('close', (code) => {
126
+ resolve({ code: code || 0, stdout, stderr });
127
+ });
128
+
129
+ child.on('error', () => {
130
+ resolve({ code: -1, stdout, stderr });
131
+ });
132
+ });
133
+ }
134
+
135
+ // Enhanced axios function
136
+ async function fetchWithAxios(
137
+ url: string,
138
+ options: AxiosRequestConfig = {}
139
+ ): Promise<{
140
+ ok: boolean;
141
+ status: number;
142
+ statusText: string;
143
+ json: () => Promise<any>;
144
+ headers: any;
145
+ }> {
146
+ try {
147
+ // Configure axios with better defaults for network issues
148
+ const axiosConfig: AxiosRequestConfig = {
149
+ timeout: 30000,
150
+ maxRedirects: 5,
151
+ validateStatus: (status) => status < 500, // Accept all status codes < 500
152
+ ...options
153
+ };
154
+
155
+ const response = await axios(url, axiosConfig);
156
+ return {
157
+ ok: response.status >= 200 && response.status < 300,
158
+ status: response.status,
159
+ statusText: response.statusText,
160
+ json: async () => response.data,
161
+ headers: response.headers
162
+ };
163
+ } catch (error: any) {
164
+ // Handle network errors more gracefully
165
+ let status = error.response?.status || 0;
166
+ let statusText = error.response?.statusText || error.message;
167
+
168
+ // Handle specific network error cases
169
+ if (error.code === 'ENOTFOUND') {
170
+ statusText = 'DNS resolution failed - please check your internet connection';
171
+ } else if (error.code === 'ECONNRESET') {
172
+ statusText = 'Connection reset - please check your network connection';
173
+ } else if (error.code === 'ETIMEDOUT') {
174
+ statusText = 'Connection timeout - please check your network connection';
175
+ } else if (error.message.includes('protocol mismatch')) {
176
+ statusText = 'Protocol mismatch - please check your network configuration';
177
+ }
178
+
179
+ return {
180
+ ok: false,
181
+ status,
182
+ statusText,
183
+ json: async () => error.response?.data || {},
184
+ headers: error.response?.headers || {}
185
+ };
186
+ }
187
+ }
188
+
189
+ // Fetch GitHub releases with retry
190
+ async function fetchGitHubReleases(
191
+ repo: string,
192
+ count: number = 10,
193
+ retries: number = 3
194
+ ): Promise<GitHubRelease[]> {
195
+ const url = `https://api.github.com/repos/${repo}/releases?per_page=${count}`;
196
+
197
+ for (let attempt = 1; attempt <= retries; attempt++) {
198
+ try {
199
+ if (attempt > 1) {
200
+ console.log(chalk.gray(` Retry ${attempt}/${retries}...`));
201
+ }
202
+
203
+ const response = await fetchWithAxios(url, {
204
+ headers: {
205
+ 'User-Agent': 'dubhe-cli',
206
+ Accept: 'application/vnd.github.v3+json'
207
+ }
208
+ });
209
+
210
+ if (!response.ok) {
211
+ if (response.status === 403) {
212
+ throw new Error(
213
+ `GitHub API rate limit: ${response.status}. Please retry later or set GITHUB_TOKEN environment variable`
214
+ );
215
+ }
216
+ throw new Error(`GitHub API request failed: ${response.status} ${response.statusText}`);
217
+ }
218
+
219
+ const releases = await response.json();
220
+ return releases;
221
+ } catch (error) {
222
+ if (attempt > 1) {
223
+ console.log(
224
+ chalk.yellow(
225
+ ` ⚠️ Attempt ${attempt} failed: ${
226
+ error instanceof Error ? error.message : String(error)
227
+ }`
228
+ )
229
+ );
230
+ }
231
+
232
+ if (attempt === retries) {
233
+ console.error(chalk.red(` ❌ Failed to fetch releases after ${retries} attempts`));
234
+ return [];
235
+ }
236
+
237
+ // Wait 1 second before retry
238
+ await new Promise((resolve) => setTimeout(resolve, 1000 * attempt));
239
+ }
240
+ }
241
+
242
+ return [];
243
+ }
244
+
245
+ // Find compatible assets for current system
246
+ function findCompatibleAssets(release: GitHubRelease, systemInfo: SystemInfo): string[] {
247
+ const assets = release.assets.filter((asset) => {
248
+ const name = asset.name.toLowerCase();
249
+
250
+ // Platform matching with various aliases
251
+ const platformVariants = [
252
+ systemInfo.platformForAsset.toLowerCase(),
253
+ ...(systemInfo.platformForAsset === 'macos' ? ['darwin', 'apple'] : []),
254
+ ...(systemInfo.platformForAsset === 'windows' ? ['win', 'win32', 'windows'] : []),
255
+ ...(systemInfo.platformForAsset === 'ubuntu' ? ['linux', 'gnu'] : [])
256
+ ];
257
+
258
+ // Architecture matching with various aliases
259
+ const archVariants = [
260
+ systemInfo.archForAsset.toLowerCase(),
261
+ ...(systemInfo.archForAsset === 'x86_64' ? ['amd64', 'x64'] : []),
262
+ ...(systemInfo.archForAsset === 'aarch64' ? ['arm64'] : [])
263
+ ];
264
+
265
+ const platformMatch = platformVariants.some((variant) => name.includes(variant));
266
+ const archMatch = archVariants.some((variant) => name.includes(variant));
267
+
268
+ // Check for archive formats
269
+ const isArchive =
270
+ name.endsWith('.tar.gz') ||
271
+ name.endsWith('.zip') ||
272
+ name.endsWith('.tgz') ||
273
+ name.endsWith('.tar.bz2') ||
274
+ name.endsWith('.tar.xz');
275
+
276
+ return platformMatch && archMatch && isArchive;
277
+ });
278
+
279
+ return assets.map((asset) => asset.name);
280
+ }
281
+
282
+ // Get available versions for a tool
283
+ async function getAvailableVersions(
284
+ toolName: string,
285
+ systemInfo: SystemInfo
286
+ ): Promise<Array<{ version: string; hasCompatibleAsset: boolean }>> {
287
+ const config = TOOL_CONFIGS[toolName];
288
+ if (!config) return [];
289
+
290
+ const releases = await fetchGitHubReleases(config.repo, 10);
291
+
292
+ return releases.map((release) => ({
293
+ version: release.tag_name,
294
+ hasCompatibleAsset: findCompatibleAssets(release, systemInfo).length > 0
295
+ }));
296
+ }
297
+
298
+ // Auto-add PATH to shell configuration file
299
+ async function autoAddToShellConfig(installDir: string): Promise<void> {
300
+ try {
301
+ // Detect current shell
302
+ const shell = detectCurrentShell();
303
+ if (!shell) {
304
+ console.log(chalk.gray(`Please add to PATH: export PATH="$PATH:${installDir}"`));
305
+ return;
306
+ }
307
+
308
+ const { shellName, configFile } = shell;
309
+ const pathCommand =
310
+ shellName === 'fish'
311
+ ? `set -gx PATH $PATH ${installDir}`
312
+ : `export PATH="$PATH:${installDir}"`;
313
+
314
+ // Check if PATH is already added
315
+ if (fs.existsSync(configFile)) {
316
+ const content = fs.readFileSync(configFile, 'utf8');
317
+ if (content.includes(installDir)) {
318
+ console.log(chalk.green(` ✓ PATH already configured in ${configFile}`));
319
+ return;
320
+ }
321
+ }
322
+
323
+ // Add PATH to configuration file
324
+ const comment = shellName === 'fish' ? '# Added by dubhe doctor' : '# Added by dubhe doctor';
325
+ const pathLine = `${comment}\n${pathCommand}`;
326
+
327
+ fs.appendFileSync(configFile, `\n${pathLine}\n`);
328
+
329
+ console.log(chalk.green(` ✓ Automatically added to PATH in ${configFile}`));
330
+ console.log(chalk.blue(` 📝 To apply changes: source ${configFile} or restart terminal`));
331
+ } catch (error) {
332
+ console.log(
333
+ chalk.yellow(
334
+ ` ⚠️ Could not auto-configure PATH: ${
335
+ error instanceof Error ? error.message : String(error)
336
+ }`
337
+ )
338
+ );
339
+ console.log(chalk.gray(` Please manually add to PATH: export PATH="$PATH:${installDir}"`));
340
+ }
341
+ }
342
+
343
+ // Detect current shell and return shell info
344
+ function detectCurrentShell(): { shellName: string; configFile: string } | null {
345
+ const homeDir = os.homedir();
346
+
347
+ // Method 1: Check SHELL environment variable
348
+ const shellEnv = process.env.SHELL;
349
+ if (shellEnv) {
350
+ if (shellEnv.includes('zsh')) {
351
+ return {
352
+ shellName: 'zsh',
353
+ configFile: path.join(homeDir, '.zshrc')
354
+ };
355
+ } else if (shellEnv.includes('bash')) {
356
+ // On macOS, prefer .bash_profile, on Linux prefer .bashrc
357
+ const bashProfile = path.join(homeDir, '.bash_profile');
358
+ const bashrc = path.join(homeDir, '.bashrc');
359
+ return {
360
+ shellName: 'bash',
361
+ configFile:
362
+ process.platform === 'darwin' && fs.existsSync(bashProfile) ? bashProfile : bashrc
363
+ };
364
+ } else if (shellEnv.includes('fish')) {
365
+ const fishConfigDir = path.join(homeDir, '.config', 'fish');
366
+ if (!fs.existsSync(fishConfigDir)) {
367
+ fs.mkdirSync(fishConfigDir, { recursive: true });
368
+ }
369
+ return {
370
+ shellName: 'fish',
371
+ configFile: path.join(fishConfigDir, 'config.fish')
372
+ };
373
+ }
374
+ }
375
+
376
+ // Method 2: Check which config files exist
377
+ const possibleConfigs = [
378
+ { name: 'zsh', file: path.join(homeDir, '.zshrc') },
379
+ {
380
+ name: 'bash',
381
+ file:
382
+ process.platform === 'darwin'
383
+ ? path.join(homeDir, '.bash_profile')
384
+ : path.join(homeDir, '.bashrc')
385
+ },
386
+ { name: 'bash', file: path.join(homeDir, '.bashrc') }
387
+ ];
388
+
389
+ for (const config of possibleConfigs) {
390
+ if (fs.existsSync(config.file)) {
391
+ return {
392
+ shellName: config.name,
393
+ configFile: config.file
394
+ };
395
+ }
396
+ }
397
+
398
+ // Method 3: Try to create default based on common patterns
399
+ if (process.env.ZSH || fs.existsSync('/bin/zsh')) {
400
+ return {
401
+ shellName: 'zsh',
402
+ configFile: path.join(homeDir, '.zshrc')
403
+ };
404
+ }
405
+
406
+ return null;
407
+ }
408
+
409
+ // Download and install tool
410
+ async function downloadAndInstallTool(toolName: string, version?: string): Promise<boolean> {
411
+ const config = TOOL_CONFIGS[toolName];
412
+ if (!config) {
413
+ console.error(`Unknown tool: ${toolName}`);
414
+ return false;
415
+ }
416
+
417
+ const systemInfo = getSystemInfo();
418
+ console.log(chalk.gray(` System: ${systemInfo.platform}/${systemInfo.arch}`));
419
+
420
+ try {
421
+ // Fetch releases
422
+ console.log(chalk.gray(` Fetching release information...`));
423
+ const releases = await fetchGitHubReleases(config.repo, 10);
424
+ if (releases.length === 0) {
425
+ console.error(chalk.red(` ❌ Unable to fetch releases for ${config.name}`));
426
+ return false;
427
+ }
428
+
429
+ let selectedRelease: GitHubRelease | null = null;
430
+
431
+ if (version) {
432
+ // Find specific version
433
+ if (!version.startsWith('v')) {
434
+ version = `v${version}`;
435
+ }
436
+ selectedRelease = releases.find((r) => r.tag_name === version) || null;
437
+ if (!selectedRelease) {
438
+ console.error(`Version ${version} not found`);
439
+ return false;
440
+ }
441
+ } else {
442
+ // Find latest compatible version
443
+ for (const release of releases) {
444
+ const compatibleAssets = findCompatibleAssets(release, systemInfo);
445
+ if (compatibleAssets.length > 0) {
446
+ selectedRelease = release;
447
+ break;
448
+ }
449
+ }
450
+ }
451
+
452
+ if (!selectedRelease) {
453
+ console.error(`No compatible version found`);
454
+ return false;
455
+ }
456
+
457
+ // Find compatible asset
458
+ const compatibleAssets = findCompatibleAssets(selectedRelease, systemInfo);
459
+ if (compatibleAssets.length === 0) {
460
+ console.error(`Version ${selectedRelease.tag_name} has no compatible binaries`);
461
+ return false;
462
+ }
463
+
464
+ const assetName = compatibleAssets[0];
465
+ const asset = selectedRelease.assets.find((a) => a.name === assetName);
466
+ if (!asset) {
467
+ console.error(`Asset file not found: ${assetName}`);
468
+ return false;
469
+ }
470
+
471
+ console.log(chalk.green(` ✓ Found compatible version: ${selectedRelease.tag_name}`));
472
+ console.log(chalk.gray(` Download file: ${asset.name}`));
473
+
474
+ // Verify download link
475
+ try {
476
+ const headResponse = await fetchWithAxios(asset.browser_download_url, {
477
+ method: 'HEAD',
478
+ headers: { 'User-Agent': 'dubhe-cli' }
479
+ });
480
+ if (!headResponse.ok) {
481
+ console.log(
482
+ chalk.yellow(` ⚠️ Warning: Unable to access download file (${headResponse.status})`)
483
+ );
484
+ } else {
485
+ const fileSize = headResponse.headers['content-length'];
486
+ if (fileSize) {
487
+ console.log(
488
+ chalk.gray(
489
+ ` File size: ${Math.round((parseInt(fileSize) / 1024 / 1024) * 100) / 100} MB`
490
+ )
491
+ );
492
+ }
493
+ }
494
+ } catch (_error) {
495
+ console.log(chalk.yellow(` ⚠️ Warning: Unable to verify download file`));
496
+ }
497
+
498
+ // Create install directory
499
+ if (!fs.existsSync(config.installDir)) {
500
+ fs.mkdirSync(config.installDir, { recursive: true });
501
+ console.log(chalk.gray(` Created install directory: ${config.installDir}`));
502
+ }
503
+
504
+ // Download file with retry and progress bar
505
+ console.log(chalk.blue(` 📥 Downloading...`));
506
+
507
+ const tempFile = path.join(os.tmpdir(), asset.name);
508
+ const maxRetries = 3;
509
+
510
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
511
+ try {
512
+ if (attempt > 1) {
513
+ console.log(chalk.gray(` Attempt ${attempt} to download...`));
514
+ }
515
+
516
+ await downloadWithAxios(asset.browser_download_url, tempFile);
517
+ break;
518
+ } catch (error) {
519
+ const errorMsg = error instanceof Error ? error.message : String(error);
520
+ console.log(chalk.yellow(` ⚠️ Download failed (attempt ${attempt}): ${errorMsg}`));
521
+
522
+ if (attempt === maxRetries) {
523
+ throw new Error(`Download failed after ${maxRetries} attempts: ${errorMsg}`);
524
+ }
525
+
526
+ // Wait before retry
527
+ console.log(chalk.gray(` Waiting ${attempt * 2} seconds before retry...`));
528
+ await new Promise((resolve) => setTimeout(resolve, attempt * 2000));
529
+ }
530
+ }
531
+
532
+ // Extract and install
533
+ console.log(chalk.blue(' 📦 Extracting and installing...'));
534
+
535
+ const extractDir = path.join(os.tmpdir(), `extract_${Date.now()}`);
536
+ fs.mkdirSync(extractDir, { recursive: true });
537
+
538
+ if (asset.name.endsWith('.tar.gz') || asset.name.endsWith('.tgz')) {
539
+ // Extract tar.gz / tgz
540
+ const tarResult = await execCommand('tar', ['-xzf', tempFile, '-C', extractDir]);
541
+ if (tarResult.code !== 0) {
542
+ throw new Error(`Extraction failed: ${tarResult.stderr}`);
543
+ }
544
+ } else if (asset.name.endsWith('.tar.bz2')) {
545
+ // Extract tar.bz2
546
+ const tarResult = await execCommand('tar', ['-xjf', tempFile, '-C', extractDir]);
547
+ if (tarResult.code !== 0) {
548
+ throw new Error(`Extraction failed: ${tarResult.stderr}`);
549
+ }
550
+ } else if (asset.name.endsWith('.tar.xz')) {
551
+ // Extract tar.xz
552
+ const tarResult = await execCommand('tar', ['-xJf', tempFile, '-C', extractDir]);
553
+ if (tarResult.code !== 0) {
554
+ throw new Error(`Extraction failed: ${tarResult.stderr}`);
555
+ }
556
+ } else if (asset.name.endsWith('.zip')) {
557
+ // Extract zip (requires unzip command)
558
+ const unzipResult = await execCommand('unzip', ['-q', tempFile, '-d', extractDir]);
559
+ if (unzipResult.code !== 0) {
560
+ throw new Error(`Extraction failed: ${unzipResult.stderr}`);
561
+ }
562
+ } else {
563
+ throw new Error(`Unsupported compression format: ${asset.name}`);
564
+ }
565
+
566
+ // Find binary file
567
+ const findBinary = (dir: string): string | null => {
568
+ const files = fs.readdirSync(dir, { withFileTypes: true });
569
+ for (const file of files) {
570
+ const fullPath = path.join(dir, file.name);
571
+ if (file.isDirectory()) {
572
+ const result = findBinary(fullPath);
573
+ if (result) return result;
574
+ } else if (file.name === config.binaryName || file.name === `${config.binaryName}.exe`) {
575
+ return fullPath;
576
+ }
577
+ }
578
+ return null;
579
+ };
580
+
581
+ const binaryPath = findBinary(extractDir);
582
+ if (!binaryPath) {
583
+ throw new Error(`Cannot find ${config.binaryName} binary in extracted files`);
584
+ }
585
+
586
+ // Copy binary to install directory
587
+ const targetPath = path.join(
588
+ config.installDir,
589
+ config.binaryName + (process.platform === 'win32' ? '.exe' : '')
590
+ );
591
+ fs.copyFileSync(binaryPath, targetPath);
592
+
593
+ // Make executable on Unix systems
594
+ if (process.platform !== 'win32') {
595
+ fs.chmodSync(targetPath, 0o755);
596
+ }
597
+
598
+ // Cleanup
599
+ fs.rmSync(tempFile, { force: true });
600
+ fs.rmSync(extractDir, { recursive: true, force: true });
601
+
602
+ console.log(chalk.green(` ✅ Installation completed!`));
603
+ console.log(chalk.gray(` Location: ${targetPath}`));
604
+ console.log(chalk.gray(` Version: ${selectedRelease.tag_name}`));
605
+
606
+ // Check if install directory is in PATH
607
+ const currentPath = process.env.PATH || '';
608
+ if (!currentPath.includes(config.installDir)) {
609
+ console.log(
610
+ chalk.yellow(' ⚠️ Warning: Install directory is not in PATH environment variable')
611
+ );
612
+
613
+ if (process.platform === 'win32') {
614
+ console.log(chalk.gray(` Please add to PATH: set PATH=%PATH%;${config.installDir}`));
615
+ } else {
616
+ // Auto-add to shell configuration file
617
+ await autoAddToShellConfig(config.installDir);
618
+ }
619
+ }
620
+
621
+ return true;
622
+ } catch (error) {
623
+ console.error(chalk.red(`❌ Installation failed: ${error}`));
624
+ return false;
625
+ }
626
+ }
627
+
628
+ // Interactive version selection
629
+ async function selectVersion(toolName: string): Promise<string | null> {
630
+ const systemInfo = getSystemInfo();
631
+ const versions = await getAvailableVersions(toolName, systemInfo);
632
+
633
+ if (versions.length === 0) {
634
+ console.log(chalk.red(`Unable to get version information for ${toolName}`));
635
+ return null;
636
+ }
637
+
638
+ const compatibleVersions = versions.filter((v) => v.hasCompatibleAsset).slice(0, 5);
639
+
640
+ if (compatibleVersions.length === 0) {
641
+ console.log(chalk.red(`No compatible versions found for current system`));
642
+ return null;
643
+ }
644
+
645
+ console.log(chalk.blue(`\n📋 Select version for ${toolName}`));
646
+ console.log(chalk.gray(`System: ${systemInfo.platform}/${systemInfo.arch}`));
647
+ console.log(chalk.gray(`Compatible versions (latest 5):\n`));
648
+
649
+ const choices = compatibleVersions.map((version, index) => ({
650
+ name: `${version.version} ${index === 0 ? chalk.green('(latest)') : chalk.gray('(available)')}`,
651
+ value: version.version,
652
+ short: version.version
653
+ }));
654
+
655
+ try {
656
+ const answer = await inquirer.prompt([
657
+ {
658
+ type: 'list',
659
+ name: 'version',
660
+ message: 'Please select a version to install:',
661
+ choices: [
662
+ ...choices,
663
+ new inquirer.Separator(),
664
+ {
665
+ name: chalk.gray('Cancel installation'),
666
+ value: 'cancel'
667
+ }
668
+ ],
669
+ default: choices[0].value
670
+ }
671
+ ]);
672
+
673
+ if (answer.version === 'cancel') {
674
+ console.log(chalk.gray('Installation cancelled'));
675
+ return null;
676
+ }
677
+
678
+ return answer.version;
679
+ } catch (_error) {
680
+ console.log(chalk.gray('\nInstallation cancelled'));
681
+ return null;
682
+ }
683
+ }
684
+
685
+ // Check if binary exists in install directory
686
+ function checkBinaryExists(toolName: string): boolean {
687
+ const config = TOOL_CONFIGS[toolName];
688
+ if (!config) return false;
689
+
690
+ const binaryPath = path.join(
691
+ config.installDir,
692
+ config.binaryName + (process.platform === 'win32' ? '.exe' : '')
693
+ );
694
+
695
+ return fs.existsSync(binaryPath);
696
+ }
697
+
698
+ // Check dubhe-indexer version consistency with sui-cli
699
+ async function checkDubheIndexerVersionConsistency(): Promise<CheckResult> {
700
+ try {
701
+ const currentSuiCliVersion = packageJson.version;
702
+
703
+ // Get dubhe-indexer version
704
+ const result = await execCommand('dubhe-indexer', ['--version']);
705
+ if (result.code !== 0) {
706
+ return {
707
+ name: 'Dubhe-indexer Version Consistency',
708
+ status: 'warning',
709
+ message: 'Cannot get dubhe-indexer version',
710
+ fixSuggestion: 'Unable to verify version consistency'
711
+ };
712
+ }
713
+
714
+ // Parse version from output (expected format: "dubhe-indexer 1.2.0-pre.46" or similar)
715
+ const versionMatch = result.stdout.trim().match(/dubhe-indexer\s+(\S+)/);
716
+ if (!versionMatch) {
717
+ return {
718
+ name: 'Dubhe-indexer Version Consistency',
719
+ status: 'warning',
720
+ message: 'Cannot parse dubhe-indexer version',
721
+ fixSuggestion: 'Unable to verify version consistency'
722
+ };
723
+ }
724
+
725
+ const dubheIndexerVersion = versionMatch[1];
726
+
727
+ // Compare versions
728
+ if (currentSuiCliVersion === dubheIndexerVersion) {
729
+ return {
730
+ name: 'Dubhe-indexer Version Consistency',
731
+ status: 'success',
732
+ message: `Versions match (${currentSuiCliVersion})`
733
+ };
734
+ } else {
735
+ return {
736
+ name: 'Dubhe-indexer Version Consistency',
737
+ status: 'warning',
738
+ message: `Version mismatch: sui-cli ${currentSuiCliVersion}, dubhe-indexer ${dubheIndexerVersion}`,
739
+ fixSuggestion: `Consider reinstalling dubhe-indexer to match sui-cli version ${currentSuiCliVersion}`
740
+ };
741
+ }
742
+ } catch (_error) {
743
+ return {
744
+ name: 'Dubhe-indexer Version Consistency',
745
+ status: 'warning',
746
+ message: 'Version check failed',
747
+ fixSuggestion: 'Unable to verify version consistency'
748
+ };
749
+ }
750
+ }
751
+
752
+ // Check if command is available in PATH
753
+ async function checkCommand(
754
+ command: string,
755
+ versionFlag: string = '--version'
756
+ ): Promise<CheckResult> {
757
+ try {
758
+ const result = await execCommand(command, [versionFlag]);
759
+ if (result.code === 0) {
760
+ const version = result.stdout.trim().split('\n')[0];
761
+ return {
762
+ name: command,
763
+ status: 'success',
764
+ message: `Installed ${version}`
765
+ };
766
+ } else {
767
+ // Check if binary exists in install directory but not in PATH
768
+ if (checkBinaryExists(command)) {
769
+ const shell = detectCurrentShell();
770
+ const shellConfig = shell ? shell.configFile : '~/.zshrc (or ~/.bashrc)';
771
+
772
+ return {
773
+ name: command,
774
+ status: 'warning',
775
+ message: 'Installed but not in PATH',
776
+ fixSuggestion: `Binary exists in install directory. Please apply PATH changes: source ${shellConfig} (or restart terminal), then run dubhe doctor again`
777
+ };
778
+ }
779
+
780
+ return {
781
+ name: command,
782
+ status: 'error',
783
+ message: 'Not installed',
784
+ fixSuggestion: getInstallSuggestion(command)
785
+ };
786
+ }
787
+ } catch (_error) {
788
+ // Check if binary exists in install directory but not in PATH
789
+ if (checkBinaryExists(command)) {
790
+ const shell = detectCurrentShell();
791
+ const shellConfig = shell ? shell.configFile : '~/.zshrc (or ~/.bashrc)';
792
+
793
+ return {
794
+ name: command,
795
+ status: 'warning',
796
+ message: 'Installed but not in PATH',
797
+ fixSuggestion: `Binary exists in install directory. Please apply PATH changes: source ${shellConfig} (or restart terminal), then run dubhe doctor again`
798
+ };
799
+ }
800
+
801
+ return {
802
+ name: command,
803
+ status: 'error',
804
+ message: 'Not installed',
805
+ fixSuggestion: getInstallSuggestion(command)
806
+ };
807
+ }
808
+ }
809
+
810
+ // Get installation suggestions
811
+ function getInstallSuggestion(command: string): string {
812
+ const suggestions: Record<string, string> = {
813
+ docker: 'Visit https://docs.docker.com/get-docker/ to install Docker',
814
+ 'docker-compose': 'Visit https://docs.docker.com/compose/install/ to install Docker Compose',
815
+ sui: 'Run `dubhe doctor --install sui` to auto-install, or visit https://docs.sui.io/guides/developer/getting-started/sui-install',
816
+ 'dubhe-indexer':
817
+ 'Run `dubhe doctor --install dubhe-indexer` to auto-install, or download from https://github.com/0xobelisk/dubhe/releases',
818
+ pnpm: 'Run: npm install -g pnpm',
819
+ node: 'Visit https://nodejs.org/ to download and install Node.js'
820
+ };
821
+
822
+ return suggestions[command] || `Please install ${command}`;
823
+ }
824
+
825
+ // Check Node.js version
826
+ async function checkNodeVersion(): Promise<CheckResult> {
827
+ try {
828
+ const result = await execCommand('node', ['--version']);
829
+ if (result.code === 0) {
830
+ const version = result.stdout.trim();
831
+ const versionNumber = parseFloat(version.replace('v', ''));
832
+
833
+ if (versionNumber >= 18) {
834
+ return {
835
+ name: 'Node.js Version',
836
+ status: 'success',
837
+ message: `${version} (meets requirement >=18.0)`
838
+ };
839
+ } else {
840
+ return {
841
+ name: 'Node.js Version',
842
+ status: 'warning',
843
+ message: `${version} (recommend upgrade to >=18.0)`,
844
+ fixSuggestion: 'Please upgrade Node.js to 18.0 or higher'
845
+ };
846
+ }
847
+ } else {
848
+ return {
849
+ name: 'Node.js Version',
850
+ status: 'error',
851
+ message: 'Not installed',
852
+ fixSuggestion: 'Please install Node.js 18.0 or higher'
853
+ };
854
+ }
855
+ } catch (_error) {
856
+ return {
857
+ name: 'Node.js Version',
858
+ status: 'error',
859
+ message: 'Check failed',
860
+ fixSuggestion: 'Please install Node.js'
861
+ };
862
+ }
863
+ }
864
+
865
+ // Check Docker service status
866
+ async function checkDockerService(): Promise<CheckResult> {
867
+ try {
868
+ const result = await execCommand('docker', ['info']);
869
+ if (result.code === 0) {
870
+ return {
871
+ name: 'Docker Service',
872
+ status: 'success',
873
+ message: 'Running'
874
+ };
875
+ } else {
876
+ return {
877
+ name: 'Docker Service',
878
+ status: 'warning',
879
+ message: 'Not running',
880
+ fixSuggestion: 'Please start Docker service'
881
+ };
882
+ }
883
+ } catch (_error) {
884
+ return {
885
+ name: 'Docker Service',
886
+ status: 'error',
887
+ message: 'Check failed',
888
+ fixSuggestion: 'Please install and start Docker'
889
+ };
890
+ }
891
+ }
892
+
893
+ // Check NPM configuration
894
+ async function checkNpmConfig(): Promise<CheckResult> {
895
+ try {
896
+ const result = await execCommand('npm', ['config', 'get', 'registry']);
897
+ if (result.code === 0) {
898
+ const registry = result.stdout.trim();
899
+ return {
900
+ name: 'NPM Configuration',
901
+ status: 'success',
902
+ message: `Configured (${registry})`
903
+ };
904
+ } else {
905
+ return {
906
+ name: 'NPM Configuration',
907
+ status: 'warning',
908
+ message: 'Configuration issue',
909
+ fixSuggestion: 'Check NPM configuration: npm config list'
910
+ };
911
+ }
912
+ } catch (_error) {
913
+ return {
914
+ name: 'NPM Configuration',
915
+ status: 'warning',
916
+ message: 'Check failed',
917
+ fixSuggestion: 'Please install Node.js and NPM'
918
+ };
919
+ }
920
+ }
921
+
922
+ // Check if port is available
923
+ async function checkPortAvailable(port: number): Promise<boolean> {
924
+ // Check both localhost and all interfaces
925
+ const hosts = ['127.0.0.1', '0.0.0.0'];
926
+
927
+ for (const host of hosts) {
928
+ const available = await checkPortOnHost(port, host);
929
+ if (!available) {
930
+ return false; // Port is occupied on this host
931
+ }
932
+ }
933
+
934
+ return true; // Port is available on all checked hosts
935
+ }
936
+
937
+ // Check if port is available on specific host
938
+ async function checkPortOnHost(port: number, host: string): Promise<boolean> {
939
+ return new Promise((resolve) => {
940
+ const server = net.createServer();
941
+
942
+ // Set a timeout to avoid hanging
943
+ const timeout = setTimeout(() => {
944
+ server.close();
945
+ resolve(false); // Assume occupied if timeout
946
+ }, 2000);
947
+
948
+ // Try to bind to the port - if this fails, port is in use
949
+ server.listen(port, host, () => {
950
+ clearTimeout(timeout);
951
+ server.close(() => {
952
+ resolve(true); // Port is available on this host
953
+ });
954
+ });
955
+
956
+ server.on('error', (err: any) => {
957
+ clearTimeout(timeout);
958
+ server.close();
959
+ // If error code is EADDRINUSE, port is definitely in use
960
+ if (err.code === 'EADDRINUSE') {
961
+ resolve(false); // Port is in use
962
+ } else {
963
+ // For other errors, also assume port is not available
964
+ resolve(false);
965
+ }
966
+ });
967
+ });
968
+ }
969
+
970
+ // Check PostgreSQL port (5432)
971
+ async function checkPostgreSQLPort(): Promise<CheckResult> {
972
+ try {
973
+ const isAvailable = await checkPortAvailable(5432);
974
+
975
+ if (isAvailable) {
976
+ return {
977
+ name: 'PostgreSQL Port (5432)',
978
+ status: 'success',
979
+ message: 'Available'
980
+ };
981
+ } else {
982
+ return {
983
+ name: 'PostgreSQL Port (5432)',
984
+ status: 'warning',
985
+ message: 'Port is occupied',
986
+ fixSuggestion:
987
+ 'Port 5432 is in use. Check if PostgreSQL is already running or stop the service using this port. This may cause template startup failure.'
988
+ };
989
+ }
990
+ } catch (_error) {
991
+ return {
992
+ name: 'PostgreSQL Port (5432)',
993
+ status: 'warning',
994
+ message: 'Check failed',
995
+ fixSuggestion: 'Unable to check port status'
996
+ };
997
+ }
998
+ }
999
+
1000
+ // Check GraphQL Server port (4000)
1001
+ async function checkGraphQLPort(): Promise<CheckResult> {
1002
+ try {
1003
+ const isAvailable = await checkPortAvailable(4000);
1004
+
1005
+ if (isAvailable) {
1006
+ return {
1007
+ name: 'GraphQL Server Port (4000)',
1008
+ status: 'success',
1009
+ message: 'Available'
1010
+ };
1011
+ } else {
1012
+ return {
1013
+ name: 'GraphQL Server Port (4000)',
1014
+ status: 'warning',
1015
+ message: 'Port is occupied',
1016
+ fixSuggestion:
1017
+ 'Port 4000 is in use. Check if GraphQL server is already running or stop the service using this port. This may cause template startup failure.'
1018
+ };
1019
+ }
1020
+ } catch (_error) {
1021
+ return {
1022
+ name: 'GraphQL Server Port (4000)',
1023
+ status: 'warning',
1024
+ message: 'Check failed',
1025
+ fixSuggestion: 'Unable to check port status'
1026
+ };
1027
+ }
1028
+ }
1029
+
1030
+ // Create table row data
1031
+ function formatTableRow(result: CheckResult): string[] {
1032
+ const statusIcon = {
1033
+ success: chalk.green('✓'),
1034
+ warning: chalk.yellow('!'),
1035
+ error: chalk.red('✗')
1036
+ };
1037
+
1038
+ const statusText = {
1039
+ success: chalk.green('Pass'),
1040
+ warning: chalk.yellow('Warning'),
1041
+ error: chalk.red('Fail')
1042
+ };
1043
+
1044
+ // Decide what content to display based on status
1045
+ let fixContent = '';
1046
+ if (result.status === 'success') {
1047
+ fixContent = result.message;
1048
+ } else {
1049
+ fixContent = result.fixSuggestion || result.message;
1050
+ }
1051
+
1052
+ return [result.name, `${statusIcon[result.status]} ${statusText[result.status]}`, fixContent];
1053
+ }
1054
+
1055
+ // Main check function
1056
+ async function runDoctorChecks(options: {
1057
+ install?: string;
1058
+ selectVersion?: boolean;
1059
+ listVersions?: string;
1060
+ debug?: boolean;
1061
+ }) {
1062
+ console.log(chalk.bold.blue('\n🔍 Dubhe Doctor - Development Environment Checker\n'));
1063
+
1064
+ // Handle list-versions option
1065
+ if (options.listVersions) {
1066
+ const toolName = options.listVersions;
1067
+ if (!TOOL_CONFIGS[toolName]) {
1068
+ console.error(chalk.red(`❌ Unsupported tool: ${toolName}`));
1069
+ handlerExit(1);
1070
+ }
1071
+
1072
+ console.log(chalk.blue(`📋 Available versions for ${toolName}:`));
1073
+ const systemInfo = getSystemInfo();
1074
+ console.log(chalk.gray(`System: ${systemInfo.platform}/${systemInfo.arch}\n`));
1075
+
1076
+ // Get 10 versions directly to avoid duplicate calls
1077
+ const config = TOOL_CONFIGS[toolName];
1078
+ const releases = await fetchGitHubReleases(config.repo, 10);
1079
+
1080
+ if (releases.length === 0) {
1081
+ console.log(chalk.red('Unable to get version information'));
1082
+ handlerExit(1);
1083
+ }
1084
+
1085
+ // Process version compatibility check
1086
+ const versions = releases.map((release) => ({
1087
+ version: release.tag_name,
1088
+ hasCompatibleAsset: findCompatibleAssets(release, systemInfo).length > 0,
1089
+ publishDate: new Date(release.published_at).toLocaleDateString('en-US')
1090
+ }));
1091
+
1092
+ const table = new Table({
1093
+ head: [
1094
+ chalk.bold.cyan('Version'),
1095
+ chalk.bold.cyan('Compatibility'),
1096
+ chalk.bold.cyan('Release Date')
1097
+ ],
1098
+ colWidths: [30, 15, 25]
1099
+ });
1100
+
1101
+ versions.forEach((version) => {
1102
+ table.push([
1103
+ version.version,
1104
+ version.hasCompatibleAsset ? chalk.green('✓ Compatible') : chalk.red('✗ Incompatible'),
1105
+ version.publishDate
1106
+ ]);
1107
+ });
1108
+
1109
+ console.log(table.toString());
1110
+
1111
+ if (options.debug && versions.length > 0) {
1112
+ console.log(chalk.blue('\n🔍 Debug Information:'));
1113
+ const latestCompatible = versions.find((v) => v.hasCompatibleAsset);
1114
+ if (latestCompatible) {
1115
+ const release = releases.find((r) => r.tag_name === latestCompatible.version);
1116
+ if (release) {
1117
+ console.log(chalk.gray(`Latest compatible version: ${latestCompatible.version}`));
1118
+ console.log(chalk.gray(`Available asset files:`));
1119
+ release.assets.forEach((asset) => {
1120
+ console.log(chalk.gray(` - ${asset.name}`));
1121
+ });
1122
+
1123
+ const compatibleAssets = findCompatibleAssets(release, systemInfo);
1124
+ console.log(chalk.gray(`Compatible asset files:`));
1125
+ compatibleAssets.forEach((asset) => {
1126
+ console.log(chalk.green(` ✓ ${asset}`));
1127
+ });
1128
+ }
1129
+ }
1130
+ }
1131
+
1132
+ handlerExit();
1133
+ }
1134
+
1135
+ console.log(chalk.gray('Checking your development environment...\n'));
1136
+
1137
+ // Handle install option
1138
+ if (options.install) {
1139
+ const toolName = options.install;
1140
+ if (!TOOL_CONFIGS[toolName]) {
1141
+ console.error(chalk.red(`❌ Unsupported tool: ${toolName}`));
1142
+ console.log(chalk.gray(`Supported tools: ${Object.keys(TOOL_CONFIGS).join(', ')}`));
1143
+ handlerExit(1);
1144
+ }
1145
+
1146
+ let version: string | null = null;
1147
+ if (options.selectVersion) {
1148
+ version = await selectVersion(toolName);
1149
+ if (!version) {
1150
+ handlerExit(1);
1151
+ }
1152
+ } else if (toolName === 'dubhe-indexer') {
1153
+ // Default to sui-cli version for dubhe-indexer
1154
+ version = packageJson.version;
1155
+ console.log(
1156
+ chalk.blue(`📦 Installing dubhe-indexer version ${version} (matching sui-cli version)`)
1157
+ );
1158
+ }
1159
+
1160
+ const success = await downloadAndInstallTool(toolName, version || undefined);
1161
+ handlerExit(success ? 0 : 1);
1162
+ }
1163
+
1164
+ const results: CheckResult[] = [];
1165
+
1166
+ // Execute all checks
1167
+ console.log('Running checks...\n');
1168
+
1169
+ // Required tools check
1170
+ const nodeCheck = await checkNodeVersion();
1171
+ results.push(nodeCheck);
1172
+
1173
+ const pnpmCheck = await checkCommand('pnpm');
1174
+ results.push(pnpmCheck);
1175
+
1176
+ // Package manager configuration check
1177
+ const npmConfigCheck = await checkNpmConfig();
1178
+ // Treat npm config as optional, don't affect overall status
1179
+ if (npmConfigCheck.status === 'error') {
1180
+ npmConfigCheck.status = 'warning';
1181
+ }
1182
+ results.push(npmConfigCheck);
1183
+
1184
+ // Docker related checks
1185
+ const dockerCheck = await checkCommand('docker');
1186
+ results.push(dockerCheck);
1187
+
1188
+ let dockerServiceCheck: CheckResult | null = null;
1189
+ if (dockerCheck.status === 'success') {
1190
+ dockerServiceCheck = await checkDockerService();
1191
+ results.push(dockerServiceCheck);
1192
+ }
1193
+
1194
+ const dockerComposeCheck = await checkCommand('docker-compose');
1195
+ results.push(dockerComposeCheck);
1196
+
1197
+ // Sui CLI check
1198
+ const suiCheck = await checkCommand('sui');
1199
+ results.push(suiCheck);
1200
+
1201
+ // Dubhe indexer check
1202
+ const dubheIndexerCheck = await checkCommand('dubhe-indexer');
1203
+ results.push(dubheIndexerCheck);
1204
+
1205
+ // Dubhe indexer version consistency check (only if basic check passed)
1206
+ if (dubheIndexerCheck.status === 'success') {
1207
+ const dubheIndexerVersionCheck = await checkDubheIndexerVersionConsistency();
1208
+ results.push(dubheIndexerVersionCheck);
1209
+ }
1210
+
1211
+ // Port availability checks
1212
+ const postgresPortCheck = await checkPostgreSQLPort();
1213
+ results.push(postgresPortCheck);
1214
+
1215
+ const graphqlPortCheck = await checkGraphQLPort();
1216
+ results.push(graphqlPortCheck);
1217
+
1218
+ // Create and display table
1219
+ const table = new Table({
1220
+ head: [
1221
+ chalk.bold.cyan('Check Item'),
1222
+ chalk.bold.cyan('Result'),
1223
+ chalk.bold.cyan('Description/Fix Suggestion')
1224
+ ],
1225
+ colWidths: [25, 15, 60],
1226
+ style: {
1227
+ head: ['cyan'],
1228
+ border: ['grey']
1229
+ },
1230
+ wordWrap: true
1231
+ });
1232
+
1233
+ // Add table rows
1234
+ results.forEach((result) => {
1235
+ table.push(formatTableRow(result));
1236
+ });
1237
+
1238
+ console.log(table.toString());
1239
+
1240
+ // Summarize results
1241
+ const summary = {
1242
+ success: results.filter((r) => r.status === 'success').length,
1243
+ warning: results.filter((r) => r.status === 'warning').length,
1244
+ error: results.filter((r) => r.status === 'error').length
1245
+ };
1246
+
1247
+ console.log('\n' + chalk.bold('📊 Check Summary:'));
1248
+ console.log(` ${chalk.green('✓ Passed:')} ${summary.success} items`);
1249
+ console.log(` ${chalk.yellow('! Warning:')} ${summary.warning} items`);
1250
+ console.log(` ${chalk.red('✗ Failed:')} ${summary.error} items`);
1251
+
1252
+ // Handle dubhe-indexer version inconsistency
1253
+ const versionInconsistencyWarning = results.find(
1254
+ (r) =>
1255
+ r.name === 'Dubhe-indexer Version Consistency' &&
1256
+ r.status === 'warning' &&
1257
+ r.message.includes('Version mismatch')
1258
+ );
1259
+
1260
+ if (versionInconsistencyWarning) {
1261
+ console.log(chalk.yellow('\n⚠️ Dubhe-indexer version inconsistency detected!'));
1262
+ console.log(chalk.gray(` ${versionInconsistencyWarning.message}`));
1263
+
1264
+ try {
1265
+ const answer = await inquirer.prompt([
1266
+ {
1267
+ type: 'confirm',
1268
+ name: 'reinstallDubheIndexer',
1269
+ message: 'Would you like to reinstall dubhe-indexer to match the sui-cli version?',
1270
+ default: true
1271
+ }
1272
+ ]);
1273
+
1274
+ if (answer.reinstallDubheIndexer) {
1275
+ console.log(chalk.blue('\n📦 Reinstalling dubhe-indexer...\n'));
1276
+ console.log(chalk.blue(`${'='.repeat(60)}`));
1277
+ console.log(chalk.blue('📦 Installing dubhe-indexer...'));
1278
+ console.log(chalk.blue(`${'='.repeat(60)}`));
1279
+
1280
+ // Get the current sui-cli version to install matching dubhe-indexer
1281
+ const success = await downloadAndInstallTool('dubhe-indexer', packageJson.version);
1282
+
1283
+ if (success) {
1284
+ console.log(chalk.green('\n✅ Dubhe-indexer reinstallation completed successfully!'));
1285
+ console.log(
1286
+ chalk.blue(' Please restart your terminal or run: source ~/.zshrc (or ~/.bashrc)')
1287
+ );
1288
+ console.log(chalk.blue(' Then run: dubhe doctor to verify the installation'));
1289
+ } else {
1290
+ console.log(chalk.red('\n❌ Dubhe-indexer reinstallation failed'));
1291
+ console.log(
1292
+ chalk.gray(' You can try manual installation: dubhe doctor --install dubhe-indexer')
1293
+ );
1294
+ }
1295
+ } else {
1296
+ console.log(chalk.gray('\nVersion inconsistency ignored. You can reinstall later with:'));
1297
+ console.log(chalk.gray(' dubhe doctor --install dubhe-indexer'));
1298
+ }
1299
+ } catch (_error) {
1300
+ console.log(chalk.gray('\nVersion inconsistency check cancelled.'));
1301
+ }
1302
+ }
1303
+
1304
+ // Handle missing tools
1305
+ const allFailedTools = results.filter((r) => r.status === 'error');
1306
+ const autoInstallableTools = allFailedTools.filter((r) => TOOL_CONFIGS[r.name]);
1307
+ const manualInstallTools = allFailedTools.filter((r) => !TOOL_CONFIGS[r.name]);
1308
+
1309
+ // Show manual installation suggestions for non-auto-installable tools
1310
+ if (manualInstallTools.length > 0) {
1311
+ console.log(chalk.blue('\n🔧 Missing tools that require manual installation:'));
1312
+ manualInstallTools.forEach((tool) => {
1313
+ console.log(` ${chalk.red('✗')} ${tool.name}: ${tool.fixSuggestion || tool.message}`);
1314
+ });
1315
+ }
1316
+
1317
+ // Auto-install missing tools that support it
1318
+ if (autoInstallableTools.length > 0) {
1319
+ // Check if any of the tools are already installed in the install directory
1320
+ const alreadyInstalledTools = autoInstallableTools.filter((tool) =>
1321
+ checkBinaryExists(tool.name)
1322
+ );
1323
+ const notInstalledTools = autoInstallableTools.filter((tool) => !checkBinaryExists(tool.name));
1324
+
1325
+ if (alreadyInstalledTools.length > 0) {
1326
+ const installedNames = alreadyInstalledTools.map((tool) => tool.name).join(', ');
1327
+ const installDir = TOOL_CONFIGS[alreadyInstalledTools[0].name]?.installDir || '~/.dubhe/bin';
1328
+ const shell = detectCurrentShell();
1329
+ const shellConfig = shell ? shell.configFile : '~/.zshrc (or ~/.bashrc)';
1330
+
1331
+ console.log(chalk.yellow(`\n⚠️ Tools already installed but not in PATH: ${installedNames}`));
1332
+ console.log(chalk.gray(` Location: ${installDir}`));
1333
+ console.log(chalk.blue(' To fix this, apply PATH changes:'));
1334
+ console.log(chalk.green(` source ${shellConfig}`));
1335
+ console.log(chalk.blue(' Or restart your terminal, then run: dubhe doctor'));
1336
+ console.log(
1337
+ chalk.gray(
1338
+ ` If you want to reinstall, remove the files from ${installDir} and run dubhe doctor again`
1339
+ )
1340
+ );
1341
+ }
1342
+
1343
+ if (notInstalledTools.length > 0) {
1344
+ const notInstalledNames = notInstalledTools.map((tool) => tool.name).join(', ');
1345
+ console.log(chalk.blue(`\n🚀 Auto-installable tools detected: ${notInstalledNames}`));
1346
+
1347
+ try {
1348
+ const answer = await inquirer.prompt([
1349
+ {
1350
+ type: 'confirm',
1351
+ name: 'installAll',
1352
+ message: `Would you like to automatically install these tools? (${notInstalledNames})`,
1353
+ default: true
1354
+ }
1355
+ ]);
1356
+
1357
+ if (answer.installAll) {
1358
+ console.log(chalk.blue('\n📦 Starting installation of auto-installable tools...\n'));
1359
+
1360
+ let installationResults: Array<{ name: string; success: boolean }> = [];
1361
+
1362
+ for (const tool of notInstalledTools) {
1363
+ console.log(chalk.blue(`${'='.repeat(60)}`));
1364
+ console.log(chalk.blue(`📦 Installing ${tool.name}...`));
1365
+ console.log(chalk.blue(`${'='.repeat(60)}`));
1366
+
1367
+ // Use sui-cli version for dubhe-indexer
1368
+ const installVersion = tool.name === 'dubhe-indexer' ? packageJson.version : undefined;
1369
+ if (tool.name === 'dubhe-indexer') {
1370
+ console.log(
1371
+ chalk.blue(` Using version ${installVersion} (matching sui-cli version)`)
1372
+ );
1373
+ }
1374
+
1375
+ const success = await downloadAndInstallTool(tool.name, installVersion);
1376
+ installationResults.push({ name: tool.name, success });
1377
+
1378
+ if (success) {
1379
+ console.log(chalk.green(`\n✅ ${tool.name} installation completed successfully!`));
1380
+ } else {
1381
+ console.log(chalk.red(`\n❌ ${tool.name} installation failed`));
1382
+ console.log(
1383
+ chalk.gray(` Manual installation: dubhe doctor --install ${tool.name}`)
1384
+ );
1385
+ }
1386
+ console.log(''); // Add spacing between tools
1387
+ }
1388
+
1389
+ // Show installation summary
1390
+ console.log(chalk.blue(`${'='.repeat(60)}`));
1391
+ console.log(chalk.bold('📋 Installation Summary:'));
1392
+ console.log(chalk.blue(`${'='.repeat(60)}`));
1393
+
1394
+ installationResults.forEach((result) => {
1395
+ const status = result.success ? chalk.green('✅ Success') : chalk.red('❌ Failed');
1396
+ console.log(` ${result.name}: ${status}`);
1397
+ });
1398
+
1399
+ const successCount = installationResults.filter((r) => r.success).length;
1400
+ const failureCount = installationResults.length - successCount;
1401
+
1402
+ console.log(
1403
+ `\n ${chalk.green('Successful:')} ${successCount}/${installationResults.length}`
1404
+ );
1405
+ if (failureCount > 0) {
1406
+ console.log(` ${chalk.red('Failed:')} ${failureCount}/${installationResults.length}`);
1407
+ }
1408
+
1409
+ // Check if any tools were successfully installed
1410
+ if (successCount > 0) {
1411
+ const shell = detectCurrentShell();
1412
+ const shellConfig = shell ? shell.configFile : '~/.zshrc (or ~/.bashrc)';
1413
+
1414
+ console.log(chalk.blue('\n🔄 Next Steps:'));
1415
+ console.log(chalk.yellow(' 1. Apply PATH changes by running:'));
1416
+ console.log(chalk.green(` source ${shellConfig}`));
1417
+ console.log(chalk.yellow(' 2. Or restart your terminal'));
1418
+ console.log(chalk.yellow(' 3. Then run the doctor check again:'));
1419
+ console.log(chalk.green(' dubhe doctor'));
1420
+ console.log(
1421
+ chalk.gray('\n This will verify that all tools are properly configured.')
1422
+ );
1423
+ } else {
1424
+ console.log(
1425
+ chalk.red('\n❌ All installations failed. Please check the error messages above.')
1426
+ );
1427
+ }
1428
+ } else {
1429
+ console.log(
1430
+ chalk.gray('\nAuto-installation skipped. You can install them manually later:')
1431
+ );
1432
+ notInstalledTools.forEach((tool) => {
1433
+ console.log(chalk.gray(` dubhe doctor --install ${tool.name}`));
1434
+ });
1435
+ }
1436
+ } catch (_error) {
1437
+ console.log(chalk.gray('\nInstallation cancelled. You can install them manually later:'));
1438
+ notInstalledTools.forEach((tool) => {
1439
+ console.log(chalk.gray(` dubhe doctor --install ${tool.name}`));
1440
+ });
1441
+ }
1442
+ }
1443
+ }
1444
+
1445
+ // If no auto-installable tools are missing, show final status
1446
+ if (autoInstallableTools.length === 0) {
1447
+ if (summary.error > 0) {
1448
+ console.log(
1449
+ chalk.red(
1450
+ '\n❌ Your environment has some issues. Please fix them according to the suggestions above.'
1451
+ )
1452
+ );
1453
+ handlerExit(1);
1454
+ } else if (summary.warning > 0) {
1455
+ console.log(
1456
+ chalk.yellow(
1457
+ '\n⚠️ Your environment is basically ready, but we recommend fixing the warnings for better development experience.'
1458
+ )
1459
+ );
1460
+ } else {
1461
+ console.log(
1462
+ chalk.green('\n✅ Congratulations! Your development environment is fully ready!')
1463
+ );
1464
+ }
1465
+ }
1466
+
1467
+ console.log(
1468
+ chalk.gray(
1469
+ '\n💡 Tip: For more help, visit https://docs.sui.io/ or https://github.com/0xobelisk/dubhe'
1470
+ )
1471
+ );
1472
+ }
1473
+
1474
+ const commandModule: CommandModule = {
1475
+ command: 'doctor',
1476
+ describe: 'Check if local development environment is ready',
1477
+ builder(yargs) {
1478
+ return yargs
1479
+ .option('install', {
1480
+ type: 'string',
1481
+ describe: 'Auto-install specified tool (sui, dubhe-indexer)',
1482
+ choices: Object.keys(TOOL_CONFIGS)
1483
+ })
1484
+ .option('select-version', {
1485
+ type: 'boolean',
1486
+ default: false,
1487
+ describe: 'Select specific version for installation'
1488
+ })
1489
+ .option('list-versions', {
1490
+ type: 'string',
1491
+ describe: 'List available versions for specified tool',
1492
+ choices: Object.keys(TOOL_CONFIGS)
1493
+ })
1494
+ .option('debug', {
1495
+ type: 'boolean',
1496
+ default: false,
1497
+ describe: 'Show detailed debug information'
1498
+ });
1499
+ },
1500
+ async handler(argv) {
1501
+ try {
1502
+ await runDoctorChecks({
1503
+ install: argv.install as string | undefined,
1504
+ selectVersion: argv['select-version'] as boolean,
1505
+ listVersions: argv['list-versions'] as string | undefined,
1506
+ debug: argv.debug as boolean
1507
+ });
1508
+ } catch (error) {
1509
+ console.error(chalk.red('Error occurred during check:'), error);
1510
+ handlerExit(1);
1511
+ }
1512
+ }
1513
+ };
1514
+
1515
+ export default commandModule;