Compare commits

...

81 Commits

Author SHA1 Message Date
jkunz a0010e7f0f v3.4.0 2026-05-09 13:48:16 +00:00
jkunz d65e1ed4f6 feat(smartshell): add cwd-aware execution options, structured strict-mode errors, and safer process tree termination 2026-05-09 13:48:16 +00:00
jkunz e61b352576 v3.3.8 2026-03-15 18:42:08 +00:00
jkunz b7882ef60f fix(repo): remove obsolete Serena project configuration files 2026-03-15 18:42:08 +00:00
jkunz cd5194c365 v3.3.7 2026-03-05 10:18:43 +00:00
jkunz 71cc64b6d9 fix(smartshell): avoid triple shell nesting, improve WSL path filtering, and use chunked log buffer to reduce memory usage 2026-03-05 10:18:43 +00:00
jkunz f254a9e078 v3.3.6 2026-03-04 18:13:53 +00:00
jkunz 3d6a33f8d2 fix(smartshell): use close event on child processes to ensure exit handling and update dependency versions 2026-03-04 18:13:53 +00:00
jkunz d37071dae0 fix(spawn): use detached:true so children are immune to terminal SIGINT
Children now get their own process group. Terminal Ctrl+C only reaches
the parent, which then does orderly tree-kill while children are still
alive and the process tree is intact.
2026-03-04 00:49:29 +00:00
jkunz 181d352e21 fix(deps): bump smartexit to ^2.0.1 for PID-tracking fix 2026-03-04 00:04:22 +00:00
jkunz 8a0a18f4da v3.3.3 2026-03-03 23:41:59 +00:00
jkunz bdc09afedd fix(deps): upgrade @push.rocks/smartexit to ^2.0.0 2026-03-03 23:41:49 +00:00
jkunz 68060e8565 v3.3.2 2026-03-03 22:36:40 +00:00
jkunz f2552cda79 fix(release): add @git.zone/cli release configuration with registries and public access 2026-03-03 22:36:40 +00:00
jkunz b898382305 v3.3.1 2026-03-03 22:35:20 +00:00
jkunz 5f8f38c2e6 fix(deps): bump @push.rocks/smartexit dependency to ^1.1.1 2026-03-03 22:35:20 +00:00
jkunz 61f76af7d1 3.3.0 2025-08-17 15:20:26 +00:00
jkunz 529b33fda1 feat(smartshell): Add secure spawn APIs, PTY support, interactive/streaming control, timeouts and buffer limits; update README and tests 2025-08-17 15:20:26 +00:00
jkunz f8e431f41e feat(smartshell): Add passthrough option for exec methods and corresponding tests 2025-08-17 14:01:04 +00:00
jkunz 5a32817349 3.2.4 2025-08-16 09:52:49 +00:00
jkunz 35d22175db fix(tests): Update tests & CI config, bump deps, add docs and project configs 2025-08-16 09:52:49 +00:00
philkunz cd3675280a 3.2.3 2025-02-20 12:37:11 +01:00
philkunz 7c14102324 fix(core): Refactor Smartshell class for improved code clarity and performance 2025-02-20 12:37:10 +01:00
philkunz cb41dbaf1c 3.2.2 2024-12-13 19:03:51 +01:00
philkunz 149eb800e7 fix(core): Fix minor code style and formatting issues 2024-12-13 19:03:50 +01:00
philkunz 91e84c8422 3.2.1 2024-12-13 18:55:34 +01:00
philkunz ff26cd0678 fix(dependencies): Update @types/node dependency version 2024-12-13 18:55:34 +01:00
philkunz acdd729e06 3.2.0 2024-12-09 02:52:14 +01:00
philkunz 522fbfc42c feat(SmartExecution): Add support for scheduling restarts to SmartExecution 2024-12-09 02:52:14 +01:00
philkunz b854715940 3.1.0 2024-12-09 02:39:31 +01:00
philkunz 35f59054f8 feat(core): Refactor codebase and update dependencies. 2024-12-09 02:39:31 +01:00
philkunz c9a3de2207 3.0.6 2024-09-17 17:02:43 +02:00
philkunz 6904097960 fix(core): Fix interactive shell execution and update dependencies 2024-09-17 17:02:42 +02:00
philkunz 1474fd541f update description 2024-05-29 14:16:08 +02:00
philkunz 9befccefd6 3.0.5 2024-04-18 13:42:51 +02:00
philkunz 415c9de553 fix(core): update 2024-04-18 13:42:51 +02:00
philkunz 980a2c9781 update tsconfig 2024-04-14 18:17:36 +02:00
philkunz c13a0f5d48 update tsconfig 2024-04-01 21:40:56 +02:00
philkunz 71e239c5b1 update npmextra.json: githost 2024-04-01 19:59:36 +02:00
philkunz 0d7c87051b update npmextra.json: githost 2024-03-30 21:48:37 +01:00
philkunz 067f1a9c17 3.0.4 2024-03-16 11:18:53 +01:00
philkunz e7cf3bcb5e fix(core): update 2024-03-16 11:18:53 +01:00
philkunz 18cfa3e16a 3.0.3 2023-06-22 14:17:50 +02:00
philkunz ea921766dc fix(core): update 2023-06-22 14:17:49 +02:00
philkunz 7e6d632afb 3.0.2 2023-06-22 14:16:16 +02:00
philkunz 25c61d7d7d fix(core): update 2023-06-22 14:16:16 +02:00
philkunz d84c7a16a4 3.0.1 2023-06-22 13:54:40 +02:00
philkunz c5937da870 fix(core): update 2023-06-22 13:54:39 +02:00
philkunz ec29db26ef 3.0.0 2023-06-22 11:51:45 +02:00
philkunz e4e08910c7 BREAKING CHANGE(core): switched to ES syntax and added support for interactivity 2023-06-22 11:51:44 +02:00
philkunz 730a4a05a4 2.0.30 2021-11-26 15:17:52 +01:00
philkunz 20a2804924 fix(core): cosmetics 2021-11-26 15:17:52 +01:00
philkunz d7247add7e 2.0.29 2021-11-07 19:18:01 +01:00
philkunz b304b01ab6 fix(core): update 2021-11-07 19:18:01 +01:00
philkunz 9ba5447e72 2.0.28 2021-08-17 18:19:53 +02:00
philkunz 6cb7ab8f19 fix(core): update 2021-08-17 18:19:52 +02:00
philkunz efdb80ddba 2.0.27 2021-07-26 21:24:13 +02:00
philkunz db712b2223 fix(core): update 2021-07-26 21:24:13 +02:00
philkunz 0199160013 2.0.26 2020-05-22 01:23:27 +00:00
philkunz 199fa19899 fix(core): update 2020-05-22 01:23:27 +00:00
philkunz 23a3230f07 2.0.25 2019-08-27 20:15:23 +02:00
philkunz ad0b7ac21c fix(core): update 2019-08-27 20:15:22 +02:00
philkunz c8c0cbd47a 2.0.24 2019-08-27 19:41:25 +02:00
philkunz 213dac474e fix(core): update 2019-08-27 19:41:25 +02:00
philkunz a4c188051a 2.0.23 2019-05-29 10:56:46 +02:00
philkunz 62195b63d6 fix(core): update 2019-05-29 10:56:45 +02:00
philkunz 16ba3803a4 2.0.22 2019-05-28 11:14:33 +02:00
philkunz 613241cdcb fix(core): update 2019-05-28 11:14:32 +02:00
philkunz f5df21e144 2.0.21 2019-05-28 10:43:55 +02:00
philkunz ba8c2d06d8 fix(core): update 2019-05-28 10:43:54 +02:00
philkunz 9bb0999f0e 2.0.20 2019-05-27 15:31:15 +02:00
philkunz 1beb3a0bbe 2.0.19 2019-05-27 15:30:52 +02:00
philkunz c1133e9131 fix(core): update 2019-05-27 15:30:52 +02:00
philkunz 48dd3c3cca 2.0.18 2019-05-27 15:25:30 +02:00
philkunz f0a5be41ea fix(core): update 2019-05-27 15:25:30 +02:00
philkunz 970d28a4ad 2.0.17 2019-05-23 23:29:36 +02:00
philkunz 76f2126eb3 fix(core): update 2019-05-23 23:29:36 +02:00
philkunz a6f164602c 2.0.16 2019-05-22 15:45:09 +02:00
philkunz f8457ad58d fix(core): update 2019-05-22 15:45:08 +02:00
philkunz 8ceac74a1f 2.0.15 2019-05-19 22:41:20 +02:00
philkunz f63c4456bf fix(core): update 2019-05-19 22:41:20 +02:00
34 changed files with 11106 additions and 2076 deletions
+18 -2
View File
@@ -1,4 +1,20 @@
.nogit/
# artifacts
coverage/
node_modules/
pages/
public/
pages/
# installs
node_modules/
# caches
.yarn/
.cache/
.rpt2_cache
# builds
dist/
dist_*/
# custom
-125
View File
@@ -1,125 +0,0 @@
# gitzone standard
image: hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: "$CI_BUILD_STAGE"
stages:
- security
- test
- release
- metadata
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
tags:
- docker
- notpriv
snyk:
stage: security
script:
- npmci npm prepare
- npmci command npm install -g snyk
- npmci command npm install --ignore-scripts
- npmci command snyk test
tags:
- docker
- notpriv
# ====================
# test stage
# ====================
testLTS:
stage: test
script:
- npmci npm prepare
- npmci node install lts
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
testSTABLE:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
image: docker:stable
allow_failure: true
services:
- docker:stable-dind
script:
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/')
- docker run
--env SOURCE_CODE="$PWD"
--volume "$PWD":/code
--volume /var/run/docker.sock:/var/run/docker.sock
"registry.gitlab.com/gitlab-org/security-products/codequality:$SP_VERSION" /code
artifacts:
paths: [codeclimate.json]
tags:
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- docker
- notpriv
pages:
image: hosttoday/ht-docker-node:npmci
stage: metadata
script:
- npmci command npm install -g typedoc typescript
- npmci npm prepare
- npmci npm install
- npmci command typedoc --module "commonjs" --target "ES2016" --out public/ ts/
tags:
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true
+41
View File
@@ -0,0 +1,41 @@
{
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public",
"npmRegistryUrl": "registry.npmjs.org"
},
"gitzone": {
"projectType": "npm",
"module": {
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartshell",
"description": "A library for executing shell commands using promises.",
"npmPackagename": "@push.rocks/smartshell",
"license": "MIT",
"keywords": [
"shell commands",
"promises",
"asynchronous execution",
"child processes",
"environment management",
"command streaming",
"interactive commands",
"process management",
"typescript"
]
}
},
"tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy 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.\n"
},
"@git.zone/cli": {
"release": {
"registries": [
"https://registry.npmjs.org",
"https://verdaccio.lossless.digital"
],
"accessLevel": "public"
}
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "npm test",
"name": "Run npm test",
"request": "launch",
"type": "node-terminal"
}
]
}
+26
View File
@@ -0,0 +1,26 @@
{
"json.schemas": [
{
"fileMatch": ["/.smartconfig.json"],
"schema": {
"type": "object",
"properties": {
"npmci": {
"type": "object",
"description": "settings for npmci"
},
"gitzone": {
"type": "object",
"description": "settings for gitzone",
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm", "wcc"]
}
}
}
}
}
}
]
}
-32
View File
@@ -1,32 +0,0 @@
# smartshell
shell actions designed as promises
## Availabililty
[![npm](https://pushrocks.gitlab.io/assets/repo-button-npm.svg)](https://www.npmjs.com/package/smartshell)
[![git](https://pushrocks.gitlab.io/assets/repo-button-git.svg)](https://GitLab.com/pushrocks/smartshell)
[![git](https://pushrocks.gitlab.io/assets/repo-button-mirror.svg)](https://github.com/pushrocks/smartshell)
[![docs](https://pushrocks.gitlab.io/assets/repo-button-docs.svg)](https://pushrocks.gitlab.io/smartshell/)
## Status for master
[![build status](https://GitLab.com/pushrocks/smartshell/badges/master/build.svg)](https://GitLab.com/pushrocks/smartshell/commits/master)
[![coverage report](https://GitLab.com/pushrocks/smartshell/badges/master/coverage.svg)](https://GitLab.com/pushrocks/smartshell/commits/master)
[![npm downloads per month](https://img.shields.io/npm/dm/smartshell.svg)](https://www.npmjs.com/package/smartshell)
[![Dependency Status](https://david-dm.org/pushrocks/smartshell.svg)](https://david-dm.org/pushrocks/smartshell)
[![bitHound Dependencies](https://www.bithound.io/github/pushrocks/smartshell/badges/dependencies.svg)](https://www.bithound.io/github/pushrocks/smartshell/master/dependencies/npm)
[![bitHound Code](https://www.bithound.io/github/pushrocks/smartshell/badges/code.svg)](https://www.bithound.io/github/pushrocks/smartshell)
[![TypeScript](https://img.shields.io/badge/TypeScript-2.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%206.x.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
## Usage
Use TypeScript for best in class instellisense.
For further information read the linked docs at the top of this README.
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
[![repo-footer](https://pushrocks.gitlab.io/assets/repo-footer.svg)](https://push.rocks)
+152
View File
@@ -0,0 +1,152 @@
# Changelog
## 2026-05-09 - 3.4.0 - feat(smartshell)
add cwd-aware execution options, structured strict-mode errors, and safer process tree termination
- adds cwd and env runtime options across exec, spawn, interactive, wait-for-line, and PTY execution APIs
- introduces SmartshellError with exit code, signal, stdout, stderr, and combined result details for strict-mode failures
- terminates timed-out commands via process tree killing to prevent detached child processes from continuing after timeout
## 2026-03-15 - 3.3.8 - fix(repo)
remove obsolete Serena project configuration files
- Deletes the .serena project configuration from the repository
- Cleans up editor or tooling metadata that is not part of the package runtime or source code
## 2026-03-05 - 3.3.7 - fix(smartshell)
avoid triple shell nesting, improve WSL path filtering, and use chunked log buffer to reduce memory usage
- Spawn uses the executor shell binary directly (e.g. /bin/bash) and removes extra bash -c wrapping to avoid triple shell nesting
- Only filter out /mnt/c/ and other WSL-specific PATH entries when running under WSL (adds _isWSL detection)
- Replace single concatenated Buffer with chunked buffering in ShellLog (lazy concatenation, logLength property) and update checks to use logLength
- Remove unused dependency "tree-kill" from package.json
## 2026-03-04 - 3.3.6 - fix(smartshell)
use 'close' event on child processes to ensure exit handling and update dependency versions
- Replace child_process 'exit' listeners with 'close' in ts/classes.smartshell.ts (two occurrences) to ensure handlers run after stdio streams are closed.
- Bump devDependencies: @git.zone/tsbuild ^2.7.3 -> ^4.1.2, @git.zone/tsrun ^1.6.2 -> ^2.0.1, @git.zone/tstest ^2.8.3 -> ^3.2.0, @types/node ^22.19.13 -> ^25.3.3.
- Bump dependencies: @push.rocks/smartexit ^2.0.1 -> ^2.0.3, which ^5.0.0 -> ^6.0.1.
## 2026-03-03 - 3.3.2 - fix(release)
add @git.zone/cli release configuration with registries and public access
- Updated file: npmextra.json
- Added @git.zone/cli.release.registries: https://verdaccio.lossleess.digital, https://registry.npmjs.org
- Set @git.zone/cli.release.accessLevel to "public"
## 2026-03-03 - 3.3.1 - fix(deps)
bump @push.rocks/smartexit dependency to ^1.1.1
- Updated @push.rocks/smartexit from ^1.0.23 to ^1.1.1
- Only package.json was modified
- Project current version is 3.3.0; recommend a patch release to 3.3.1
## 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.
- Refactored core classes with improved structure and modularization.
- Updated tsbuild, tsrun, tapbundle, and @types/node dependencies to newer versions.
- Improved build script in package.json to use tsbuild with tsfolders.
## 2024-09-17 - 3.0.6 - fix(core)
Fix interactive shell execution and update dependencies
- Corrected the interactive shell execution logic by separating it into a dedicated method.
- Updated development dependencies for `@git.zone/tsbuild`, `@git.zone/tsrun`, `@git.zone/tstest`, `@push.rocks/tapbundle`, and `@types/node`.
- Updated runtime dependencies for `@push.rocks/smartpromise`, and `@types/which`.
- Removed legacy .gitlab-ci.yml file.
## 2024-05-29 - 3.0.5 - Documentation
update description
## 2024-04-18 - 3.0.4 to 3.0.5 - Maintenance
Bug fixes and configuration updates
- fix(core): update
- update tsconfig
- update npmextra.json: githost
## 2024-03-16 - 3.0.3 to 3.0.4 - Maintenance
Bug fixes
- fix(core): update
## 2023-06-22 - 2.0.30 to 3.0.3 - Major Update
Major changes including breaking changes, bug fixes, and improvements.
- BREAKING CHANGE(core): switched to ES syntax and added support for interactivity
- fix(core): update
## 2021-11-07 - 2.0.27 to 2.0.30 - Maintenance
Bug fixes
- fix(core): cosmetics
- fix(core): update
## 2021-08-17 - 2.0.26 to 2.0.27 - Maintenance
Bug fixes
- fix(core): update
## 2020-05-22 - 2.0.25 to 2.0.26 - Maintenance
Bug fixes
- fix(core): update
## 2019-08-27 - 2.0.22 to 2.0.25 - Maintenance
Bug fixes
- fix(core): update
## 2019-05-28 - 2.0.16 to 2.0.22 - Maintenance
Bug fixes
- fix(core): update
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Task Venture Capital GmbH
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-7
View File
@@ -1,7 +0,0 @@
{
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public",
"npmRegistryUrl": "registry.npmjs.org"
}
}
-1634
View File
File diff suppressed because it is too large Load Diff
+46 -22
View File
@@ -1,40 +1,64 @@
{
"name": "@pushrocks/smartshell",
"name": "@push.rocks/smartshell",
"private": false,
"version": "2.0.14",
"description": "shell actions designed as promises",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"version": "3.4.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/)",
"build": "(tsbuild)"
"test": "(tstest test/ --verbose --logfile --timeout 20)",
"build": "(tsbuild tsfolders --web)",
"buildDocs": "tsdoc"
},
"repository": {
"type": "git",
"url": "git+ssh://git@gitlab.com/pushrocks/smartshell.git"
"url": "https://code.foss.global/push.rocks/smartshell.git"
},
"keywords": [
"shell",
"promise"
"shell commands",
"promises",
"asynchronous execution",
"child processes",
"environment management",
"command streaming",
"interactive commands",
"process management",
"typescript"
],
"author": "Lossless GmbH",
"license": "MIT",
"bugs": {
"url": "https://gitlab.com/pushrocks/smartshell/issues"
},
"homepage": "https://gitlab.com/pushrocks/smartshell#README",
"homepage": "https://code.foss.global/push.rocks/smartshell",
"devDependencies": {
"@gitzone/tsbuild": "^2.1.11",
"@gitzone/tsrun": "^1.2.6",
"@gitzone/tstest": "^1.0.20",
"@pushrocks/tapbundle": "^3.0.9",
"@types/node": "^12.0.1",
"tslint": "^5.16.0",
"tslint-config-prettier": "^1.18.0"
"@git.zone/tsbuild": "^4.4.1",
"@git.zone/tsrun": "^2.0.4",
"@git.zone/tstest": "^3.6.6",
"@types/node": "^25.6.2"
},
"dependencies": {
"@pushrocks/smartpromise": "^3.0.2",
"@types/which": "^1.3.1",
"which": "^1.3.1"
}
"@push.rocks/smartdelay": "^3.1.0",
"@push.rocks/smartexit": "^2.0.3",
"@push.rocks/smartpromise": "^4.2.4",
"@types/which": "^3.0.4",
"which": "^7.0.0"
},
"files": [
"ts/**/*",
"ts_web/**/*",
"dist/**/*",
"dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
".smartconfig.json",
"readme.md"
],
"browserslist": [
"last 1 chrome versions"
],
"packageManager": "pnpm@10.14.0+sha512.ad27a79641b49c3e481a16a805baa71817a04bbe06a38d17e60e2eaee83f6a146c6a688125f5792e48dd5ba30e7da52a5cda4c3992b9ccf333f9ce223af84748"
}
+8065
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
+629
View File
@@ -0,0 +1,629 @@
# @push.rocks/smartshell
`@push.rocks/smartshell` is a TypeScript-first Node.js library for running shell commands with modern async APIs. It wraps `child_process` in promises, adds strict and silent execution modes, supports streaming and programmatic stdin control, exposes safer shell-free spawn methods for untrusted arguments, and gives you practical process controls like timeouts, process-tree termination, custom environments, working directories, and optional PTY-backed terminal emulation.
## Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
## Install
```bash
pnpm add @push.rocks/smartshell
```
PTY support is optional and only needed when a command requires a real terminal:
```bash
pnpm add --save-optional node-pty
```
## Quick Start
```typescript
import { Smartshell } from '@push.rocks/smartshell';
const shell = new Smartshell({
executor: 'bash',
});
const result = await shell.exec('echo "hello from smartshell"');
console.log(result.exitCode); // 0
console.log(result.stdout); // hello from smartshell
```
Use `execSpawn()` whenever command arguments include user input or any other untrusted value:
```typescript
const filenameFromUser = 'report.txt; rm -rf /';
// Safe: no shell is used, so metacharacters are treated as argument text.
const result = await shell.execSpawn('cat', [filenameFromUser], {
silent: true,
});
```
## What It Does
- Promise-based command execution for `async`/`await` code.
- Shell-based methods for trusted command strings.
- Shell-free spawn methods for safer argument handling.
- Silent, strict, streaming, passthrough, and interactive-control modes.
- Process-tree cleanup through `@push.rocks/smartexit`.
- Timeout support for terminating long-running process trees.
- `cwd`, `env`, and `AbortSignal` support.
- Bounded output buffering with `maxBuffer`.
- Separate `stderr` capture plus the historical combined output buffer.
- Optional PTY support through `node-pty` for terminal-native programs.
- A small `SmartExecution` helper for restarting long-running commands.
- The `which` utility re-exported for command discovery.
## Execution Modes
### Standard Execution
`exec()` runs a trusted command string through the configured shell and resolves with an `IExecResult`.
```typescript
const result = await shell.exec('git --version');
console.log(result.exitCode);
console.log(result.stdout);
```
Shell execution is convenient for hardcoded command strings, pipes, redirects, globbing, and shell syntax:
```typescript
await shell.exec('mkdir -p dist && cp assets/*.json dist/');
```
### Silent Execution
`execSilent()` captures output without writing it to the current process stdout.
```typescript
const result = await shell.execSilent('node --version');
console.log(result.stdout.trim());
```
### Strict Execution
`execStrict()` rejects with `SmartshellError` when the command exits with a non-zero code or is terminated by a signal.
```typescript
import { SmartshellError } from '@push.rocks/smartshell';
try {
await shell.execStrict('pnpm test');
} catch (error) {
if (error instanceof SmartshellError) {
console.error(error.message);
console.error(error.exitCode);
console.error(error.stderr);
}
}
```
Use `execStrictSilent()` for strict behavior without console output:
```typescript
await shell.execStrictSilent('pnpm build');
```
### Streaming Execution
`execStreaming()` starts a command and returns immediately with the child process, a final result promise, and process-control helpers.
```typescript
const streaming = await shell.execStreaming('pnpm install');
streaming.childProcess.stdout?.on('data', (chunk) => {
process.stdout.write(`[install] ${chunk}`);
});
const result = await streaming.finalPromise;
console.log(result.exitCode);
```
Streaming executions can be controlled explicitly:
```typescript
const server = await shell.execStreaming('pnpm dev', false, {
cwd: '/path/to/app',
});
await server.keyboardInterrupt(); // SIGINT
await server.terminate(); // SIGTERM
await server.kill(); // SIGKILL
await server.customSignal('SIGHUP');
```
`execStreamingSilent()` starts a streaming command without printing output automatically.
### Passthrough Execution
`execPassthrough()` pipes the current process stdin into the command. This is useful for commands that should receive real user input while still returning a result.
```typescript
await shell.execPassthrough('read name && echo "hello $name"');
```
`execStreamingPassthrough()` combines passthrough stdin with the streaming interface.
### Programmatic Input Control
`execInteractiveControl()` returns methods for sending stdin manually.
```typescript
const interactive = await shell.execInteractiveControl('cat');
await interactive.sendLine('first line');
await interactive.sendInput('second line without newline');
await interactive.sendInput('\n');
interactive.endInput();
const result = await interactive.finalPromise;
console.log(result.stdout);
```
`execStreamingInteractiveControl()` gives you both programmatic input and streaming process controls:
```typescript
const repl = await shell.execStreamingInteractiveControl('node');
await repl.sendLine('console.log(21 * 2)');
await repl.sendLine('.exit');
await repl.finalPromise;
```
### Interactive Shell Execution
`execInteractive()` runs a trusted shell command with inherited stdio. It is meant for fully interactive terminal use and returns `void`; in CI environments it intentionally does nothing.
```typescript
await shell.execInteractive('vim readme.md');
```
## Secure Spawn APIs
The `execSpawn()` family uses `child_process.spawn()` with `shell: false`. That means shell metacharacters are not interpreted.
```typescript
const result = await shell.execSpawn('git', ['status', '--short'], {
cwd: '/path/to/repo',
silent: true,
});
```
### Why Spawn Matters
```typescript
const userInput = 'file.txt; rm -rf /';
// Dangerous: shell syntax in userInput can be interpreted.
await shell.exec(`cat ${userInput}`);
// Safe: userInput is passed as one literal argument.
await shell.execSpawn('cat', [userInput]);
```
### Spawn Streaming
```typescript
const streaming = await shell.execSpawnStreaming('pnpm', ['test'], {
cwd: '/path/to/package',
});
const result = await streaming.finalPromise;
```
### Spawn Interactive Control
```typescript
const interactive = await shell.execSpawnInteractiveControl('cat', []);
await interactive.sendLine('hello');
interactive.endInput();
const result = await interactive.finalPromise;
```
PTY mode is currently available for shell-based interactive-control methods, not for `execSpawn()`.
## PTY Support
Some tools behave differently when they are connected to pipes instead of a real terminal. Editors, REPLs, password prompts, full-screen terminal UIs, readline prompts, and programs that depend on ANSI terminal behavior often need a PTY.
Install the optional dependency first:
```bash
pnpm add --save-optional node-pty
```
Then use the PTY-specific methods:
```typescript
const prompt = await shell.execInteractiveControlPty(
'bash -c \'read -p "Name: " name && echo "Hello $name"\''
);
await prompt.sendLine('Ada');
const result = await prompt.finalPromise;
console.log(result.stdout);
```
Streaming PTY control works the same way, with PTY-backed process controls:
```typescript
const nodeRepl = await shell.execStreamingInteractiveControlPty('node');
await nodeRepl.sendLine('console.log("PTY ready")');
await nodeRepl.sendLine('.exit');
await nodeRepl.finalPromise;
```
PTY output combines stdout and stderr because terminal sessions expose a single terminal data stream.
## Runtime Options
Most execution methods accept these options:
```typescript
interface TExecCommandOptions {
ptyCols?: number;
ptyRows?: number;
ptyTerm?: string;
ptyShell?: string;
maxBuffer?: number;
onData?: (chunk: Buffer | string) => void;
timeout?: number;
debug?: boolean;
env?: NodeJS.ProcessEnv;
cwd?: string;
signal?: AbortSignal;
}
```
### Working Directory
Prefer the `cwd` option over embedding `cd ... && ...` into command strings:
```typescript
await shell.execStrict('pnpm build', {
cwd: '/path/to/package',
});
await shell.execSpawn('git', ['status', '--short'], {
cwd: '/path/to/repo',
});
```
### Environment Variables
```typescript
await shell.execSpawn('node', ['server.js'], {
env: {
...process.env,
NODE_ENV: 'production',
PORT: '3000',
},
});
```
### Timeouts
Timeouts terminate the process tree with `SIGTERM`.
```typescript
const result = await shell.execSpawn('sleep', ['10'], {
timeout: 500,
});
console.log(result.signal); // SIGTERM on typical POSIX platforms
```
### Bounded Output Buffers
Regular shell and spawn executions keep a combined output buffer. `maxBuffer` limits that buffer and replaces it with a truncation marker if the limit is exceeded.
```typescript
const result = await shell.exec('long-running-output-command', {
maxBuffer: 10 * 1024 * 1024,
onData: (chunk) => {
// Stream chunks elsewhere while smartshell protects its own buffer.
process.stdout.write(chunk);
},
});
```
### Debug Logging
```typescript
const streaming = await shell.execSpawnStreaming('sleep', ['30'], {
debug: true,
});
await streaming.terminate();
await streaming.finalPromise;
```
## Results and Errors
### `IExecResult`
```typescript
interface IExecResult {
exitCode: number;
stdout: string;
combinedOutput?: string;
signal?: NodeJS.Signals;
stderr?: string;
}
```
Important: `stdout` intentionally preserves smartshell's legacy behavior and contains the combined stdout/stderr buffer. Use `stderr` when you need stderr separately, and use `combinedOutput` when you want to make that combined-buffer behavior explicit in your own code.
### `SmartshellError`
Strict methods reject with `SmartshellError` and expose the command result details directly:
```typescript
class SmartshellError extends Error {
command: string;
result: IExecResult;
exitCode: number;
stdout: string;
combinedOutput?: string;
stderr?: string;
signal?: NodeJS.Signals;
}
```
### Streaming and Interactive Results
```typescript
interface IExecResultStreaming {
childProcess: import('child_process').ChildProcess;
finalPromise: Promise<IExecResult>;
kill: () => Promise<void>;
terminate: () => Promise<void>;
keyboardInterrupt: () => Promise<void>;
customSignal: (signal: string) => Promise<void>;
sendInput: (input: string) => Promise<void>;
sendLine: (line: string) => Promise<void>;
endInput: () => void;
}
interface IExecResultInteractive extends IExecResult {
sendInput: (input: string) => Promise<void>;
sendLine: (line: string) => Promise<void>;
endInput: () => void;
finalPromise: Promise<IExecResult>;
}
```
## Waiting for Output
`execAndWaitForLine()` starts a streaming command and resolves when stdout matches a regular expression.
```typescript
await shell.execAndWaitForLine(
'pnpm dev',
/Server listening on port 3000/,
false,
{
timeout: 30_000,
terminateOnMatch: true,
cwd: '/path/to/app',
}
);
```
Use `execAndWaitForLineSilent()` to suppress automatic output:
```typescript
await shell.execAndWaitForLineSilent('node server.js', /ready/, {
timeout: 10_000,
});
```
If the process ends before a match or the timeout expires, the promise rejects.
## Environment Customization
`ShellEnv` is available through each `Smartshell` instance as `shell.shellEnv`. It lets you source files and add PATH directories before shell-based command strings execute.
```typescript
const shell = new Smartshell({
executor: 'bash',
sourceFilePaths: ['/opt/project/env.sh'],
pathDirectories: ['/opt/project/bin'],
});
shell.shellEnv.addSourceFiles(['./local.env.sh']);
shell.shellEnv.pathDirArray.push('/custom/bin');
await shell.exec('my-tool --version');
```
`ShellEnv` also imports the current `PATH` and appends `SMARTSHELL_PATH` when that environment variable is set. On WSL it filters Windows path entries that commonly break POSIX shell execution.
## SmartExecution
`SmartExecution` is a tiny restart helper for long-running commands such as development servers. It lazily creates its own bash-backed `Smartshell` and keeps one streaming execution active.
```typescript
import { SmartExecution } from '@push.rocks/smartshell';
const devServer = new SmartExecution('pnpm dev');
await devServer.restart(); // starts the command
await devServer.restart(); // kills the current process tree and starts it again
```
If multiple restarts are requested while a restart is already in progress, they are collapsed into one additional restart.
## Command Discovery
The package re-exports `which` for checking whether an executable is available.
```typescript
import { which } from '@push.rocks/smartshell';
const gitPath = await which('git');
console.log(gitPath);
```
## API Overview
| API | Purpose | Shell interpretation |
| --- | --- | --- |
| `new Smartshell({ executor })` | Create an execution context using `bash` or `sh` | Depends on method |
| `exec(command, options?)` | Run a trusted shell command | Yes |
| `execSilent(command, options?)` | Run a trusted shell command without automatic output | Yes |
| `execStrict(command, options?)` | Reject on non-zero exit or signal | Yes |
| `execStrictSilent(command, options?)` | Strict and silent shell execution | Yes |
| `execStreaming(command, silent?, options?)` | Return streaming process controls | Yes |
| `execStreamingSilent(command, options?)` | Streaming shell execution without automatic output | Yes |
| `execInteractive(command, options?)` | Inherit stdio for fully interactive terminal use | Yes |
| `execPassthrough(command, options?)` | Pipe current stdin into the command | Yes |
| `execStreamingPassthrough(command, options?)` | Streaming plus stdin passthrough | Yes |
| `execInteractiveControl(command, options?)` | Send stdin programmatically | Yes |
| `execStreamingInteractiveControl(command, options?)` | Streaming plus programmatic stdin | Yes |
| `execInteractiveControlPty(command, options?)` | Programmatic stdin through a PTY | Yes |
| `execStreamingInteractiveControlPty(command, options?)` | Streaming PTY control | Yes |
| `execSpawn(command, args?, options?)` | Run an executable with literal args | No |
| `execSpawnStreaming(command, args?, options?)` | Streaming shell-free spawn | No |
| `execSpawnInteractiveControl(command, args?, options?)` | Programmatic stdin with shell-free spawn | No |
| `execAndWaitForLine(command, regex, silent?, options?)` | Resolve when stdout matches | Yes |
| `execAndWaitForLineSilent(command, regex, options?)` | Silent output wait | Yes |
| `new SmartExecution(command)` | Restartable streaming command helper | Yes |
| `which(command)` | Resolve executable path | No command execution |
## Security Guide
Command execution is powerful and dangerous when untrusted input is involved. The rule is simple: use shell-based APIs for trusted command strings, and use spawn APIs for untrusted arguments.
### Prefer Spawn for Untrusted Data
```typescript
// Do not do this with untrusted values.
await shell.exec(`git checkout ${branchFromRequest}`);
// Do this instead.
await shell.execSpawn('git', ['checkout', branchFromRequest]);
```
### Avoid Shell-Built Paths
```typescript
// Risky if pathFromUser contains shell syntax.
await shell.exec(`cat ${pathFromUser}`);
// Safer: validate the path and pass it as a literal argument.
await shell.execSpawn('cat', [pathFromUser]);
```
### Set Resource Limits
For user-triggered commands, set a timeout and a sensible buffer limit:
```typescript
await shell.execSpawn('convert', [inputPath, outputPath], {
timeout: 60_000,
maxBuffer: 20 * 1024 * 1024,
silent: true,
});
```
### Control the Environment
Pass an explicit `env` when secrets or inherited environment variables matter:
```typescript
await shell.execSpawn('node', ['worker.js'], {
env: {
PATH: process.env.PATH,
NODE_ENV: 'production',
},
});
```
## Real-World Recipes
### Build Pipeline
```typescript
const shell = new Smartshell({ executor: 'bash' });
await shell.execStrict('rm -rf dist');
await shell.execStrict('pnpm build');
await shell.execStrict('pnpm test');
```
### Safe Git Automation
```typescript
async function checkoutAndTag(branch: string, tag: string) {
const shell = new Smartshell({ executor: 'bash' });
await shell.execSpawn('git', ['checkout', branch], { strict: true });
await shell.execSpawn('git', ['tag', tag], { strict: true });
}
```
### Wait for a Development Server
```typescript
const server = shell.execAndWaitForLine(
'pnpm dev',
/ready|listening/i,
false,
{
cwd: '/path/to/app',
timeout: 30_000,
}
);
await server;
```
### Restart on File Changes
```typescript
import { watch } from 'node:fs';
import { SmartExecution } from '@push.rocks/smartshell';
const execution = new SmartExecution('pnpm dev');
await execution.restart();
watch('./src', { recursive: true }, async () => {
await execution.restart();
});
```
## License and Legal Information
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [license](./license) file.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
### Company Information
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or 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.
+250
View File
@@ -0,0 +1,250 @@
import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as smartshell from '../ts/index.js';
const getErrorMessage = (error: unknown): string => error instanceof Error ? error.message : String(error);
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 = getErrorMessage(error);
}
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 = getErrorMessage(error);
}
expect(errorThrown).toBeTrue();
expect(errorMessage).toContain('terminated by signal');
});
tap.test('strict mode errors should expose command result details', async () => {
const testSmartshell = new smartshell.Smartshell({
executor: 'bash',
sourceFilePaths: [],
});
let caughtError: smartshell.SmartshellError | null = null;
try {
await testSmartshell.execSpawn('bash', ['-c', 'echo stdout-value; echo stderr-value >&2; exit 7'], {
strict: true,
silent: true,
});
} catch (error) {
caughtError = error as smartshell.SmartshellError;
}
expect(caughtError).toBeInstanceOf(smartshell.SmartshellError);
expect(caughtError!.command).toEqual('bash');
expect(caughtError!.exitCode).toEqual(7);
expect(caughtError!.stdout).toContain('stdout-value');
expect(caughtError!.combinedOutput).toContain('stderr-value');
expect(caughtError!.stderr).toContain('stderr-value');
expect(caughtError!.result.exitCode).toEqual(7);
});
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 = getErrorMessage(error);
}
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 = getErrorMessage(error);
}
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(getErrorMessage(error)).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
View 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
View 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();
+147
View File
@@ -0,0 +1,147 @@
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 {
// @ts-ignore - node-pty is an optional runtime dependency.
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
View 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
View 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();
+230
View File
@@ -0,0 +1,230 @@
import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as smartshell from '../ts/index.js';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
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 run in the configured cwd', async () => {
const testSmartshell = new smartshell.Smartshell({
executor: 'bash',
sourceFilePaths: [],
});
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'smartshell-cwd-'));
try {
const result = await testSmartshell.execSpawn('node', ['-e', 'console.log(process.cwd())'], {
cwd: tmpDir,
silent: true,
});
expect(result.exitCode).toEqual(0);
expect(result.stdout.trim()).toEqual(tmpDir);
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
tap.test('execSilent should run shell commands in the configured cwd', async () => {
const testSmartshell = new smartshell.Smartshell({
executor: 'bash',
sourceFilePaths: [],
});
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'smartshell-shell-cwd-'));
try {
const result = await testSmartshell.execSilent('pwd', { cwd: tmpDir });
expect(result.exitCode).toEqual(0);
expect(result.stdout.trim()).toEqual(tmpDir);
} finally {
fs.rmSync(tmpDir, { recursive: true, force: true });
}
});
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 as NodeJS.ErrnoException).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 timeout should terminate the spawned process tree', async () => {
const testSmartshell = new smartshell.Smartshell({
executor: 'bash',
sourceFilePaths: [],
});
const markerPath = path.join(os.tmpdir(), `smartshell-spawn-timeout-${process.pid}-${Date.now()}`);
try {
const result = await testSmartshell.execSpawn(
'bash',
['-c', `(sleep 0.6; touch "${markerPath}") & wait`],
{ timeout: 100, silent: true },
);
await new Promise((resolve) => setTimeout(resolve, 800));
expect(result.exitCode).not.toEqual(0);
expect(fs.existsSync(markerPath)).toBeFalse();
} finally {
fs.rmSync(markerPath, { force: true });
}
});
tap.test('exec timeout should terminate the shell process tree', async () => {
const testSmartshell = new smartshell.Smartshell({
executor: 'bash',
sourceFilePaths: [],
});
const markerPath = path.join(os.tmpdir(), `smartshell-shell-timeout-${process.pid}-${Date.now()}`);
try {
const result = await testSmartshell.execSilent(`(sleep 0.6; touch "${markerPath}") & wait`, {
timeout: 100,
});
await new Promise((resolve) => setTimeout(resolve, 800));
expect(result.exitCode).not.toEqual(0);
expect(fs.existsSync(markerPath)).toBeFalse();
} finally {
fs.rmSync(markerPath, { force: true });
}
});
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();
+16 -12
View File
@@ -1,36 +1,36 @@
import { expect, tap } from '@pushrocks/tapbundle';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as smartshell from '../ts';
import * as smartpromise from '@pushrocks/smartpromise';
import * as smartshell from '../ts/index.js';
import * as smartpromise from '@push.rocks/smartpromise';
let testSmartshell: smartshell.Smartshell;
tap.test('smartshell should create a Smartshell instance', async () => {
testSmartshell = new smartshell.Smartshell({
executor: 'bash',
sourceFilePaths: []
sourceFilePaths: [],
});
expect(testSmartshell).to.be.instanceof(smartshell.Smartshell);
expect(testSmartshell).toBeInstanceOf(smartshell.Smartshell);
});
tap.test('smartshell should run async', async () => {
let execResult = await testSmartshell.exec('npm -v');
expect(execResult.stdout).to.match(/[0-9\.]*/);
expect(execResult.stdout).toMatch(/[0-9\.]*/);
});
tap.test('smartshell should run async and silent', async () => {
let execResult = await testSmartshell.execSilent('npm -v');
expect(execResult.stdout).to.match(/[0-9\.]*/);
expect(execResult.stdout).toMatch(/[0-9\.]*/);
});
tap.test('smartshell should stream a shell execution', async () => {
let done = smartpromise.defer();
let execStreamingResponse = await testSmartshell.execStreaming('npm -v');
execStreamingResponse.childProcess.stdout.on('data', data => {
execStreamingResponse.childProcess.stdout!.on('data', (data) => {
done.resolve(data);
});
let data = await done.promise;
expect(data).to.match(/[0-9\.]*/);
expect(data).toMatch(/[0-9\.]*/);
await execStreamingResponse.finalPromise;
});
@@ -39,15 +39,19 @@ tap.test('it should execute and wait for a line in the output', async () => {
});
tap.test('smartshell should run async', async () => {
return testSmartshell.execSilent('sleep 1 && npm -v').then(async execResult => {
return testSmartshell.execSilent('sleep 1 && npm -v').then(async (execResult) => {
console.log(execResult.stdout);
});
});
tap.test('should be able to find git', async () => {
testSmartshell.exec('git --version');
await testSmartshell.exec('git --version');
});
tap.test('should spawn an interactive cli', async () => {
await testSmartshell.execInteractive('echo "hi"');
});
tap.start({
throwOnError: true
throwOnError: true,
});
+8
View File
@@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartshell',
version: '3.4.0',
description: 'A library for executing shell commands using promises.'
}
@@ -28,29 +28,38 @@ export class ShellEnv {
}
}
/**
* Detect if running under Windows Subsystem for Linux
*/
private static _isWSL(): boolean {
return !!(
process.env.WSL_DISTRO_NAME ||
process.env.WSLENV ||
(process.platform === 'linux' && process.env.PATH?.includes('/mnt/c/'))
);
}
/**
* imports path into the shell from env if available and returns it with
*/
private _setPath(commandStringArg): string {
private _setPath(commandStringArg: string): string {
let commandResult = commandStringArg;
let commandPaths: string[] = [];
commandPaths = commandPaths.concat(process.env.PATH.split(':'));
commandPaths = commandPaths.concat(process.env.PATH?.split(':') ?? []);
if (process.env.SMARTSHELL_PATH) {
commandPaths = commandPaths.concat(process.env.SMARTSHELL_PATH.split(':'));
}
// lets filter for unwanted paths
// Windows WSL
commandPaths = commandPaths.filter(commandPathArg => {
const filterResult =
!commandPathArg.startsWith('/mnt/c/') &&
!commandPathArg.startsWith('Files/1E') &&
!commandPathArg.includes(' ');
if (!filterResult) {
// console.log(`${commandPathArg} will be filtered!`);
}
return filterResult;
});
// Only filter out WSL-specific paths when actually running under WSL
if (ShellEnv._isWSL()) {
commandPaths = commandPaths.filter((commandPathArg) => {
return (
!commandPathArg.startsWith('/mnt/c/') &&
!commandPathArg.startsWith('Files/1E') &&
!commandPathArg.includes(' ')
);
});
}
commandResult = `PATH=${commandPaths.join(':')} && ${commandStringArg}`;
return commandResult;
@@ -73,24 +82,28 @@ export class ShellEnv {
this.sourceFileArray = [];
}
createEnvExecString(commandArg): string {
public createEnvExecString(commandArg: string): string {
let commandResult = '';
let sourceString = '';
switch (this.executor) {
case 'bash':
for (let sourceFilePath of this.sourceFileArray) {
sourceString = sourceString + `source ${sourceFilePath} && `;
}
commandResult = `bash -c '${sourceString}${commandArg}'`;
break;
case 'sh':
for (let sourceFilePath of this.sourceFileArray) {
sourceString = sourceString + `source ${sourceFilePath} && `;
}
commandResult = `${sourceString}${commandArg}`;
break;
// deal with sourcestring
for (const sourceFilePath of this.sourceFileArray) {
sourceString = sourceString + `source ${sourceFilePath} && `;
}
// deal with available path
let pathString = 'PATH=$PATH';
for (const pathDir of this.pathDirArray) {
pathString += `:${pathDir}`;
}
pathString += ` && `;
// For both bash and sh executors, build the command string directly.
// The shell nesting is handled by spawn() using the appropriate shell binary.
// Previously bash executor wrapped in `bash -c '...'` which caused triple
// shell nesting (Node spawn sh -> bash -c -> command). Now spawn() uses
// shell: '/bin/bash' directly, so we don't need the extra wrapping.
commandResult = `${pathString}${sourceString}${commandArg}`;
commandResult = this._setPath(commandResult);
return commandResult;
}
+68
View File
@@ -0,0 +1,68 @@
import * as plugins from './plugins.js';
/**
* a log handler for spawned logs
* making sure the process doesn't run out of memory
*/
export class ShellLog {
private chunks: Buffer[] = [];
private totalLength = 0;
/**
* Get the accumulated log as a single Buffer.
* Concatenation happens lazily only when accessed.
*/
public get logStore(): Buffer {
if (this.chunks.length === 0) {
return Buffer.alloc(0);
}
if (this.chunks.length === 1) {
return this.chunks[0];
}
// Flatten chunks into a single buffer
const combined = Buffer.concat(this.chunks, this.totalLength);
// Replace chunks array with the single combined buffer for future access
this.chunks = [combined];
return combined;
}
/**
* Set the log store directly (used for truncation).
*/
public set logStore(value: Buffer) {
this.chunks = [value];
this.totalLength = value.length;
}
/**
* Get the current total length of buffered data without concatenating.
*/
public get logLength(): number {
return this.totalLength;
}
/**
* log data to console
* @param dataArg
*/
public writeToConsole(dataArg: string | Buffer): void {
// make sure we have the data as string
process.stdout.write(dataArg);
}
/**
* add data to Buffer for later consumption
* @param dataArg
*/
public addToBuffer(dataArg: string | Buffer): void {
// make sure we have the data as Buffer
const dataBuffer: Buffer = Buffer.isBuffer(dataArg) ? dataArg : Buffer.from(dataArg);
this.chunks.push(dataBuffer);
this.totalLength += dataBuffer.length;
}
public logAndAdd(dataArg: string | Buffer): void {
this.writeToConsole(dataArg);
this.addToBuffer(dataArg);
}
}
+55
View File
@@ -0,0 +1,55 @@
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;
}
/**
* 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;
}
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();
}
}
}
+973
View File
@@ -0,0 +1,973 @@
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;
/** stdout currently preserves smartshell's legacy combined stdout/stderr buffer. */
combinedOutput?: string;
signal?: NodeJS.Signals;
stderr?: string;
}
export class SmartshellError extends Error {
public command: string;
public result: IExecResult;
public exitCode: number;
public stdout: string;
public combinedOutput?: string;
public stderr?: string;
public signal?: NodeJS.Signals;
constructor(command: string, result: IExecResult) {
const reason = result.signal
? `terminated by signal ${result.signal}`
: `exited with code ${result.exitCode}`;
super(`Command "${command}" ${reason}`);
this.name = 'SmartshellError';
this.command = command;
this.result = result;
this.exitCode = result.exitCode;
this.stdout = result.stdout;
this.combinedOutput = result.combinedOutput;
this.stderr = result.stderr;
this.signal = result.signal;
}
}
export interface IExecResultInteractive extends IExecResult {
sendInput: (input: string) => Promise<void>;
sendLine: (line: string) => Promise<void>;
endInput: () => void;
finalPromise: Promise<IExecResult>;
}
export interface IExecResultStreaming {
childProcess: cp.ChildProcess;
finalPromise: Promise<IExecResult>;
kill: () => Promise<void>;
terminate: () => Promise<void>;
keyboardInterrupt: () => Promise<void>;
customSignal: (signal: plugins.smartexit.TProcessSignal) => Promise<void>;
sendInput: (input: string) => Promise<void>;
sendLine: (line: string) => Promise<void>;
endInput: () => void;
}
export interface IExecRuntimeOptions {
ptyCols?: number;
ptyRows?: number;
ptyTerm?: string;
ptyShell?: string;
maxBuffer?: number;
onData?: (chunk: Buffer | string) => void;
timeout?: number;
debug?: boolean;
env?: NodeJS.ProcessEnv;
cwd?: string;
signal?: AbortSignal;
}
interface IExecOptions extends IExecRuntimeOptions {
commandString: string;
silent?: boolean;
strict?: boolean;
streaming?: boolean;
interactive?: boolean;
passthrough?: boolean;
interactiveControl?: boolean;
usePty?: boolean;
}
export interface ISpawnOptions extends IExecRuntimeOptions {
command: string;
args?: string[];
silent?: boolean;
strict?: boolean;
streaming?: boolean;
interactive?: boolean;
passthrough?: boolean;
interactiveControl?: boolean;
usePty?: boolean;
}
export type TExecCommandOptions = IExecRuntimeOptions;
export class Smartshell {
public shellEnv: ShellEnv;
public smartexit = new plugins.smartexit.SmartExit();
constructor(optionsArg: IShellEnvContructorOptions) {
this.shellEnv = new ShellEnv(optionsArg);
}
/**
* Executes a given command asynchronously.
*/
private async _exec(options: IExecOptions): Promise<IExecResult | IExecResultStreaming | IExecResultInteractive | void> {
if (options.interactive) {
return await this._execInteractive({
commandString: options.commandString,
cwd: options.cwd,
env: options.env,
});
}
return await this._execCommand(options);
}
/**
* Executes an interactive command.
*/
private async _execInteractive(options: Pick<IExecOptions, 'commandString' | 'cwd' | 'env'>): Promise<void> {
// Skip interactive execution in CI environments.
if (process.env.CI) {
return;
}
return new Promise<void>((resolve) => {
const shell = cp.spawn(options.commandString, {
stdio: 'inherit',
shell: true,
detached: true,
cwd: options.cwd || process.cwd(),
env: options.env || process.env,
});
this.smartexit.addProcess(shell);
shell.on('close', (code) => {
console.log(`Interactive shell terminated with code ${code}`);
this.smartexit.removeProcess(shell);
resolve();
});
});
}
/**
* Executes a command with args array (shell:false) for security
*/
private async _execSpawn(options: ISpawnOptions): Promise<IExecResult | IExecResultStreaming | IExecResultInteractive> {
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) {
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: options.cwd || process.cwd(),
env: options.env || process.env,
detached: true, // Own process group — immune to terminal SIGINT, managed by smartexit
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...`);
}
void this.killProcessTree(execChildProcess.pid, 'SIGTERM', options.debug);
}, 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.logLength > 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.logLength > 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 combinedOutput = shellLogInstance.logStore.toString();
const execResult: IExecResult = {
exitCode,
stdout: combinedOutput,
combinedOutput,
signal: signal || undefined,
stderr: stderrBuffer,
};
if (options.strict && exitCode !== 0) {
reject(new SmartshellError(options.command, execResult));
} else {
resolve(execResult);
}
};
execChildProcess.once('close', 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 this.killProcessTree(execChildProcess.pid, 'SIGKILL', options.debug);
},
terminate: async () => {
if (options.debug) {
console.log(`[smartshell] Running tree kill with SIGTERM on process ${execChildProcess.pid}`);
}
await this.killProcessTree(execChildProcess.pid, 'SIGTERM', options.debug);
},
keyboardInterrupt: async () => {
if (options.debug) {
console.log(`[smartshell] Running tree kill with SIGINT on process ${execChildProcess.pid}`);
}
await this.killProcessTree(execChildProcess.pid, 'SIGINT', options.debug);
},
customSignal: async (signal: plugins.smartexit.TProcessSignal) => {
if (options.debug) {
console.log(`[smartshell] Running tree kill with custom signal ${signal} on process ${execChildProcess.pid}`);
}
await this.killProcessTree(execChildProcess.pid, signal, options.debug);
},
} as IExecResultStreaming;
}
// 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);
}
// Use the executor's shell binary directly to avoid triple shell nesting.
// Previously: Node spawn(shell:true) → /bin/sh → bash -c → command (3 layers)
// Now: Node spawn(shell:bash) → command (1 layer)
const shellBinary = this.shellEnv.executor === 'bash' ? '/bin/bash' : true;
const execChildProcess = cp.spawn(commandToExecute, [], {
shell: shellBinary,
cwd: options.cwd || process.cwd(),
env: options.env || process.env,
detached: true, // Own process group — immune to terminal SIGINT, managed by smartexit
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...`);
}
void this.killProcessTree(execChildProcess.pid, 'SIGTERM', options.debug);
}, 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.logLength > 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.logLength > 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 combinedOutput = shellLogInstance.logStore.toString();
const execResult: IExecResult = {
exitCode,
stdout: combinedOutput,
combinedOutput,
signal: signal || undefined,
stderr: stderrBuffer,
};
if (options.strict && exitCode !== 0) {
reject(new SmartshellError(options.commandString, execResult));
} else {
resolve(execResult);
}
};
execChildProcess.once('close', 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 this.killProcessTree(execChildProcess.pid, 'SIGKILL', options.debug);
},
terminate: async () => {
if (options.debug) {
console.log(`[smartshell] Running tree kill with SIGTERM on process ${execChildProcess.pid}`);
}
await this.killProcessTree(execChildProcess.pid, 'SIGTERM', options.debug);
},
keyboardInterrupt: async () => {
if (options.debug) {
console.log(`[smartshell] Running tree kill with SIGINT on process ${execChildProcess.pid}`);
}
await this.killProcessTree(execChildProcess.pid, 'SIGINT', options.debug);
},
customSignal: async (signal: plugins.smartexit.TProcessSignal) => {
if (options.debug) {
console.log(`[smartshell] Running tree kill with custom signal ${signal} on process ${execChildProcess.pid}`);
}
await this.killProcessTree(execChildProcess.pid, signal, options.debug);
},
} as IExecResultStreaming;
}
// For non-streaming mode, wait for the process to complete.
return await childProcessEnded;
}
private async killProcessTree(
pid: number | undefined,
signal: plugins.smartexit.TProcessSignal,
debug?: boolean,
): Promise<void> {
if (!pid) {
return;
}
if (debug) {
console.log(`[smartshell] Killing process tree ${pid} with ${signal}`);
}
try {
await plugins.smartexit.SmartExit.killTreeByPid(pid, signal);
} catch (error) {
if (debug) {
console.log(`[smartshell] Tree kill failed for ${pid}: ${error}`);
}
try {
process.kill(pid, signal as NodeJS.Signals);
} catch {
// Process already exited or is not accessible.
}
}
}
public async exec(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResult> {
const result = await this._exec({ commandString, ...options });
// Type assertion is safe here because non-streaming, non-interactive exec always returns IExecResult
return result as IExecResult;
}
public async execSilent(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResult> {
return (await this._exec({ commandString, ...options, silent: true })) as IExecResult;
}
public async execStrict(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResult> {
return (await this._exec({ commandString, ...options, strict: true })) as IExecResult;
}
public async execStrictSilent(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResult> {
return (await this._exec({ commandString, ...options, silent: true, strict: true })) as IExecResult;
}
public async execStreaming(
commandString: string,
silent: boolean = false,
options: TExecCommandOptions = {},
): Promise<IExecResultStreaming> {
return (await this._exec({ commandString, ...options, silent, streaming: true })) as IExecResultStreaming;
}
public async execStreamingSilent(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultStreaming> {
return (await this._exec({ commandString, ...options, silent: true, streaming: true })) as IExecResultStreaming;
}
public async execInteractive(commandString: string, options: TExecCommandOptions = {}): Promise<void> {
await this._exec({ commandString, ...options, interactive: true });
}
public async execPassthrough(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResult> {
return await this._exec({ commandString, ...options, passthrough: true }) as IExecResult;
}
public async execStreamingPassthrough(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultStreaming> {
return await this._exec({ commandString, ...options, streaming: true, passthrough: true }) as IExecResultStreaming;
}
public async execInteractiveControl(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultInteractive> {
return await this._exec({ commandString, ...options, interactiveControl: true }) as IExecResultInteractive;
}
public async execStreamingInteractiveControl(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultStreaming> {
return await this._exec({ commandString, ...options, streaming: true, interactiveControl: true }) as IExecResultStreaming;
}
public async execInteractiveControlPty(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultInteractive> {
return await this._exec({ commandString, ...options, interactiveControl: true, usePty: true }) as IExecResultInteractive;
}
public async execStreamingInteractiveControlPty(commandString: string, options: TExecCommandOptions = {}): Promise<IExecResultStreaming> {
return await this._exec({ commandString, ...options, 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, ...options, streaming: true }) 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, ...options, interactiveControl: true }) as IExecResultInteractive;
}
public async execAndWaitForLine(
commandString: string,
regex: RegExp,
silent: boolean = false,
options: { timeout?: number; terminateOnMatch?: boolean; cwd?: string; env?: NodeJS.ProcessEnv } = {}
): Promise<void> {
const execStreamingResult = await this.execStreaming(commandString, silent, {
cwd: options.cwd,
env: options.env,
});
const stdout = execStreamingResult.childProcess.stdout;
if (!stdout) {
await execStreamingResult.terminate();
throw new Error('stdout is not available for this process');
}
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
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
stdout.removeListener('data', dataHandler);
// Terminate process if requested
if (options.terminateOnMatch) {
await execStreamingResult.terminate();
await execStreamingResult.finalPromise;
}
resolve();
}
};
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);
}
});
});
}
public async execAndWaitForLineSilent(commandString: string, regex: RegExp, options?: { timeout?: number; terminateOnMatch?: boolean; cwd?: string; env?: NodeJS.ProcessEnv }): 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: options.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);
});
let timeoutHandle: NodeJS.Timeout | null = null;
if (options.timeout) {
timeoutHandle = setTimeout(() => {
if (options.debug) {
console.log(`[smartshell] Timeout reached for PTY process ${ptyProcess.pid}, terminating...`);
}
ptyProcess.kill('SIGTERM');
}, options.timeout);
}
// Wrap PTY termination into a Promise
const childProcessEnded: Promise<IExecResult> = new Promise((resolve, reject) => {
ptyProcess.onExit(({ exitCode, signal }: { exitCode: number; signal?: number }) => {
if (timeoutHandle) {
clearTimeout(timeoutHandle);
}
this.smartexit.removeProcess({ pid: ptyProcess.pid } as any);
const combinedOutput = shellLogInstance.logStore.toString();
const execResult: IExecResult = {
exitCode: exitCode ?? (signal ? 1 : 0),
stdout: combinedOutput,
combinedOutput,
};
if (options.strict && exitCode !== 0) {
reject(new SmartshellError(options.commandString, execResult));
} 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;
}
}
+3 -1
View File
@@ -1 +1,3 @@
export * from './smartshell.classes.smartshell';
export * from './classes.smartshell.js';
export * from './classes.smartexecution.js';
export { which } from './plugins.js';
+6
View File
@@ -0,0 +1,6 @@
import * as smartdelay from '@push.rocks/smartdelay';
import * as smartexit from '@push.rocks/smartexit';
import * as smartpromise from '@push.rocks/smartpromise';
import which from 'which';
export { smartdelay, smartexit, smartpromise, which };
-38
View File
@@ -1,38 +0,0 @@
import * as plugins from './smartshell.plugins';
/**
* a log handler for spawned logs
* making sure the process doesn't run out of memory
*/
export class ShellLog {
logStore = Buffer.from('');
/**
* log data to console
* @param dataArg
*/
logToConsole(dataArg: string | Buffer): void {
// make sure we have the data as string
process.stdout.write(dataArg);
}
/**
* add data to Buffer for later consumption
* @param dataArg
*/
addToBuffer(dataArg: string | Buffer): void {
// make sure we have the data as Buffer
const dataBuffer: Buffer = (() => {
if (!Buffer.isBuffer(dataArg)) {
return Buffer.from(dataArg);
}
return dataArg;
})();
this.logStore = Buffer.concat([this.logStore, dataBuffer]);
}
logAndAdd(dataArg: string | Buffer): void {
this.logToConsole(dataArg);
this.addToBuffer(dataArg);
}
}
-154
View File
@@ -1,154 +0,0 @@
// -- imports --
import * as plugins from './smartshell.plugins';
import { ShellEnv, IShellEnvContructorOptions, TExecutor } from './smartshell.classes.shellenv';
import { ShellLog } from './smartshell.classes.shelllog';
import * as cp from 'child_process';
import { Deferred } from '@pushrocks/smartpromise';
// -- interfaces --
/**
* interface for ExecResult
*/
export interface IExecResult {
exitCode: number;
stdout: string;
}
/**
* interface for streaming ExecResult
*/
export interface IExecResultStreaming {
childProcess: cp.ChildProcess;
finalPromise: Promise<IExecResult>;
kill: () => void;
}
// -- SmartShell --
export class Smartshell {
shellEnv: ShellEnv;
constructor(optionsArg: IShellEnvContructorOptions) {
this.shellEnv = new ShellEnv(optionsArg);
}
/**
* executes a given command async
* @param commandStringArg
*/
private async _exec(
commandStringArg: string,
silentArg: boolean = false,
strictArg = false,
streamingArg = false
): Promise<IExecResult | IExecResultStreaming> {
// flow control promises
const done = plugins.smartpromise.defer<IExecResult | IExecResultStreaming>();
const childProcessEnded = plugins.smartpromise.defer<IExecResult>();
// build commandToExecute
let commandToExecute = commandStringArg;
commandToExecute = this.shellEnv.createEnvExecString(commandStringArg);
const spawnlogInstance = new ShellLog();
const execChildProcess = cp.spawn(commandToExecute, [], {
shell: true,
env: process.env,
detached: true
});
execChildProcess.stdout.on('data', data => {
if (!silentArg) {
spawnlogInstance.logToConsole(data);
}
spawnlogInstance.addToBuffer(data);
});
execChildProcess.stderr.on('data', data => {
if (!silentArg) {
spawnlogInstance.logToConsole(data);
}
spawnlogInstance.addToBuffer(data);
});
if (streamingArg) {
done.resolve({
childProcess: execChildProcess,
finalPromise: childProcessEnded.promise,
kill: () => {
// this notation with the - kills the whole process group
process.kill(-execChildProcess.pid);
}
});
}
execChildProcess.on('exit', (code, signal) => {
if (strictArg && code === 1) {
done.reject();
}
const execResult = {
exitCode: code,
stdout: spawnlogInstance.logStore.toString()
};
if (!streamingArg) {
done.resolve(execResult);
}
childProcessEnded.resolve(execResult);
});
const result = await done.promise;
return result;
}
async exec(commandStringArg: string): Promise<IExecResult> {
return (await this._exec(commandStringArg, false)) as IExecResult;
}
/**
* executes a given command async and silent
* @param commandStringArg
*/
async execSilent(commandStringArg: string): Promise<IExecResult> {
return (await this._exec(commandStringArg, true)) as IExecResult;
}
/**
* executes a command async and strict, meaning it rejects the promise if something happens
*/
async execStrict(commandStringArg: string): Promise<IExecResult> {
return (await this._exec(commandStringArg, true, true)) as IExecResult;
}
/**
* executes a command and allows you to stream output
*/
async execStreaming(
commandStringArg: string,
silentArg: boolean = false
): Promise<IExecResultStreaming> {
return (await this._exec(commandStringArg, silentArg, false, true)) as IExecResultStreaming;
}
async execStreamingSilent(commandStringArg: string) {
return (await this.execStreaming(commandStringArg, true)) as IExecResultStreaming;
}
/**
* executes a command and returns promise that will be fullfilled once an putput line matches RegexArg
* @param commandStringArg
* @param regexArg
*/
async execAndWaitForLine(commandStringArg: string, regexArg: RegExp, silentArg: boolean = false) {
let done = plugins.smartpromise.defer();
let execStreamingResult = await this.execStreaming(commandStringArg, silentArg);
execStreamingResult.childProcess.stdout.on('data', (stdOutChunk: string) => {
if (regexArg.test(stdOutChunk)) {
done.resolve();
}
});
return done.promise;
}
async execAndWaitForLineSilent(commandStringArg: string, regexArg: RegExp) {
this.execAndWaitForLine(commandStringArg, regexArg, true);
}
}
-4
View File
@@ -1,4 +0,0 @@
import * as smartpromise from '@pushrocks/smartpromise';
import * as which from 'which';
export { smartpromise, which };
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"types": ["node"],
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}
-17
View File
@@ -1,17 +0,0 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}