← Files Flows by plugin.spaceARCHIVED FILE

scripts/run.ps1

7.74 KB · Nov 30, 2026 · 00:17 UTC

↓ Download file

# Bootstrap with Windows PowerShell 5.1+ or PowerShell 7; no global Node install.
$ErrorActionPreference = 'Stop'
$flowArguments = @($args)
$flowCommand = if ($flowArguments.Count) { $flowArguments[0] } else { '--help' }
if ($flowCommand -in @('--help', '-h', 'help')) {
    Write-Output 'Flows: & <PLUGIN_ROOT>/scripts/run.ps1 <command> [arguments]'
    Write-Output 'Commands: mcp, serve, library, validate, test-scenarios, setup-capture, capture, capture-status, attach-screen, runtime'
    Write-Output 'Uses Node.js 22.13+ or downloads a checksum-verified private runtime from nodejs.org.'
    Write-Output 'FLOWS_OFFLINE=1 disables downloads; FLOWS_USE_MANAGED_NODE=1 selects the private runtime.'
    exit 0
}
if ($flowCommand -notin @('mcp', 'serve', 'library', 'validate', 'test-scenarios', 'setup-capture', 'capture', 'capture-status', 'attach-screen', 'runtime')) {
    [Console]::Error.WriteLine("Flows: unknown command: $flowCommand. Use --help.")
    exit 2
}
$flowArguments = @($flowArguments | Select-Object -Skip 1)
$flowEntry = if ($flowCommand -eq 'runtime') { Join-Path $PSScriptRoot 'check-runtime.mjs' } else { Join-Path $PSScriptRoot "$flowCommand.mjs" }
$flowCheck = Join-Path $PSScriptRoot 'check-runtime.mjs'
$flowNeedNpm = $flowCommand -eq 'setup-capture' -and $flowArguments -contains '--install'

function Test-FlowNode([string] $NodePath, [bool] $NeedNpm = $flowNeedNpm, [string] $Expected = '') {
    $checkArguments = @($flowCheck, '--check')
    if ($NeedNpm) { $checkArguments += '--npm' }
    if ($Expected) { $checkArguments += @('--expected', $Expected) }
    try {
        & $NodePath @checkArguments 2>$null | Out-Null
        return $LASTEXITCODE -eq 0
    } catch { return $false }
}

