-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.ps1
More file actions
315 lines (280 loc) · 13.8 KB
/
Copy pathinstall.ps1
File metadata and controls
315 lines (280 loc) · 13.8 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
# BVM Installer for Windows (PowerShell)
# Unified Installation Logic: strict isolation, idempotency, and path precedence.
param([switch]$Local)
$ErrorActionPreference = "Stop"
# --- Fix: Enforce TLS 1.2 ---
try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } catch {}
# --- Platform Detection ---
if ($PSVersionTable.ContainsKey('OS')) {
$osName = $PSVersionTable.OS.ToString()
$bvmIsWindows = $osName -like '*Windows*'
} else {
try { $bvmIsWindows = (Get-CimInstance -ClassName Win32_OperatingSystem).Caption -like "*Windows*" } catch { $bvmIsWindows = $true }
}
if (-not $bvmIsWindows) { Write-Error "BVM install.ps1 is intended for Windows."; exit 1 }
# --- Dependency Check ---
if (-not (Get-Command "tar" -ErrorAction SilentlyContinue)) { Write-Error "Error: 'tar' command not found."; exit 1 }
if (-not [Environment]::Is64BitOperatingSystem) { Write-Error "BVM requires a 64-bit version of Windows."; exit 1 }
# --- Path Configuration ---
$BVM_DIR = if ($env:BVM_DIR) { $env:BVM_DIR } else { Join-Path $HOME ".bvm" }
$BVM_BIN_DIR = Join-Path $BVM_DIR "bin"
$BVM_SHIMS_DIR = Join-Path $BVM_DIR "shims"
$BVM_SRC_DIR = Join-Path $BVM_DIR "src"
$BVM_RUNTIME_DIR = Join-Path $BVM_DIR "runtime"
$BVM_ALIAS_DIR = Join-Path $BVM_DIR "aliases"
$BVM_VERSIONS_DIR = Join-Path $BVM_DIR "versions"
$CURL_CMD = if (Get-Command "curl.exe" -ErrorAction SilentlyContinue) { "curl.exe" } else { "curl" }
# --- 1. Resolve Network & BVM Version ---
function Detect-NetworkZone {
if ($env:BVM_REGION) { return $env:BVM_REGION }
try {
$Test = Invoke-WebRequest -Uri "https://registry.npmmirror.com" -Method Head -TimeoutSec 1.5 -UseBasicParsing -ErrorAction SilentlyContinue
if ($Test.StatusCode -eq 200) { return "cn" }
} catch {}
return "global"
}
function Assert-Sha512Integrity {
param(
[Parameter(Mandatory = $true)][string]$Path,
[Parameter(Mandatory = $true)][string]$Integrity
)
if (-not $Integrity.StartsWith("sha512-")) {
throw "Registry metadata is missing a valid SHA-512 integrity value."
}
$ExpectedBytes = [Convert]::FromBase64String($Integrity.Substring(7))
if ($ExpectedBytes.Length -ne 64) {
throw "Registry SHA-512 integrity value has an invalid length."
}
$ExpectedHex = -join ($ExpectedBytes | ForEach-Object { $_.ToString("x2") })
$Stream = [IO.File]::OpenRead($Path)
try {
$Hasher = [Security.Cryptography.SHA512]::Create()
try {
$ActualBytes = $Hasher.ComputeHash($Stream)
} finally {
$Hasher.Dispose()
}
} finally {
$Stream.Dispose()
}
$ActualHex = -join ($ActualBytes | ForEach-Object { $_.ToString("x2") })
if ($ActualHex -ne $ExpectedHex) {
Remove-Item $Path -Force -ErrorAction SilentlyContinue
throw "SHA-512 integrity verification failed for $Path."
}
}
function Get-RegistryCandidates {
$Explicit = if ($env:BVM_REGISTRY) { $env:BVM_REGISTRY } else { $env:BVM_DOWNLOAD_MIRROR }
if ($Explicit) {
return @($Explicit.TrimEnd('/'))
}
return @(
"https://registry.npmmirror.com",
"https://mirrors.cloud.tencent.com/npm",
"https://registry.npmjs.org"
)
}
function Get-LatestPackageVersion {
param([Parameter(Mandatory = $true)][string]$Package)
foreach ($Registry in $REGISTRIES) {
try {
$Tags = Invoke-RestMethod -Uri "$Registry/-/package/$Package/dist-tags" -TimeoutSec 5
if ($Tags.latest) { return $Tags.latest }
} catch {}
}
return $null
}
function Save-RegistryPackage {
param(
[Parameter(Mandatory = $true)][string]$Package,
[Parameter(Mandatory = $true)][string]$Version,
[Parameter(Mandatory = $true)][string]$Destination
)
foreach ($Registry in $REGISTRIES) {
try {
$Metadata = Invoke-RestMethod -Uri "$Registry/$Package/$Version" -TimeoutSec 10
$TarballUrl = $Metadata.dist.tarball
$Integrity = $Metadata.dist.integrity
if (-not $TarballUrl -or -not $Integrity -or -not $Integrity.StartsWith("sha512-")) { continue }
Remove-Item $Destination -Force -ErrorAction SilentlyContinue
& $CURL_CMD "-#SfL" "-C" "-" "--connect-timeout" "20" "--max-time" "600" "--retry" "3" "-o" "$Destination" "$TarballUrl"
if ($LASTEXITCODE -ne 0) { continue }
Assert-Sha512Integrity -Path $Destination -Integrity $Integrity
return $Registry
} catch {
Remove-Item $Destination -Force -ErrorAction SilentlyContinue
}
}
throw "Unable to download a verified package from the configured registries: $Package@$Version"
}
function Test-Avx2Support {
try {
$Probe = Add-Type -MemberDefinition '[DllImport("kernel32.dll")] public static extern bool IsProcessorFeaturePresent(int ProcessorFeature);' -Name 'Kernel32' -Namespace 'Win32' -PassThru
return $Probe::IsProcessorFeaturePresent(40)
} catch {
return $false
}
}
$BVM_REGION = Detect-NetworkZone
$REGISTRIES = @(Get-RegistryCandidates)
$DEFAULT_BVM_VER = "v1.1.43"
$FALLBACK_BUN_VERSION = "1.3.11"
$BVM_VER = if ($env:BVM_INSTALL_VERSION) { $env:BVM_INSTALL_VERSION } else { "" }
if (-not $BVM_VER) {
$LatestBvm = Get-LatestPackageVersion -Package "bvm-core"
$BVM_VER = if ($LatestBvm) { "v$LatestBvm" } else { $DEFAULT_BVM_VER }
}
Write-Host "BVM Installer ($BVM_REGION) - Resolving $BVM_VER..." -ForegroundColor Cyan
# --- 2. Setup Directories (Idempotent) ---
$Dirs = @($BVM_DIR, $BVM_SRC_DIR, $BVM_RUNTIME_DIR, $BVM_BIN_DIR, $BVM_SHIMS_DIR, $BVM_ALIAS_DIR, $BVM_VERSIONS_DIR)
foreach ($d in $Dirs) {
if (-not (Test-Path $d)) {
New-Item -ItemType Directory -Force -Path $d | Out-Null
}
}
# --- 3. Download BVM Source ---
if ($Local) {
if ((Test-Path "dist\index.js") -and (Test-Path "dist\bvm-shim.js")) {
Write-Host "Explicitly using local BVM core assets (-Local)." -ForegroundColor Green
$BVM_VER = "v-local"
Copy-Item "dist\index.js" (Join-Path $BVM_SRC_DIR "index.js") -Force
Copy-Item "dist\bvm-shim.js" (Join-Path $BVM_BIN_DIR "bvm-shim.js") -Force
} else {
Write-Error "-Local switch provided but dist\index.js or dist\bvm-shim.js not found."
exit 1
}
} else {
$BVM_PLAIN_VER = $BVM_VER.TrimStart('v')
$TMP_TGZ = Join-Path $BVM_DIR "bvm-core.tgz"
Save-RegistryPackage -Package "bvm-core" -Version $BVM_PLAIN_VER -Destination $TMP_TGZ | Out-Null
$EXT_DIR = Join-Path $BVM_DIR "temp_bvm_extract"
if (Test-Path $EXT_DIR) { Remove-Item $EXT_DIR -Recurse -Force }
New-Item -ItemType Directory -Path $EXT_DIR | Out-Null
& tar -xf "$TMP_TGZ" -C "$EXT_DIR"
Copy-Item (Join-Path $EXT_DIR "package\dist\index.js") (Join-Path $BVM_SRC_DIR "index.js") -Force
Copy-Item (Join-Path $EXT_DIR "package\dist\bvm-shim.js") (Join-Path $BVM_BIN_DIR "bvm-shim.js") -Force
Remove-Item $TMP_TGZ -Force
Remove-Item $EXT_DIR -Recurse -Force
}
# --- 4. Bootstrap Runtime (Using System Bun if available, READ-ONLY) ---
$SYSTEM_BUN_BIN = Get-Command "bun" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source
if ($SYSTEM_BUN_BIN -and ($SYSTEM_BUN_BIN -like "*\.bvm\shims*" -or $SYSTEM_BUN_BIN -like "*\.bvm\bin*")) {
$SYSTEM_BUN_BIN = $null
}
$SYSTEM_BUN_VER = ""
if ($SYSTEM_BUN_BIN) { try { $SYSTEM_BUN_VER = (bun --version) -replace "^v", "" } catch {} }
$USE_SYSTEM_AS_RUNTIME = $false
$BUN_VER = ""
if ($SYSTEM_BUN_BIN) {
# We copy the system bun to BVM's internal runtime store for bootstrapping.
Write-Host "Bootstrapping with detected system Bun v$SYSTEM_BUN_VER..." -ForegroundColor Gray
$SYS_VER_NAME = "v$SYSTEM_BUN_VER"
$SYS_RUNTIME_DIR = Join-Path $BVM_RUNTIME_DIR $SYS_VER_NAME
$SYS_BIN_DIR = Join-Path $SYS_RUNTIME_DIR "bin"
if (-not (Test-Path $SYS_BIN_DIR)) { New-Item -ItemType Directory -Path $SYS_BIN_DIR -Force | Out-Null }
Copy-Item $SYSTEM_BUN_BIN (Join-Path $SYS_BIN_DIR "bun.exe") -Force
Copy-Item $SYSTEM_BUN_BIN (Join-Path $SYS_BIN_DIR "bunx.exe") -Force
# Generate bunfig.toml
$WinRuntimeDir = $SYS_RUNTIME_DIR.Replace('/', '\')
$WinBinDir = $SYS_BIN_DIR.Replace('/', '\')
$BunfigContent = "[install]`nglobalDir = `"$($WinRuntimeDir.Replace('\', '\\'))`"`nglobalBinDir = `"$($WinBinDir.Replace('\', '\\'))`"`n"
Set-Content -Path (Join-Path $SYS_RUNTIME_DIR "bunfig.toml") -Value $BunfigContent -Encoding Ascii
# Link registry to physical runtime
$SYS_VERSIONS_LINK = Join-Path $BVM_VERSIONS_DIR $SYS_VER_NAME
if (Test-Path $SYS_VERSIONS_LINK) { Remove-Item -Recurse -Force $SYS_VERSIONS_LINK | Out-Null }
New-Item -ItemType Junction -Path $SYS_VERSIONS_LINK -Value $SYS_RUNTIME_DIR | Out-Null
# Smoke Test
$BvmIndex = Join-Path $BVM_SRC_DIR "index.js"
& $SYSTEM_BUN_BIN $BvmIndex --version | Out-Null
if ($LASTEXITCODE -eq 0) {
$USE_SYSTEM_AS_RUNTIME = $true
$BUN_VER = $SYS_VER_NAME
$TARGET_PHYSICAL_DIR = $SYS_RUNTIME_DIR
}
}
if ($USE_SYSTEM_AS_RUNTIME) {
# Already set up
} else {
$BunLatest = Get-LatestPackageVersion -Package "bun"
$BUN_VER = if ($BunLatest) { "v$BunLatest" } else { "v$FALLBACK_BUN_VERSION" }
$TARGET_PHYSICAL_DIR = Join-Path $BVM_RUNTIME_DIR $BUN_VER
if (-not (Test-Path (Join-Path $TARGET_PHYSICAL_DIR "bin\bun.exe"))) {
$TMP = Join-Path $BVM_DIR "bun-runtime.tgz"
# ... (keep download logic) ...
if ($env:BVM_LOCAL_RUNTIME_PATH -and (Test-Path $env:BVM_LOCAL_RUNTIME_PATH)) {
Write-Host "Using local runtime archive: $env:BVM_LOCAL_RUNTIME_PATH" -ForegroundColor Green
$TMP = $env:BVM_LOCAL_RUNTIME_PATH
} else {
Write-Host "Downloading Runtime (bun@$($BUN_VER.TrimStart('v')))..."
$BUN_PACKAGE_SUFFIX = if (Test-Avx2Support) { "" } else { "-baseline" }
$BUN_PACKAGE = "@oven/bun-windows-x64$BUN_PACKAGE_SUFFIX"
$BUN_PLAIN_VER = $BUN_VER.TrimStart('v')
Save-RegistryPackage -Package $BUN_PACKAGE -Version $BUN_PLAIN_VER -Destination $TMP | Out-Null
}
$EXT = Join-Path $BVM_DIR "temp_extract"
if (Test-Path $EXT) { Remove-Item $EXT -Recurse -Force | Out-Null }
New-Item -ItemType Directory -Path $EXT | Out-Null
& tar -xf "$TMP" -C "$EXT"
$FoundBun = Get-ChildItem -Path $EXT -Filter "bun.exe" -Recurse | Select-Object -First 1
$BIN_DEST = Join-Path $TARGET_PHYSICAL_DIR "bin"
if (-not (Test-Path $BIN_DEST)) { New-Item -ItemType Directory -Path $BIN_DEST -Force | Out-Null }
Move-Item -Path $FoundBun.FullName -Destination (Join-Path $BIN_DEST "bun.exe") -Force
Copy-Item (Join-Path $BIN_DEST "bun.exe") (Join-Path $BIN_DEST "bunx.exe") -Force
# Generate bunfig.toml
$WinRuntimeDir = $TARGET_PHYSICAL_DIR.Replace('/', '\')
$WinBinDir = $BIN_DEST.Replace('/', '\')
$BunfigContent = "[install]`nglobalDir = `"$($WinRuntimeDir.Replace('\', '\\'))`"`nglobalBinDir = `"$($WinBinDir.Replace('\', '\\'))`"`n"
Set-Content -Path (Join-Path $TARGET_PHYSICAL_DIR "bunfig.toml") -Value $BunfigContent -Encoding Ascii
Remove-Item $TMP -Force
Remove-Item $EXT -Recurse -Force
}
# Link registry to physical runtime
$VERSIONS_LINK = Join-Path $BVM_VERSIONS_DIR $BUN_VER
if (Test-Path $VERSIONS_LINK) { Remove-Item -Recurse -Force $VERSIONS_LINK | Out-Null }
New-Item -ItemType Junction -Path $VERSIONS_LINK -Value $TARGET_PHYSICAL_DIR | Out-Null
}
# --- 5. Link Runtime ---
$PRIVATE_RUNTIME_LINK = Join-Path $BVM_RUNTIME_DIR "current"
if (Test-Path $PRIVATE_RUNTIME_LINK) { Remove-Item -Recurse -Force $PRIVATE_RUNTIME_LINK | Out-Null }
New-Item -ItemType Junction -Path $PRIVATE_RUNTIME_LINK -Value $TARGET_PHYSICAL_DIR | Out-Null
$USER_CURRENT_LINK = Join-Path $BVM_DIR "current"
if (Test-Path $USER_CURRENT_LINK) { Remove-Item -Recurse -Force $USER_CURRENT_LINK | Out-Null }
New-Item -ItemType Junction -Path $USER_CURRENT_LINK -Value (Join-Path $BVM_VERSIONS_DIR $BUN_VER) | Out-Null
Set-Content -Path (Join-Path $BVM_ALIAS_DIR "default") -Value $BUN_VER -Encoding Ascii
# --- 6. Create Shims ---
Write-Host "Updating shims..." -ForegroundColor Gray
$WinBvmDir = $BVM_DIR.Replace('/', '\')
$BvmWrapper = @"
@echo off
set "BVM_DIR=$WinBvmDir"
"%BVM_DIR%\runtime\current\bin\bun.exe" "%BVM_DIR%\src\index.js" %*
"@
Set-Content -Path (Join-Path $BVM_BIN_DIR "bvm.cmd") -Value $BvmWrapper -Encoding Ascii
$CMD_NAMES = @("bun", "bunx")
foreach ($name in $CMD_NAMES) {
$tpl = @"
@echo off
set "BVM_DIR=$WinBvmDir"
set "BUN_INSTALL=%BVM_DIR%\current"
if not exist ".bvmrc" (
"%BVM_DIR%\current\bin\$name.exe" %*
exit /b %errorlevel%
)
"%BVM_DIR%\runtime\current\bin\bun.exe" "%BVM_DIR%\bin\bvm-shim.js" "$name" %*
"@
Set-Content -Path (Join-Path $BVM_SHIMS_DIR "$name.cmd") -Value $tpl -Encoding Ascii
}
# --- 7. Configure Path (Purge Old & Prepend New) ---
Write-Host "Configuring PATH (Shim Proxy mode)..." -ForegroundColor Gray
$RawPath = [Environment]::GetEnvironmentVariable("Path", "User")
# Clean previous BVM entries
$cleanPathList = $RawPath -split ";" | Where-Object { $_ -notlike "*\.bvm*" -and -not [string]::IsNullOrEmpty($_) }
$FinalPath = "$BVM_SHIMS_DIR;$BVM_BIN_DIR;" + ($cleanPathList -join ';') + ";$BVM_DIR\current\bin"
[Environment]::SetEnvironmentVariable("Path", $FinalPath, "User")
$env:Path = "$BVM_SHIMS_DIR;$BVM_BIN_DIR;$env:Path;$BVM_DIR\current\bin"
# --- 8. Initialize BVM (Self-Repair) ---
& (Join-Path $TARGET_PHYSICAL_DIR "bin\bun.exe") (Join-Path $BVM_SRC_DIR "index.js") setup --silent
Write-Host "`n[OK] BVM installed successfully!" -ForegroundColor Green
Write-Host "IMPORTANT: Please close this terminal and open a NEW one to apply changes." -ForegroundColor Cyan
Write-Host "NOTE: Global packages (bun install -g) are isolated per version." -ForegroundColor Yellow
Write-Host " BVM shims are used to proxy all commands safely." -ForegroundColor Yellow