-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup-claude-code.sh
More file actions
1763 lines (1520 loc) · 60.2 KB
/
setup-claude-code.sh
File metadata and controls
1763 lines (1520 loc) · 60.2 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 bash
# =============================================================================
# Claude Code One-Click Deployment Script for Offline/Online System
# =============================================================================
# Purpose: Set up Claude Code for a team member using offline packages or
# automatic download with automatic mirror source detection.
#
# Usage: bash setup-claude-code.sh [--offline-path PATH] [--auto-download]
#
# Author: DeepTrial (Enhanced)
# Version: 2.1 - With Mirror Source Detection
# =============================================================================
set -euo pipefail
# ---------------------------------------------------------------------------
# Configuration & Constants
# ---------------------------------------------------------------------------
# Get absolute path of script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Convert to absolute path in case it's relative
SCRIPT_DIR="$(cd "$SCRIPT_DIR" && pwd)"
USER_CLAUDE_DIR="$HOME/.claude"
USER_TMPDIR="$HOME/.claude/tmp"
BASHRC="$HOME/.bashrc"
# GitHub Release Configuration
GITHUB_REPO="anthropics/claude-code"
GITHUB_API_URL="https://api.github.com/repos/${GITHUB_REPO}/releases/latest"
# Default offline package path (relative to script location)
DEFAULT_OFFLINE_PATH="${SCRIPT_DIR}/claude-offline-packages"
# Sentinel markers for shell config
SETUP_START="# >>> CLAUDE_CODE_SETUP >>>"
SETUP_END="# <<< CLAUDE_CODE_SETUP <<<"
NODE_START="# >>> CLAUDE_CODE_NODE >>>"
NODE_END="# <<< CLAUDE_CODE_NODE <<<"
# Network timeout settings (seconds)
NETWORK_TIMEOUT=10
CURL_RETRY=2
# ---------------------------------------------------------------------------
# Mirror Source Configuration
# ---------------------------------------------------------------------------
# Node.js binary mirror sources
NODE_MIRRORS=(
"https://nodejs.org/dist/"
"https://npmmirror.com/mirrors/node/"
"http://mirrors.cloud.tencent.com/nodejs-release/"
)
# npm registry mirror sources
NPM_MIRRORS=(
"https://registry.npmjs.org/"
"https://registry.npmmirror.com"
)
# nvm install script mirror sources
NVM_INSTALL_MIRRORS=(
"https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh"
"https://cdn.jsdelivr.net/gh/nvm-sh/nvm@v0.39.7/install.sh"
"https://raw.gitmirror.com/nvm-sh/nvm/v0.39.7/install.sh"
)
# GitHub API/Release mirror sources (for fetching download URLs)
GITHUB_MIRRORS=(
"https://api.github.com"
"https://hub.gitmirror.com/https://api.github.com"
"https://ghproxy.com/https://api.github.com"
"https://ghps.cc/https://api.github.com"
)
# ---------------------------------------------------------------------------
# Uninstall Functions
# ---------------------------------------------------------------------------
# Detect if Claude Code is already installed
detect_existing_installation() {
local found=false
local install_paths=""
# Check if claude exists in PATH (use type instead of command -v for speed)
if type claude >/dev/null 2>&1; then
found=true
install_paths=" - Claude binary: $(type -P claude 2>/dev/null || echo 'in PATH')"
fi
# Check for npm global installation - use only direct path checks, no npm commands
# Get home directory for path construction
local home_dir="$HOME"
# Check common npm global paths
if [ -d "$home_dir/.local/lib/node_modules/@anthropic-ai/claude-code" ]; then
found=true
install_paths="$install_paths
- npm global: $home_dir/.local/lib/node_modules/@anthropic-ai/claude-code"
elif [ -d "/usr/local/lib/node_modules/@anthropic-ai/claude-code" ]; then
found=true
install_paths="$install_paths
- npm global: /usr/local/lib/node_modules/@anthropic-ai/claude-code"
elif [ -d "/usr/lib/node_modules/@anthropic-ai/claude-code" ]; then
found=true
install_paths="$install_paths
- npm global: /usr/lib/node_modules/@anthropic-ai/claude-code"
fi
# Check WSL Windows npm path
if [ -f /proc/version ] && grep -q Microsoft /proc/version 2>/dev/null; then
# Extract username from Windows path
local win_user="${USER:-$(whoami)}"
local win_npm_path="/mnt/c/Users/$win_user/AppData/Roaming/npm/node_modules/@anthropic-ai/claude-code"
if [ -d "$win_npm_path" ]; then
found=true
install_paths="$install_paths
- Windows npm: $win_npm_path"
fi
fi
# Check ~/.claude directory
if [ -d "$home_dir/.claude" ]; then
found=true
install_paths="$install_paths
- Config directory: $home_dir/.claude"
fi
# Check ~/.claude.json
if [ -f "$home_dir/.claude.json" ]; then
found=true
install_paths="$install_paths
- Config file: $home_dir/.claude.json"
fi
# Check .bashrc for configuration
if [ -f "$BASHRC" ] && grep -q "$SETUP_START" "$BASHRC" 2>/dev/null; then
found=true
install_paths="$install_paths
- Shell configuration: $BASHRC"
fi
if [ "$found" = true ]; then
echo "$install_paths"
return 0
else
return 1
fi
}
# Uninstall Claude Code
uninstall_claude_code() {
echo "============================================================================="
echo " Claude Code Uninstaller"
echo "============================================================================="
echo ""
# Detect existing installation
local existing
existing=$(detect_existing_installation)
# Also check for npm global installation (avoid all npm commands which can hang on WSL)
local npm_global_claude=""
# Check common npm global paths directly
if [ -d "$HOME/.local/lib/node_modules/@anthropic-ai/claude-code" ]; then
npm_global_claude="npm: $HOME/.local/lib/node_modules/@anthropic-ai/claude-code"
elif [ -d "/usr/local/lib/node_modules/@anthropic-ai/claude-code" ]; then
npm_global_claude="npm: /usr/local/lib/node_modules/@anthropic-ai/claude-code"
elif [ -d "/usr/lib/node_modules/@anthropic-ai/claude-code" ]; then
npm_global_claude="npm: /usr/lib/node_modules/@anthropic-ai/claude-code"
fi
if [ -z "$existing" ] && [ -z "$npm_global_claude" ]; then
log_warn "No existing Claude Code installation detected."
return 0
fi
if [ -n "$existing" ]; then
echo "Detected existing installation at:"
echo "$existing"
echo ""
fi
if [ -n "$npm_global_claude" ]; then
echo "Detected npm global installation:"
echo " $npm_global_claude"
echo ""
fi
read -p "Are you sure you want to uninstall Claude Code? [y/N]: " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
log_info "Uninstall cancelled."
return 0
fi
echo ""
log_info "Starting uninstallation..."
# 1. Backup configuration (ask user)
if [ -d "$HOME/.claude" ] || [ -f "$HOME/.claude.json" ]; then
read -p "Do you want to backup configuration files before uninstalling? [Y/n]: " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Nn]$ ]]; then
local backup_dir="$HOME/.claude-backup-$(date +%Y%m%d_%H%M%S)"
mkdir -p "$backup_dir"
if [ -d "$HOME/.claude" ]; then
cp -r "$HOME/.claude" "$backup_dir/"
log_ok "Configuration backed up to: $backup_dir"
fi
if [ -f "$HOME/.claude.json" ]; then
cp "$HOME/.claude.json" "$backup_dir/"
fi
fi
fi
# 2. Remove npm global installation if exists (Linux side)
if [ -n "$npm_global_claude" ]; then
log_info "Removing npm global installation of Claude Code..."
# Check if npm is available and not pointing to Windows
if type npm >/dev/null 2>&1 && ! which npm | grep -q "/mnt/c"; then
npm uninstall -g @anthropic-ai/claude-code 2>/dev/null || {
log_warn "Failed to remove npm global installation automatically"
log_info "You may need to run manually: npm uninstall -g @anthropic-ai/claude-code"
}
else
log_warn "npm not available or using Windows npm, skipping npm uninstall"
log_info "You may need to manually remove: $npm_global_claude"
fi
fi
# 2.5 Special handling for WSL Windows npm installations
if [ -f /proc/version ] && grep -q "Microsoft" /proc/version 2>/dev/null; then
# Check for Windows npm claude
local windows_npm_claude="/mnt/c/Users/$USER/AppData/Roaming/npm/claude"
if [ -f "$windows_npm_claude" ] || [ -L "$windows_npm_claude" ]; then
log_warn "Detected Windows npm installation at: $windows_npm_claude"
log_info "Attempting to remove Windows npm installation..."
# Try to use Windows npm to uninstall (with timeout to prevent hanging)
if type cmd.exe >/dev/null 2>&1; then
log_info "Running: cmd.exe /C npm uninstall -g @anthropic-ai/claude-code"
timeout 10 cmd.exe /C "npm uninstall -g @anthropic-ai/claude-code" 2>/dev/null || {
log_warn "Failed to uninstall via Windows npm (timed out or failed)"
}
fi
# Directly remove the files if npm uninstall failed
if [ -f "$windows_npm_claude" ] || [ -L "$windows_npm_claude" ]; then
log_info "Manually removing Windows npm files..."
rm -f "$windows_npm_claude" 2>/dev/null || true
rm -f "/mnt/c/Users/$USER/AppData/Roaming/npm/claude.cmd" 2>/dev/null || true
rm -rf "/mnt/c/Users/$USER/AppData/Roaming/npm/node_modules/@anthropic-ai" 2>/dev/null || true
fi
log_ok "Windows npm installation removed"
fi
# Also check for other common Windows npm paths
for win_path in "/mnt/c/Program Files/nodejs/claude" "/mnt/c/ProgramData/npm/claude"; do
if [ -f "$win_path" ] 2>/dev/null; then
log_warn "Found additional Windows installation at: $win_path"
rm -f "$win_path" 2>/dev/null || true
fi
done
fi
# 3. Remove wrapper alias from .bashrc
if [ -f "$BASHRC" ]; then
# Remove claude wrapper alias
if grep -q "claude-wrapper" "$BASHRC" 2>/dev/null; then
log_info "Removing claude wrapper alias from .bashrc..."
sed -i '/# Claude Code wrapper/d' "$BASHRC"
sed -i "/alias claude='bash/d" "$BASHRC" 2>/dev/null || true
log_ok "Removed wrapper alias"
fi
if grep -q "$SETUP_START" "$BASHRC" 2>/dev/null; then
log_info "Removing PATH/TMPDIR configuration from .bashrc..."
sed -i "/$SETUP_START/,/$SETUP_END/d" "$BASHRC"
log_ok "Removed PATH/TMPDIR configuration"
fi
if grep -q "$NODE_START" "$BASHRC" 2>/dev/null; then
log_info "Removing Node.js configuration from .bashrc..."
sed -i "/$NODE_START/,/$NODE_END/d" "$BASHRC"
log_ok "Removed Node.js configuration"
fi
# Remove NVM configuration (if added by this script)
if grep -q "NVM CONFIGURATION" "$BASHRC" 2>/dev/null; then
read -p "Remove NVM configuration from .bashrc? (Select 'n' if you use nvm for other projects) [y/N]: " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
sed -i '/# >>> NVM CONFIGURATION >>>/,/# <<< NVM CONFIGURATION <<</d' "$BASHRC"
log_ok "Removed NVM configuration"
fi
fi
# Remove Node.js PATH (if installed to ~/.local/node)
if grep -q "/.local/node/bin" "$BASHRC" 2>/dev/null; then
read -p "Remove Node.js PATH from .bashrc? (Select 'n' if you use this Node.js for other projects) [y/N]: " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
sed -i '/\/\.local\/node\/bin/d' "$BASHRC"
log_ok "Removed Node.js PATH"
fi
fi
fi
# 4. Delete configuration files
if [ -f "$HOME/.claude.json" ]; then
log_info "Removing ~/.claude.json..."
rm -f "$HOME/.claude.json"
log_ok "Removed ~/.claude.json"
fi
# 5. Delete ~/.claude directory
if [ -d "$HOME/.claude" ]; then
log_info "Removing ~/.claude directory..."
rm -rf "$HOME/.claude"
log_ok "Removed ~/.claude directory"
fi
# 6. Ask if user wants to remove offline packages
if [ -d "$USER_CLAUDE_DIR/offline-packages" ]; then
read -p "Remove downloaded offline packages? [y/N]: " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
rm -rf "$USER_CLAUDE_DIR/offline-packages"
log_ok "Removed offline packages"
fi
fi
# 7. Ask if user wants to remove Node.js
if [ -d "$HOME/.local/node" ]; then
echo ""
log_warn "Detected Node.js installation at: $HOME/.local/node"
read -p "Remove this Node.js installation? (Select 'n' if you use it for other projects) [y/N]: " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
rm -rf "$HOME/.local/node"
log_ok "Removed Node.js from $HOME/.local/node"
fi
fi
# 8. Ask if user wants to remove nvm
if [ -d "$HOME/.nvm" ]; then
echo ""
log_warn "Detected nvm installation at: $HOME/.nvm"
read -p "Remove nvm? (Select 'n' if you use it for other projects) [y/N]: " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
rm -rf "$HOME/.nvm"
log_ok "Removed nvm from $HOME/.nvm"
fi
fi
echo ""
echo "============================================================================="
echo " Uninstallation Complete"
echo "============================================================================="
echo ""
echo "Claude Code has been uninstalled."
echo ""
echo "IMPORTANT: To complete the uninstallation, please:"
echo " 1. Close and reopen your terminal (NOT just source ~/.bashrc)"
echo " This ensures all environment variables are cleared"
echo " 2. Or run: exec bash -l"
echo " 3. Verify: which claude (should return nothing)"
echo ""
# 9. For WSL: optionally fix PATH to remove Windows npm
if [ -f /proc/version ] && grep -q "Microsoft" /proc/version 2>/dev/null; then
if echo "$PATH" | grep -q "/mnt/c.*npm"; then
echo ""
read -p "Detected Windows npm in WSL PATH. Add automatic fix to .bashrc? [Y/n]: " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Nn]$ ]]; then
log_info "Adding PATH fix to .bashrc..."
cat >> "$BASHRC" << 'WSLFIX'
# >>> WSL PATH FIX >>>
# Remove Windows npm from PATH to avoid conflicts
export PATH=$(echo "$PATH" | tr ':' '\n' | grep -v '/mnt/c.*npm' | tr '\n' ':')
# <<< WSL PATH FIX <<<
WSLFIX
log_ok "PATH fix added to .bashrc"
fi
fi
fi
# WSL specific warning
if [ -f /proc/version ] && grep -q "Microsoft" /proc/version 2>/dev/null; then
echo "============================================================================="
echo " WSL Environment Detected"
echo "============================================================================="
echo ""
echo "You appear to be running in WSL (Windows Subsystem for Linux)."
echo ""
echo "IF YOU STILL SEE 'Permission denied' ERRORS:"
echo ""
echo "1. Remove Windows npm from your WSL PATH:"
echo " Add this line to your ~/.bashrc:"
echo ""
echo " export PATH=\$(echo \$PATH | tr ':' '\\n' | grep -v '/mnt/c.*npm' | tr '\\n' ':')"
echo ""
echo "2. Or manually remove Windows npm files:"
echo " rm -f /mnt/c/Users/\$USER/AppData/Roaming/npm/claude"
echo " rm -f /mnt/c/Users/\$USER/AppData/Roaming/npm/claude.cmd"
echo ""
echo "3. Alternative - Open Windows PowerShell and run:"
echo " npm uninstall -g @anthropic-ai/claude-code"
echo ""
echo "4. Then restart your terminal completely"
echo "============================================================================="
fi
echo ""
return 0
}
# ---------------------------------------------------------------------------
# Helper Functions
# ---------------------------------------------------------------------------
log_info() {
echo "[INFO] $1"
}
log_ok() {
echo " [OK] $1"
}
log_warn() {
echo " [WARN] $1"
}
log_error() {
echo " [ERROR] $1" >&2
}
# 检查命令是否存在
command_exists() {
command -v "$1" >/dev/null 2>&1
}
# Test if URL is accessible
test_url_accessible() {
local url="$1"
local timeout="${2:-$NETWORK_TIMEOUT}"
if command_exists curl; then
curl -fsSL --max-time "$timeout" --retry "$CURL_RETRY" -I "$url" >/dev/null 2>&1
elif command_exists wget; then
wget --timeout="$timeout" --tries="$CURL_RETRY" -q --spider "$url" 2>/dev/null
else
return 1
fi
}
# Download file (with mirror fallback)
download_with_mirrors() {
local output_file="$1"
shift
local mirrors=("$@")
local success=false
for mirror in "${mirrors[@]}"; do
log_info "Trying mirror: $mirror"
if command_exists curl; then
if curl -fsSL --max-time "$NETWORK_TIMEOUT" --retry "$CURL_RETRY" \
-o "$output_file" "$mirror" 2>/dev/null; then
success=true
log_ok "Downloaded from: $mirror"
break
fi
elif command_exists wget; then
if wget --timeout="$NETWORK_TIMEOUT" --tries="$CURL_RETRY" \
-q -O "$output_file" "$mirror" 2>/dev/null; then
success=true
log_ok "Downloaded from: $mirror"
break
fi
fi
log_warn "Failed to download from: $mirror"
done
if [ "$success" = true ]; then
return 0
else
return 1
fi
}
# Select fastest Node.js mirror
select_fastest_node_mirror() {
log_info "Testing Node.js mirrors for best speed..."
local best_mirror="${NODE_MIRRORS[0]}"
local min_time=9999
for mirror in "${NODE_MIRRORS[@]}"; do
local start_time end_time elapsed
start_time=$(date +%s%N 2>/dev/null || echo "$(date +%s)000000000")
if test_url_accessible "$mirror" 3; then
end_time=$(date +%s%N 2>/dev/null || echo "$(date +%s)000000000")
elapsed=$(( (end_time - start_time) / 1000000 )) # 转换为毫秒
log_info " $mirror: ${elapsed}ms"
if [ "$elapsed" -lt "$min_time" ]; then
min_time=$elapsed
best_mirror="$mirror"
fi
else
log_warn " $mirror: UNREACHABLE"
fi
done
log_ok "Selected Node.js mirror: $best_mirror"
echo "$best_mirror"
}
# Select fastest npm registry mirror
select_fastest_npm_mirror() {
log_info "Testing npm registry mirrors for best speed..."
local best_mirror="${NPM_MIRRORS[0]}"
local min_time=9999
for mirror in "${NPM_MIRRORS[@]}"; do
local start_time end_time elapsed
start_time=$(date +%s%N 2>/dev/null || echo "$(date +%s)000000000")
# Test registry availability
if command_exists curl; then
if curl -fsSL --max-time 5 "$mirror/@anthropic-ai/claude-code" >/dev/null 2>&1; then
end_time=$(date +%s%N 2>/dev/null || echo "$(date +%s)000000000")
elapsed=$(( (end_time - start_time) / 1000000 ))
log_info " $mirror: ${elapsed}ms"
if [ "$elapsed" -lt "$min_time" ]; then
min_time=$elapsed
best_mirror="$mirror"
fi
else
log_warn " $mirror: UNREACHABLE"
fi
fi
done
log_ok "Selected npm mirror: $best_mirror"
echo "$best_mirror"
}
# Select fastest GitHub API mirror
select_fastest_github_mirror() {
log_info "Testing GitHub mirrors for best speed..."
local best_mirror="${GITHUB_MIRRORS[0]}"
local min_time=9999
for mirror in "${GITHUB_MIRRORS[@]}"; do
local start_time end_time elapsed
start_time=$(date +%s%N 2>/dev/null || echo "$(date +%s)000000000")
# Test API availability
if command_exists curl; then
if curl -fsSL --max-time 5 "$mirror/repos/anthropics/claude-code/releases/latest" >/dev/null 2>&1; then
end_time=$(date +%s%N 2>/dev/null || echo "$(date +%s)000000000")
elapsed=$(( (end_time - start_time) / 1000000 ))
log_info " $mirror: ${elapsed}ms"
if [ "$elapsed" -lt "$min_time" ]; then
min_time=$elapsed
best_mirror="$mirror"
fi
else
log_warn " $mirror: UNREACHABLE"
fi
fi
done
log_ok "Selected GitHub mirror: $best_mirror"
echo "$best_mirror"
}
# Get Node.js major version number
get_node_major_version() {
local version
version=$(node --version 2>/dev/null | sed 's/v//' | cut -d. -f1)
echo "${version:-0}"
}
# Check if Node.js meets requirements (>= 18, including v25+)
# Supports Node.js 18, 20, 22, 25 and future versions
check_nodejs_requirement() {
local min_version=18
local max_tested_version=30 # Future-proof: tested up to v25, should work for higher
if ! command_exists node; then
return 1
fi
local current_version
current_version=$(get_node_major_version)
# Check if version is >= 18
if [ "$current_version" -ge "$min_version" ]; then
# Warn if version is very new (beyond tested range)
if [ "$current_version" -gt "$max_tested_version" ]; then
log_warn "Node.js v$current_version is newer than tested versions (up to v$max_tested_version)"
log_info "It should work, but if you encounter issues, consider using Node.js LTS (v20 or v22)"
fi
return 0
else
return 1
fi
}
# Get recommended Node.js version based on availability
get_recommended_node_version() {
local node_version
node_version=$(get_node_major_version)
# If we already have a suitable version, use it
if [ "$node_version" -ge 18 ]; then
echo "$node_version"
return
fi
# Default to 20 (LTS with good compatibility)
echo "20"
}
# Download and install Node.js binary
# Supports versions 18, 20, 22, 25 and future versions
download_and_install_nodejs() {
local install_dir="$1"
local version="${2:-20.18.0}" # Updated to latest LTS
local arch="linux-x64"
log_info "Downloading Node.js v${version}..."
local mirror
mirror=$(select_fastest_node_mirror)
local filename="node-v${version}-${arch}.tar.xz"
local download_url="${mirror}v${version}/${filename}"
local temp_file="/tmp/${filename}"
log_info "Downloading from: $download_url"
if command_exists curl; then
if ! curl -fsSL --progress-bar --max-time 300 -o "$temp_file" "$download_url"; then
log_error "Failed to download Node.js"
return 1
fi
elif command_exists wget; then
if ! wget --progress=bar:force --timeout=300 -O "$temp_file" "$download_url"; then
log_error "Failed to download Node.js"
return 1
fi
else
log_error "Neither curl nor wget is available"
return 1
fi
log_info "Extracting Node.js to $install_dir..."
mkdir -p "$install_dir"
tar -xJf "$temp_file" -C "$install_dir" --strip-components=1
rm -f "$temp_file"
# Add to PATH
if ! grep -q "$install_dir/bin" "$BASHRC" 2>/dev/null; then
echo "export PATH=\"$install_dir/bin:\$PATH\"" >> "$BASHRC"
fi
export PATH="$install_dir/bin:$PATH"
log_ok "Node.js v${version} installed to $install_dir"
return 0
}
# Get the latest LTS or specific Node version
download_latest_node() {
local install_dir="$1"
local preferred_version="${2:-20}"
log_info "Attempting to install Node.js v${preferred_version}..."
# Map major version to latest known release
local version_map
case "$preferred_version" in
18) version_map="18.20.5" ;;
20) version_map="20.18.0" ;;
22) version_map="22.11.0" ;;
25) version_map="25.0.0" ;; # Latest as of 2026
*) version_map="${preferred_version}.0.0" ;; # Try generic for future versions
esac
# Try specific version first
if download_and_install_nodejs "$install_dir" "$version_map"; then
return 0
fi
# Fall back to latest LTS
log_warn "Failed to download Node.js v${version_map}, trying LTS..."
if download_and_install_nodejs "$install_dir" "20.18.0"; then
return 0
fi
return 1
}
# Install Node.js (using nvm or direct download)
# Supports Node.js 18, 20, 22, 25 and future versions
install_nodejs() {
log_info "Installing Node.js (>= 18, supports up to v25+)..."
# Determine best version to install (prefer 20 if no suitable version exists)
local target_version
target_version=$(get_recommended_node_version)
# Method 1: Check if nvm already exists
if [ -s "$HOME/.nvm/nvm.sh" ]; then
log_info "Using existing nvm to install Node.js..."
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
# Set Node.js mirror source for nvm (use npmmirror for Node.js binaries)
export NVM_NODEJS_ORG_MIRROR="https://npmmirror.com/mirrors/node/"
# Try to install preferred version, fallback to lts if not available
if ! nvm install "$target_version" 2>/dev/null; then
log_warn "Node.js $target_version not available via nvm, trying LTS..."
if ! nvm install 20 2>/dev/null; then
log_warn "Node.js 20 not available, trying any LTS..."
nvm install --lts || {
log_error "Failed to install Node.js via nvm"
return 1
}
fi
fi
nvm use "$target_version" 2>/dev/null || nvm use 20 2>/dev/null || nvm use --lts
nvm alias default "$target_version" 2>/dev/null || nvm alias default 20 2>/dev/null || nvm alias default --lts
log_ok "Node.js installed via nvm"
return 0
fi
# Method 2: Install nvm then install Node.js
log_info "Installing nvm..."
local nvm_install_script="/tmp/nvm-install.sh"
if download_with_mirrors "$nvm_install_script" "${NVM_INSTALL_MIRRORS[@]}"; then
chmod +x "$nvm_install_script"
# Install nvm without modifying shell config (we'll do it manually)
PROFILE=/dev/null bash "$nvm_install_script" 2>/dev/null || bash "$nvm_install_script"
rm -f "$nvm_install_script"
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
# 添加到 .bashrc
if ! grep -q "NVM_DIR" "$BASHRC" 2>/dev/null; then
cat >> "$BASHRC" << 'NVMBLOCK'
# >>> NVM CONFIGURATION >>>
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
# <<< NVM CONFIGURATION <<<
NVMBLOCK
fi
# 设置镜像源
local npm_mirror
npm_mirror=$(select_fastest_npm_mirror)
export NVM_NODEJS_ORG_MIRROR="${npm_mirror/https:\/\/registry.npmmirror.com\/}/mirrors/node/"
# Try to install preferred version, fallback to 20 then lts
if ! nvm install "$target_version" 2>/dev/null; then
log_warn "Node.js $target_version not available, trying 20..."
if ! nvm install 20 2>/dev/null; then
log_warn "Node.js 20 not available, trying LTS..."
nvm install --lts || {
log_error "Failed to install Node.js via nvm"
return 1
}
fi
fi
nvm use "$target_version" 2>/dev/null || nvm use 20 2>/dev/null || nvm use --lts
nvm alias default "$target_version" 2>/dev/null || nvm alias default 20 2>/dev/null || nvm alias default --lts
log_ok "Node.js installed via nvm"
return 0
fi
# Method 3: Download binary directly
log_info "Downloading Node.js binary directly..."
if download_latest_node "$HOME/.local/node" "$target_version"; then
return 0
fi
log_error "Failed to install Node.js"
return 1
}
# Ensure Node.js is available
ensure_nodejs() {
log_info "Checking Node.js environment..."
if check_nodejs_requirement; then
local node_version
node_version=$(node --version)
log_ok "Node.js $node_version is available"
return 0
fi
log_warn "Node.js >= 18 is required but not found"
read -p "Do you want to install Node.js automatically? [Y/n]: " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Nn]$ ]]; then
if install_nodejs; then
# 重新检查
if check_nodejs_requirement; then
local node_version
node_version=$(node --version)
log_ok "Node.js $node_version is now available"
return 0
else
log_error "Node.js installation failed"
return 1
fi
else
log_error "Node.js installation failed"
return 1
fi
else
log_error "Node.js >= 18 is required. Please install it manually and re-run this script."
return 1
fi
}
# Download offline packages from GitHub Release
download_offline_packages() {
log_info "Downloading offline packages from GitHub Release..."
local download_dir="$1"
mkdir -p "$download_dir"
# Get fastest GitHub mirror
local github_mirror
github_mirror=$(select_fastest_github_mirror)
log_info "Using GitHub mirror: $github_mirror"
# Get latest release download URL
log_info "Fetching latest release info..."
local release_info
release_info=$(curl -fsSL --max-time "$NETWORK_TIMEOUT" "$github_mirror/repos/${GITHUB_REPO}/releases/latest" 2>/dev/null) || {
log_error "Failed to fetch release info"
return 1
}
local download_url
download_url=$(echo "$release_info" | grep "browser_download_url.*claude-offline-packages.tar.gz\"" | head -1 | cut -d '"' -f 4)
if [ -z "$download_url" ]; then
log_error "Could not find offline packages in latest release"
log_info "Trying to download from alternative source..."
# Fallback: Direct npm install
log_info "Installing Claude Code directly via npm..."
# Set fastest npm mirror
local npm_mirror
npm_mirror=$(select_fastest_npm_mirror)
npm config set registry "$npm_mirror"
mkdir -p "$download_dir"
cd "$download_dir"
npm install @anthropic-ai/claude-code --production
# 创建 .bin 链接
mkdir -p node_modules/.bin
if [ -f "node_modules/@anthropic-ai/claude-code/cli.js" ]; then
ln -sf ../@anthropic-ai/claude-code/cli.js node_modules/.bin/claude
chmod +x node_modules/.bin/claude
fi
log_ok "Claude Code installed via npm"
return 0
fi
# Use mirror to accelerate download
local accelerated_url
if [[ "$github_mirror" == "https://api.github.com" ]]; then
accelerated_url="$download_url"
else
# Replace API URL with download acceleration URL
accelerated_url="${github_mirror/https:\/\/api.github.com/https:\/\/github.com}"
accelerated_url="${download_url/https:\/\/github.com/$accelerated_url}"
fi
log_info "Downloading from: $accelerated_url"
local temp_file="$download_dir/claude-offline-packages.tar.gz"
# Download file
if command_exists wget; then
wget -q --show-progress --timeout=300 -O "$temp_file" "$accelerated_url"
else
curl -fsSL --progress-bar --max-time 300 -o "$temp_file" "$accelerated_url"
fi
# Verify download
if [ ! -f "$temp_file" ] || [ ! -s "$temp_file" ]; then
log_error "Download failed or file is empty"
return 1
fi
# Extract
log_info "Extracting packages..."
tar -xzf "$temp_file" -C "$download_dir" --strip-components=1
rm -f "$temp_file"
log_ok "Offline packages downloaded and extracted"
return 0
}
# Find offline package path
# Supports both old (node_modules) and new (.tgz + package.json) formats
find_offline_packages() {
local paths=(
"${SCRIPT_DIR}/claude-offline-packages"
"${SCRIPT_DIR}/../claude-offline-packages"
"$HOME/claude-offline-packages"
"/opt/claude-offline-packages"
"/usr/local/claude-offline-packages"
)
for path in "${paths[@]}"; do
# Check new format: pre-extracted node_modules with @anthropic-ai/claude-code
if [ -r "$path/node_modules/@anthropic-ai/claude-code/cli.js" ]; then
echo "$path"
return 0
fi
# Check alternative format: package.json with .tgz files (needs extraction)
if [ -f "$path/package.json" ] && ls "$path"/*.tgz >/dev/null 2>&1; then
echo "$path"
return 0
fi
# Check old format: pre-installed node_modules with .bin/claude
if [ -r "$path/node_modules/.bin/claude" ]; then
echo "$path"
return 0
fi
done
return 1
}
# Install offline packages from .tgz files
install_from_tgz_packages() {
local pkg_dir="$1"
local target_dir="$2"
log_info "Installing from local .tgz packages..."
mkdir -p "$target_dir"
cd "$target_dir"
# Copy package files
cp "$pkg_dir/package.json" "$pkg_dir/package-lock.json" . 2>/dev/null || true
cp "$pkg_dir"/*.tgz . 2>/dev/null || true
# Install dependencies
if [ -f "package.json" ]; then
npm ci --production 2>/dev/null || npm install --production 2>/dev/null || {
log_warn "npm install failed, trying npm ci..."
npm ci --production
}
fi
log_ok "Packages installed to $target_dir"
}