$flowStage = $null
$flowLockStream = $null
try {
    $flowNode = $null
    if ($env:FLOWS_NODE) {
        if (-not (Test-FlowNode $env:FLOWS_NODE)) { throw 'FLOWS_NODE must point to Node.js 22.13+ (with npm for capture setup). Unset it to use automatic setup.' }
        $flowNode = $env:FLOWS_NODE
    } elseif ($env:FLOWS_USE_MANAGED_NODE -ne '1') {
        $candidate = Get-Command node -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
        if ($candidate -and (Test-FlowNode $candidate.Source)) { $flowNode = $candidate.Source }
    }
    if (-not $flowNode) {
        if ([Environment]::OSVersion.Platform -ne 'Win32NT') { throw 'Use scripts/run.sh on macOS and Linux.' }
        $version = (Get-Content -LiteralPath (Join-Path $PSScriptRoot '../runtime/node-version.txt') -Raw).Trim()
        if ($version -notmatch '^\d+\.\d+\.\d+$') { throw 'Invalid bundled Node.js version.' }
        $architecture = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE }
        $arch = switch ($architecture) {
            'AMD64' { 'x64' }
            'ARM64' { 'arm64' }
            'x86' { 'x86' }
            default { throw 'Automatic setup supports x64, ARM64 and x86 Windows. Provide Node.js 22.13+ on this architecture.' }
        }
        $dist = "node-v$version-win-$arch"
        $archive = "$dist.zip"
        $checksums = Get-Content -LiteralPath (Join-Path $PSScriptRoot '../runtime/SHASUMS256.txt')
        $checksumLine = @($checksums | Where-Object { ($_ -split '\s+')[1] -eq $archive })
        if ($checksumLine.Count -ne 1) { throw 'Missing bundled checksum for this platform.' }
        $checksum = ($checksumLine[0] -split '\s+')[0]
        if ($checksum -notmatch '^[a-f0-9]{64}$') { throw 'Invalid bundled checksum.' }
        $cache = if ($env:FLOWS_RUNTIME_DIR) { $env:FLOWS_RUNTIME_DIR } else { Join-Path $env:LOCALAPPDATA 'Flows/runtime/node' }
        if (-not [IO.Path]::IsPathRooted($cache)) { throw 'FLOWS_RUNTIME_DIR must be an absolute path.' }
        $target = Join-Path $cache $dist
        $flowNode = Join-Path $target 'node.exe'
        function Test-FlowCache {
            return (Test-Path -LiteralPath (Join-Path $target '.flows-runtime-ready')) -and (Test-FlowNode $flowNode $true $version)
        }
        if (-not (Test-FlowCache)) {
            if ($env:FLOWS_OFFLINE -eq '1') { throw 'No compatible Node.js or cached runtime. Connect to the internet and rerun without FLOWS_OFFLINE, or set FLOWS_NODE to Node.js 22.13+.' }
            [IO.Directory]::CreateDirectory($cache) | Out-Null
            $lockPath = Join-Path $cache ".$dist.lock"
            $waiting = 0
            while (-not $flowLockStream) {
                try { $flowLockStream = [IO.File]::Open($lockPath, [IO.FileMode]::OpenOrCreate, [IO.FileAccess]::ReadWrite, [IO.FileShare]::None) }
                catch [IO.IOException] {
                    if (Test-FlowCache) { break }
                    $waiting++
                    if ($waiting -gt 60) { throw "Runtime setup is locked at $lockPath. Wait for the other setup to finish and retry." }
                    if ($waiting -eq 1) { [Console]::Error.WriteLine('Flows: waiting for another runtime setup...') }
                    Start-Sleep -Seconds 1
                }
            }
            if (-not (Test-FlowCache)) {
                $flowStage = Join-Path $cache ('.download-' + [Guid]::NewGuid().ToString('N'))
                [IO.Directory]::CreateDirectory($flowStage) | Out-Null
                $download = Join-Path $flowStage $archive
                [Console]::Error.WriteLine("Flows: preparing private Node.js $version for win-$arch from nodejs.org...")
                $previousTls = [Net.ServicePointManager]::SecurityProtocol
                try {
                    [Net.ServicePointManager]::SecurityProtocol = $previousTls -bor [Net.SecurityProtocolType]::Tls12
                    Invoke-WebRequest -UseBasicParsing -Uri "https://nodejs.org/dist/v$version/$archive" -OutFile $download -TimeoutSec 300 -MaximumRedirection 0
                } catch { throw 'Could not download Node.js. Check your connection/proxy and retry; no global installation was changed.' }
                finally { [Net.ServicePointManager]::SecurityProtocol = $previousTls }
                if ((Get-FileHash -LiteralPath $download -Algorithm SHA256).Hash.ToLowerInvariant() -ne $checksum) { throw 'Node.js checksum mismatch. Download discarded; retry or update the Flows package.' }
                Expand-Archive -LiteralPath $download -DestinationPath $flowStage
                $extracted = Join-Path $flowStage $dist
                if (-not (Test-FlowNode (Join-Path $extracted 'node.exe') $true $version)) { throw 'Downloaded Node.js cannot run on this OS. Provide compatible Node.js 22.13+ using FLOWS_NODE.' }
                [IO.File]::WriteAllText((Join-Path $extracted '.flows-runtime-ready'), $checksum)
                if (Test-Path -LiteralPath $target) {
                    if ((Get-Item -LiteralPath $target).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Runtime cache target is a link. Choose a dedicated FLOWS_RUNTIME_DIR.' }
                    Move-Item -LiteralPath $target -Destination (Join-Path $flowStage 'previous-runtime')
                }
                Move-Item -LiteralPath $extracted -Destination $target
                [Console]::Error.WriteLine("Flows: runtime ready in $target")
            }
        }
    }
} catch {
    [Console]::Error.WriteLine("Flows: $($_.Exception.Message)")
    exit 1
} finally {
    if ($flowStage -and (Test-Path -LiteralPath $flowStage)) { Remove-Item -LiteralPath $flowStage -Recurse -Force }
    # Leave the empty lock file in place: deleting it after close races a waiter.
    # Windows releases the exclusive handle automatically even after a crash.
    if ($flowLockStream) { $flowLockStream.Dispose() }
}
$previousPath = $env:PATH
try {
    $env:PATH = (Split-Path -Parent $flowNode) + [IO.Path]::PathSeparator + $previousPath
    & $flowNode $flowEntry @flowArguments
    $flowExitCode = $LASTEXITCODE
} finally { $env:PATH = $previousPath }
exit $flowExitCode

SHA-256: 04130719e4dd1c81f8bdf9f1553f54b780a817d8a0e65ffcc636d00369d4f04d