| 1 | $ErrorActionPreference = 'Continue' |
| 2 | $OutputEncoding = [Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) |
| 3 | $__rx_pipe = [IO.Pipes.NamedPipeClientStream]::new('.', $env:REASONIX_PWSH_PIPE, [IO.Pipes.PipeDirection]::InOut) |
| 4 | $__rx_pipe.Connect(10000) |
| 5 | $__rx_reader = [IO.BinaryReader]::new($__rx_pipe) |
| 6 | $__rx_writer = [IO.BinaryWriter]::new($__rx_pipe) |
| 7 | function __rx_send($frame) { |
| 8 | $bytes = [Text.Encoding]::UTF8.GetBytes(($frame | ConvertTo-Json -Compress)) |
| 9 | $__rx_writer.Write([int]$bytes.Length) |
| 10 | $__rx_writer.Write($bytes) |
| 11 | $__rx_writer.Flush() |
| 12 | } |
| 13 | __rx_send @{version=1; kind='ready'; id=''} |
| 14 | while ($true) { |
| 15 | $__rx_size = $__rx_reader.ReadInt32() |
| 16 | if ($__rx_size -le 0 -or $__rx_size -gt 4194304) { throw 'Invalid control frame size' } |
| 17 | $__rx_bytes = $__rx_reader.ReadBytes($__rx_size) |
| 18 | if ($__rx_bytes.Length -ne $__rx_size) { throw 'Truncated control frame' } |
| 19 | $__rx_request = [Text.Encoding]::UTF8.GetString($__rx_bytes) | ConvertFrom-Json |
| 20 | if ($__rx_request.version -ne 1 -or $__rx_request.kind -ne 'run') { throw 'Invalid control request' } |
| 21 | __rx_send @{version=1; kind='started'; id=$__rx_request.id} |
| 22 | [Console]::Out.Write($__rx_request.start + "`n") |
| 23 | $LASTEXITCODE = $null |
| 24 | $__rx_status = 1 |
| 25 | try { |
| 26 | # Dot sourcing keeps user variables, functions and location in this session. |
| 27 | # Capture status inside the script, before Out-Default changes $? itself. |
| 28 | $__rx_script = [scriptblock]::Create($__rx_request.command + "`n" + '$__rx_ok = $?; if (!$__rx_ok -and ($null -eq $LASTEXITCODE -or $LASTEXITCODE -eq 0)) { $__rx_status = 1 } elseif ($null -ne $LASTEXITCODE) { $__rx_status = [int]$LASTEXITCODE } else { $__rx_status = 0 }') |
| 29 | . $__rx_script 2>&1 | Out-Default |
| 30 | } catch { |
| 31 | $__rx_status = 1 |
| 32 | [Console]::Error.WriteLine($_.ToString()) |
| 33 | } |
| 34 | [Console]::Error.Flush() |
| 35 | [Console]::Out.Write($__rx_request.end + [string]$__rx_status + "`n") |
| 36 | [Console]::Out.Flush() |
| 37 | __rx_send @{version=1; kind='completed'; id=$__rx_request.id; exitCode=$__rx_status} |
| 38 | } |
| 39 |