Compare commits
13 Commits
Author | SHA1 | Date | |
---|---|---|---|
61f76af7d1 | |||
529b33fda1 | |||
f8e431f41e | |||
5a32817349 | |||
35d22175db | |||
cd3675280a | |||
7c14102324 | |||
cb41dbaf1c | |||
149eb800e7 | |||
91e84c8422 | |||
ff26cd0678 | |||
acdd729e06 | |||
522fbfc42c |
BIN
.serena/cache/typescript/document_symbols_cache_v23-06-25.pkl
vendored
Normal file
BIN
.serena/cache/typescript/document_symbols_cache_v23-06-25.pkl
vendored
Normal file
Binary file not shown.
68
.serena/project.yml
Normal file
68
.serena/project.yml
Normal file
@@ -0,0 +1,68 @@
|
||||
# language of the project (csharp, python, rust, java, typescript, go, cpp, or ruby)
|
||||
# * For C, use cpp
|
||||
# * For JavaScript, use typescript
|
||||
# Special requirements:
|
||||
# * csharp: Requires the presence of a .sln file in the project folder.
|
||||
language: typescript
|
||||
|
||||
# whether to use the project's gitignore file to ignore files
|
||||
# Added on 2025-04-07
|
||||
ignore_all_files_in_gitignore: true
|
||||
# list of additional paths to ignore
|
||||
# same syntax as gitignore, so you can use * and **
|
||||
# Was previously called `ignored_dirs`, please update your config if you are using that.
|
||||
# Added (renamed) on 2025-04-07
|
||||
ignored_paths: []
|
||||
|
||||
# whether the project is in read-only mode
|
||||
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
|
||||
# Added on 2025-04-18
|
||||
read_only: false
|
||||
|
||||
|
||||
# list of tool names to exclude. We recommend not excluding any tools, see the readme for more details.
|
||||
# Below is the complete list of tools for convenience.
|
||||
# To make sure you have the latest list of tools, and to view their descriptions,
|
||||
# execute `uv run scripts/print_tool_overview.py`.
|
||||
#
|
||||
# * `activate_project`: Activates a project by name.
|
||||
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
|
||||
# * `create_text_file`: Creates/overwrites a file in the project directory.
|
||||
# * `delete_lines`: Deletes a range of lines within a file.
|
||||
# * `delete_memory`: Deletes a memory from Serena's project-specific memory store.
|
||||
# * `execute_shell_command`: Executes a shell command.
|
||||
# * `find_referencing_code_snippets`: Finds code snippets in which the symbol at the given location is referenced.
|
||||
# * `find_referencing_symbols`: Finds symbols that reference the symbol at the given location (optionally filtered by type).
|
||||
# * `find_symbol`: Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
|
||||
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
|
||||
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
|
||||
# * `initial_instructions`: Gets the initial instructions for the current project.
|
||||
# Should only be used in settings where the system prompt cannot be set,
|
||||
# e.g. in clients you have no control over, like Claude Desktop.
|
||||
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
|
||||
# * `insert_at_line`: Inserts content at a given line in a file.
|
||||
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
|
||||
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
|
||||
# * `list_memories`: Lists memories in Serena's project-specific memory store.
|
||||
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
|
||||
# * `prepare_for_new_conversation`: Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
|
||||
# * `read_file`: Reads a file within the project directory.
|
||||
# * `read_memory`: Reads the memory with the given name from Serena's project-specific memory store.
|
||||
# * `remove_project`: Removes a project from the Serena configuration.
|
||||
# * `replace_lines`: Replaces a range of lines within a file with new content.
|
||||
# * `replace_symbol_body`: Replaces the full definition of a symbol.
|
||||
# * `restart_language_server`: Restarts the language server, may be necessary when edits not through Serena happen.
|
||||
# * `search_for_pattern`: Performs a search for a pattern in the project.
|
||||
# * `summarize_changes`: Provides instructions for summarizing the changes made to the codebase.
|
||||
# * `switch_modes`: Activates modes by providing a list of their names
|
||||
# * `think_about_collected_information`: Thinking tool for pondering the completeness of collected information.
|
||||
# * `think_about_task_adherence`: Thinking tool for determining whether the agent is still on track with the current task.
|
||||
# * `think_about_whether_you_are_done`: Thinking tool for determining whether the task is truly completed.
|
||||
# * `write_memory`: Writes a named memory (for future reference) to Serena's project-specific memory store.
|
||||
excluded_tools: []
|
||||
|
||||
# initial prompt for the project. It will always be given to the LLM upon activating the project
|
||||
# (contrary to the memories, which are loaded on demand).
|
||||
initial_prompt: ""
|
||||
|
||||
project_name: "smartshell"
|
47
changelog.md
47
changelog.md
@@ -1,5 +1,52 @@
|
||||
# Changelog
|
||||
|
||||
## 2025-08-17 - 3.3.0 - feat(smartshell)
|
||||
Add secure spawn APIs, PTY support, interactive/streaming control, timeouts and buffer limits; update README and tests
|
||||
|
||||
- Introduce execSpawn family (execSpawn, execSpawnStreaming, execSpawnInteractiveControl) for shell-free, secure execution of untrusted input (shell:false).
|
||||
- Add PTY support (optional node-pty) with execInteractiveControlPty and execStreamingInteractiveControlPty; PTY is lazy-loaded and documented as an optional dependency.
|
||||
- Expose interactive control primitives (sendInput, sendLine, endInput, finalPromise) for both spawn and shell-based executions, and streaming interfaces with process control (terminate, kill, keyboardInterrupt, customSignal).
|
||||
- Implement timeouts, maxBuffer limits and onData callbacks to prevent OOM, stream output incrementally, and support early termination and debugging logs.
|
||||
- Improve process lifecycle handling: safe unpipe/unpipe-on-error, smartexit integration, and safer signal-based tree-kill behavior.
|
||||
- Enhance execAndWaitForLine with timeout and terminateOnMatch options to allow pattern-based waits with configurable behavior.
|
||||
- Update README with a Security Guide recommending execSpawn for untrusted input, PTY usage guidance, and new feature documentation (timeouts, buffer limits, debug mode, environment control).
|
||||
- Add extensive tests covering error handling, interactive control, passthrough, PTY behavior, spawn behavior, silent/streaming modes and environment propagation.
|
||||
|
||||
## 2025-08-16 - 3.2.4 - fix(tests)
|
||||
Update tests & CI config, bump deps, add docs and project configs
|
||||
|
||||
- Add comprehensive README overhaul with detailed usage, examples, API reference and best practices.
|
||||
- Add extensive silent-mode tests (test/test.silent.ts) to validate execSilent, execStrictSilent, execStreamingSilent and execAndWaitForLineSilent behaviors.
|
||||
- Update test runner and script: test script now runs tstest with --verbose, --logfile and --timeout; tests now import tapbundle from @git.zone/tstest.
|
||||
- Fix import in test/test.ts to use @git.zone/tstest/tapbundle.
|
||||
- Bump devDependencies: @git.zone/tsbuild -> ^2.6.4, @git.zone/tstest -> ^2.3.2; bump @push.rocks/smartpromise -> ^4.2.3.
|
||||
- Add typings entry and packageManager field to package.json.
|
||||
- Add project configuration files (.serena/project.yml) and local settings (.claude/settings.local.json).
|
||||
|
||||
## 2025-02-20 - 3.2.3 - fix(core)
|
||||
Refactor Smartshell class for improved code clarity and performance
|
||||
|
||||
- Refactored `_exec` method to improve code clarity.
|
||||
- Introduced `IExecOptions` interface for better type handling.
|
||||
- Replaced promise defer with native promises in command execution methods.
|
||||
- Improved logging and error handling in child process execution.
|
||||
- Ensured robust process management with signals handling.
|
||||
|
||||
## 2024-12-13 - 3.2.2 - fix(core)
|
||||
Fix minor code style and formatting issues
|
||||
|
||||
|
||||
## 2024-12-13 - 3.2.1 - fix(dependencies)
|
||||
Update @types/node dependency version
|
||||
|
||||
- Updated @types/node dependency from version ^22.10.1 to ^22.10.2.
|
||||
|
||||
## 2024-12-09 - 3.2.0 - feat(SmartExecution)
|
||||
Add support for scheduling restarts to SmartExecution
|
||||
|
||||
- Introduced the ability to handle consecutive restarts efficiently in SmartExecution.
|
||||
- Ensures that multiple restart requests merge into a single additional restart request if one is already in progress.
|
||||
|
||||
## 2024-12-09 - 3.1.0 - feat(core)
|
||||
Refactor codebase and update dependencies.
|
||||
|
||||
|
16
package.json
16
package.json
@@ -1,13 +1,13 @@
|
||||
{
|
||||
"name": "@push.rocks/smartshell",
|
||||
"private": false,
|
||||
"version": "3.1.0",
|
||||
"version": "3.3.0",
|
||||
"description": "A library for executing shell commands using promises.",
|
||||
"main": "dist_ts/index.js",
|
||||
"typings": "dist_ts/index.d.ts",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "(tstest test/)",
|
||||
"test": "(tstest test/ --verbose --logfile --timeout 20)",
|
||||
"build": "(tsbuild tsfolders --web)",
|
||||
"buildDocs": "tsdoc"
|
||||
},
|
||||
@@ -33,16 +33,15 @@
|
||||
},
|
||||
"homepage": "https://code.foss.global/push.rocks/smartshell",
|
||||
"devDependencies": {
|
||||
"@git.zone/tsbuild": "^2.2.0",
|
||||
"@git.zone/tsbuild": "^2.6.4",
|
||||
"@git.zone/tsrun": "^1.3.3",
|
||||
"@git.zone/tstest": "^1.0.90",
|
||||
"@push.rocks/tapbundle": "^5.5.3",
|
||||
"@types/node": "^22.10.1"
|
||||
"@git.zone/tstest": "^2.3.2",
|
||||
"@types/node": "^22.10.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@push.rocks/smartdelay": "^3.0.1",
|
||||
"@push.rocks/smartexit": "^1.0.23",
|
||||
"@push.rocks/smartpromise": "^4.0.4",
|
||||
"@push.rocks/smartpromise": "^4.2.3",
|
||||
"@types/which": "^3.0.4",
|
||||
"tree-kill": "^1.2.2",
|
||||
"which": "^5.0.0"
|
||||
@@ -61,5 +60,6 @@
|
||||
],
|
||||
"browserslist": [
|
||||
"last 1 chrome versions"
|
||||
]
|
||||
],
|
||||
"packageManager": "pnpm@10.14.0+sha512.ad27a79641b49c3e481a16a805baa71817a04bbe06a38d17e60e2eaee83f6a146c6a688125f5792e48dd5ba30e7da52a5cda4c3992b9ccf333f9ce223af84748"
|
||||
}
|
||||
|
7010
pnpm-lock.yaml
generated
7010
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
671
readme.md
671
readme.md
@@ -1,136 +1,617 @@
|
||||
# @push.rocks/smartshell
|
||||
shell actions designed as promises
|
||||
# @push.rocks/smartshell 🐚
|
||||
**Execute shell commands with superpowers in Node.js**
|
||||
|
||||
## Install
|
||||
[](https://www.npmjs.com/package/@push.rocks/smartshell)
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
|
||||
To install `@push.rocks/smartshell`, use npm:
|
||||
## ⚠️ Security Notice
|
||||
|
||||
```sh
|
||||
**IMPORTANT:** Please read the [Security Guide](#security-guide) below for critical information about command execution and input handling. Always use `execSpawn` methods for untrusted input.
|
||||
|
||||
## Why smartshell? 🚀
|
||||
|
||||
Tired of wrestling with Node.js child processes? Meet `@push.rocks/smartshell` - your promise-based shell command companion that makes executing system commands feel like a breeze. Whether you're building automation scripts, CI/CD pipelines, or need fine-grained control over shell execution, smartshell has got you covered.
|
||||
|
||||
### ✨ Key Features
|
||||
|
||||
- 🎯 **Promise-based API** - Async/await ready for modern codebases
|
||||
- 🔇 **Silent execution modes** - Control output verbosity
|
||||
- 📡 **Streaming support** - Real-time output for long-running processes
|
||||
- 🎮 **Interactive commands** - Handle user input programmatically
|
||||
- 🛡️ **Secure execution** - Shell-free methods for untrusted input
|
||||
- ⚡ **Smart execution modes** - Strict, silent, or streaming
|
||||
- 🔍 **Pattern matching** - Wait for specific output patterns
|
||||
- 🌍 **Environment management** - Custom env vars and PATH handling
|
||||
- 💾 **Memory protection** - Built-in buffer limits prevent OOM
|
||||
- ⏱️ **Timeout support** - Automatic process termination
|
||||
- 🖥️ **PTY support** - Full terminal emulation (optional)
|
||||
- 🎨 **Cross-platform** - Windows, macOS, and Linux ready
|
||||
- 🛡️ **TypeScript first** - Full type safety and IntelliSense
|
||||
|
||||
## Installation 📦
|
||||
|
||||
```bash
|
||||
# Using npm
|
||||
npm install @push.rocks/smartshell --save
|
||||
```
|
||||
|
||||
Or if you prefer using Yarn:
|
||||
|
||||
```sh
|
||||
# Using yarn
|
||||
yarn add @push.rocks/smartshell
|
||||
|
||||
# Using pnpm (recommended)
|
||||
pnpm add @push.rocks/smartshell
|
||||
|
||||
# Optional: For PTY support (terminal emulation)
|
||||
pnpm add --save-optional node-pty
|
||||
```
|
||||
|
||||
Ensure that you have TypeScript and the related dependencies installed as well since `@push.rocks/smartshell` is designed to work with TypeScript.
|
||||
|
||||
## Usage
|
||||
|
||||
The `@push.rocks/smartshell` package simplifies running shell commands within Node.js applications by wrapping these commands within promises. This approach enhances the readability and maintainability of code that relies on shell execution, making it particularly useful in automation scripts, build processes, and any scenario where interaction with the system shell is required.
|
||||
|
||||
### Getting Started with `@push.rocks/smartshell`
|
||||
|
||||
First, ensure that you import `Smartshell` from `@push.rocks/smartshell` using ESM syntax in your TypeScript file:
|
||||
## Quick Start 🏃♂️
|
||||
|
||||
```typescript
|
||||
import { Smartshell } from '@push.rocks/smartshell';
|
||||
|
||||
// Create your shell instance
|
||||
const shell = new Smartshell({
|
||||
executor: 'bash' // or 'sh' for lighter shells
|
||||
});
|
||||
|
||||
// Run a simple command
|
||||
const result = await shell.exec('echo "Hello, World!"');
|
||||
console.log(result.stdout); // "Hello, World!"
|
||||
console.log(result.signal); // undefined (no signal)
|
||||
console.log(result.stderr); // "" (no errors)
|
||||
```
|
||||
|
||||
### Creating a Smartshell Instance
|
||||
## Security-First Execution 🔒
|
||||
|
||||
Before executing any shell command, you need to create an instance of `Smartshell`. The constructor accepts configuration options such as the shell executor (`bash` or `sh`), and optionally, paths to source files and directories to include in the shell’s environment.
|
||||
### Secure Command Execution with execSpawn
|
||||
|
||||
When dealing with untrusted input, **always use execSpawn methods** which don't use shell interpretation:
|
||||
|
||||
```typescript
|
||||
const smartShellInstance = new Smartshell({
|
||||
executor: 'bash', // or 'sh'
|
||||
// ❌ DANGEROUS with untrusted input
|
||||
const userInput = "file.txt; rm -rf /";
|
||||
await shell.exec(`cat ${userInput}`); // Command injection!
|
||||
|
||||
// ✅ SAFE with untrusted input
|
||||
await shell.execSpawn('cat', [userInput]); // Arguments are properly escaped
|
||||
```
|
||||
|
||||
### execSpawn Family Methods
|
||||
|
||||
```typescript
|
||||
// Basic secure execution
|
||||
const result = await shell.execSpawn('ls', ['-la', '/home']);
|
||||
|
||||
// Streaming secure execution
|
||||
const streaming = await shell.execSpawnStreaming('npm', ['install']);
|
||||
await streaming.finalPromise;
|
||||
|
||||
// Interactive secure execution
|
||||
const interactive = await shell.execSpawnInteractiveControl('cat', []);
|
||||
await interactive.sendLine('Hello');
|
||||
interactive.endInput();
|
||||
await interactive.finalPromise;
|
||||
```
|
||||
|
||||
## Production Features 🏭
|
||||
|
||||
### Resource Management
|
||||
|
||||
Prevent memory issues with built-in buffer limits:
|
||||
|
||||
```typescript
|
||||
const result = await shell.exec('large-output-command', {
|
||||
maxBuffer: 10 * 1024 * 1024, // 10MB limit
|
||||
onData: (chunk) => {
|
||||
// Process chunks as they arrive
|
||||
console.log('Received:', chunk.toString());
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Executing Commands
|
||||
### Timeout Support
|
||||
|
||||
#### Basic Execution
|
||||
|
||||
To execute a shell command, use the `exec` method. This method returns a promise that resolves with an execution result object containing `exitCode` and `stdout`.
|
||||
Automatically terminate long-running processes:
|
||||
|
||||
```typescript
|
||||
(async () => {
|
||||
const result = await smartShellInstance.exec('echo "Hello, SmartShell"');
|
||||
console.log(result.stdout); // Outputs: Hello, SmartShell
|
||||
})();
|
||||
```
|
||||
|
||||
#### Silent Execution
|
||||
|
||||
If you prefer not to display the output in the console, use `execSilent`:
|
||||
|
||||
```typescript
|
||||
(async () => {
|
||||
const result = await smartShellInstance.execSilent('ls');
|
||||
console.log(result.stdout); // Outputs the list of files and directories
|
||||
})();
|
||||
```
|
||||
|
||||
#### Strict Execution
|
||||
|
||||
For scenarios where an execution error should immediately throw an exception, use `execStrict`:
|
||||
|
||||
```typescript
|
||||
(async () => {
|
||||
try {
|
||||
const result = await smartShellInstance.execStrict('exit 1');
|
||||
} catch (error) {
|
||||
console.error('Command execution failed');
|
||||
}
|
||||
})();
|
||||
```
|
||||
|
||||
#### Streaming Output
|
||||
|
||||
Some commands benefit from streaming output as they execute, especially long-running tasks. For these cases, use `execStreaming`:
|
||||
|
||||
```typescript
|
||||
(async () => {
|
||||
const execStreamingResult = await smartShellInstance.execStreaming('tail -f /var/log/system.log');
|
||||
|
||||
execStreamingResult.childProcess.stdout.on('data', (data) => {
|
||||
console.log(data.toString());
|
||||
try {
|
||||
const result = await shell.execSpawn('long-process', [], {
|
||||
timeout: 5000 // 5 second timeout
|
||||
});
|
||||
|
||||
// Remember to handle the process termination as necessary.
|
||||
})();
|
||||
} catch (error) {
|
||||
console.log('Process timed out');
|
||||
}
|
||||
```
|
||||
|
||||
### Advanced Usage
|
||||
### Debug Mode
|
||||
|
||||
#### Executing With Custom Environment Variables
|
||||
|
||||
`smartshell` allows for the execution of commands within a modified environment, facilitating the use of custom variables or altered PATH values:
|
||||
Enable detailed logging for troubleshooting:
|
||||
|
||||
```typescript
|
||||
(async () => {
|
||||
smartShellInstance.shellEnv.addSourceFiles(['/path/to/envFile']);
|
||||
smartShellInstance.shellEnv.pathDirArray.push('/custom/bin');
|
||||
const result = await shell.exec('command', {
|
||||
debug: true // Logs process lifecycle events
|
||||
});
|
||||
```
|
||||
|
||||
### Custom Environment
|
||||
|
||||
Control the execution environment precisely:
|
||||
|
||||
```typescript
|
||||
const result = await shell.execSpawn('node', ['script.js'], {
|
||||
env: {
|
||||
NODE_ENV: 'production',
|
||||
PATH: '/usr/bin:/bin',
|
||||
CUSTOM_VAR: 'value'
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Interactive Control 🎮
|
||||
|
||||
### Programmatic Input Control
|
||||
|
||||
Send input to processes programmatically:
|
||||
|
||||
```typescript
|
||||
const interactive = await shell.execInteractiveControl('cat');
|
||||
|
||||
// Send input line by line
|
||||
await interactive.sendLine('Line 1');
|
||||
await interactive.sendLine('Line 2');
|
||||
|
||||
// Send raw input without newline
|
||||
await interactive.sendInput('partial');
|
||||
|
||||
// Close stdin
|
||||
interactive.endInput();
|
||||
|
||||
// Wait for completion
|
||||
const result = await interactive.finalPromise;
|
||||
```
|
||||
|
||||
### Passthrough Mode
|
||||
|
||||
Connect stdin for real keyboard interaction:
|
||||
|
||||
```typescript
|
||||
// User can type directly
|
||||
await shell.execPassthrough('vim file.txt');
|
||||
```
|
||||
|
||||
## PTY Support - Full Terminal Emulation 🖥️
|
||||
|
||||
Smartshell provides two modes for executing interactive commands:
|
||||
|
||||
1. **Pipe Mode (Default)** - Fast, simple, no dependencies
|
||||
2. **PTY Mode** - Full terminal emulation for advanced interactive programs
|
||||
|
||||
### When to Use Each Mode
|
||||
|
||||
#### Use Pipe Mode (Default) When:
|
||||
- Running simple commands that read from stdin
|
||||
- Using tools like `cat`, `grep`, `sed`, `awk`
|
||||
- Running basic scripts that don't need terminal features
|
||||
- You want maximum performance and simplicity
|
||||
- You don't want native dependencies
|
||||
|
||||
#### Use PTY Mode When:
|
||||
- Running commands that require a real terminal:
|
||||
- Password prompts (`sudo`, `ssh`, `su`)
|
||||
- Interactive editors (`vim`, `nano`, `emacs`)
|
||||
- Terminal UIs (`htop`, `less`, `more`)
|
||||
- Programs with fancy prompts (`bash read -p`)
|
||||
- Tab completion and readline features
|
||||
- You need terminal features:
|
||||
- ANSI colors and escape sequences
|
||||
- Terminal size control
|
||||
- Signal handling (Ctrl+C, Ctrl+Z)
|
||||
- Line discipline and special key handling
|
||||
|
||||
### Installing PTY Support
|
||||
|
||||
PTY support requires the optional `node-pty` dependency:
|
||||
|
||||
```bash
|
||||
# Install as optional dependency
|
||||
pnpm add --save-optional node-pty
|
||||
|
||||
# Note: node-pty requires compilation and has platform-specific requirements
|
||||
# - On Windows: Requires Visual Studio Build Tools
|
||||
# - On macOS/Linux: Requires Python and build tools
|
||||
```
|
||||
|
||||
### PTY Usage Examples
|
||||
|
||||
```typescript
|
||||
// Use PTY for commands that need terminal features
|
||||
const ptyInteractive = await shell.execInteractiveControlPty(
|
||||
"bash -c 'read -p \"Enter name: \" name && echo \"Hello, $name\"'"
|
||||
);
|
||||
await ptyInteractive.sendLine('John');
|
||||
const result = await ptyInteractive.finalPromise;
|
||||
// With PTY, the prompt "Enter name: " will be visible in stdout
|
||||
|
||||
// Streaming with PTY for real-time interaction
|
||||
const ptyStreaming = await shell.execStreamingInteractiveControlPty('vim test.txt');
|
||||
await ptyStreaming.sendInput('i'); // Enter insert mode
|
||||
await ptyStreaming.sendInput('Hello from PTY!');
|
||||
await ptyStreaming.sendInput('\x1b'); // ESC key
|
||||
await ptyStreaming.sendInput(':wq\r'); // Save and quit
|
||||
```
|
||||
|
||||
### PTY vs Pipe Mode Comparison
|
||||
|
||||
| Feature | Pipe Mode | PTY Mode |
|
||||
|---------|-----------|----------|
|
||||
| Dependencies | None | node-pty |
|
||||
| Terminal Detection | `isatty()` returns false | `isatty()` returns true |
|
||||
| Prompt Display | May not show | Always shows |
|
||||
| Colors | Often disabled | Enabled |
|
||||
| Signal Handling | Basic | Full (Ctrl+C, Ctrl+Z, etc.) |
|
||||
| Line Ending | `\n` | `\r` (carriage return) |
|
||||
| EOF Signal | Stream end | `\x04` (Ctrl+D) |
|
||||
|
||||
### Common PTY Patterns
|
||||
|
||||
```typescript
|
||||
// Password input (PTY required)
|
||||
const sudo = await shell.execInteractiveControlPty('sudo ls /root');
|
||||
await sudo.sendLine('mypassword');
|
||||
const result = await sudo.finalPromise;
|
||||
|
||||
// Interactive REPL with colors
|
||||
const node = await shell.execStreamingInteractiveControlPty('node');
|
||||
await node.sendLine('console.log("PTY supports colors!")');
|
||||
await node.sendLine('.exit');
|
||||
|
||||
// Handling terminal colors
|
||||
const ls = await shell.execInteractiveControlPty('ls --color=always');
|
||||
const result = await ls.finalPromise;
|
||||
// result.stdout will contain ANSI color codes
|
||||
```
|
||||
|
||||
### PTY Fallback Strategy
|
||||
|
||||
Always provide a fallback for when PTY isn't available:
|
||||
|
||||
```typescript
|
||||
try {
|
||||
// Try PTY mode first
|
||||
const result = await shell.execInteractiveControlPty(command);
|
||||
// ...
|
||||
} catch (error) {
|
||||
if (error.message.includes('node-pty')) {
|
||||
// Fallback to pipe mode
|
||||
console.warn('PTY not available, using pipe mode');
|
||||
const result = await shell.execInteractiveControl(command);
|
||||
// ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Advanced Pattern Matching 🔍
|
||||
|
||||
### Enhanced execAndWaitForLine
|
||||
|
||||
Wait for patterns with timeout and auto-termination:
|
||||
|
||||
```typescript
|
||||
// Wait with timeout
|
||||
await shell.execAndWaitForLine(
|
||||
'npm start',
|
||||
/Server listening on port/,
|
||||
false, // silent
|
||||
{
|
||||
timeout: 30000, // 30 second timeout
|
||||
terminateOnMatch: true // Kill process after match
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
## Core Concepts 💡
|
||||
|
||||
### The Smartshell Instance
|
||||
|
||||
The heart of smartshell is the `Smartshell` class. Each instance maintains its own environment and configuration:
|
||||
|
||||
```typescript
|
||||
const shell = new Smartshell({
|
||||
executor: 'bash', // Choose your shell: 'bash' or 'sh'
|
||||
sourceFilePaths: ['/path/to/env.sh'], // Optional: source files on init
|
||||
});
|
||||
```
|
||||
|
||||
## Execution Modes 🎛️
|
||||
|
||||
### Standard Execution
|
||||
|
||||
Perfect for general commands where you want to see the output:
|
||||
|
||||
```typescript
|
||||
const result = await shell.exec('ls -la');
|
||||
console.log(result.stdout); // Directory listing
|
||||
console.log(result.exitCode); // 0 for success
|
||||
console.log(result.signal); // Signal if terminated
|
||||
console.log(result.stderr); // Error output
|
||||
```
|
||||
|
||||
### Silent Execution
|
||||
|
||||
Run commands without printing to console - ideal for capturing output:
|
||||
|
||||
```typescript
|
||||
const result = await shell.execSilent('cat /etc/hostname');
|
||||
// Output is NOT printed to console but IS captured in result
|
||||
console.log(result.stdout); // Access the captured output here
|
||||
```
|
||||
|
||||
### Strict Execution
|
||||
|
||||
Throws an error if the command fails - great for critical operations:
|
||||
|
||||
```typescript
|
||||
try {
|
||||
await shell.execStrict('critical-command');
|
||||
console.log('✅ Command succeeded!');
|
||||
} catch (error) {
|
||||
console.error('❌ Command failed:', error.message);
|
||||
// Error includes exit code or signal information
|
||||
}
|
||||
```
|
||||
|
||||
### Streaming Execution
|
||||
|
||||
For long-running processes or when you need real-time output:
|
||||
|
||||
```typescript
|
||||
const streaming = await shell.execStreaming('npm install');
|
||||
|
||||
// Access the child process directly
|
||||
streaming.childProcess.stdout.on('data', (chunk) => {
|
||||
console.log('📦 Installing:', chunk.toString());
|
||||
});
|
||||
|
||||
// Control the process
|
||||
await streaming.terminate(); // SIGTERM
|
||||
await streaming.kill(); // SIGKILL
|
||||
await streaming.keyboardInterrupt(); // SIGINT
|
||||
|
||||
// Wait for completion
|
||||
await streaming.finalPromise;
|
||||
```
|
||||
|
||||
## Real-World Examples 🌍
|
||||
|
||||
### Build Pipeline
|
||||
|
||||
```typescript
|
||||
const shell = new Smartshell({ executor: 'bash' });
|
||||
|
||||
// Clean build directory
|
||||
await shell.execSilent('rm -rf dist');
|
||||
|
||||
// Run TypeScript compiler
|
||||
const buildResult = await shell.execStrict('tsc');
|
||||
|
||||
// Run tests
|
||||
await shell.execStrict('npm test');
|
||||
|
||||
// Build succeeded!
|
||||
console.log('✅ Build pipeline completed successfully');
|
||||
```
|
||||
|
||||
### CI/CD with Security
|
||||
|
||||
```typescript
|
||||
async function deployApp(branch: string, untrustedTag: string) {
|
||||
const shell = new Smartshell({ executor: 'bash' });
|
||||
|
||||
const result = await smartShellInstance.exec('echo $CUSTOM_VAR');
|
||||
console.log(result.stdout); // Outputs the value of CUSTOM_VAR
|
||||
})();
|
||||
// Use execSpawn for untrusted input
|
||||
await shell.execSpawnStrict('git', ['checkout', branch]);
|
||||
await shell.execSpawnStrict('git', ['tag', untrustedTag]);
|
||||
|
||||
// Safe to use exec for hardcoded commands
|
||||
await shell.execStrict('npm run build');
|
||||
await shell.execStrict('npm run deploy');
|
||||
}
|
||||
```
|
||||
|
||||
### Interactive Mode
|
||||
|
||||
For commands that require interactive terminal input (not typically recommended for automated scripts), you can use `execInteractive`:
|
||||
### Docker Compose Helper
|
||||
|
||||
```typescript
|
||||
(async () => {
|
||||
await smartShellInstance.execInteractive('npm init');
|
||||
})();
|
||||
const shell = new Smartshell({ executor: 'bash' });
|
||||
|
||||
// Start services and wait for readiness
|
||||
console.log('🐳 Starting Docker services...');
|
||||
await shell.execAndWaitForLine(
|
||||
'docker-compose up',
|
||||
/All services are ready/,
|
||||
false,
|
||||
{
|
||||
timeout: 60000,
|
||||
terminateOnMatch: false // Keep running after match
|
||||
}
|
||||
);
|
||||
|
||||
// Run migrations
|
||||
await shell.execStrict('docker-compose exec app npm run migrate');
|
||||
console.log('✅ Environment ready!');
|
||||
```
|
||||
|
||||
### Waiting for Specific Output
|
||||
|
||||
To wait for a specific line before proceeding, you might use `execAndWaitForLine`. This is useful for waiting on a process to log a certain message:
|
||||
### Development Server with Auto-Restart
|
||||
|
||||
```typescript
|
||||
(async () => {
|
||||
await smartShellInstance.execAndWaitForLine('npm run watch', /Compilation complete./);
|
||||
console.log('The watch process has finished compiling.');
|
||||
})();
|
||||
import { SmartExecution } from '@push.rocks/smartshell';
|
||||
|
||||
const shell = new Smartshell({ executor: 'bash' });
|
||||
const devServer = new SmartExecution(shell, 'npm run dev');
|
||||
|
||||
// Watch for file changes and restart
|
||||
fs.watch('./src', async () => {
|
||||
console.log('🔄 Changes detected, restarting...');
|
||||
await devServer.restart();
|
||||
});
|
||||
```
|
||||
|
||||
Given the vast array of features offered by `@push.rocks/smartshell`, integrating shell operations into your TypeScript applications becomes both straightforward and powerful. By harnessing promises and async/await syntax, `smartshell` effectively streamlines shell interactions, making your code cleaner and more intuitive.
|
||||
## API Reference 📚
|
||||
|
||||
### Smartshell Class
|
||||
|
||||
| Method | Description | Security |
|
||||
|--------|-------------|----------|
|
||||
| `exec(command)` | Execute with shell | ⚠️ Vulnerable to injection |
|
||||
| `execSpawn(cmd, args)` | Execute without shell | ✅ Safe for untrusted input |
|
||||
| `execSilent(command)` | Execute without console output | ⚠️ Vulnerable to injection |
|
||||
| `execStrict(command)` | Execute, throw on failure | ⚠️ Vulnerable to injection |
|
||||
| `execStreaming(command)` | Stream output in real-time | ⚠️ Vulnerable to injection |
|
||||
| `execSpawnStreaming(cmd, args)` | Stream without shell | ✅ Safe for untrusted input |
|
||||
| `execInteractive(command)` | Interactive terminal mode | ⚠️ Vulnerable to injection |
|
||||
| `execInteractiveControl(command)` | Programmatic input control | ⚠️ Vulnerable to injection |
|
||||
| `execSpawnInteractiveControl(cmd, args)` | Programmatic control without shell | ✅ Safe for untrusted input |
|
||||
| `execPassthrough(command)` | Connect stdin passthrough | ⚠️ Vulnerable to injection |
|
||||
| `execInteractiveControlPty(command)` | PTY with programmatic control | ⚠️ Vulnerable to injection |
|
||||
| `execStreamingInteractiveControlPty(command)` | PTY streaming with control | ⚠️ Vulnerable to injection |
|
||||
| `execAndWaitForLine(cmd, regex, silent, opts)` | Wait for pattern match | ⚠️ Vulnerable to injection |
|
||||
|
||||
### Result Interfaces
|
||||
|
||||
```typescript
|
||||
interface IExecResult {
|
||||
exitCode: number; // Process exit code
|
||||
stdout: string; // Standard output
|
||||
signal?: NodeJS.Signals; // Termination signal
|
||||
stderr?: string; // Error output
|
||||
}
|
||||
|
||||
interface IExecResultStreaming {
|
||||
childProcess: ChildProcess; // Node.js ChildProcess instance
|
||||
finalPromise: Promise<IExecResult>; // Resolves when process exits
|
||||
sendInput: (input: string) => Promise<void>;
|
||||
sendLine: (line: string) => Promise<void>;
|
||||
endInput: () => void;
|
||||
kill: () => Promise<void>;
|
||||
terminate: () => Promise<void>;
|
||||
keyboardInterrupt: () => Promise<void>;
|
||||
customSignal: (signal: NodeJS.Signals) => Promise<void>;
|
||||
}
|
||||
|
||||
interface IExecResultInteractive extends IExecResult {
|
||||
sendInput: (input: string) => Promise<void>;
|
||||
sendLine: (line: string) => Promise<void>;
|
||||
endInput: () => void;
|
||||
finalPromise: Promise<IExecResult>;
|
||||
}
|
||||
```
|
||||
|
||||
### Options Interface
|
||||
|
||||
```typescript
|
||||
interface IExecOptions {
|
||||
silent?: boolean; // Suppress console output
|
||||
strict?: boolean; // Throw on non-zero exit
|
||||
streaming?: boolean; // Return streaming interface
|
||||
interactive?: boolean; // Interactive mode
|
||||
passthrough?: boolean; // Connect stdin
|
||||
interactiveControl?: boolean; // Programmatic input
|
||||
usePty?: boolean; // Use pseudo-terminal
|
||||
ptyShell?: string; // Custom PTY shell
|
||||
ptyCols?: number; // PTY columns (default 120)
|
||||
ptyRows?: number; // PTY rows (default 30)
|
||||
ptyTerm?: string; // Terminal type (default 'xterm-256color')
|
||||
maxBuffer?: number; // Max output buffer (bytes)
|
||||
onData?: (chunk: Buffer | string) => void; // Data callback
|
||||
timeout?: number; // Execution timeout (ms)
|
||||
debug?: boolean; // Enable debug logging
|
||||
env?: NodeJS.ProcessEnv; // Custom environment
|
||||
signal?: AbortSignal; // Abort signal
|
||||
}
|
||||
```
|
||||
|
||||
## Security Guide
|
||||
|
||||
### Command Injection Prevention
|
||||
|
||||
The standard `exec` methods use `shell: true`, which can lead to command injection vulnerabilities:
|
||||
|
||||
```typescript
|
||||
// ❌ DANGEROUS - Never do this with untrusted input
|
||||
const userInput = "file.txt; rm -rf /";
|
||||
await smartshell.exec(`cat ${userInput}`); // Will execute rm -rf /
|
||||
|
||||
// ✅ SAFE - Arguments are properly escaped
|
||||
await smartshell.execSpawn('cat', [userInput]); // Will look for literal filename
|
||||
```
|
||||
|
||||
### Best Practices
|
||||
|
||||
1. **Always validate input**: Even with secure methods, validate user input
|
||||
2. **Use execSpawn for untrusted data**: Never pass user input to shell-based methods
|
||||
3. **Set resource limits**: Use `maxBuffer` and `timeout` for untrusted commands
|
||||
4. **Control environment**: Don't inherit all env vars for sensitive operations
|
||||
5. **Restrict signals**: Only allow specific signals from user input
|
||||
|
||||
### Path Traversal Protection
|
||||
|
||||
```typescript
|
||||
// ❌ VULNERABLE
|
||||
const file = userInput; // Could be "../../../etc/passwd"
|
||||
await shell.exec(`cat ${file}`);
|
||||
|
||||
// ✅ SECURE
|
||||
const path = require('path');
|
||||
const safePath = path.join('/allowed/directory', path.basename(userInput));
|
||||
await shell.execSpawn('cat', [safePath]);
|
||||
```
|
||||
|
||||
## Tips & Best Practices 💎
|
||||
|
||||
1. **Security first**: Use `execSpawn` for any untrusted input
|
||||
2. **Set resource limits**: Always use `maxBuffer` and `timeout` for untrusted commands
|
||||
3. **Choose the right executor**: Use `bash` for full features, `sh` for minimal overhead
|
||||
4. **Use strict mode for critical operations**: Ensures failures don't go unnoticed
|
||||
5. **Stream long-running processes**: Better UX and memory efficiency
|
||||
6. **Leverage silent modes**: When you only need to capture output
|
||||
7. **Handle errors gracefully**: Check both `exitCode` and `signal`
|
||||
8. **Clean up resources**: Streaming processes should be properly terminated
|
||||
9. **Control environment**: Don't inherit all env vars for sensitive operations
|
||||
10. **Enable debug mode**: For development and troubleshooting
|
||||
11. **Use PTY for terminal UIs**: When programs need real terminal features
|
||||
12. **Provide fallbacks**: Always handle PTY unavailability gracefully
|
||||
|
||||
## Environment Customization
|
||||
|
||||
Smartshell provides powerful environment management:
|
||||
|
||||
```typescript
|
||||
// Add custom source files
|
||||
shell.shellEnv.addSourceFiles([
|
||||
'/home/user/.custom_env',
|
||||
'./project.env.sh'
|
||||
]);
|
||||
|
||||
// Modify PATH
|
||||
shell.shellEnv.pathDirArray.push('/custom/bin');
|
||||
shell.shellEnv.pathDirArray.push('/usr/local/special');
|
||||
|
||||
// Your custom environment is ready
|
||||
const result = await shell.exec('my-custom-command');
|
||||
```
|
||||
|
||||
## Shell Detection
|
||||
|
||||
Need to check if a command exists? We export the `which` utility:
|
||||
|
||||
```typescript
|
||||
import { which } from '@push.rocks/smartshell';
|
||||
|
||||
try {
|
||||
const gitPath = await which('git');
|
||||
console.log(`Git found at: ${gitPath}`);
|
||||
} catch (error) {
|
||||
console.log('Git is not installed');
|
||||
}
|
||||
```
|
||||
|
||||
## License and Legal Information
|
||||
|
||||
@@ -149,4 +630,4 @@ Registered at District court Bremen HRB 35230 HB, Germany
|
||||
|
||||
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
||||
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
222
test/test.errorHandling.ts
Normal file
222
test/test.errorHandling.ts
Normal file
@@ -0,0 +1,222 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
tap.test('should handle EPIPE errors gracefully', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const streaming = await testSmartshell.execStreamingInteractiveControl('head -n 1');
|
||||
|
||||
// Send more data after head exits (will cause EPIPE)
|
||||
await streaming.sendLine('Line 1');
|
||||
|
||||
// This should not throw even though head has exited
|
||||
let errorThrown = false;
|
||||
try {
|
||||
await streaming.sendLine('Line 2');
|
||||
await streaming.sendLine('Line 3');
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
// EPIPE or destroyed stdin is expected
|
||||
}
|
||||
|
||||
const result = await streaming.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Line 1');
|
||||
});
|
||||
|
||||
tap.test('should handle strict mode with non-zero exit codes', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let errorThrown = false;
|
||||
let errorMessage = '';
|
||||
|
||||
try {
|
||||
await testSmartshell.execStrict('exit 42');
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
errorMessage = error.message;
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
expect(errorMessage).toContain('exited with code 42');
|
||||
});
|
||||
|
||||
tap.test('should handle strict mode with signal termination', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let errorThrown = false;
|
||||
let errorMessage = '';
|
||||
|
||||
try {
|
||||
// Use execSpawn with strict mode and kill it
|
||||
const result = testSmartshell.execSpawn('sleep', ['10'], {
|
||||
strict: true,
|
||||
timeout: 100 // Will cause SIGTERM
|
||||
});
|
||||
await result;
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
errorMessage = error.message;
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
expect(errorMessage).toContain('terminated by signal');
|
||||
});
|
||||
|
||||
tap.test('execAndWaitForLine with timeout should reject properly', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let errorThrown = false;
|
||||
let errorMessage = '';
|
||||
|
||||
try {
|
||||
await testSmartshell.execAndWaitForLine(
|
||||
'sleep 5 && echo "Too late"',
|
||||
/Too late/,
|
||||
false,
|
||||
{ timeout: 100 }
|
||||
);
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
errorMessage = error.message;
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
expect(errorMessage).toContain('Timeout waiting for pattern');
|
||||
});
|
||||
|
||||
tap.test('execAndWaitForLine with terminateOnMatch should stop process', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const start = Date.now();
|
||||
await testSmartshell.execAndWaitForLine(
|
||||
'echo "Match this" && sleep 5',
|
||||
/Match this/,
|
||||
false,
|
||||
{ terminateOnMatch: true }
|
||||
);
|
||||
const duration = Date.now() - start;
|
||||
|
||||
// Should terminate immediately after match, not wait for sleep
|
||||
expect(duration).toBeLessThan(2000);
|
||||
});
|
||||
|
||||
tap.test('should handle process ending without matching pattern', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let errorThrown = false;
|
||||
let errorMessage = '';
|
||||
|
||||
try {
|
||||
await testSmartshell.execAndWaitForLine(
|
||||
'echo "Wrong text"',
|
||||
/Never appears/,
|
||||
false
|
||||
);
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
errorMessage = error.message;
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
expect(errorMessage).toContain('Process ended without matching pattern');
|
||||
});
|
||||
|
||||
tap.test('passthrough unpipe should handle destroyed stdin gracefully', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// This should complete without throwing even if stdin operations fail
|
||||
const result = await testSmartshell.execPassthrough('echo "Test passthrough unpipe"');
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Test passthrough unpipe');
|
||||
});
|
||||
|
||||
tap.test('should handle write after stream destroyed', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const interactive = await testSmartshell.execInteractiveControl('true'); // Exits immediately
|
||||
|
||||
// Wait for process to exit
|
||||
await interactive.finalPromise;
|
||||
|
||||
// Try to write after process has exited
|
||||
let errorThrown = false;
|
||||
try {
|
||||
await interactive.sendLine('This should fail');
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
expect(error.message).toContain('destroyed');
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
});
|
||||
|
||||
tap.test('debug mode should log additional information', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Capture console.log output
|
||||
const originalLog = console.log;
|
||||
let debugOutput = '';
|
||||
console.log = (msg: string) => {
|
||||
debugOutput += msg + '\n';
|
||||
};
|
||||
|
||||
try {
|
||||
const streaming = await testSmartshell.execSpawnStreaming('echo', ['Debug test'], {
|
||||
debug: true
|
||||
});
|
||||
await streaming.terminate();
|
||||
await streaming.finalPromise;
|
||||
} finally {
|
||||
console.log = originalLog;
|
||||
}
|
||||
|
||||
// Should have logged debug messages
|
||||
expect(debugOutput).toContain('[smartshell]');
|
||||
});
|
||||
|
||||
tap.test('custom environment variables should be passed correctly', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const result = await testSmartshell.execSpawn('bash', ['-c', 'echo $CUSTOM_VAR'], {
|
||||
env: {
|
||||
...process.env,
|
||||
CUSTOM_VAR: 'test_value_123'
|
||||
}
|
||||
});
|
||||
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('test_value_123');
|
||||
});
|
||||
|
||||
export default tap.start();
|
84
test/test.interactiveControl.ts
Normal file
84
test/test.interactiveControl.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
tap.test('should handle programmatic input control with simple commands', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Use cat which works well with pipe mode
|
||||
const interactive = await testSmartshell.execInteractiveControl('cat');
|
||||
|
||||
// Send input programmatically
|
||||
await interactive.sendLine('TestUser');
|
||||
interactive.endInput();
|
||||
|
||||
// Wait for completion
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('TestUser');
|
||||
});
|
||||
|
||||
tap.test('should handle streaming interactive control with cat', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Use cat for reliable pipe mode operation
|
||||
const streaming = await testSmartshell.execStreamingInteractiveControl('cat');
|
||||
|
||||
// Send multiple inputs
|
||||
await streaming.sendLine('One');
|
||||
await streaming.sendLine('Two');
|
||||
streaming.endInput();
|
||||
|
||||
const result = await streaming.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('One');
|
||||
expect(result.stdout).toContain('Two');
|
||||
});
|
||||
|
||||
tap.test('should handle sendInput without newline', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Use cat for testing input without newline
|
||||
const interactive = await testSmartshell.execInteractiveControl('cat');
|
||||
|
||||
// Send characters without newline, then newline, then EOF
|
||||
await interactive.sendInput('ABC');
|
||||
await interactive.sendInput('DEF');
|
||||
await interactive.sendInput('\n');
|
||||
interactive.endInput();
|
||||
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('ABCDEF');
|
||||
});
|
||||
|
||||
tap.test('should mix passthrough and interactive control modes', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test that passthrough still works
|
||||
const passthroughResult = await testSmartshell.execPassthrough('echo "Passthrough works"');
|
||||
expect(passthroughResult.exitCode).toEqual(0);
|
||||
expect(passthroughResult.stdout).toContain('Passthrough works');
|
||||
|
||||
// Test that interactive control works
|
||||
const interactiveResult = await testSmartshell.execInteractiveControl('echo "Interactive control works"');
|
||||
const finalResult = await interactiveResult.finalPromise;
|
||||
expect(finalResult.exitCode).toEqual(0);
|
||||
expect(finalResult.stdout).toContain('Interactive control works');
|
||||
});
|
||||
|
||||
// Note: Tests requiring bash read with prompts should use PTY mode
|
||||
// See test.pty.ts for examples of testing commands that require terminal features
|
||||
|
||||
export default tap.start();
|
42
test/test.passthrough.ts
Normal file
42
test/test.passthrough.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
tap.test('should handle passthrough for interactive commands', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test with a simple echo command that doesn't need input
|
||||
const result = await testSmartshell.execPassthrough('echo "Testing passthrough"');
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Testing passthrough');
|
||||
});
|
||||
|
||||
tap.test('should handle streaming passthrough', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test streaming passthrough with a simple command
|
||||
const streamingResult = await testSmartshell.execStreamingPassthrough('echo "Testing streaming passthrough"');
|
||||
const finalResult = await streamingResult.finalPromise;
|
||||
|
||||
expect(finalResult.exitCode).toEqual(0);
|
||||
expect(finalResult.stdout).toContain('Testing streaming passthrough');
|
||||
});
|
||||
|
||||
tap.test('should allow normal exec without passthrough', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Regular exec should still work as before
|
||||
const result = await testSmartshell.exec('echo "Normal exec"');
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Normal exec');
|
||||
});
|
||||
|
||||
export default tap.start();
|
146
test/test.pty.ts
Normal file
146
test/test.pty.ts
Normal file
@@ -0,0 +1,146 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
// Helper to check if node-pty is available
|
||||
const isPtyAvailable = async (): Promise<boolean> => {
|
||||
try {
|
||||
await import('node-pty');
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
tap.test('PTY: should handle bash read with prompts correctly', async (tools) => {
|
||||
const ptyAvailable = await isPtyAvailable();
|
||||
if (!ptyAvailable) {
|
||||
console.log('Skipping PTY test - node-pty not installed');
|
||||
return;
|
||||
}
|
||||
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// This test should work with PTY (bash read with prompt)
|
||||
const interactive = await testSmartshell.execInteractiveControlPty("bash -c 'read -p \"Enter name: \" name && echo \"Hello, $name\"'");
|
||||
|
||||
// Send input programmatically
|
||||
await interactive.sendLine('TestUser');
|
||||
|
||||
// Wait for completion
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Enter name:'); // Prompt should be visible with PTY
|
||||
expect(result.stdout).toContain('Hello, TestUser');
|
||||
});
|
||||
|
||||
tap.test('PTY: should handle terminal colors and escape sequences', async (tools) => {
|
||||
const ptyAvailable = await isPtyAvailable();
|
||||
if (!ptyAvailable) {
|
||||
console.log('Skipping PTY test - node-pty not installed');
|
||||
return;
|
||||
}
|
||||
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// ls --color=auto should produce colors in PTY mode
|
||||
const result = await testSmartshell.execInteractiveControlPty('ls --color=always /tmp');
|
||||
const finalResult = await result.finalPromise;
|
||||
|
||||
expect(finalResult.exitCode).toEqual(0);
|
||||
// Check for ANSI escape sequences (colors) in output
|
||||
const hasColors = /\x1b\[[0-9;]*m/.test(finalResult.stdout);
|
||||
expect(hasColors).toEqual(true);
|
||||
});
|
||||
|
||||
tap.test('PTY: should handle interactive password prompt simulation', async (tools) => {
|
||||
const ptyAvailable = await isPtyAvailable();
|
||||
if (!ptyAvailable) {
|
||||
console.log('Skipping PTY test - node-pty not installed');
|
||||
return;
|
||||
}
|
||||
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Simulate a password prompt scenario
|
||||
const interactive = await testSmartshell.execStreamingInteractiveControlPty(
|
||||
"bash -c 'read -s -p \"Password: \" pass && echo && echo \"Got password of length ${#pass}\"'"
|
||||
);
|
||||
|
||||
await tools.delayFor(100);
|
||||
await interactive.sendLine('secretpass');
|
||||
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Password:');
|
||||
expect(result.stdout).toContain('Got password of length 10');
|
||||
});
|
||||
|
||||
tap.test('PTY: should handle terminal size options', async (tools) => {
|
||||
const ptyAvailable = await isPtyAvailable();
|
||||
if (!ptyAvailable) {
|
||||
console.log('Skipping PTY test - node-pty not installed');
|
||||
return;
|
||||
}
|
||||
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Check terminal size using stty
|
||||
const result = await testSmartshell.execInteractiveControlPty('stty size');
|
||||
const finalResult = await result.finalPromise;
|
||||
|
||||
expect(finalResult.exitCode).toEqual(0);
|
||||
// Default size should be 30 rows x 120 cols as set in _execCommandPty
|
||||
expect(finalResult.stdout).toContain('30 120');
|
||||
});
|
||||
|
||||
tap.test('PTY: should handle Ctrl+C (SIGINT) properly', async (tools) => {
|
||||
const ptyAvailable = await isPtyAvailable();
|
||||
if (!ptyAvailable) {
|
||||
console.log('Skipping PTY test - node-pty not installed');
|
||||
return;
|
||||
}
|
||||
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Start a long-running process
|
||||
const streaming = await testSmartshell.execStreamingInteractiveControlPty('sleep 10');
|
||||
|
||||
// Send interrupt after a short delay
|
||||
await tools.delayFor(100);
|
||||
await streaming.keyboardInterrupt();
|
||||
|
||||
const result = await streaming.finalPromise;
|
||||
// Process should exit with non-zero code due to interrupt
|
||||
expect(result.exitCode).not.toEqual(0);
|
||||
});
|
||||
|
||||
tap.test('Regular pipe mode should still work alongside PTY', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Regular mode should work without PTY
|
||||
const interactive = await testSmartshell.execInteractiveControl('echo "Pipe mode works"');
|
||||
const result = await interactive.finalPromise;
|
||||
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Pipe mode works');
|
||||
});
|
||||
|
||||
export default tap.start();
|
104
test/test.silent.ts
Normal file
104
test/test.silent.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
let testSmartshell: smartshell.Smartshell;
|
||||
|
||||
tap.test('setup for silent execution tests', async () => {
|
||||
testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
expect(testSmartshell).toBeInstanceOf(smartshell.Smartshell);
|
||||
});
|
||||
|
||||
tap.test('execSilent should capture output without printing to console', async () => {
|
||||
const result = await testSmartshell.execSilent('echo "Hidden from console"');
|
||||
expect(result.stdout).toContain('Hidden from console');
|
||||
expect(result.exitCode).toEqual(0);
|
||||
});
|
||||
|
||||
tap.test('execSilent should capture multi-line output', async () => {
|
||||
const result = await testSmartshell.execSilent('echo "Line 1" && echo "Line 2" && echo "Line 3"');
|
||||
const lines = result.stdout.trim().split('\n');
|
||||
expect(lines).toHaveLength(3);
|
||||
expect(lines[0]).toEqual('Line 1');
|
||||
expect(lines[1]).toEqual('Line 2');
|
||||
expect(lines[2]).toEqual('Line 3');
|
||||
});
|
||||
|
||||
tap.test('execSilent should capture error output', async () => {
|
||||
const result = await testSmartshell.execSilent('echo "This works" && exit 1');
|
||||
expect(result.stdout).toContain('This works');
|
||||
expect(result.exitCode).toEqual(1);
|
||||
});
|
||||
|
||||
tap.test('execSilent should parse command output programmatically', async () => {
|
||||
// Test that we can programmatically process the captured output
|
||||
const result = await testSmartshell.execSilent('echo "apple,banana,cherry"');
|
||||
const items = result.stdout.trim().split(',');
|
||||
expect(items).toHaveLength(3);
|
||||
expect(items[0]).toEqual('apple');
|
||||
expect(items[1]).toEqual('banana');
|
||||
expect(items[2]).toEqual('cherry');
|
||||
});
|
||||
|
||||
tap.test('execStrictSilent should capture output and throw on error', async () => {
|
||||
// Test successful command
|
||||
const successResult = await testSmartshell.execStrictSilent('echo "Success"');
|
||||
expect(successResult.stdout).toContain('Success');
|
||||
expect(successResult.exitCode).toEqual(0);
|
||||
|
||||
// Test that it throws on error
|
||||
let errorThrown = false;
|
||||
try {
|
||||
await testSmartshell.execStrictSilent('echo "Error output" && exit 1');
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
}
|
||||
expect(errorThrown).toBeTrue();
|
||||
});
|
||||
|
||||
tap.test('execStreamingSilent should capture streaming output without console display', async () => {
|
||||
const streamingResult = await testSmartshell.execStreamingSilent('echo "Line 1" && sleep 0.1 && echo "Line 2"');
|
||||
|
||||
let capturedData = '';
|
||||
streamingResult.childProcess.stdout.on('data', (data) => {
|
||||
capturedData += data.toString();
|
||||
});
|
||||
|
||||
await streamingResult.finalPromise;
|
||||
expect(capturedData).toContain('Line 1');
|
||||
expect(capturedData).toContain('Line 2');
|
||||
});
|
||||
|
||||
tap.test('execAndWaitForLineSilent should wait for pattern without console output', async () => {
|
||||
// This should complete without printing to console
|
||||
await testSmartshell.execAndWaitForLineSilent('echo "Starting..." && echo "Ready to go"', /Ready to go/);
|
||||
});
|
||||
|
||||
tap.test('execSilent should handle commands with quotes', async () => {
|
||||
const result = await testSmartshell.execSilent('echo "Hello World"');
|
||||
expect(result.stdout.trim()).toEqual('Hello World');
|
||||
});
|
||||
|
||||
tap.test('execSilent should capture large output', async () => {
|
||||
// Generate 100 lines of output
|
||||
const result = await testSmartshell.execSilent('for i in {1..100}; do echo "Line $i"; done');
|
||||
const lines = result.stdout.trim().split('\n');
|
||||
expect(lines).toHaveLength(100);
|
||||
expect(lines[0]).toEqual('Line 1');
|
||||
expect(lines[99]).toEqual('Line 100');
|
||||
});
|
||||
|
||||
tap.test('execSilent vs exec output comparison', async () => {
|
||||
// Both should capture the same output, but exec prints to console
|
||||
const silentResult = await testSmartshell.execSilent('echo "Test output"');
|
||||
const normalResult = await testSmartshell.exec('echo "Test output"');
|
||||
|
||||
expect(silentResult.stdout).toEqual(normalResult.stdout);
|
||||
expect(silentResult.exitCode).toEqual(normalResult.exitCode);
|
||||
});
|
||||
|
||||
export default tap.start({
|
||||
throwOnError: true,
|
||||
});
|
54
test/test.simpleInteractive.ts
Normal file
54
test/test.simpleInteractive.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
tap.test('should send input to cat command', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Use cat which simply echoes what it receives
|
||||
const interactive = await testSmartshell.execInteractiveControl('cat');
|
||||
|
||||
// Send some text and close stdin
|
||||
await interactive.sendLine('Hello World');
|
||||
interactive.endInput(); // Close stdin properly
|
||||
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Hello World');
|
||||
});
|
||||
|
||||
tap.test('should work with simple echo', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// This should work without any input
|
||||
const interactive = await testSmartshell.execInteractiveControl('echo "Direct test"');
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Direct test');
|
||||
});
|
||||
|
||||
tap.test('should handle streaming with input control', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test with streaming and cat
|
||||
const streaming = await testSmartshell.execStreamingInteractiveControl('cat');
|
||||
|
||||
await streaming.sendLine('Line 1');
|
||||
await streaming.sendLine('Line 2');
|
||||
streaming.endInput(); // Close stdin
|
||||
|
||||
const result = await streaming.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Line 1');
|
||||
expect(result.stdout).toContain('Line 2');
|
||||
});
|
||||
|
||||
export default tap.start();
|
150
test/test.spawn.ts
Normal file
150
test/test.spawn.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
tap.test('execSpawn should execute commands with args array (shell:false)', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test basic command with args
|
||||
const result = await testSmartshell.execSpawn('echo', ['Hello', 'World']);
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Hello World');
|
||||
});
|
||||
|
||||
tap.test('execSpawn should handle command not found errors', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let errorThrown = false;
|
||||
try {
|
||||
await testSmartshell.execSpawn('nonexistentcommand123', ['arg1']);
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
expect(error.code).toEqual('ENOENT');
|
||||
}
|
||||
expect(errorThrown).toBeTrue();
|
||||
});
|
||||
|
||||
tap.test('execSpawn should properly escape arguments', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test that shell metacharacters are treated as literals
|
||||
const result = await testSmartshell.execSpawn('echo', ['$HOME', '&&', 'ls']);
|
||||
expect(result.exitCode).toEqual(0);
|
||||
// Should output literal strings, not expanded/executed
|
||||
expect(result.stdout).toContain('$HOME && ls');
|
||||
});
|
||||
|
||||
tap.test('execSpawn streaming should work', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const streaming = await testSmartshell.execSpawnStreaming('echo', ['Streaming test']);
|
||||
const result = await streaming.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Streaming test');
|
||||
});
|
||||
|
||||
tap.test('execSpawn interactive control should work', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const interactive = await testSmartshell.execSpawnInteractiveControl('cat', []);
|
||||
|
||||
await interactive.sendLine('Input line');
|
||||
interactive.endInput();
|
||||
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Input line');
|
||||
});
|
||||
|
||||
tap.test('execSpawn should capture stderr', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// ls on non-existent directory should produce stderr
|
||||
const result = await testSmartshell.execSpawn('ls', ['/nonexistent/directory/path']);
|
||||
expect(result.exitCode).not.toEqual(0);
|
||||
expect(result.stderr).toBeTruthy();
|
||||
expect(result.stderr).toContain('No such file or directory');
|
||||
});
|
||||
|
||||
tap.test('execSpawn with timeout should terminate process', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const start = Date.now();
|
||||
const result = await testSmartshell.execSpawn('sleep', ['10'], { timeout: 100 });
|
||||
const duration = Date.now() - start;
|
||||
|
||||
// Process should be terminated by timeout
|
||||
expect(duration).toBeLessThan(500);
|
||||
expect(result.exitCode).not.toEqual(0);
|
||||
expect(result.signal).toBeTruthy(); // Should have been killed by signal
|
||||
});
|
||||
|
||||
tap.test('execSpawn with maxBuffer should truncate output', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Generate large output
|
||||
const result = await testSmartshell.execSpawn('bash', ['-c', 'for i in {1..1000}; do echo "Line $i with some padding text to make it longer"; done'], {
|
||||
maxBuffer: 1024, // Very small buffer
|
||||
});
|
||||
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('[Output truncated - exceeded maxBuffer]');
|
||||
});
|
||||
|
||||
tap.test('execSpawn with onData callback should stream data', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let dataReceived = '';
|
||||
const result = await testSmartshell.execSpawn('echo', ['Test data'], {
|
||||
onData: (chunk) => {
|
||||
dataReceived += chunk.toString();
|
||||
}
|
||||
});
|
||||
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(dataReceived).toContain('Test data');
|
||||
});
|
||||
|
||||
tap.test('execSpawn with signal should report signal in result', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const streaming = await testSmartshell.execSpawnStreaming('sleep', ['10']);
|
||||
|
||||
// Send SIGTERM after a short delay
|
||||
setTimeout(() => streaming.terminate(), 100);
|
||||
|
||||
const result = await streaming.finalPromise;
|
||||
expect(result.exitCode).not.toEqual(0);
|
||||
expect(result.signal).toEqual('SIGTERM');
|
||||
});
|
||||
|
||||
export default tap.start();
|
@@ -1,4 +1,4 @@
|
||||
import { expect, tap } from '@push.rocks/tapbundle';
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
|
||||
import * as smartshell from '../ts/index.js';
|
||||
import * as smartpromise from '@push.rocks/smartpromise';
|
||||
|
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartshell',
|
||||
version: '3.1.0',
|
||||
version: '3.3.0',
|
||||
description: 'A library for executing shell commands using promises.'
|
||||
}
|
||||
|
@@ -1,24 +1,55 @@
|
||||
import * as plugins from './plugins.js'
|
||||
import * as plugins from './plugins.js';
|
||||
import { Smartshell, type IExecResultStreaming } from './classes.smartshell.js';
|
||||
|
||||
export interface IDeferred<T> {
|
||||
resolve: (value?: T | PromiseLike<T>) => void;
|
||||
reject: (reason?: any) => void;
|
||||
promise: Promise<T>;
|
||||
}
|
||||
|
||||
export class SmartExecution {
|
||||
public smartshell: Smartshell;
|
||||
public currentStreamingExecution: IExecResultStreaming;
|
||||
public commandString: string;
|
||||
|
||||
private isRestartInProgress = false;
|
||||
private isAnotherRestartRequested = false;
|
||||
|
||||
constructor(commandStringArg: string) {
|
||||
this.commandString = commandStringArg;
|
||||
}
|
||||
|
||||
public async restart() {
|
||||
if (!this.smartshell) {
|
||||
this.smartshell = new Smartshell({
|
||||
executor: 'bash',
|
||||
});
|
||||
/**
|
||||
* Schedules a restart. If a restart is currently in progress, any additional calls
|
||||
* to restart will merge into a single additional restart request, which will only execute
|
||||
* once the current restart completes.
|
||||
*/
|
||||
public async restart(): Promise<void> {
|
||||
if (this.isRestartInProgress) {
|
||||
// If there's already a restart in progress, just mark that another restart was requested
|
||||
this.isAnotherRestartRequested = true;
|
||||
return;
|
||||
}
|
||||
if (this.currentStreamingExecution) {
|
||||
await this.currentStreamingExecution.kill();
|
||||
|
||||
this.isRestartInProgress = true;
|
||||
try {
|
||||
if (!this.smartshell) {
|
||||
this.smartshell = new Smartshell({
|
||||
executor: 'bash',
|
||||
});
|
||||
}
|
||||
if (this.currentStreamingExecution) {
|
||||
await this.currentStreamingExecution.kill();
|
||||
}
|
||||
this.currentStreamingExecution = await this.smartshell.execStreaming(this.commandString);
|
||||
} finally {
|
||||
this.isRestartInProgress = false;
|
||||
}
|
||||
|
||||
// If another restart was requested while we were busy, we handle it now
|
||||
if (this.isAnotherRestartRequested) {
|
||||
this.isAnotherRestartRequested = false;
|
||||
await this.restart();
|
||||
}
|
||||
this.currentStreamingExecution = await this.smartshell.execStreaming(this.commandString);
|
||||
}
|
||||
}
|
@@ -2,13 +2,21 @@ import * as plugins from './plugins.js';
|
||||
import { ShellEnv } from './classes.shellenv.js';
|
||||
import type { IShellEnvContructorOptions, TExecutor } from './classes.shellenv.js';
|
||||
import { ShellLog } from './classes.shelllog.js';
|
||||
|
||||
import * as cp from 'child_process';
|
||||
|
||||
// -- interfaces --
|
||||
export interface IExecResult {
|
||||
exitCode: number;
|
||||
stdout: string;
|
||||
signal?: NodeJS.Signals;
|
||||
stderr?: string;
|
||||
}
|
||||
|
||||
export interface IExecResultInteractive extends IExecResult {
|
||||
sendInput: (input: string) => Promise<void>;
|
||||
sendLine: (line: string) => Promise<void>;
|
||||
endInput: () => void;
|
||||
finalPromise: Promise<IExecResult>;
|
||||
}
|
||||
|
||||
export interface IExecResultStreaming {
|
||||
@@ -17,7 +25,36 @@ export interface IExecResultStreaming {
|
||||
kill: () => Promise<void>;
|
||||
terminate: () => Promise<void>;
|
||||
keyboardInterrupt: () => Promise<void>;
|
||||
customSignal: (signalArg: plugins.smartexit.TProcessSignal) => Promise<void>;
|
||||
customSignal: (signal: plugins.smartexit.TProcessSignal) => Promise<void>;
|
||||
sendInput: (input: string) => Promise<void>;
|
||||
sendLine: (line: string) => Promise<void>;
|
||||
endInput: () => void;
|
||||
}
|
||||
|
||||
interface IExecOptions {
|
||||
commandString: string;
|
||||
silent?: boolean;
|
||||
strict?: boolean;
|
||||
streaming?: boolean;
|
||||
interactive?: boolean;
|
||||
passthrough?: boolean;
|
||||
interactiveControl?: boolean;
|
||||
usePty?: boolean;
|
||||
ptyCols?: number;
|
||||
ptyRows?: number;
|
||||
ptyTerm?: string;
|
||||
ptyShell?: string;
|
||||
maxBuffer?: number;
|
||||
onData?: (chunk: Buffer | string) => void;
|
||||
timeout?: number;
|
||||
debug?: boolean;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface ISpawnOptions extends Omit<IExecOptions, 'commandString'> {
|
||||
command: string;
|
||||
args?: string[];
|
||||
}
|
||||
|
||||
export class Smartshell {
|
||||
@@ -29,129 +66,490 @@ export class Smartshell {
|
||||
}
|
||||
|
||||
/**
|
||||
* executes a given command async
|
||||
* Executes a given command asynchronously.
|
||||
*/
|
||||
private async _exec(options: {
|
||||
commandString: string;
|
||||
silent?: boolean;
|
||||
strict?: boolean;
|
||||
streaming?: boolean;
|
||||
interactive?: boolean;
|
||||
}): Promise<IExecResult | IExecResultStreaming | void> {
|
||||
private async _exec(options: IExecOptions): Promise<IExecResult | IExecResultStreaming | void> {
|
||||
if (options.interactive) {
|
||||
return await this._execInteractive(options);
|
||||
return await this._execInteractive({ commandString: options.commandString });
|
||||
}
|
||||
|
||||
return await this._execCommand(options);
|
||||
}
|
||||
|
||||
private async _execInteractive(options: {
|
||||
commandString: string;
|
||||
interactive?: boolean;
|
||||
}): Promise<void> {
|
||||
/**
|
||||
* Executes an interactive command.
|
||||
*/
|
||||
private async _execInteractive(options: Pick<IExecOptions, 'commandString'>): Promise<void> {
|
||||
// Skip interactive execution in CI environments.
|
||||
if (process.env.CI) {
|
||||
return;
|
||||
}
|
||||
|
||||
const done = plugins.smartpromise.defer();
|
||||
return new Promise<void>((resolve) => {
|
||||
const shell = cp.spawn(options.commandString, {
|
||||
stdio: 'inherit',
|
||||
shell: true,
|
||||
detached: true,
|
||||
});
|
||||
|
||||
const shell = cp.spawn(options.commandString, {
|
||||
stdio: 'inherit',
|
||||
shell: true,
|
||||
detached: true
|
||||
this.smartexit.addProcess(shell);
|
||||
|
||||
shell.on('close', (code) => {
|
||||
console.log(`Interactive shell terminated with code ${code}`);
|
||||
this.smartexit.removeProcess(shell);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
this.smartexit.addProcess(shell);
|
||||
|
||||
shell.on('close', (code) => {
|
||||
console.log(`interactive shell terminated with code ${code}`);
|
||||
this.smartexit.removeProcess(shell);
|
||||
done.resolve();
|
||||
});
|
||||
|
||||
await done.promise;
|
||||
}
|
||||
|
||||
private async _execCommand(options: {
|
||||
commandString: string;
|
||||
silent?: boolean;
|
||||
strict?: boolean;
|
||||
streaming?: boolean;
|
||||
}): Promise<IExecResult | IExecResultStreaming> {
|
||||
const done = plugins.smartpromise.defer<IExecResult | IExecResultStreaming>();
|
||||
const childProcessEnded = plugins.smartpromise.defer<IExecResult>();
|
||||
|
||||
const commandToExecute = this.shellEnv.createEnvExecString(options.commandString);
|
||||
|
||||
/**
|
||||
* Executes a command with args array (shell:false) for security
|
||||
*/
|
||||
private async _execSpawn(options: ISpawnOptions): Promise<IExecResult | IExecResultStreaming | IExecResultInteractive> {
|
||||
const shellLogInstance = new ShellLog();
|
||||
const execChildProcess = cp.spawn(commandToExecute, [], {
|
||||
shell: true,
|
||||
let stderrBuffer = '';
|
||||
const maxBuffer = options.maxBuffer || 200 * 1024 * 1024; // Default 200MB
|
||||
let bufferExceeded = false;
|
||||
|
||||
// Handle PTY mode if requested
|
||||
if (options.usePty) {
|
||||
throw new Error('PTY mode is not yet supported with execSpawn. Use exec methods with shell:true for PTY.');
|
||||
}
|
||||
|
||||
const execChildProcess = cp.spawn(options.command, options.args || [], {
|
||||
shell: false, // SECURITY: Never use shell with untrusted input
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
env: options.env || process.env,
|
||||
detached: false,
|
||||
signal: options.signal,
|
||||
});
|
||||
|
||||
this.smartexit.addProcess(execChildProcess);
|
||||
|
||||
// Handle timeout
|
||||
let timeoutHandle: NodeJS.Timeout | null = null;
|
||||
if (options.timeout) {
|
||||
timeoutHandle = setTimeout(() => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Timeout reached for process ${execChildProcess.pid}, terminating...`);
|
||||
}
|
||||
execChildProcess.kill('SIGTERM');
|
||||
}, options.timeout);
|
||||
}
|
||||
|
||||
// Connect stdin if passthrough is enabled (but not for interactive control)
|
||||
if (options.passthrough && !options.interactiveControl && execChildProcess.stdin) {
|
||||
process.stdin.pipe(execChildProcess.stdin);
|
||||
}
|
||||
|
||||
// Create input methods for interactive control
|
||||
const sendInput = async (input: string): Promise<void> => {
|
||||
if (!execChildProcess.stdin) {
|
||||
throw new Error('stdin is not available for this process');
|
||||
}
|
||||
if (execChildProcess.stdin.destroyed || !execChildProcess.stdin.writable) {
|
||||
throw new Error('stdin has been destroyed or is not writable');
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
execChildProcess.stdin.write(input, 'utf8', (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const sendLine = async (line: string): Promise<void> => {
|
||||
return sendInput(line + '\n');
|
||||
};
|
||||
|
||||
const endInput = (): void => {
|
||||
if (execChildProcess.stdin && !execChildProcess.stdin.destroyed) {
|
||||
execChildProcess.stdin.end();
|
||||
}
|
||||
};
|
||||
|
||||
// Capture stdout and stderr output
|
||||
execChildProcess.stdout.on('data', (data) => {
|
||||
if (!options.silent) {
|
||||
shellLogInstance.writeToConsole(data);
|
||||
}
|
||||
shellLogInstance.addToBuffer(data);
|
||||
|
||||
if (options.onData) {
|
||||
options.onData(data);
|
||||
}
|
||||
|
||||
if (!bufferExceeded) {
|
||||
shellLogInstance.addToBuffer(data);
|
||||
if (shellLogInstance.logStore.length > maxBuffer) {
|
||||
bufferExceeded = true;
|
||||
shellLogInstance.logStore = Buffer.from('[Output truncated - exceeded maxBuffer]');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
execChildProcess.stderr.on('data', (data) => {
|
||||
if (!options.silent) {
|
||||
shellLogInstance.writeToConsole(data);
|
||||
}
|
||||
shellLogInstance.addToBuffer(data);
|
||||
});
|
||||
|
||||
execChildProcess.on('exit', (code, signal) => {
|
||||
this.smartexit.removeProcess(execChildProcess);
|
||||
if (options.strict && code === 1) {
|
||||
done.reject();
|
||||
|
||||
const dataStr = data.toString();
|
||||
stderrBuffer += dataStr;
|
||||
|
||||
if (options.onData) {
|
||||
options.onData(data);
|
||||
}
|
||||
|
||||
const execResult = {
|
||||
exitCode: code,
|
||||
stdout: shellLogInstance.logStore.toString(),
|
||||
if (!bufferExceeded) {
|
||||
shellLogInstance.addToBuffer(data);
|
||||
if (shellLogInstance.logStore.length > maxBuffer) {
|
||||
bufferExceeded = true;
|
||||
shellLogInstance.logStore = Buffer.from('[Output truncated - exceeded maxBuffer]');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Wrap child process termination into a Promise
|
||||
const childProcessEnded: Promise<IExecResult> = new Promise((resolve, reject) => {
|
||||
const handleExit = (code: number | null, signal: NodeJS.Signals | null) => {
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
this.smartexit.removeProcess(execChildProcess);
|
||||
|
||||
// Safely unpipe stdin when process ends if passthrough was enabled
|
||||
if (options.passthrough && !options.interactiveControl) {
|
||||
try {
|
||||
if (execChildProcess.stdin && !execChildProcess.stdin.destroyed) {
|
||||
process.stdin.unpipe(execChildProcess.stdin);
|
||||
}
|
||||
} catch (err) {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Error unpiping stdin: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const exitCode = typeof code === 'number' ? code : (signal ? 1 : 0);
|
||||
const execResult: IExecResult = {
|
||||
exitCode,
|
||||
stdout: shellLogInstance.logStore.toString(),
|
||||
signal: signal || undefined,
|
||||
stderr: stderrBuffer,
|
||||
};
|
||||
|
||||
if (options.strict && exitCode !== 0) {
|
||||
const errorMsg = signal
|
||||
? `Command "${options.command}" terminated by signal ${signal}`
|
||||
: `Command "${options.command}" exited with code ${exitCode}`;
|
||||
reject(new Error(errorMsg));
|
||||
} else {
|
||||
resolve(execResult);
|
||||
}
|
||||
};
|
||||
|
||||
if (!options.streaming) {
|
||||
done.resolve(execResult);
|
||||
}
|
||||
childProcessEnded.resolve(execResult);
|
||||
execChildProcess.once('exit', handleExit);
|
||||
execChildProcess.once('error', (error) => {
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
this.smartexit.removeProcess(execChildProcess);
|
||||
|
||||
// Safely unpipe stdin when process errors if passthrough was enabled
|
||||
if (options.passthrough && !options.interactiveControl && execChildProcess.stdin) {
|
||||
try {
|
||||
if (!execChildProcess.stdin.destroyed) {
|
||||
process.stdin.unpipe(execChildProcess.stdin);
|
||||
}
|
||||
} catch (err) {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Error unpiping stdin on error: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
|
||||
// If interactive control is enabled but not streaming, return interactive interface
|
||||
if (options.interactiveControl && !options.streaming) {
|
||||
return {
|
||||
exitCode: 0, // Will be updated when process ends
|
||||
stdout: '', // Will be updated when process ends
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
finalPromise: childProcessEnded,
|
||||
} as IExecResultInteractive;
|
||||
}
|
||||
|
||||
// If streaming mode is enabled, return a streaming interface
|
||||
if (options.streaming) {
|
||||
done.resolve({
|
||||
return {
|
||||
childProcess: execChildProcess,
|
||||
finalPromise: childProcessEnded.promise,
|
||||
finalPromise: childProcessEnded,
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
kill: async () => {
|
||||
console.log(`running tree kill with SIGKILL on process ${execChildProcess.pid}`);
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGKILL on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGKILL');
|
||||
},
|
||||
terminate: async () => {
|
||||
console.log(`running tree kill with SIGTERM on process ${execChildProcess.pid}`);
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGTERM on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGTERM');
|
||||
},
|
||||
keyboardInterrupt: async () => {
|
||||
console.log(`running tree kill with SIGINT on process ${execChildProcess.pid}`);
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGINT on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGINT');
|
||||
},
|
||||
customSignal: async (signalArg: plugins.smartexit.TProcessSignal) => {
|
||||
console.log(`running tree kill with custom signal ${signalArg} on process ${execChildProcess.pid}`);
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, signalArg);
|
||||
customSignal: async (signal: plugins.smartexit.TProcessSignal) => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with custom signal ${signal} on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, signal);
|
||||
},
|
||||
});
|
||||
} as IExecResultStreaming;
|
||||
}
|
||||
|
||||
return await done.promise;
|
||||
// For non-streaming mode, wait for the process to complete
|
||||
return await childProcessEnded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a command and returns either a non-streaming result or a streaming interface.
|
||||
*/
|
||||
private async _execCommand(options: IExecOptions): Promise<IExecResult | IExecResultStreaming | IExecResultInteractive> {
|
||||
const commandToExecute = this.shellEnv.createEnvExecString(options.commandString);
|
||||
const shellLogInstance = new ShellLog();
|
||||
let stderrBuffer = '';
|
||||
const maxBuffer = options.maxBuffer || 200 * 1024 * 1024; // Default 200MB
|
||||
let bufferExceeded = false;
|
||||
|
||||
// Handle PTY mode if requested
|
||||
if (options.usePty) {
|
||||
return await this._execCommandPty(options, commandToExecute, shellLogInstance);
|
||||
}
|
||||
|
||||
const execChildProcess = cp.spawn(commandToExecute, [], {
|
||||
shell: true,
|
||||
cwd: process.cwd(),
|
||||
env: options.env || process.env,
|
||||
detached: false,
|
||||
signal: options.signal,
|
||||
});
|
||||
|
||||
this.smartexit.addProcess(execChildProcess);
|
||||
|
||||
// Handle timeout
|
||||
let timeoutHandle: NodeJS.Timeout | null = null;
|
||||
if (options.timeout) {
|
||||
timeoutHandle = setTimeout(() => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Timeout reached for process ${execChildProcess.pid}, terminating...`);
|
||||
}
|
||||
execChildProcess.kill('SIGTERM');
|
||||
}, options.timeout);
|
||||
}
|
||||
|
||||
// Connect stdin if passthrough is enabled (but not for interactive control)
|
||||
if (options.passthrough && !options.interactiveControl && execChildProcess.stdin) {
|
||||
process.stdin.pipe(execChildProcess.stdin);
|
||||
}
|
||||
|
||||
// Create input methods for interactive control
|
||||
const sendInput = async (input: string): Promise<void> => {
|
||||
if (!execChildProcess.stdin) {
|
||||
throw new Error('stdin is not available for this process');
|
||||
}
|
||||
if (execChildProcess.stdin.destroyed || !execChildProcess.stdin.writable) {
|
||||
throw new Error('stdin has been destroyed or is not writable');
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
execChildProcess.stdin.write(input, 'utf8', (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const sendLine = async (line: string): Promise<void> => {
|
||||
return sendInput(line + '\n');
|
||||
};
|
||||
|
||||
const endInput = (): void => {
|
||||
if (execChildProcess.stdin && !execChildProcess.stdin.destroyed) {
|
||||
execChildProcess.stdin.end();
|
||||
}
|
||||
};
|
||||
|
||||
// Capture stdout and stderr output
|
||||
execChildProcess.stdout.on('data', (data) => {
|
||||
if (!options.silent) {
|
||||
shellLogInstance.writeToConsole(data);
|
||||
}
|
||||
|
||||
if (options.onData) {
|
||||
options.onData(data);
|
||||
}
|
||||
|
||||
if (!bufferExceeded) {
|
||||
shellLogInstance.addToBuffer(data);
|
||||
if (shellLogInstance.logStore.length > maxBuffer) {
|
||||
bufferExceeded = true;
|
||||
shellLogInstance.logStore = Buffer.from('[Output truncated - exceeded maxBuffer]');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
execChildProcess.stderr.on('data', (data) => {
|
||||
if (!options.silent) {
|
||||
shellLogInstance.writeToConsole(data);
|
||||
}
|
||||
|
||||
const dataStr = data.toString();
|
||||
stderrBuffer += dataStr;
|
||||
|
||||
if (options.onData) {
|
||||
options.onData(data);
|
||||
}
|
||||
|
||||
if (!bufferExceeded) {
|
||||
shellLogInstance.addToBuffer(data);
|
||||
if (shellLogInstance.logStore.length > maxBuffer) {
|
||||
bufferExceeded = true;
|
||||
shellLogInstance.logStore = Buffer.from('[Output truncated - exceeded maxBuffer]');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Wrap child process termination into a Promise
|
||||
const childProcessEnded: Promise<IExecResult> = new Promise((resolve, reject) => {
|
||||
const handleExit = (code: number | null, signal: NodeJS.Signals | null) => {
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
this.smartexit.removeProcess(execChildProcess);
|
||||
|
||||
// Safely unpipe stdin when process ends if passthrough was enabled
|
||||
if (options.passthrough && !options.interactiveControl) {
|
||||
try {
|
||||
if (execChildProcess.stdin && !execChildProcess.stdin.destroyed) {
|
||||
process.stdin.unpipe(execChildProcess.stdin);
|
||||
}
|
||||
} catch (err) {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Error unpiping stdin: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const exitCode = typeof code === 'number' ? code : (signal ? 1 : 0);
|
||||
const execResult: IExecResult = {
|
||||
exitCode,
|
||||
stdout: shellLogInstance.logStore.toString(),
|
||||
signal: signal || undefined,
|
||||
stderr: stderrBuffer,
|
||||
};
|
||||
|
||||
if (options.strict && exitCode !== 0) {
|
||||
const errorMsg = signal
|
||||
? `Command "${options.commandString}" terminated by signal ${signal}`
|
||||
: `Command "${options.commandString}" exited with code ${exitCode}`;
|
||||
reject(new Error(errorMsg));
|
||||
} else {
|
||||
resolve(execResult);
|
||||
}
|
||||
};
|
||||
|
||||
execChildProcess.once('exit', handleExit);
|
||||
execChildProcess.once('error', (error) => {
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
this.smartexit.removeProcess(execChildProcess);
|
||||
|
||||
// Safely unpipe stdin when process errors if passthrough was enabled
|
||||
if (options.passthrough && !options.interactiveControl && execChildProcess.stdin) {
|
||||
try {
|
||||
if (!execChildProcess.stdin.destroyed) {
|
||||
process.stdin.unpipe(execChildProcess.stdin);
|
||||
}
|
||||
} catch (err) {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Error unpiping stdin on error: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
|
||||
// If interactive control is enabled but not streaming, return interactive interface
|
||||
if (options.interactiveControl && !options.streaming) {
|
||||
return {
|
||||
exitCode: 0, // Will be updated when process ends
|
||||
stdout: '', // Will be updated when process ends
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
finalPromise: childProcessEnded,
|
||||
} as IExecResultInteractive;
|
||||
}
|
||||
|
||||
// If streaming mode is enabled, return a streaming interface
|
||||
if (options.streaming) {
|
||||
return {
|
||||
childProcess: execChildProcess,
|
||||
finalPromise: childProcessEnded,
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
kill: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGKILL on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGKILL');
|
||||
},
|
||||
terminate: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGTERM on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGTERM');
|
||||
},
|
||||
keyboardInterrupt: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGINT on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGINT');
|
||||
},
|
||||
customSignal: async (signal: plugins.smartexit.TProcessSignal) => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with custom signal ${signal} on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, signal);
|
||||
},
|
||||
} as IExecResultStreaming;
|
||||
}
|
||||
|
||||
// For non-streaming mode, wait for the process to complete.
|
||||
return await childProcessEnded;
|
||||
}
|
||||
|
||||
public async exec(commandString: string): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString })) as IExecResult;
|
||||
const result = await this._exec({ commandString });
|
||||
// Type assertion is safe here because non-streaming, non-interactive exec always returns IExecResult
|
||||
return result as IExecResult;
|
||||
}
|
||||
|
||||
public async execSilent(commandString: string): Promise<IExecResult> {
|
||||
@@ -166,41 +564,310 @@ export class Smartshell {
|
||||
return (await this._exec({ commandString, silent: true, strict: true })) as IExecResult;
|
||||
}
|
||||
|
||||
public async execStreaming(
|
||||
commandString: string,
|
||||
silent: boolean = false
|
||||
): Promise<IExecResultStreaming> {
|
||||
public async execStreaming(commandString: string, silent: boolean = false): Promise<IExecResultStreaming> {
|
||||
return (await this._exec({ commandString, silent, streaming: true })) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execStreamingSilent(commandString: string): Promise<IExecResultStreaming> {
|
||||
return (await this._exec({
|
||||
commandString,
|
||||
silent: true,
|
||||
streaming: true,
|
||||
})) as IExecResultStreaming;
|
||||
return (await this._exec({ commandString, silent: true, streaming: true })) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execInteractive(commandString: string) {
|
||||
public async execInteractive(commandString: string): Promise<void> {
|
||||
await this._exec({ commandString, interactive: true });
|
||||
}
|
||||
|
||||
public async execPassthrough(commandString: string): Promise<IExecResult> {
|
||||
return await this._exec({ commandString, passthrough: true }) as IExecResult;
|
||||
}
|
||||
|
||||
public async execStreamingPassthrough(commandString: string): Promise<IExecResultStreaming> {
|
||||
return await this._exec({ commandString, streaming: true, passthrough: true }) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execInteractiveControl(commandString: string): Promise<IExecResultInteractive> {
|
||||
return await this._exec({ commandString, interactiveControl: true }) as IExecResultInteractive;
|
||||
}
|
||||
|
||||
public async execStreamingInteractiveControl(commandString: string): Promise<IExecResultStreaming> {
|
||||
return await this._exec({ commandString, streaming: true, interactiveControl: true }) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execInteractiveControlPty(commandString: string): Promise<IExecResultInteractive> {
|
||||
return await this._exec({ commandString, interactiveControl: true, usePty: true }) as IExecResultInteractive;
|
||||
}
|
||||
|
||||
public async execStreamingInteractiveControlPty(commandString: string): Promise<IExecResultStreaming> {
|
||||
return await this._exec({ commandString, streaming: true, interactiveControl: true, usePty: true }) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a command with args array (shell:false) for security
|
||||
* This is the recommended API for untrusted input
|
||||
*/
|
||||
public async execSpawn(command: string, args: string[] = [], options: Omit<ISpawnOptions, 'command' | 'args'> = {}): Promise<IExecResult> {
|
||||
const result = await this._execSpawn({ command, args, ...options });
|
||||
// Type assertion is safe here because non-streaming, non-interactive exec always returns IExecResult
|
||||
return result as IExecResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a command with args array in streaming mode
|
||||
*/
|
||||
public async execSpawnStreaming(command: string, args: string[] = [], options: Omit<ISpawnOptions, 'command' | 'args' | 'streaming'> = {}): Promise<IExecResultStreaming> {
|
||||
return await this._execSpawn({ command, args, streaming: true, ...options }) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a command with args array with interactive control
|
||||
*/
|
||||
public async execSpawnInteractiveControl(command: string, args: string[] = [], options: Omit<ISpawnOptions, 'command' | 'args' | 'interactiveControl'> = {}): Promise<IExecResultInteractive> {
|
||||
return await this._execSpawn({ command, args, interactiveControl: true, ...options }) as IExecResultInteractive;
|
||||
}
|
||||
|
||||
public async execAndWaitForLine(
|
||||
commandString: string,
|
||||
regexArg: RegExp,
|
||||
silentArg: boolean = false
|
||||
) {
|
||||
let done = plugins.smartpromise.defer();
|
||||
let execStreamingResult = await this.execStreaming(commandString, silentArg);
|
||||
execStreamingResult.childProcess.stdout.on('data', (stdOutChunk: string) => {
|
||||
if (regexArg.test(stdOutChunk)) {
|
||||
done.resolve();
|
||||
regex: RegExp,
|
||||
silent: boolean = false,
|
||||
options: { timeout?: number; terminateOnMatch?: boolean } = {}
|
||||
): Promise<void> {
|
||||
const execStreamingResult = await this.execStreaming(commandString, silent);
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let matched = false;
|
||||
let timeoutHandle: NodeJS.Timeout | null = null;
|
||||
|
||||
// Set up timeout if specified
|
||||
if (options.timeout) {
|
||||
timeoutHandle = setTimeout(async () => {
|
||||
if (!matched) {
|
||||
matched = true;
|
||||
// Remove listener to prevent memory leak
|
||||
execStreamingResult.childProcess.stdout.removeAllListeners('data');
|
||||
await execStreamingResult.terminate();
|
||||
reject(new Error(`Timeout waiting for pattern after ${options.timeout}ms`));
|
||||
}
|
||||
}, options.timeout);
|
||||
}
|
||||
|
||||
const dataHandler = async (chunk: Buffer | string) => {
|
||||
const data = typeof chunk === 'string' ? chunk : chunk.toString();
|
||||
if (!matched && regex.test(data)) {
|
||||
matched = true;
|
||||
|
||||
// Clear timeout if set
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
|
||||
// Remove listener to prevent memory leak
|
||||
execStreamingResult.childProcess.stdout.removeListener('data', dataHandler);
|
||||
|
||||
// Terminate process if requested
|
||||
if (options.terminateOnMatch) {
|
||||
await execStreamingResult.terminate();
|
||||
await execStreamingResult.finalPromise;
|
||||
}
|
||||
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
|
||||
execStreamingResult.childProcess.stdout.on('data', dataHandler);
|
||||
|
||||
// Also resolve/reject when process ends
|
||||
execStreamingResult.finalPromise.then(() => {
|
||||
if (!matched) {
|
||||
matched = true;
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
reject(new Error('Process ended without matching pattern'));
|
||||
}
|
||||
}).catch((err) => {
|
||||
if (!matched) {
|
||||
matched = true;
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
return done.promise;
|
||||
}
|
||||
|
||||
public async execAndWaitForLineSilent(commandString: string, regexArg: RegExp) {
|
||||
return this.execAndWaitForLine(commandString, regexArg, true);
|
||||
public async execAndWaitForLineSilent(commandString: string, regex: RegExp, options?: { timeout?: number; terminateOnMatch?: boolean }): Promise<void> {
|
||||
return this.execAndWaitForLine(commandString, regex, true, options);
|
||||
}
|
||||
}
|
||||
|
||||
private nodePty: any = null;
|
||||
|
||||
private async lazyLoadNodePty(): Promise<any> {
|
||||
if (this.nodePty) {
|
||||
return this.nodePty;
|
||||
}
|
||||
|
||||
try {
|
||||
// Try to load node-pty if available
|
||||
// @ts-ignore - node-pty is optional
|
||||
this.nodePty = await import('node-pty');
|
||||
return this.nodePty;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
'node-pty is required for PTY support but is not installed.\n' +
|
||||
'Please install it as an optional dependency:\n' +
|
||||
' pnpm add --save-optional node-pty\n' +
|
||||
'Note: node-pty requires compilation and may have platform-specific requirements.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async _execCommandPty(
|
||||
options: IExecOptions,
|
||||
commandToExecute: string,
|
||||
shellLogInstance: ShellLog
|
||||
): Promise<IExecResult | IExecResultStreaming | IExecResultInteractive> {
|
||||
const pty = await this.lazyLoadNodePty();
|
||||
|
||||
// Platform-aware shell selection
|
||||
let shell: string;
|
||||
let shellArgs: string[];
|
||||
|
||||
if (options.ptyShell) {
|
||||
// User-provided shell override
|
||||
shell = options.ptyShell;
|
||||
shellArgs = ['-c', commandToExecute];
|
||||
} else if (process.platform === 'win32') {
|
||||
// Windows: Use PowerShell by default, or cmd as fallback
|
||||
const powershell = process.env.PROGRAMFILES
|
||||
? `${process.env.PROGRAMFILES}\\PowerShell\\7\\pwsh.exe`
|
||||
: 'powershell.exe';
|
||||
|
||||
// Check if PowerShell Core exists, otherwise use Windows PowerShell
|
||||
const fs = await import('fs');
|
||||
if (fs.existsSync(powershell)) {
|
||||
shell = powershell;
|
||||
shellArgs = ['-NoProfile', '-NonInteractive', '-Command', commandToExecute];
|
||||
} else if (process.env.COMSPEC) {
|
||||
shell = process.env.COMSPEC;
|
||||
shellArgs = ['/d', '/s', '/c', commandToExecute];
|
||||
} else {
|
||||
shell = 'cmd.exe';
|
||||
shellArgs = ['/d', '/s', '/c', commandToExecute];
|
||||
}
|
||||
} else {
|
||||
// POSIX: Use SHELL env var or bash as default
|
||||
shell = process.env.SHELL || '/bin/bash';
|
||||
shellArgs = ['-c', commandToExecute];
|
||||
}
|
||||
|
||||
// Create PTY process
|
||||
const ptyProcess = pty.spawn(shell, shellArgs, {
|
||||
name: options.ptyTerm || 'xterm-256color',
|
||||
cols: options.ptyCols || 120,
|
||||
rows: options.ptyRows || 30,
|
||||
cwd: process.cwd(),
|
||||
env: options.env || process.env,
|
||||
});
|
||||
|
||||
// Add to smartexit (wrap in a minimal object with pid)
|
||||
this.smartexit.addProcess({ pid: ptyProcess.pid } as any);
|
||||
|
||||
// Handle output (stdout and stderr are combined in PTY)
|
||||
ptyProcess.onData((data: string) => {
|
||||
if (!options.silent) {
|
||||
shellLogInstance.writeToConsole(data);
|
||||
}
|
||||
shellLogInstance.addToBuffer(data);
|
||||
});
|
||||
|
||||
// Wrap PTY termination into a Promise
|
||||
const childProcessEnded: Promise<IExecResult> = new Promise((resolve, reject) => {
|
||||
ptyProcess.onExit(({ exitCode, signal }: { exitCode: number; signal?: number }) => {
|
||||
this.smartexit.removeProcess({ pid: ptyProcess.pid } as any);
|
||||
|
||||
const execResult: IExecResult = {
|
||||
exitCode: exitCode ?? (signal ? 1 : 0),
|
||||
stdout: shellLogInstance.logStore.toString(),
|
||||
};
|
||||
|
||||
if (options.strict && exitCode !== 0) {
|
||||
reject(new Error(`Command "${options.commandString}" exited with code ${exitCode}`));
|
||||
} else {
|
||||
resolve(execResult);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Create input methods for PTY
|
||||
const sendInput = async (input: string): Promise<void> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
ptyProcess.write(input);
|
||||
resolve();
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const sendLine = async (line: string): Promise<void> => {
|
||||
// Use \r for PTY (carriage return is typical for terminal line discipline)
|
||||
return sendInput(line + '\r');
|
||||
};
|
||||
|
||||
const endInput = (): void => {
|
||||
// Send EOF (Ctrl+D) to PTY
|
||||
ptyProcess.write('\x04');
|
||||
};
|
||||
|
||||
// If interactive control is enabled but not streaming, return interactive interface
|
||||
if (options.interactiveControl && !options.streaming) {
|
||||
return {
|
||||
exitCode: 0, // Will be updated when process ends
|
||||
stdout: '', // Will be updated when process ends
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
finalPromise: childProcessEnded,
|
||||
} as IExecResultInteractive;
|
||||
}
|
||||
|
||||
// If streaming mode is enabled, return a streaming interface
|
||||
if (options.streaming) {
|
||||
return {
|
||||
childProcess: { pid: ptyProcess.pid } as any, // Minimal compatibility object
|
||||
finalPromise: childProcessEnded,
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
kill: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Killing PTY process ${ptyProcess.pid}`);
|
||||
}
|
||||
ptyProcess.kill();
|
||||
},
|
||||
terminate: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Terminating PTY process ${ptyProcess.pid}`);
|
||||
}
|
||||
ptyProcess.kill('SIGTERM');
|
||||
},
|
||||
keyboardInterrupt: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Sending SIGINT to PTY process ${ptyProcess.pid}`);
|
||||
}
|
||||
ptyProcess.kill('SIGINT');
|
||||
},
|
||||
customSignal: async (signal: plugins.smartexit.TProcessSignal) => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Sending ${signal} to PTY process ${ptyProcess.pid}`);
|
||||
}
|
||||
ptyProcess.kill(signal as any);
|
||||
},
|
||||
} as IExecResultStreaming;
|
||||
}
|
||||
|
||||
// For non-streaming mode, wait for the process to complete
|
||||
return await childProcessEnded;
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user