Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/windows.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,14 +195,14 @@ Windows PowerShell **5.1 is supported as a bootstrap/recovery host**. The Window
The public core installs **NVM for Windows v2** (`AuthorSoftware.NVMWindows`) in place of standalone `OpenJS.NodeJS.LTS`. The bootstrap pins NVM **2.0.1**, which is available in WinGet and code-signed. On a clean machine it installs and activates the latest Node LTS with `nvm install lts` and `nvm use lts`.

- **No Node or NVM:** install NVM and Node LTS, then open a new PowerShell session.
- **NVM v2 already present:** keep the selected/default Node version unchanged.
- **NVM v2 already present:** keep a valid selected/default Node version unchanged. If there is no default, install and activate Node LTS; if the installation cannot be inspected reliably, stop without changing the default.
- **WinGet-managed standalone Node.js (`OpenJS.NodeJS.LTS` or `OpenJS.NodeJS`):** offer migration with a default answer of No.
- **`-Force`:** selects package groups, but does not authorize migration without `-MigrateNodeToNvm`.
- **Unrecognized standalone Node, NVM v1, Scoop/fnm/Volta, or another Node executable on PATH:** skip automatic changes and explain the conflict. Clean up manually and rerun.

An approved migration saves an npm inventory and invokes the community NVM installer with adoption. NVM copies the existing version and global modules; it can uninstall standalone Node during installation, before this bootstrap verifies the replacement. The bootstrap checks the adopted version and saved package versions before attempting to remove any standalone package still present. See the [NVM installer documentation](https://docs.nvm-windows.com/install/installers/).

The inventory contains package names and versions, not a backup of their files. The adopted Node version remains the default so its global modules remain available; additional Node versions manage their own global modules.
The inventory contains package names and versions, not a backup of their files. Migration stops if npm is unavailable, reports an error, or returns a package without a version. The adopted Node version remains the default so its global modules remain available; additional Node versions manage their own global modules.

If WinGet cannot remove the old runtime, the installer reports an incomplete migration, returns a failure, and leaves the state for manual repair rather than deleting files. Explicit noninteractive migration also fails instead of silently skipping when unsupported Node/NVM installations are detected. The earlier executable may continue to shadow NVM on PATH. Close and reopen PowerShell, then verify:

Expand Down
53 changes: 53 additions & 0 deletions tests/windows-node-tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,59 @@ Assert-NodePlan -State $legacy -Expected 'LegacyNvm' -ExplicitMigration
$ambiguous = New-TestNodeState -StandaloneIds @('OpenJS.NodeJS.LTS') -OtherNodePaths @('C:\tools\node.exe')
Assert-NodePlan -State $ambiguous -Expected 'OtherNode' -ExplicitMigration

# Exercise the existing-manager path without installing or changing Node.
$nodeModule = Get-Module Dotfiles.WindowsNode
& $nodeModule {
function script:dotfilesFakeDefault { $global:LASTEXITCODE = 0; return $script:testDefaultOutput }
$script:testDefaultOutput = "Default : none`nLast : v24.22.1"
if (Test-DotfilesNvmDefault -NvmExecutable 'dotfilesFakeDefault') { throw 'Previous Node version must not be mistaken for the default.' }
$script:testDefaultOutput = "Default : v26.13.0`nLast : v24.22.1"
if (-not (Test-DotfilesNvmDefault -NvmExecutable 'dotfilesFakeDefault')) { throw 'Valid default was not detected.' }
$script:testDefault = $true
$script:testInstallCount = 0
function script:Get-DotfilesNodeState {
[pscustomobject]@{ NvmExecutable = 'dotfilesFakeNvm'; HasLegacyNvm = $false; OtherNodePaths = @(); HasStandaloneNode = $false; StandaloneIds = @() }
}
function script:Test-DotfilesNvmDefault { param($NvmExecutable) return $script:testDefault }
function script:Install-DotfilesNodeLts { param($NvmExecutable) $script:testInstallCount++ }
function script:dotfilesFakeNvm { $global:LASTEXITCODE = 0; return '[]' }
Invoke-DotfilesNvmBootstrap
if ($script:testInstallCount -ne 0) { throw 'A valid NVM default must not be changed.' }
$script:testDefault = $false
Invoke-DotfilesNvmBootstrap -DryRun
if ($script:testInstallCount -ne 0) { throw 'Dry-run must not install Node.' }
Invoke-DotfilesNvmBootstrap
if ($script:testInstallCount -ne 1) { throw 'NVM without a default must install Node LTS.' }
}
Import-Module (Join-Path $repoRoot 'windows/Dotfiles.WindowsNode.psm1') -Force

# Use a disposable npm command and profile directory; never inspect real globals.
$inventoryRoot = Join-Path ([IO.Path]::GetTempPath()) ("dotfiles-node-inventory-" + [guid]::NewGuid())
New-Item -ItemType Directory -Path $inventoryRoot | Out-Null
$originalLocalAppData = $env:LOCALAPPDATA
try {
$env:LOCALAPPDATA = $inventoryRoot
$fakeNode = Join-Path $inventoryRoot 'node.exe'
$fakeNpm = Join-Path $inventoryRoot 'npm.cmd'
$state = [pscustomobject]@{ StandalonePaths = @($fakeNode); StandaloneIds = @('OpenJS.NodeJS.LTS') }
$nodeModule = Get-Module Dotfiles.WindowsNode
Set-Content -LiteralPath $fakeNpm -Value '@echo {"dependencies":{"example":{"version":"1.2.3"}}}'
$savedPath = & $nodeModule { param($testState) Save-DotfilesNodeInventory -State $testState } $state
$inventory = Get-Content -LiteralPath $savedPath -Raw | ConvertFrom-Json
if (@($inventory.GlobalPackages) -notcontains '[email protected]') { throw 'Expected npm package inventory.' }
Set-Content -LiteralPath $fakeNpm -Value @('@echo {"dependencies":{}}', '@exit /b 1')
$failed = $false
try { & $nodeModule { param($testState) Save-DotfilesNodeInventory -State $testState } $state } catch { $failed = $true }
if (-not $failed) { throw 'Failed npm inventory must stop migration.' }
Set-Content -LiteralPath $fakeNpm -Value '@echo {"dependencies":{"example":{}}}'
$failed = $false
try { & $nodeModule { param($testState) Save-DotfilesNodeInventory -State $testState } $state } catch { $failed = $true }
if (-not $failed) { throw 'Missing npm package version must stop migration.' }
} finally {
$env:LOCALAPPDATA = $originalLocalAppData
Remove-Item -LiteralPath $inventoryRoot -Recurse -Force -ErrorAction SilentlyContinue
}

$saved = [pscustomobject]@{ GlobalPackages = @('@scope/[email protected]', '[email protected]') }
$adopted = '{"dependencies":{"@scope/tool":{"version":"1.2.3"},"example":{"version":"4.5.6"}}}' | ConvertFrom-Json
Assert-DotfilesNpmInventory -Saved $saved -Adopted $adopted
Expand Down
32 changes: 20 additions & 12 deletions windows/Dotfiles.WindowsNode.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -115,24 +115,23 @@ function Save-DotfilesNodeInventory {
$globals = @()
if ($npmPath) {
$raw = (& $npmPath ls -g --depth=0 --json 2>$null | Out-String).Trim()
if (-not $raw) { throw 'npm returned no global inventory; migration was cancelled.' }
if ($LASTEXITCODE -ne 0 -or -not $raw) { throw 'npm global inventory failed; migration was cancelled.' }
try {
$inventory = $raw | ConvertFrom-Json -ErrorAction Stop
if ($inventory.dependencies) {
foreach ($item in $inventory.dependencies.PSObject.Properties) {
$dependencies = $inventory.PSObject.Properties['dependencies']
if ($dependencies -and $dependencies.Value) {
foreach ($item in $dependencies.Value.PSObject.Properties) {
if ($item.Name -in @('npm', 'corepack')) { continue }
if ($item.Value.version) {
$globals += "$($item.Name)@$($item.Value.version)"
} else {
$globals += $item.Name
}
$version = $item.Value.PSObject.Properties['version']
if (-not $version -or [string]::IsNullOrWhiteSpace([string]$version.Value)) { throw 'Package version missing.' }
$globals += "$($item.Name)@$($version.Value)"
}
}
} catch {
throw 'Unable to parse npm global inventory; migration was cancelled.'
}
} else {
Write-Warning 'npm not found; the migration inventory will not contain global packages.'
throw 'npm not found; cannot inventory global packages. Migration was cancelled.'
}

$dir = Join-Path $env:LOCALAPPDATA 'dotfiles\node-migration'
Expand All @@ -152,7 +151,7 @@ function Test-DotfilesNvmDefault {
param([Parameter(Mandatory = $true)][string]$NvmExecutable)
try {
$default = (& $NvmExecutable default 2>$null | Out-String).Trim()
return ($LASTEXITCODE -eq 0 -and $default -match 'v?\d+\.\d+\.\d+')
return ($LASTEXITCODE -eq 0 -and $default -match '(?m)^\s*Default\s*:\s*v?\d+\.\d+\.\d+\s*$')
} catch {
return $false
}
Expand Down Expand Up @@ -201,7 +200,16 @@ function Invoke-DotfilesNvmBootstrap {
return
}
'Existing' {
Write-Host ' NVM v2 already installed; keeping its current Node.js version unchanged.'
if (Test-DotfilesNvmDefault -NvmExecutable $state.NvmExecutable) {
Write-Host ' NVM v2 already installed; keeping its current Node.js version unchanged.'
return
}
$installedJson = (& $state.NvmExecutable list --json 2>$null | Out-String).Trim()
if ($LASTEXITCODE -ne 0 -or -not $installedJson.StartsWith('[')) { throw 'Cannot inspect installed NVM versions; leaving the default unchanged.' }
try { $installed = @($installedJson | ConvertFrom-Json -ErrorAction Stop) } catch { throw 'Cannot parse installed NVM versions; leaving the default unchanged.' }
if (@($installed | Where-Object { $_ -and $_.default }).Count -gt 0) { throw 'NVM reports a default that could not be verified; leaving it unchanged.' }
if ($DryRun) { Write-Host ' Would install and activate Node.js LTS for existing NVM without a default.'; return }
Install-DotfilesNodeLts -NvmExecutable $state.NvmExecutable
return
}
'Prompt' {
Expand Down Expand Up @@ -252,7 +260,7 @@ function Invoke-DotfilesNvmBootstrap {
# Verify the adopted executable and npm global inventory before removing
# any standalone installation still present after the NVM installer.
$versionText = (& $nvmExe default 2>$null | Out-String)
if ($versionText -notmatch 'v?(\d+\.\d+\.\d+)') { throw 'Cannot identify the adopted Node version.' }
if ($versionText -notmatch '(?m)^\s*Default\s*:\s*v?(\d+\.\d+\.\d+)\s*$') { throw 'Cannot identify the adopted Node version.' }
$adoptedDir = Join-Path (Split-Path -Parent $nvmExe) ("installs\v" + $Matches[1])
$adoptedNode = Join-Path $adoptedDir 'node.exe'
$adoptedNpm = Join-Path $adoptedDir 'node_modules\npm\bin\npm-cli.js'
Expand Down
Loading