npx.ps1 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/usr/bin/env pwsh
  2. Set-StrictMode -Version 'Latest'
  3. $NODE_EXE="$PSScriptRoot/node.exe"
  4. if (-not (Test-Path $NODE_EXE)) {
  5. $NODE_EXE="$PSScriptRoot/node"
  6. }
  7. if (-not (Test-Path $NODE_EXE)) {
  8. $NODE_EXE="node"
  9. }
  10. $NPM_PREFIX_JS="$PSScriptRoot/node_modules/npm/bin/npm-prefix.js"
  11. $NPX_CLI_JS="$PSScriptRoot/node_modules/npm/bin/npx-cli.js"
  12. $NPM_PREFIX=(& $NODE_EXE $NPM_PREFIX_JS)
  13. if ($LASTEXITCODE -ne 0) {
  14. Write-Host "Could not determine Node.js install directory"
  15. exit 1
  16. }
  17. $NPM_PREFIX_NPX_CLI_JS="$NPM_PREFIX/node_modules/npm/bin/npx-cli.js"
  18. if (Test-Path $NPM_PREFIX_NPX_CLI_JS) {
  19. $NPX_CLI_JS=$NPM_PREFIX_NPX_CLI_JS
  20. }
  21. if ($MyInvocation.ExpectingInput) { # takes pipeline input
  22. $input | & $NODE_EXE $NPX_CLI_JS $args
  23. } elseif (-not $MyInvocation.Line) { # used "-File" argument
  24. & $NODE_EXE $NPX_CLI_JS $args
  25. } else { # used "-Command" argument
  26. if (($MyInvocation | Get-Member -Name 'Statement') -and $MyInvocation.Statement) {
  27. $NPX_ORIGINAL_COMMAND = $MyInvocation.Statement
  28. } else {
  29. $NPX_ORIGINAL_COMMAND = (
  30. [Management.Automation.InvocationInfo].GetProperty('ScriptPosition', [Reflection.BindingFlags] 'Instance, NonPublic')
  31. ).GetValue($MyInvocation).Text
  32. }
  33. $NODE_EXE = $NODE_EXE.Replace("``", "````")
  34. $NPX_CLI_JS = $NPX_CLI_JS.Replace("``", "````")
  35. $NPX_COMMAND_ARRAY = [Management.Automation.Language.Parser]::ParseInput($NPX_ORIGINAL_COMMAND, [ref] $null, [ref] $null).
  36. EndBlock.Statements.PipelineElements.CommandElements.Extent.Text
  37. $NPX_ARGS = ($NPX_COMMAND_ARRAY | Select-Object -Skip 1) -join ' '
  38. Invoke-Expression "& `"$NODE_EXE`" `"$NPX_CLI_JS`" $NPX_ARGS"
  39. }
  40. exit $LASTEXITCODE