Compare commits
125 Commits
Author | SHA1 | Date | |
---|---|---|---|
61f76af7d1 | |||
529b33fda1 | |||
f8e431f41e | |||
5a32817349 | |||
35d22175db | |||
cd3675280a | |||
7c14102324 | |||
cb41dbaf1c | |||
149eb800e7 | |||
91e84c8422 | |||
ff26cd0678 | |||
acdd729e06 | |||
522fbfc42c | |||
b854715940 | |||
35f59054f8 | |||
c9a3de2207 | |||
6904097960 | |||
1474fd541f | |||
9befccefd6 | |||
415c9de553 | |||
980a2c9781 | |||
c13a0f5d48 | |||
71e239c5b1 | |||
0d7c87051b | |||
067f1a9c17 | |||
e7cf3bcb5e | |||
18cfa3e16a | |||
ea921766dc | |||
7e6d632afb | |||
25c61d7d7d | |||
d84c7a16a4 | |||
c5937da870 | |||
ec29db26ef | |||
e4e08910c7 | |||
730a4a05a4 | |||
20a2804924 | |||
d7247add7e | |||
b304b01ab6 | |||
9ba5447e72 | |||
6cb7ab8f19 | |||
efdb80ddba | |||
db712b2223 | |||
0199160013 | |||
199fa19899 | |||
23a3230f07 | |||
ad0b7ac21c | |||
c8c0cbd47a | |||
213dac474e | |||
a4c188051a | |||
62195b63d6 | |||
16ba3803a4 | |||
613241cdcb | |||
f5df21e144 | |||
ba8c2d06d8 | |||
9bb0999f0e | |||
1beb3a0bbe | |||
c1133e9131 | |||
48dd3c3cca | |||
f0a5be41ea | |||
970d28a4ad | |||
76f2126eb3 | |||
a6f164602c | |||
f8457ad58d | |||
8ceac74a1f | |||
f63c4456bf | |||
32c33cad5b | |||
0758e58fa4 | |||
e981ca6bdd | |||
2853a48708 | |||
389f8f4a52 | |||
c1a537f052 | |||
4701341c0c | |||
d5d347721a | |||
6a047d6333 | |||
6e7b4dd18e | |||
debc5f1524 | |||
8d03561762 | |||
f516a6e753 | |||
1c4f6a8bf9 | |||
4fe3775904 | |||
dcee2d6233 | |||
39d457382f | |||
e6ed457501 | |||
0a6484762c | |||
baa3e4e6e9 | |||
0d68361381 | |||
286d80328c | |||
2a71f00ab0 | |||
80a44a43cb | |||
5ea780acda | |||
7c9cf6e70d | |||
697f789b55 | |||
f452964779 | |||
f2db8dc41f | |||
2ca593297c | |||
a63ae38437 | |||
03d442bf60 | |||
901348dfe9 | |||
2e94eb5467 | |||
f2f048a40b | |||
db506a6eb1 | |||
66cdc7632e | |||
604fa228f7 | |||
e0e8e9f29a | |||
aa54912346 | |||
5457dcfc8d | |||
5c7b0fafea | |||
4470250091 | |||
5f17ca3d63 | |||
226a518369 | |||
9709920a72 | |||
b6589d0850 | |||
0f2d68cf5f | |||
01e6411c29 | |||
b356bcbaed | |||
35b81dc6d9 | |||
47321b02b8 | |||
7c0af2b0bc | |||
ced0ce7b53 | |||
a745a435db | |||
6aeb0c1558 | |||
4584c44248 | |||
ca175205ee | |||
|
bc2d0dda3f | ||
|
63d5fe4f1c |
20
.gitignore
vendored
20
.gitignore
vendored
@@ -1,4 +1,20 @@
|
||||
.nogit/
|
||||
|
||||
# artifacts
|
||||
coverage/
|
||||
node_modules/
|
||||
pages/
|
||||
public/
|
||||
pages/
|
||||
|
||||
# installs
|
||||
node_modules/
|
||||
|
||||
# caches
|
||||
.yarn/
|
||||
.cache/
|
||||
.rpt2_cache
|
||||
|
||||
# builds
|
||||
dist/
|
||||
dist_*/
|
||||
|
||||
# custom
|
@@ -1,68 +0,0 @@
|
||||
# gitzone standard
|
||||
image: hosttoday/ht-docker-node:npmci
|
||||
|
||||
cache:
|
||||
paths:
|
||||
- .yarn/
|
||||
key: "$CI_BUILD_STAGE"
|
||||
|
||||
stages:
|
||||
- test
|
||||
- release
|
||||
- trigger
|
||||
- pages
|
||||
|
||||
testLEGACY:
|
||||
stage: test
|
||||
script:
|
||||
- npmci test legacy
|
||||
coverage: /\d+.?\d+?\%\s*coverage/
|
||||
tags:
|
||||
- docker
|
||||
allow_failure: true
|
||||
|
||||
testLTS:
|
||||
stage: test
|
||||
script:
|
||||
- npmci test lts
|
||||
coverage: /\d+.?\d+?\%\s*coverage/
|
||||
tags:
|
||||
- docker
|
||||
|
||||
testSTABLE:
|
||||
stage: test
|
||||
script:
|
||||
- npmci test stable
|
||||
coverage: /\d+.?\d+?\%\s*coverage/
|
||||
tags:
|
||||
- docker
|
||||
|
||||
release:
|
||||
stage: release
|
||||
script:
|
||||
- npmci publish
|
||||
only:
|
||||
- tags
|
||||
tags:
|
||||
- docker
|
||||
|
||||
trigger:
|
||||
stage: trigger
|
||||
script:
|
||||
- npmci trigger
|
||||
only:
|
||||
- tags
|
||||
tags:
|
||||
- docker
|
||||
|
||||
pages:
|
||||
image: hosttoday/ht-docker-node:npmpage
|
||||
stage: pages
|
||||
script:
|
||||
- npmci command npmpage --publish gitlab
|
||||
only:
|
||||
- tags
|
||||
artifacts:
|
||||
expire_in: 1 week
|
||||
paths:
|
||||
- public
|
BIN
.serena/cache/typescript/document_symbols_cache_v23-06-25.pkl
vendored
Normal file
BIN
.serena/cache/typescript/document_symbols_cache_v23-06-25.pkl
vendored
Normal file
Binary file not shown.
68
.serena/project.yml
Normal file
68
.serena/project.yml
Normal file
@@ -0,0 +1,68 @@
|
||||
# language of the project (csharp, python, rust, java, typescript, go, cpp, or ruby)
|
||||
# * For C, use cpp
|
||||
# * For JavaScript, use typescript
|
||||
# Special requirements:
|
||||
# * csharp: Requires the presence of a .sln file in the project folder.
|
||||
language: typescript
|
||||
|
||||
# whether to use the project's gitignore file to ignore files
|
||||
# Added on 2025-04-07
|
||||
ignore_all_files_in_gitignore: true
|
||||
# list of additional paths to ignore
|
||||
# same syntax as gitignore, so you can use * and **
|
||||
# Was previously called `ignored_dirs`, please update your config if you are using that.
|
||||
# Added (renamed) on 2025-04-07
|
||||
ignored_paths: []
|
||||
|
||||
# whether the project is in read-only mode
|
||||
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
|
||||
# Added on 2025-04-18
|
||||
read_only: false
|
||||
|
||||
|
||||
# list of tool names to exclude. We recommend not excluding any tools, see the readme for more details.
|
||||
# Below is the complete list of tools for convenience.
|
||||
# To make sure you have the latest list of tools, and to view their descriptions,
|
||||
# execute `uv run scripts/print_tool_overview.py`.
|
||||
#
|
||||
# * `activate_project`: Activates a project by name.
|
||||
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
|
||||
# * `create_text_file`: Creates/overwrites a file in the project directory.
|
||||
# * `delete_lines`: Deletes a range of lines within a file.
|
||||
# * `delete_memory`: Deletes a memory from Serena's project-specific memory store.
|
||||
# * `execute_shell_command`: Executes a shell command.
|
||||
# * `find_referencing_code_snippets`: Finds code snippets in which the symbol at the given location is referenced.
|
||||
# * `find_referencing_symbols`: Finds symbols that reference the symbol at the given location (optionally filtered by type).
|
||||
# * `find_symbol`: Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
|
||||
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
|
||||
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
|
||||
# * `initial_instructions`: Gets the initial instructions for the current project.
|
||||
# Should only be used in settings where the system prompt cannot be set,
|
||||
# e.g. in clients you have no control over, like Claude Desktop.
|
||||
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
|
||||
# * `insert_at_line`: Inserts content at a given line in a file.
|
||||
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
|
||||
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
|
||||
# * `list_memories`: Lists memories in Serena's project-specific memory store.
|
||||
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
|
||||
# * `prepare_for_new_conversation`: Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
|
||||
# * `read_file`: Reads a file within the project directory.
|
||||
# * `read_memory`: Reads the memory with the given name from Serena's project-specific memory store.
|
||||
# * `remove_project`: Removes a project from the Serena configuration.
|
||||
# * `replace_lines`: Replaces a range of lines within a file with new content.
|
||||
# * `replace_symbol_body`: Replaces the full definition of a symbol.
|
||||
# * `restart_language_server`: Restarts the language server, may be necessary when edits not through Serena happen.
|
||||
# * `search_for_pattern`: Performs a search for a pattern in the project.
|
||||
# * `summarize_changes`: Provides instructions for summarizing the changes made to the codebase.
|
||||
# * `switch_modes`: Activates modes by providing a list of their names
|
||||
# * `think_about_collected_information`: Thinking tool for pondering the completeness of collected information.
|
||||
# * `think_about_task_adherence`: Thinking tool for determining whether the agent is still on track with the current task.
|
||||
# * `think_about_whether_you_are_done`: Thinking tool for determining whether the task is truly completed.
|
||||
# * `write_memory`: Writes a named memory (for future reference) to Serena's project-specific memory store.
|
||||
excluded_tools: []
|
||||
|
||||
# initial prompt for the project. It will always be given to the LLM upon activating the project
|
||||
# (contrary to the memories, which are loaded on demand).
|
||||
initial_prompt: ""
|
||||
|
||||
project_name: "smartshell"
|
11
.vscode/launch.json
vendored
Normal file
11
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"command": "npm test",
|
||||
"name": "Run npm test",
|
||||
"request": "launch",
|
||||
"type": "node-terminal"
|
||||
}
|
||||
]
|
||||
}
|
26
.vscode/settings.json
vendored
Normal file
26
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"json.schemas": [
|
||||
{
|
||||
"fileMatch": ["/npmextra.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"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
28
README.md
28
README.md
@@ -1,28 +0,0 @@
|
||||
# smartshell
|
||||
shell actions designed as promises
|
||||
|
||||
## Availabililty
|
||||
[](https://www.npmjs.com/package/smartshell)
|
||||
[](https://GitLab.com/pushrocks/smartshell)
|
||||
[](https://github.com/pushrocks/smartshell)
|
||||
[](https://pushrocks.gitlab.io/smartshell/)
|
||||
|
||||
## Status for master
|
||||
[](https://GitLab.com/pushrocks/smartshell/commits/master)
|
||||
[](https://GitLab.com/pushrocks/smartshell/commits/master)
|
||||
[](https://www.npmjs.com/package/smartshell)
|
||||
[](https://david-dm.org/pushrocks/smartshell)
|
||||
[](https://www.bithound.io/github/pushrocks/smartshell/master/dependencies/npm)
|
||||
[](https://www.bithound.io/github/pushrocks/smartshell)
|
||||
[](https://nodejs.org/dist/latest-v6.x/docs/api/)
|
||||
[](https://nodejs.org/dist/latest-v6.x/docs/api/)
|
||||
[](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)
|
||||
|
||||
[](https://push.rocks)
|
110
changelog.md
Normal file
110
changelog.md
Normal file
@@ -0,0 +1,110 @@
|
||||
# Changelog
|
||||
|
||||
## 2025-08-17 - 3.3.0 - feat(smartshell)
|
||||
Add secure spawn APIs, PTY support, interactive/streaming control, timeouts and buffer limits; update README and tests
|
||||
|
||||
- Introduce execSpawn family (execSpawn, execSpawnStreaming, execSpawnInteractiveControl) for shell-free, secure execution of untrusted input (shell:false).
|
||||
- Add PTY support (optional node-pty) with execInteractiveControlPty and execStreamingInteractiveControlPty; PTY is lazy-loaded and documented as an optional dependency.
|
||||
- Expose interactive control primitives (sendInput, sendLine, endInput, finalPromise) for both spawn and shell-based executions, and streaming interfaces with process control (terminate, kill, keyboardInterrupt, customSignal).
|
||||
- Implement timeouts, maxBuffer limits and onData callbacks to prevent OOM, stream output incrementally, and support early termination and debugging logs.
|
||||
- Improve process lifecycle handling: safe unpipe/unpipe-on-error, smartexit integration, and safer signal-based tree-kill behavior.
|
||||
- Enhance execAndWaitForLine with timeout and terminateOnMatch options to allow pattern-based waits with configurable behavior.
|
||||
- Update README with a Security Guide recommending execSpawn for untrusted input, PTY usage guidance, and new feature documentation (timeouts, buffer limits, debug mode, environment control).
|
||||
- Add extensive tests covering error handling, interactive control, passthrough, PTY behavior, spawn behavior, silent/streaming modes and environment propagation.
|
||||
|
||||
## 2025-08-16 - 3.2.4 - fix(tests)
|
||||
Update tests & CI config, bump deps, add docs and project configs
|
||||
|
||||
- Add comprehensive README overhaul with detailed usage, examples, API reference and best practices.
|
||||
- Add extensive silent-mode tests (test/test.silent.ts) to validate execSilent, execStrictSilent, execStreamingSilent and execAndWaitForLineSilent behaviors.
|
||||
- Update test runner and script: test script now runs tstest with --verbose, --logfile and --timeout; tests now import tapbundle from @git.zone/tstest.
|
||||
- Fix import in test/test.ts to use @git.zone/tstest/tapbundle.
|
||||
- Bump devDependencies: @git.zone/tsbuild -> ^2.6.4, @git.zone/tstest -> ^2.3.2; bump @push.rocks/smartpromise -> ^4.2.3.
|
||||
- Add typings entry and packageManager field to package.json.
|
||||
- Add project configuration files (.serena/project.yml) and local settings (.claude/settings.local.json).
|
||||
|
||||
## 2025-02-20 - 3.2.3 - fix(core)
|
||||
Refactor Smartshell class for improved code clarity and performance
|
||||
|
||||
- Refactored `_exec` method to improve code clarity.
|
||||
- Introduced `IExecOptions` interface for better type handling.
|
||||
- Replaced promise defer with native promises in command execution methods.
|
||||
- Improved logging and error handling in child process execution.
|
||||
- Ensured robust process management with signals handling.
|
||||
|
||||
## 2024-12-13 - 3.2.2 - fix(core)
|
||||
Fix minor code style and formatting issues
|
||||
|
||||
|
||||
## 2024-12-13 - 3.2.1 - fix(dependencies)
|
||||
Update @types/node dependency version
|
||||
|
||||
- Updated @types/node dependency from version ^22.10.1 to ^22.10.2.
|
||||
|
||||
## 2024-12-09 - 3.2.0 - feat(SmartExecution)
|
||||
Add support for scheduling restarts to SmartExecution
|
||||
|
||||
- Introduced the ability to handle consecutive restarts efficiently in SmartExecution.
|
||||
- Ensures that multiple restart requests merge into a single additional restart request if one is already in progress.
|
||||
|
||||
## 2024-12-09 - 3.1.0 - feat(core)
|
||||
Refactor codebase and update dependencies.
|
||||
|
||||
- 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
|
2
dist/index.d.ts
vendored
2
dist/index.d.ts
vendored
@@ -1,2 +0,0 @@
|
||||
export * from './smartshell.wrap';
|
||||
export * from './smartshell.classes.smartshell';
|
8
dist/index.js
vendored
8
dist/index.js
vendored
@@ -1,8 +0,0 @@
|
||||
"use strict";
|
||||
function __export(m) {
|
||||
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
|
||||
}
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
__export(require("./smartshell.wrap"));
|
||||
__export(require("./smartshell.classes.smartshell"));
|
||||
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi90cy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQUFBLHVDQUFpQztBQUNqQyxxREFBK0MifQ==
|
28
dist/smartshell.classes.smartshell.d.ts
vendored
28
dist/smartshell.classes.smartshell.d.ts
vendored
@@ -1,28 +0,0 @@
|
||||
import * as smartshellWrap from './smartshell.wrap';
|
||||
export declare type TExecutor = 'sh' | 'bash';
|
||||
export interface ISmartshellContructorOptions {
|
||||
executor: TExecutor;
|
||||
sourceFilePaths: string[];
|
||||
}
|
||||
export declare class Smartshell {
|
||||
executor: TExecutor;
|
||||
sourceFileArray: string[];
|
||||
constructor(optionsArg: ISmartshellContructorOptions);
|
||||
addSourceFiles(sourceFilePathsArray: string[]): void;
|
||||
cleanSourceFiles(): void;
|
||||
/**
|
||||
* executes silently and returns IExecResult
|
||||
* @param commandArg
|
||||
*/
|
||||
execSilent(commandArg: string): Promise<smartshellWrap.IExecResult>;
|
||||
/**
|
||||
* executes and returns IExecResult
|
||||
* @param commandArg
|
||||
*/
|
||||
exec(commandArg: string): Promise<smartshellWrap.IExecResult>;
|
||||
/**
|
||||
* creates the final sourcing string
|
||||
* @param commandArg
|
||||
*/
|
||||
private createExecString(commandArg);
|
||||
}
|
66
dist/smartshell.classes.smartshell.js
vendored
66
dist/smartshell.classes.smartshell.js
vendored
@@ -1,66 +0,0 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const smartshellWrap = require("./smartshell.wrap");
|
||||
class Smartshell {
|
||||
constructor(optionsArg) {
|
||||
this.sourceFileArray = [];
|
||||
this.executor = optionsArg.executor;
|
||||
for (let sourceFilePath of optionsArg.sourceFilePaths) {
|
||||
this.sourceFileArray.push(sourceFilePath);
|
||||
}
|
||||
}
|
||||
addSourceFiles(sourceFilePathsArray) {
|
||||
for (let sourceFilePath of sourceFilePathsArray) {
|
||||
this.sourceFileArray.push(sourceFilePath);
|
||||
}
|
||||
}
|
||||
cleanSourceFiles() {
|
||||
this.sourceFileArray = [];
|
||||
}
|
||||
/**
|
||||
* executes silently and returns IExecResult
|
||||
* @param commandArg
|
||||
*/
|
||||
execSilent(commandArg) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let execCommand = this.createExecString(commandArg);
|
||||
return yield smartshellWrap.execSilent(execCommand);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* executes and returns IExecResult
|
||||
* @param commandArg
|
||||
*/
|
||||
exec(commandArg) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let execCommand = this.createExecString(commandArg);
|
||||
return yield smartshellWrap.exec(execCommand);
|
||||
});
|
||||
}
|
||||
/**
|
||||
* creates the final sourcing string
|
||||
* @param commandArg
|
||||
*/
|
||||
createExecString(commandArg) {
|
||||
if (this.executor === 'bash') {
|
||||
let sourceString = '';
|
||||
for (let sourceFilePath of this.sourceFileArray) {
|
||||
sourceString = sourceString + `source ${sourceFilePath} && `;
|
||||
}
|
||||
return `bash -c '${sourceString} ${commandArg}'`;
|
||||
}
|
||||
else {
|
||||
return commandArg;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.Smartshell = Smartshell;
|
||||
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRzaGVsbC5jbGFzc2VzLnNtYXJ0c2hlbGwuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi90cy9zbWFydHNoZWxsLmNsYXNzZXMuc21hcnRzaGVsbC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7O0FBQ0Esb0RBQW1EO0FBVW5EO0lBR0UsWUFBYSxVQUF3QztRQURyRCxvQkFBZSxHQUFhLEVBQUUsQ0FBQTtRQUU1QixJQUFJLENBQUMsUUFBUSxHQUFHLFVBQVUsQ0FBQyxRQUFRLENBQUE7UUFDbkMsR0FBRyxDQUFDLENBQUMsSUFBSSxjQUFjLElBQUksVUFBVSxDQUFDLGVBQWUsQ0FBQyxDQUFDLENBQUM7WUFDdEQsSUFBSSxDQUFDLGVBQWUsQ0FBQyxJQUFJLENBQUMsY0FBYyxDQUFDLENBQUE7UUFDM0MsQ0FBQztJQUNILENBQUM7SUFFRCxjQUFjLENBQUMsb0JBQThCO1FBQzNDLEdBQUcsQ0FBQSxDQUFDLElBQUksY0FBYyxJQUFJLG9CQUFvQixDQUFDLENBQUMsQ0FBQztZQUMvQyxJQUFJLENBQUMsZUFBZSxDQUFDLElBQUksQ0FBQyxjQUFjLENBQUMsQ0FBQTtRQUMzQyxDQUFDO0lBQ0gsQ0FBQztJQUVELGdCQUFnQjtRQUNkLElBQUksQ0FBQyxlQUFlLEdBQUcsRUFBRSxDQUFBO0lBQzNCLENBQUM7SUFFRDs7O09BR0c7SUFDRyxVQUFVLENBQUUsVUFBa0I7O1lBQ2xDLElBQUksV0FBVyxHQUFHLElBQUksQ0FBQyxnQkFBZ0IsQ0FBQyxVQUFVLENBQUMsQ0FBQTtZQUNuRCxNQUFNLENBQUMsTUFBTSxjQUFjLENBQUMsVUFBVSxDQUFDLFdBQVcsQ0FBQyxDQUFBO1FBQ3JELENBQUM7S0FBQTtJQUVEOzs7T0FHRztJQUNHLElBQUksQ0FBRSxVQUFrQjs7WUFDNUIsSUFBSSxXQUFXLEdBQUcsSUFBSSxDQUFDLGdCQUFnQixDQUFDLFVBQVUsQ0FBQyxDQUFBO1lBQ25ELE1BQU0sQ0FBQyxNQUFNLGNBQWMsQ0FBQyxJQUFJLENBQUMsV0FBVyxDQUFDLENBQUE7UUFDL0MsQ0FBQztLQUFBO0lBRUQ7OztPQUdHO0lBQ0ssZ0JBQWdCLENBQUUsVUFBVTtRQUNsQyxFQUFFLENBQUMsQ0FBQyxJQUFJLENBQUMsUUFBUSxLQUFLLE1BQU0sQ0FBQyxDQUFDLENBQUM7WUFDN0IsSUFBSSxZQUFZLEdBQUcsRUFBRSxDQUFBO1lBQ3JCLEdBQUcsQ0FBQyxDQUFDLElBQUksY0FBYyxJQUFJLElBQUksQ0FBQyxlQUFlLENBQUMsQ0FBQyxDQUFDO2dCQUNoRCxZQUFZLEdBQUcsWUFBWSxHQUFHLFVBQVUsY0FBYyxNQUFNLENBQUE7WUFDOUQsQ0FBQztZQUNELE1BQU0sQ0FBQyxZQUFZLFlBQVksSUFBSSxVQUFVLEdBQUcsQ0FBQTtRQUNsRCxDQUFDO1FBQUMsSUFBSSxDQUFDLENBQUM7WUFDTixNQUFNLENBQUMsVUFBVSxDQUFBO1FBQ25CLENBQUM7SUFDSCxDQUFDO0NBQ0Y7QUFyREQsZ0NBcURDIn0=
|
4
dist/smartshell.plugins.d.ts
vendored
4
dist/smartshell.plugins.d.ts
vendored
@@ -1,4 +0,0 @@
|
||||
import * as shelljs from 'shelljs';
|
||||
import * as smartq from 'smartq';
|
||||
import * as which from 'which';
|
||||
export { shelljs, smartq, which };
|
9
dist/smartshell.plugins.js
vendored
9
dist/smartshell.plugins.js
vendored
@@ -1,9 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const shelljs = require("shelljs");
|
||||
exports.shelljs = shelljs;
|
||||
const smartq = require("smartq");
|
||||
exports.smartq = smartq;
|
||||
const which = require("which");
|
||||
exports.which = which;
|
||||
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRzaGVsbC5wbHVnaW5zLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vdHMvc21hcnRzaGVsbC5wbHVnaW5zLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsbUNBQWtDO0FBS2hDLDBCQUFPO0FBSlQsaUNBQWdDO0FBSzlCLHdCQUFNO0FBSlIsK0JBQThCO0FBSzVCLHNCQUFLIn0=
|
43
dist/smartshell.wrap.d.ts
vendored
43
dist/smartshell.wrap.d.ts
vendored
@@ -1,43 +0,0 @@
|
||||
/// <reference types="node" />
|
||||
import { ChildProcess } from 'child_process';
|
||||
/**
|
||||
* interface for ExecResult
|
||||
*/
|
||||
export interface IExecResult {
|
||||
exitCode: number;
|
||||
stdout: string;
|
||||
}
|
||||
/**
|
||||
* interface for streaming ExecResult
|
||||
*/
|
||||
export interface IExecResultStreaming {
|
||||
childProcess: ChildProcess;
|
||||
finalPromise: Promise<IExecResult>;
|
||||
}
|
||||
/**
|
||||
* executes a given command async
|
||||
* @param commandStringArg
|
||||
*/
|
||||
export declare let exec: (commandStringArg: string) => Promise<IExecResult>;
|
||||
/**
|
||||
* executes a given command async and silent
|
||||
* @param commandStringArg
|
||||
*/
|
||||
export declare let execSilent: (commandStringArg: string) => Promise<IExecResult>;
|
||||
/**
|
||||
* executes a command and allws you to stream output
|
||||
*/
|
||||
export declare let execStreaming: (commandStringArg: string) => {
|
||||
childProcess: ChildProcess;
|
||||
finalPromise: Promise<IExecResult>;
|
||||
};
|
||||
/**
|
||||
* executes a command and returns promise that will be fullfilled once an putput line matches RegexArg
|
||||
* @param commandStringArg
|
||||
* @param regexArg
|
||||
*/
|
||||
export declare let execAndWaitForLine: (commandStringArg: string, regexArg: RegExp) => Promise<{}>;
|
||||
/**
|
||||
* get a path
|
||||
*/
|
||||
export declare let which: (cmd: string) => Promise<string>;
|
76
dist/smartshell.wrap.js
vendored
76
dist/smartshell.wrap.js
vendored
@@ -1,76 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const plugins = require("./smartshell.plugins");
|
||||
/**
|
||||
* executes a given command async
|
||||
* @param commandStringArg
|
||||
*/
|
||||
exports.exec = (commandStringArg) => {
|
||||
let done = plugins.smartq.defer();
|
||||
plugins.shelljs.exec(commandStringArg, { async: true }, (code, stdout, stderr) => {
|
||||
done.resolve({
|
||||
exitCode: code,
|
||||
stdout: stdout
|
||||
});
|
||||
});
|
||||
return done.promise;
|
||||
};
|
||||
/**
|
||||
* executes a given command async and silent
|
||||
* @param commandStringArg
|
||||
*/
|
||||
exports.execSilent = (commandStringArg) => {
|
||||
let done = plugins.smartq.defer();
|
||||
plugins.shelljs.exec(commandStringArg, { async: true, silent: true }, (code, stdout, stderr) => {
|
||||
done.resolve({
|
||||
exitCode: code,
|
||||
stdout: stdout
|
||||
});
|
||||
});
|
||||
return done.promise;
|
||||
};
|
||||
/**
|
||||
* executes a command and allws you to stream output
|
||||
*/
|
||||
exports.execStreaming = (commandStringArg) => {
|
||||
let childProcessEnded = plugins.smartq.defer();
|
||||
let execChildProcess = plugins.shelljs.exec(commandStringArg, { async: true, silent: true }, (code, stdout, stderr) => {
|
||||
childProcessEnded.resolve({
|
||||
exitCode: code,
|
||||
stdout: stdout
|
||||
});
|
||||
});
|
||||
return {
|
||||
childProcess: execChildProcess,
|
||||
finalPromise: childProcessEnded.promise
|
||||
};
|
||||
};
|
||||
/**
|
||||
* executes a command and returns promise that will be fullfilled once an putput line matches RegexArg
|
||||
* @param commandStringArg
|
||||
* @param regexArg
|
||||
*/
|
||||
exports.execAndWaitForLine = (commandStringArg, regexArg) => {
|
||||
let done = plugins.smartq.defer();
|
||||
let execStreamingResult = exports.execStreaming(commandStringArg);
|
||||
execStreamingResult.childProcess.on('data', (stdOutChunk) => {
|
||||
if (regexArg.test(stdOutChunk)) {
|
||||
done.resolve();
|
||||
}
|
||||
});
|
||||
return done.promise;
|
||||
};
|
||||
/**
|
||||
* get a path
|
||||
*/
|
||||
exports.which = (cmd) => {
|
||||
let done = plugins.smartq.defer();
|
||||
plugins.which(cmd, (err, path) => {
|
||||
if (err) {
|
||||
done.reject(err);
|
||||
}
|
||||
done.resolve(path);
|
||||
});
|
||||
return done.promise;
|
||||
};
|
||||
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRzaGVsbC53cmFwLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vdHMvc21hcnRzaGVsbC53cmFwLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsZ0RBQStDO0FBc0IvQzs7O0dBR0c7QUFDUSxRQUFBLElBQUksR0FBRyxDQUFDLGdCQUF3QjtJQUN6QyxJQUFJLElBQUksR0FBRyxPQUFPLENBQUMsTUFBTSxDQUFDLEtBQUssRUFBZSxDQUFBO0lBQzlDLE9BQU8sQ0FBQyxPQUFPLENBQUMsSUFBSSxDQUFDLGdCQUFnQixFQUFFLEVBQUUsS0FBSyxFQUFFLElBQUksRUFBRSxFQUFFLENBQUMsSUFBSSxFQUFFLE1BQU0sRUFBRSxNQUFNO1FBQzNFLElBQUksQ0FBQyxPQUFPLENBQUM7WUFDWCxRQUFRLEVBQUUsSUFBSTtZQUNkLE1BQU0sRUFBRSxNQUFNO1NBQ2YsQ0FBQyxDQUFBO0lBQ0osQ0FBQyxDQUFDLENBQUE7SUFDRixNQUFNLENBQUMsSUFBSSxDQUFDLE9BQU8sQ0FBQTtBQUNyQixDQUFDLENBQUE7QUFFRDs7O0dBR0c7QUFDUSxRQUFBLFVBQVUsR0FBRyxDQUFDLGdCQUF3QjtJQUMvQyxJQUFJLElBQUksR0FBRyxPQUFPLENBQUMsTUFBTSxDQUFDLEtBQUssRUFBZSxDQUFBO0lBQzlDLE9BQU8sQ0FBQyxPQUFPLENBQUMsSUFBSSxDQUFDLGdCQUFnQixFQUFFLEVBQUUsS0FBSyxFQUFFLElBQUksRUFBRSxNQUFNLEVBQUUsSUFBSSxFQUFFLEVBQUUsQ0FBQyxJQUFJLEVBQUUsTUFBTSxFQUFFLE1BQU07UUFDekYsSUFBSSxDQUFDLE9BQU8sQ0FBQztZQUNYLFFBQVEsRUFBRSxJQUFJO1lBQ2QsTUFBTSxFQUFFLE1BQU07U0FDZixDQUFDLENBQUE7SUFDSixDQUFDLENBQUMsQ0FBQTtJQUNGLE1BQU0sQ0FBQyxJQUFJLENBQUMsT0FBTyxDQUFBO0FBQ3JCLENBQUMsQ0FBQTtBQUVEOztHQUVHO0FBQ1EsUUFBQSxhQUFhLEdBQUcsQ0FBQyxnQkFBd0I7SUFDbEQsSUFBSSxpQkFBaUIsR0FBRyxPQUFPLENBQUMsTUFBTSxDQUFDLEtBQUssRUFBZSxDQUFBO0lBQzNELElBQUksZ0JBQWdCLEdBQUcsT0FBTyxDQUFDLE9BQU8sQ0FBQyxJQUFJLENBQUMsZ0JBQWdCLEVBQUUsRUFBQyxLQUFLLEVBQUUsSUFBSSxFQUFFLE1BQU0sRUFBRSxJQUFJLEVBQUMsRUFBRSxDQUFDLElBQUksRUFBRSxNQUFNLEVBQUUsTUFBTTtRQUM5RyxpQkFBaUIsQ0FBQyxPQUFPLENBQUM7WUFDeEIsUUFBUSxFQUFFLElBQUk7WUFDZCxNQUFNLEVBQUUsTUFBTTtTQUNmLENBQUMsQ0FBQTtJQUNKLENBQUMsQ0FBQyxDQUFBO0lBQ0YsTUFBTSxDQUFDO1FBQ0wsWUFBWSxFQUFFLGdCQUFnQjtRQUM5QixZQUFZLEVBQUUsaUJBQWlCLENBQUMsT0FBTztLQUN4QyxDQUFBO0FBQ0gsQ0FBQyxDQUFBO0FBRUQ7Ozs7R0FJRztBQUNRLFFBQUEsa0JBQWtCLEdBQUcsQ0FBQyxnQkFBd0IsRUFBRSxRQUFnQjtJQUN6RSxJQUFJLElBQUksR0FBRyxPQUFPLENBQUMsTUFBTSxDQUFDLEtBQUssRUFBRSxDQUFBO0lBQ2pDLElBQUksbUJBQW1CLEdBQUcscUJBQWEsQ0FBQyxnQkFBZ0IsQ0FBQyxDQUFBO0lBQ3pELG1CQUFtQixDQUFDLFlBQVksQ0FBQyxFQUFFLENBQUMsTUFBTSxFQUFFLENBQUMsV0FBbUI7UUFDOUQsRUFBRSxDQUFDLENBQUMsUUFBUSxDQUFDLElBQUksQ0FBQyxXQUFXLENBQUMsQ0FBQyxDQUFDLENBQUM7WUFDL0IsSUFBSSxDQUFDLE9BQU8sRUFBRSxDQUFBO1FBQ2hCLENBQUM7SUFDSCxDQUFDLENBQUMsQ0FBQTtJQUNGLE1BQU0sQ0FBQyxJQUFJLENBQUMsT0FBTyxDQUFBO0FBQ3JCLENBQUMsQ0FBQTtBQUVEOztHQUVHO0FBQ1EsUUFBQSxLQUFLLEdBQUcsQ0FBQyxHQUFXO0lBQzdCLElBQUksSUFBSSxHQUFHLE9BQU8sQ0FBQyxNQUFNLENBQUMsS0FBSyxFQUFFLENBQUE7SUFDakMsT0FBTyxDQUFDLEtBQUssQ0FBQyxHQUFHLEVBQUUsQ0FBQyxHQUFHLEVBQUUsSUFBWTtRQUNuQyxFQUFFLENBQUMsQ0FBQyxHQUFHLENBQUMsQ0FBQyxDQUFDO1lBQ1IsSUFBSSxDQUFDLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQTtRQUNsQixDQUFDO1FBQ0QsSUFBSSxDQUFDLE9BQU8sQ0FBQyxJQUFJLENBQUMsQ0FBQTtJQUNwQixDQUFDLENBQUMsQ0FBQTtJQUNGLE1BQU0sQ0FBQyxJQUFJLENBQUMsT0FBTyxDQUFBO0FBQ3JCLENBQUMsQ0FBQSJ9
|
@@ -1,7 +1,32 @@
|
||||
{
|
||||
"npmci": {
|
||||
"globalNpmTools": [
|
||||
"npmts"
|
||||
]
|
||||
"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"
|
||||
}
|
||||
}
|
66
package.json
66
package.json
@@ -1,35 +1,65 @@
|
||||
{
|
||||
"name": "smartshell",
|
||||
"version": "1.0.6",
|
||||
"description": "shell actions designed as promises",
|
||||
"main": "dist/index.js",
|
||||
"typings": "dist/index.d.ts",
|
||||
"name": "@push.rocks/smartshell",
|
||||
"private": false,
|
||||
"version": "3.3.0",
|
||||
"description": "A library for executing shell commands using promises.",
|
||||
"main": "dist_ts/index.js",
|
||||
"typings": "dist_ts/index.d.ts",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "(npmts)"
|
||||
"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": {
|
||||
"tapbundle": "^1.0.14"
|
||||
"@git.zone/tsbuild": "^2.6.4",
|
||||
"@git.zone/tsrun": "^1.3.3",
|
||||
"@git.zone/tstest": "^2.3.2",
|
||||
"@types/node": "^22.10.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@types/shelljs": "^0.7.2",
|
||||
"@types/which": "^1.0.28",
|
||||
"shelljs": "^0.7.8",
|
||||
"smartq": "^1.1.1",
|
||||
"typings-global": "^1.0.19",
|
||||
"which": "^1.2.14"
|
||||
}
|
||||
"@push.rocks/smartdelay": "^3.0.1",
|
||||
"@push.rocks/smartexit": "^1.0.23",
|
||||
"@push.rocks/smartpromise": "^4.2.3",
|
||||
"@types/which": "^3.0.4",
|
||||
"tree-kill": "^1.2.2",
|
||||
"which": "^5.0.0"
|
||||
},
|
||||
"files": [
|
||||
"ts/**/*",
|
||||
"ts_web/**/*",
|
||||
"dist/**/*",
|
||||
"dist_*/**/*",
|
||||
"dist_ts/**/*",
|
||||
"dist_ts_web/**/*",
|
||||
"assets/**/*",
|
||||
"cli.js",
|
||||
"npmextra.json",
|
||||
"readme.md"
|
||||
],
|
||||
"browserslist": [
|
||||
"last 1 chrome versions"
|
||||
],
|
||||
"packageManager": "pnpm@10.14.0+sha512.ad27a79641b49c3e481a16a805baa71817a04bbe06a38d17e60e2eaee83f6a146c6a688125f5792e48dd5ba30e7da52a5cda4c3992b9ccf333f9ce223af84748"
|
||||
}
|
||||
|
9817
pnpm-lock.yaml
generated
Normal file
9817
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
1
readme.hints.md
Normal file
1
readme.hints.md
Normal file
@@ -0,0 +1 @@
|
||||
|
633
readme.md
Normal file
633
readme.md
Normal file
@@ -0,0 +1,633 @@
|
||||
# @push.rocks/smartshell 🐚
|
||||
**Execute shell commands with superpowers in Node.js**
|
||||
|
||||
[](https://www.npmjs.com/package/@push.rocks/smartshell)
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
|
||||
## ⚠️ Security Notice
|
||||
|
||||
**IMPORTANT:** Please read the [Security Guide](#security-guide) below for critical information about command execution and input handling. Always use `execSpawn` methods for untrusted input.
|
||||
|
||||
## Why smartshell? 🚀
|
||||
|
||||
Tired of wrestling with Node.js child processes? Meet `@push.rocks/smartshell` - your promise-based shell command companion that makes executing system commands feel like a breeze. Whether you're building automation scripts, CI/CD pipelines, or need fine-grained control over shell execution, smartshell has got you covered.
|
||||
|
||||
### ✨ Key Features
|
||||
|
||||
- 🎯 **Promise-based API** - Async/await ready for modern codebases
|
||||
- 🔇 **Silent execution modes** - Control output verbosity
|
||||
- 📡 **Streaming support** - Real-time output for long-running processes
|
||||
- 🎮 **Interactive commands** - Handle user input programmatically
|
||||
- 🛡️ **Secure execution** - Shell-free methods for untrusted input
|
||||
- ⚡ **Smart execution modes** - Strict, silent, or streaming
|
||||
- 🔍 **Pattern matching** - Wait for specific output patterns
|
||||
- 🌍 **Environment management** - Custom env vars and PATH handling
|
||||
- 💾 **Memory protection** - Built-in buffer limits prevent OOM
|
||||
- ⏱️ **Timeout support** - Automatic process termination
|
||||
- 🖥️ **PTY support** - Full terminal emulation (optional)
|
||||
- 🎨 **Cross-platform** - Windows, macOS, and Linux ready
|
||||
- 🛡️ **TypeScript first** - Full type safety and IntelliSense
|
||||
|
||||
## Installation 📦
|
||||
|
||||
```bash
|
||||
# Using npm
|
||||
npm install @push.rocks/smartshell --save
|
||||
|
||||
# Using yarn
|
||||
yarn add @push.rocks/smartshell
|
||||
|
||||
# Using pnpm (recommended)
|
||||
pnpm add @push.rocks/smartshell
|
||||
|
||||
# Optional: For PTY support (terminal emulation)
|
||||
pnpm add --save-optional node-pty
|
||||
```
|
||||
|
||||
## Quick Start 🏃♂️
|
||||
|
||||
```typescript
|
||||
import { Smartshell } from '@push.rocks/smartshell';
|
||||
|
||||
// Create your shell instance
|
||||
const shell = new Smartshell({
|
||||
executor: 'bash' // or 'sh' for lighter shells
|
||||
});
|
||||
|
||||
// Run a simple command
|
||||
const result = await shell.exec('echo "Hello, World!"');
|
||||
console.log(result.stdout); // "Hello, World!"
|
||||
console.log(result.signal); // undefined (no signal)
|
||||
console.log(result.stderr); // "" (no errors)
|
||||
```
|
||||
|
||||
## Security-First Execution 🔒
|
||||
|
||||
### Secure Command Execution with execSpawn
|
||||
|
||||
When dealing with untrusted input, **always use execSpawn methods** which don't use shell interpretation:
|
||||
|
||||
```typescript
|
||||
// ❌ DANGEROUS with untrusted input
|
||||
const userInput = "file.txt; rm -rf /";
|
||||
await shell.exec(`cat ${userInput}`); // Command injection!
|
||||
|
||||
// ✅ SAFE with untrusted input
|
||||
await shell.execSpawn('cat', [userInput]); // Arguments are properly escaped
|
||||
```
|
||||
|
||||
### execSpawn Family Methods
|
||||
|
||||
```typescript
|
||||
// Basic secure execution
|
||||
const result = await shell.execSpawn('ls', ['-la', '/home']);
|
||||
|
||||
// Streaming secure execution
|
||||
const streaming = await shell.execSpawnStreaming('npm', ['install']);
|
||||
await streaming.finalPromise;
|
||||
|
||||
// Interactive secure execution
|
||||
const interactive = await shell.execSpawnInteractiveControl('cat', []);
|
||||
await interactive.sendLine('Hello');
|
||||
interactive.endInput();
|
||||
await interactive.finalPromise;
|
||||
```
|
||||
|
||||
## Production Features 🏭
|
||||
|
||||
### Resource Management
|
||||
|
||||
Prevent memory issues with built-in buffer limits:
|
||||
|
||||
```typescript
|
||||
const result = await shell.exec('large-output-command', {
|
||||
maxBuffer: 10 * 1024 * 1024, // 10MB limit
|
||||
onData: (chunk) => {
|
||||
// Process chunks as they arrive
|
||||
console.log('Received:', chunk.toString());
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Timeout Support
|
||||
|
||||
Automatically terminate long-running processes:
|
||||
|
||||
```typescript
|
||||
try {
|
||||
const result = await shell.execSpawn('long-process', [], {
|
||||
timeout: 5000 // 5 second timeout
|
||||
});
|
||||
} catch (error) {
|
||||
console.log('Process timed out');
|
||||
}
|
||||
```
|
||||
|
||||
### Debug Mode
|
||||
|
||||
Enable detailed logging for troubleshooting:
|
||||
|
||||
```typescript
|
||||
const result = await shell.exec('command', {
|
||||
debug: true // Logs process lifecycle events
|
||||
});
|
||||
```
|
||||
|
||||
### Custom Environment
|
||||
|
||||
Control the execution environment precisely:
|
||||
|
||||
```typescript
|
||||
const result = await shell.execSpawn('node', ['script.js'], {
|
||||
env: {
|
||||
NODE_ENV: 'production',
|
||||
PATH: '/usr/bin:/bin',
|
||||
CUSTOM_VAR: 'value'
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Interactive Control 🎮
|
||||
|
||||
### Programmatic Input Control
|
||||
|
||||
Send input to processes programmatically:
|
||||
|
||||
```typescript
|
||||
const interactive = await shell.execInteractiveControl('cat');
|
||||
|
||||
// Send input line by line
|
||||
await interactive.sendLine('Line 1');
|
||||
await interactive.sendLine('Line 2');
|
||||
|
||||
// Send raw input without newline
|
||||
await interactive.sendInput('partial');
|
||||
|
||||
// Close stdin
|
||||
interactive.endInput();
|
||||
|
||||
// Wait for completion
|
||||
const result = await interactive.finalPromise;
|
||||
```
|
||||
|
||||
### Passthrough Mode
|
||||
|
||||
Connect stdin for real keyboard interaction:
|
||||
|
||||
```typescript
|
||||
// User can type directly
|
||||
await shell.execPassthrough('vim file.txt');
|
||||
```
|
||||
|
||||
## PTY Support - Full Terminal Emulation 🖥️
|
||||
|
||||
Smartshell provides two modes for executing interactive commands:
|
||||
|
||||
1. **Pipe Mode (Default)** - Fast, simple, no dependencies
|
||||
2. **PTY Mode** - Full terminal emulation for advanced interactive programs
|
||||
|
||||
### When to Use Each Mode
|
||||
|
||||
#### Use Pipe Mode (Default) When:
|
||||
- Running simple commands that read from stdin
|
||||
- Using tools like `cat`, `grep`, `sed`, `awk`
|
||||
- Running basic scripts that don't need terminal features
|
||||
- You want maximum performance and simplicity
|
||||
- You don't want native dependencies
|
||||
|
||||
#### Use PTY Mode When:
|
||||
- Running commands that require a real terminal:
|
||||
- Password prompts (`sudo`, `ssh`, `su`)
|
||||
- Interactive editors (`vim`, `nano`, `emacs`)
|
||||
- Terminal UIs (`htop`, `less`, `more`)
|
||||
- Programs with fancy prompts (`bash read -p`)
|
||||
- Tab completion and readline features
|
||||
- You need terminal features:
|
||||
- ANSI colors and escape sequences
|
||||
- Terminal size control
|
||||
- Signal handling (Ctrl+C, Ctrl+Z)
|
||||
- Line discipline and special key handling
|
||||
|
||||
### Installing PTY Support
|
||||
|
||||
PTY support requires the optional `node-pty` dependency:
|
||||
|
||||
```bash
|
||||
# Install as optional dependency
|
||||
pnpm add --save-optional node-pty
|
||||
|
||||
# Note: node-pty requires compilation and has platform-specific requirements
|
||||
# - On Windows: Requires Visual Studio Build Tools
|
||||
# - On macOS/Linux: Requires Python and build tools
|
||||
```
|
||||
|
||||
### PTY Usage Examples
|
||||
|
||||
```typescript
|
||||
// Use PTY for commands that need terminal features
|
||||
const ptyInteractive = await shell.execInteractiveControlPty(
|
||||
"bash -c 'read -p \"Enter name: \" name && echo \"Hello, $name\"'"
|
||||
);
|
||||
await ptyInteractive.sendLine('John');
|
||||
const result = await ptyInteractive.finalPromise;
|
||||
// With PTY, the prompt "Enter name: " will be visible in stdout
|
||||
|
||||
// Streaming with PTY for real-time interaction
|
||||
const ptyStreaming = await shell.execStreamingInteractiveControlPty('vim test.txt');
|
||||
await ptyStreaming.sendInput('i'); // Enter insert mode
|
||||
await ptyStreaming.sendInput('Hello from PTY!');
|
||||
await ptyStreaming.sendInput('\x1b'); // ESC key
|
||||
await ptyStreaming.sendInput(':wq\r'); // Save and quit
|
||||
```
|
||||
|
||||
### PTY vs Pipe Mode Comparison
|
||||
|
||||
| Feature | Pipe Mode | PTY Mode |
|
||||
|---------|-----------|----------|
|
||||
| Dependencies | None | node-pty |
|
||||
| Terminal Detection | `isatty()` returns false | `isatty()` returns true |
|
||||
| Prompt Display | May not show | Always shows |
|
||||
| Colors | Often disabled | Enabled |
|
||||
| Signal Handling | Basic | Full (Ctrl+C, Ctrl+Z, etc.) |
|
||||
| Line Ending | `\n` | `\r` (carriage return) |
|
||||
| EOF Signal | Stream end | `\x04` (Ctrl+D) |
|
||||
|
||||
### Common PTY Patterns
|
||||
|
||||
```typescript
|
||||
// Password input (PTY required)
|
||||
const sudo = await shell.execInteractiveControlPty('sudo ls /root');
|
||||
await sudo.sendLine('mypassword');
|
||||
const result = await sudo.finalPromise;
|
||||
|
||||
// Interactive REPL with colors
|
||||
const node = await shell.execStreamingInteractiveControlPty('node');
|
||||
await node.sendLine('console.log("PTY supports colors!")');
|
||||
await node.sendLine('.exit');
|
||||
|
||||
// Handling terminal colors
|
||||
const ls = await shell.execInteractiveControlPty('ls --color=always');
|
||||
const result = await ls.finalPromise;
|
||||
// result.stdout will contain ANSI color codes
|
||||
```
|
||||
|
||||
### PTY Fallback Strategy
|
||||
|
||||
Always provide a fallback for when PTY isn't available:
|
||||
|
||||
```typescript
|
||||
try {
|
||||
// Try PTY mode first
|
||||
const result = await shell.execInteractiveControlPty(command);
|
||||
// ...
|
||||
} catch (error) {
|
||||
if (error.message.includes('node-pty')) {
|
||||
// Fallback to pipe mode
|
||||
console.warn('PTY not available, using pipe mode');
|
||||
const result = await shell.execInteractiveControl(command);
|
||||
// ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Advanced Pattern Matching 🔍
|
||||
|
||||
### Enhanced execAndWaitForLine
|
||||
|
||||
Wait for patterns with timeout and auto-termination:
|
||||
|
||||
```typescript
|
||||
// Wait with timeout
|
||||
await shell.execAndWaitForLine(
|
||||
'npm start',
|
||||
/Server listening on port/,
|
||||
false, // silent
|
||||
{
|
||||
timeout: 30000, // 30 second timeout
|
||||
terminateOnMatch: true // Kill process after match
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
## Core Concepts 💡
|
||||
|
||||
### The Smartshell Instance
|
||||
|
||||
The heart of smartshell is the `Smartshell` class. Each instance maintains its own environment and configuration:
|
||||
|
||||
```typescript
|
||||
const shell = new Smartshell({
|
||||
executor: 'bash', // Choose your shell: 'bash' or 'sh'
|
||||
sourceFilePaths: ['/path/to/env.sh'], // Optional: source files on init
|
||||
});
|
||||
```
|
||||
|
||||
## Execution Modes 🎛️
|
||||
|
||||
### Standard Execution
|
||||
|
||||
Perfect for general commands where you want to see the output:
|
||||
|
||||
```typescript
|
||||
const result = await shell.exec('ls -la');
|
||||
console.log(result.stdout); // Directory listing
|
||||
console.log(result.exitCode); // 0 for success
|
||||
console.log(result.signal); // Signal if terminated
|
||||
console.log(result.stderr); // Error output
|
||||
```
|
||||
|
||||
### Silent Execution
|
||||
|
||||
Run commands without printing to console - ideal for capturing output:
|
||||
|
||||
```typescript
|
||||
const result = await shell.execSilent('cat /etc/hostname');
|
||||
// Output is NOT printed to console but IS captured in result
|
||||
console.log(result.stdout); // Access the captured output here
|
||||
```
|
||||
|
||||
### Strict Execution
|
||||
|
||||
Throws an error if the command fails - great for critical operations:
|
||||
|
||||
```typescript
|
||||
try {
|
||||
await shell.execStrict('critical-command');
|
||||
console.log('✅ Command succeeded!');
|
||||
} catch (error) {
|
||||
console.error('❌ Command failed:', error.message);
|
||||
// Error includes exit code or signal information
|
||||
}
|
||||
```
|
||||
|
||||
### Streaming Execution
|
||||
|
||||
For long-running processes or when you need real-time output:
|
||||
|
||||
```typescript
|
||||
const streaming = await shell.execStreaming('npm install');
|
||||
|
||||
// Access the child process directly
|
||||
streaming.childProcess.stdout.on('data', (chunk) => {
|
||||
console.log('📦 Installing:', chunk.toString());
|
||||
});
|
||||
|
||||
// Control the process
|
||||
await streaming.terminate(); // SIGTERM
|
||||
await streaming.kill(); // SIGKILL
|
||||
await streaming.keyboardInterrupt(); // SIGINT
|
||||
|
||||
// Wait for completion
|
||||
await streaming.finalPromise;
|
||||
```
|
||||
|
||||
## Real-World Examples 🌍
|
||||
|
||||
### Build Pipeline
|
||||
|
||||
```typescript
|
||||
const shell = new Smartshell({ executor: 'bash' });
|
||||
|
||||
// Clean build directory
|
||||
await shell.execSilent('rm -rf dist');
|
||||
|
||||
// Run TypeScript compiler
|
||||
const buildResult = await shell.execStrict('tsc');
|
||||
|
||||
// Run tests
|
||||
await shell.execStrict('npm test');
|
||||
|
||||
// Build succeeded!
|
||||
console.log('✅ Build pipeline completed successfully');
|
||||
```
|
||||
|
||||
### CI/CD with Security
|
||||
|
||||
```typescript
|
||||
async function deployApp(branch: string, untrustedTag: string) {
|
||||
const shell = new Smartshell({ executor: 'bash' });
|
||||
|
||||
// Use execSpawn for untrusted input
|
||||
await shell.execSpawnStrict('git', ['checkout', branch]);
|
||||
await shell.execSpawnStrict('git', ['tag', untrustedTag]);
|
||||
|
||||
// Safe to use exec for hardcoded commands
|
||||
await shell.execStrict('npm run build');
|
||||
await shell.execStrict('npm run deploy');
|
||||
}
|
||||
```
|
||||
|
||||
### Docker Compose Helper
|
||||
|
||||
```typescript
|
||||
const shell = new Smartshell({ executor: 'bash' });
|
||||
|
||||
// Start services and wait for readiness
|
||||
console.log('🐳 Starting Docker services...');
|
||||
await shell.execAndWaitForLine(
|
||||
'docker-compose up',
|
||||
/All services are ready/,
|
||||
false,
|
||||
{
|
||||
timeout: 60000,
|
||||
terminateOnMatch: false // Keep running after match
|
||||
}
|
||||
);
|
||||
|
||||
// Run migrations
|
||||
await shell.execStrict('docker-compose exec app npm run migrate');
|
||||
console.log('✅ Environment ready!');
|
||||
```
|
||||
|
||||
### Development Server with Auto-Restart
|
||||
|
||||
```typescript
|
||||
import { SmartExecution } from '@push.rocks/smartshell';
|
||||
|
||||
const shell = new Smartshell({ executor: 'bash' });
|
||||
const devServer = new SmartExecution(shell, 'npm run dev');
|
||||
|
||||
// Watch for file changes and restart
|
||||
fs.watch('./src', async () => {
|
||||
console.log('🔄 Changes detected, restarting...');
|
||||
await devServer.restart();
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference 📚
|
||||
|
||||
### Smartshell Class
|
||||
|
||||
| Method | Description | Security |
|
||||
|--------|-------------|----------|
|
||||
| `exec(command)` | Execute with shell | ⚠️ Vulnerable to injection |
|
||||
| `execSpawn(cmd, args)` | Execute without shell | ✅ Safe for untrusted input |
|
||||
| `execSilent(command)` | Execute without console output | ⚠️ Vulnerable to injection |
|
||||
| `execStrict(command)` | Execute, throw on failure | ⚠️ Vulnerable to injection |
|
||||
| `execStreaming(command)` | Stream output in real-time | ⚠️ Vulnerable to injection |
|
||||
| `execSpawnStreaming(cmd, args)` | Stream without shell | ✅ Safe for untrusted input |
|
||||
| `execInteractive(command)` | Interactive terminal mode | ⚠️ Vulnerable to injection |
|
||||
| `execInteractiveControl(command)` | Programmatic input control | ⚠️ Vulnerable to injection |
|
||||
| `execSpawnInteractiveControl(cmd, args)` | Programmatic control without shell | ✅ Safe for untrusted input |
|
||||
| `execPassthrough(command)` | Connect stdin passthrough | ⚠️ Vulnerable to injection |
|
||||
| `execInteractiveControlPty(command)` | PTY with programmatic control | ⚠️ Vulnerable to injection |
|
||||
| `execStreamingInteractiveControlPty(command)` | PTY streaming with control | ⚠️ Vulnerable to injection |
|
||||
| `execAndWaitForLine(cmd, regex, silent, opts)` | Wait for pattern match | ⚠️ Vulnerable to injection |
|
||||
|
||||
### Result Interfaces
|
||||
|
||||
```typescript
|
||||
interface IExecResult {
|
||||
exitCode: number; // Process exit code
|
||||
stdout: string; // Standard output
|
||||
signal?: NodeJS.Signals; // Termination signal
|
||||
stderr?: string; // Error output
|
||||
}
|
||||
|
||||
interface IExecResultStreaming {
|
||||
childProcess: ChildProcess; // Node.js ChildProcess instance
|
||||
finalPromise: Promise<IExecResult>; // Resolves when process exits
|
||||
sendInput: (input: string) => Promise<void>;
|
||||
sendLine: (line: string) => Promise<void>;
|
||||
endInput: () => void;
|
||||
kill: () => Promise<void>;
|
||||
terminate: () => Promise<void>;
|
||||
keyboardInterrupt: () => Promise<void>;
|
||||
customSignal: (signal: NodeJS.Signals) => Promise<void>;
|
||||
}
|
||||
|
||||
interface IExecResultInteractive extends IExecResult {
|
||||
sendInput: (input: string) => Promise<void>;
|
||||
sendLine: (line: string) => Promise<void>;
|
||||
endInput: () => void;
|
||||
finalPromise: Promise<IExecResult>;
|
||||
}
|
||||
```
|
||||
|
||||
### Options Interface
|
||||
|
||||
```typescript
|
||||
interface IExecOptions {
|
||||
silent?: boolean; // Suppress console output
|
||||
strict?: boolean; // Throw on non-zero exit
|
||||
streaming?: boolean; // Return streaming interface
|
||||
interactive?: boolean; // Interactive mode
|
||||
passthrough?: boolean; // Connect stdin
|
||||
interactiveControl?: boolean; // Programmatic input
|
||||
usePty?: boolean; // Use pseudo-terminal
|
||||
ptyShell?: string; // Custom PTY shell
|
||||
ptyCols?: number; // PTY columns (default 120)
|
||||
ptyRows?: number; // PTY rows (default 30)
|
||||
ptyTerm?: string; // Terminal type (default 'xterm-256color')
|
||||
maxBuffer?: number; // Max output buffer (bytes)
|
||||
onData?: (chunk: Buffer | string) => void; // Data callback
|
||||
timeout?: number; // Execution timeout (ms)
|
||||
debug?: boolean; // Enable debug logging
|
||||
env?: NodeJS.ProcessEnv; // Custom environment
|
||||
signal?: AbortSignal; // Abort signal
|
||||
}
|
||||
```
|
||||
|
||||
## Security Guide
|
||||
|
||||
### Command Injection Prevention
|
||||
|
||||
The standard `exec` methods use `shell: true`, which can lead to command injection vulnerabilities:
|
||||
|
||||
```typescript
|
||||
// ❌ DANGEROUS - Never do this with untrusted input
|
||||
const userInput = "file.txt; rm -rf /";
|
||||
await smartshell.exec(`cat ${userInput}`); // Will execute rm -rf /
|
||||
|
||||
// ✅ SAFE - Arguments are properly escaped
|
||||
await smartshell.execSpawn('cat', [userInput]); // Will look for literal filename
|
||||
```
|
||||
|
||||
### Best Practices
|
||||
|
||||
1. **Always validate input**: Even with secure methods, validate user input
|
||||
2. **Use execSpawn for untrusted data**: Never pass user input to shell-based methods
|
||||
3. **Set resource limits**: Use `maxBuffer` and `timeout` for untrusted commands
|
||||
4. **Control environment**: Don't inherit all env vars for sensitive operations
|
||||
5. **Restrict signals**: Only allow specific signals from user input
|
||||
|
||||
### Path Traversal Protection
|
||||
|
||||
```typescript
|
||||
// ❌ VULNERABLE
|
||||
const file = userInput; // Could be "../../../etc/passwd"
|
||||
await shell.exec(`cat ${file}`);
|
||||
|
||||
// ✅ SECURE
|
||||
const path = require('path');
|
||||
const safePath = path.join('/allowed/directory', path.basename(userInput));
|
||||
await shell.execSpawn('cat', [safePath]);
|
||||
```
|
||||
|
||||
## Tips & Best Practices 💎
|
||||
|
||||
1. **Security first**: Use `execSpawn` for any untrusted input
|
||||
2. **Set resource limits**: Always use `maxBuffer` and `timeout` for untrusted commands
|
||||
3. **Choose the right executor**: Use `bash` for full features, `sh` for minimal overhead
|
||||
4. **Use strict mode for critical operations**: Ensures failures don't go unnoticed
|
||||
5. **Stream long-running processes**: Better UX and memory efficiency
|
||||
6. **Leverage silent modes**: When you only need to capture output
|
||||
7. **Handle errors gracefully**: Check both `exitCode` and `signal`
|
||||
8. **Clean up resources**: Streaming processes should be properly terminated
|
||||
9. **Control environment**: Don't inherit all env vars for sensitive operations
|
||||
10. **Enable debug mode**: For development and troubleshooting
|
||||
11. **Use PTY for terminal UIs**: When programs need real terminal features
|
||||
12. **Provide fallbacks**: Always handle PTY unavailability gracefully
|
||||
|
||||
## Environment Customization
|
||||
|
||||
Smartshell provides powerful environment management:
|
||||
|
||||
```typescript
|
||||
// Add custom source files
|
||||
shell.shellEnv.addSourceFiles([
|
||||
'/home/user/.custom_env',
|
||||
'./project.env.sh'
|
||||
]);
|
||||
|
||||
// Modify PATH
|
||||
shell.shellEnv.pathDirArray.push('/custom/bin');
|
||||
shell.shellEnv.pathDirArray.push('/usr/local/special');
|
||||
|
||||
// Your custom environment is ready
|
||||
const result = await shell.exec('my-custom-command');
|
||||
```
|
||||
|
||||
## Shell Detection
|
||||
|
||||
Need to check if a command exists? We export the `which` utility:
|
||||
|
||||
```typescript
|
||||
import { which } from '@push.rocks/smartshell';
|
||||
|
||||
try {
|
||||
const gitPath = await which('git');
|
||||
console.log(`Git found at: ${gitPath}`);
|
||||
} catch (error) {
|
||||
console.log('Git is not installed');
|
||||
}
|
||||
```
|
||||
|
||||
## License and Legal Information
|
||||
|
||||
This 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.
|
||||
|
||||
**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 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.
|
||||
|
||||
### Company Information
|
||||
|
||||
Task Venture Capital GmbH
|
||||
Registered at District court Bremen HRB 35230 HB, Germany
|
||||
|
||||
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
||||
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
1
test/test.d.ts
vendored
1
test/test.d.ts
vendored
@@ -1 +0,0 @@
|
||||
import 'typings-test';
|
222
test/test.errorHandling.ts
Normal file
222
test/test.errorHandling.ts
Normal file
@@ -0,0 +1,222 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
tap.test('should handle EPIPE errors gracefully', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const streaming = await testSmartshell.execStreamingInteractiveControl('head -n 1');
|
||||
|
||||
// Send more data after head exits (will cause EPIPE)
|
||||
await streaming.sendLine('Line 1');
|
||||
|
||||
// This should not throw even though head has exited
|
||||
let errorThrown = false;
|
||||
try {
|
||||
await streaming.sendLine('Line 2');
|
||||
await streaming.sendLine('Line 3');
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
// EPIPE or destroyed stdin is expected
|
||||
}
|
||||
|
||||
const result = await streaming.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Line 1');
|
||||
});
|
||||
|
||||
tap.test('should handle strict mode with non-zero exit codes', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let errorThrown = false;
|
||||
let errorMessage = '';
|
||||
|
||||
try {
|
||||
await testSmartshell.execStrict('exit 42');
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
errorMessage = error.message;
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
expect(errorMessage).toContain('exited with code 42');
|
||||
});
|
||||
|
||||
tap.test('should handle strict mode with signal termination', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let errorThrown = false;
|
||||
let errorMessage = '';
|
||||
|
||||
try {
|
||||
// Use execSpawn with strict mode and kill it
|
||||
const result = testSmartshell.execSpawn('sleep', ['10'], {
|
||||
strict: true,
|
||||
timeout: 100 // Will cause SIGTERM
|
||||
});
|
||||
await result;
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
errorMessage = error.message;
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
expect(errorMessage).toContain('terminated by signal');
|
||||
});
|
||||
|
||||
tap.test('execAndWaitForLine with timeout should reject properly', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let errorThrown = false;
|
||||
let errorMessage = '';
|
||||
|
||||
try {
|
||||
await testSmartshell.execAndWaitForLine(
|
||||
'sleep 5 && echo "Too late"',
|
||||
/Too late/,
|
||||
false,
|
||||
{ timeout: 100 }
|
||||
);
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
errorMessage = error.message;
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
expect(errorMessage).toContain('Timeout waiting for pattern');
|
||||
});
|
||||
|
||||
tap.test('execAndWaitForLine with terminateOnMatch should stop process', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const start = Date.now();
|
||||
await testSmartshell.execAndWaitForLine(
|
||||
'echo "Match this" && sleep 5',
|
||||
/Match this/,
|
||||
false,
|
||||
{ terminateOnMatch: true }
|
||||
);
|
||||
const duration = Date.now() - start;
|
||||
|
||||
// Should terminate immediately after match, not wait for sleep
|
||||
expect(duration).toBeLessThan(2000);
|
||||
});
|
||||
|
||||
tap.test('should handle process ending without matching pattern', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let errorThrown = false;
|
||||
let errorMessage = '';
|
||||
|
||||
try {
|
||||
await testSmartshell.execAndWaitForLine(
|
||||
'echo "Wrong text"',
|
||||
/Never appears/,
|
||||
false
|
||||
);
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
errorMessage = error.message;
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
expect(errorMessage).toContain('Process ended without matching pattern');
|
||||
});
|
||||
|
||||
tap.test('passthrough unpipe should handle destroyed stdin gracefully', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// This should complete without throwing even if stdin operations fail
|
||||
const result = await testSmartshell.execPassthrough('echo "Test passthrough unpipe"');
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Test passthrough unpipe');
|
||||
});
|
||||
|
||||
tap.test('should handle write after stream destroyed', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const interactive = await testSmartshell.execInteractiveControl('true'); // Exits immediately
|
||||
|
||||
// Wait for process to exit
|
||||
await interactive.finalPromise;
|
||||
|
||||
// Try to write after process has exited
|
||||
let errorThrown = false;
|
||||
try {
|
||||
await interactive.sendLine('This should fail');
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
expect(error.message).toContain('destroyed');
|
||||
}
|
||||
|
||||
expect(errorThrown).toBeTrue();
|
||||
});
|
||||
|
||||
tap.test('debug mode should log additional information', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Capture console.log output
|
||||
const originalLog = console.log;
|
||||
let debugOutput = '';
|
||||
console.log = (msg: string) => {
|
||||
debugOutput += msg + '\n';
|
||||
};
|
||||
|
||||
try {
|
||||
const streaming = await testSmartshell.execSpawnStreaming('echo', ['Debug test'], {
|
||||
debug: true
|
||||
});
|
||||
await streaming.terminate();
|
||||
await streaming.finalPromise;
|
||||
} finally {
|
||||
console.log = originalLog;
|
||||
}
|
||||
|
||||
// Should have logged debug messages
|
||||
expect(debugOutput).toContain('[smartshell]');
|
||||
});
|
||||
|
||||
tap.test('custom environment variables should be passed correctly', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const result = await testSmartshell.execSpawn('bash', ['-c', 'echo $CUSTOM_VAR'], {
|
||||
env: {
|
||||
...process.env,
|
||||
CUSTOM_VAR: 'test_value_123'
|
||||
}
|
||||
});
|
||||
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('test_value_123');
|
||||
});
|
||||
|
||||
export default tap.start();
|
84
test/test.interactiveControl.ts
Normal file
84
test/test.interactiveControl.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
tap.test('should handle programmatic input control with simple commands', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Use cat which works well with pipe mode
|
||||
const interactive = await testSmartshell.execInteractiveControl('cat');
|
||||
|
||||
// Send input programmatically
|
||||
await interactive.sendLine('TestUser');
|
||||
interactive.endInput();
|
||||
|
||||
// Wait for completion
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('TestUser');
|
||||
});
|
||||
|
||||
tap.test('should handle streaming interactive control with cat', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Use cat for reliable pipe mode operation
|
||||
const streaming = await testSmartshell.execStreamingInteractiveControl('cat');
|
||||
|
||||
// Send multiple inputs
|
||||
await streaming.sendLine('One');
|
||||
await streaming.sendLine('Two');
|
||||
streaming.endInput();
|
||||
|
||||
const result = await streaming.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('One');
|
||||
expect(result.stdout).toContain('Two');
|
||||
});
|
||||
|
||||
tap.test('should handle sendInput without newline', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Use cat for testing input without newline
|
||||
const interactive = await testSmartshell.execInteractiveControl('cat');
|
||||
|
||||
// Send characters without newline, then newline, then EOF
|
||||
await interactive.sendInput('ABC');
|
||||
await interactive.sendInput('DEF');
|
||||
await interactive.sendInput('\n');
|
||||
interactive.endInput();
|
||||
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('ABCDEF');
|
||||
});
|
||||
|
||||
tap.test('should mix passthrough and interactive control modes', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test that passthrough still works
|
||||
const passthroughResult = await testSmartshell.execPassthrough('echo "Passthrough works"');
|
||||
expect(passthroughResult.exitCode).toEqual(0);
|
||||
expect(passthroughResult.stdout).toContain('Passthrough works');
|
||||
|
||||
// Test that interactive control works
|
||||
const interactiveResult = await testSmartshell.execInteractiveControl('echo "Interactive control works"');
|
||||
const finalResult = await interactiveResult.finalPromise;
|
||||
expect(finalResult.exitCode).toEqual(0);
|
||||
expect(finalResult.stdout).toContain('Interactive control works');
|
||||
});
|
||||
|
||||
// Note: Tests requiring bash read with prompts should use PTY mode
|
||||
// See test.pty.ts for examples of testing commands that require terminal features
|
||||
|
||||
export default tap.start();
|
47
test/test.js
47
test/test.js
@@ -1,47 +0,0 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
require("typings-test");
|
||||
const smartchai_1 = require("smartchai");
|
||||
const smartshell = require("../dist/index");
|
||||
let testSmartshell;
|
||||
describe('smartshell', function () {
|
||||
it('it should run async', function () {
|
||||
this.timeout(1000000);
|
||||
return smartshell.exec('npm -v').then((execResult) => {
|
||||
smartchai_1.expect(execResult.stdout).to.match(/[0-9\.]*/);
|
||||
});
|
||||
});
|
||||
it('should run async and silent', function () {
|
||||
return smartshell.execSilent('npm -v').then((execResult) => {
|
||||
smartchai_1.expect(execResult.stdout).to.match(/[0-9\.]*/);
|
||||
});
|
||||
});
|
||||
it('should stream a shell execution', function () {
|
||||
let execStreamingResponse = smartshell.execStreaming('npm -v');
|
||||
execStreamingResponse.childProcess.stdout.on('data', (data) => {
|
||||
console.log('Received ' + data);
|
||||
});
|
||||
return execStreamingResponse.finalPromise;
|
||||
});
|
||||
it('should create a Smartshell instance', function () {
|
||||
testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: []
|
||||
});
|
||||
smartchai_1.expect(testSmartshell).to.be.instanceof(smartshell.Smartshell);
|
||||
});
|
||||
it('should run async', function () {
|
||||
return testSmartshell.execSilent('sleep 1 && npm -v').then((execResult) => __awaiter(this, void 0, void 0, function* () {
|
||||
console.log(execResult.stdout);
|
||||
}));
|
||||
});
|
||||
});
|
||||
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVzdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbInRlc3QudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7OztBQUFBLHdCQUFxQjtBQUNyQix5Q0FBa0M7QUFFbEMsNENBQTJDO0FBRTNDLElBQUksY0FBcUMsQ0FBQTtBQUV6QyxRQUFRLENBQUMsWUFBWSxFQUFFO0lBQ3JCLEVBQUUsQ0FBQyxxQkFBcUIsRUFBRTtRQUN4QixJQUFJLENBQUMsT0FBTyxDQUFDLE9BQU8sQ0FBQyxDQUFBO1FBQ3JCLE1BQU0sQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLFFBQVEsQ0FBQyxDQUFDLElBQUksQ0FBQyxDQUFDLFVBQVU7WUFDL0Msa0JBQU0sQ0FBQyxVQUFVLENBQUMsTUFBTSxDQUFDLENBQUMsRUFBRSxDQUFDLEtBQUssQ0FBQyxVQUFVLENBQUMsQ0FBQTtRQUNoRCxDQUFDLENBQUMsQ0FBQTtJQUNKLENBQUMsQ0FBQyxDQUFBO0lBQ0YsRUFBRSxDQUFDLDZCQUE2QixFQUFFO1FBQ2hDLE1BQU0sQ0FBQyxVQUFVLENBQUMsVUFBVSxDQUFDLFFBQVEsQ0FBQyxDQUFDLElBQUksQ0FBQyxDQUFDLFVBQVU7WUFDckQsa0JBQU0sQ0FBQyxVQUFVLENBQUMsTUFBTSxDQUFDLENBQUMsRUFBRSxDQUFDLEtBQUssQ0FBQyxVQUFVLENBQUMsQ0FBQTtRQUNoRCxDQUFDLENBQUMsQ0FBQTtJQUNKLENBQUMsQ0FBQyxDQUFBO0lBQ0YsRUFBRSxDQUFDLGlDQUFpQyxFQUFFO1FBQ3BDLElBQUkscUJBQXFCLEdBQUcsVUFBVSxDQUFDLGFBQWEsQ0FBQyxRQUFRLENBQUMsQ0FBQTtRQUM5RCxxQkFBcUIsQ0FBQyxZQUFZLENBQUMsTUFBTSxDQUFDLEVBQUUsQ0FBQyxNQUFNLEVBQUUsQ0FBQyxJQUFJO1lBQ3hELE9BQU8sQ0FBQyxHQUFHLENBQUMsV0FBVyxHQUFHLElBQUksQ0FBQyxDQUFBO1FBQ2pDLENBQUMsQ0FBQyxDQUFBO1FBQ0YsTUFBTSxDQUFDLHFCQUFxQixDQUFDLFlBQVksQ0FBQTtJQUMzQyxDQUFDLENBQUMsQ0FBQTtJQUNGLEVBQUUsQ0FBQyxxQ0FBcUMsRUFBRTtRQUN4QyxjQUFjLEdBQUcsSUFBSSxVQUFVLENBQUMsVUFBVSxDQUFDO1lBQ3pDLFFBQVEsRUFBRSxNQUFNO1lBQ2hCLGVBQWUsRUFBRSxFQUFFO1NBQ3BCLENBQUMsQ0FBQTtRQUNGLGtCQUFNLENBQUMsY0FBYyxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxVQUFVLENBQUMsVUFBVSxDQUFDLFVBQVUsQ0FBQyxDQUFBO0lBQ2hFLENBQUMsQ0FBQyxDQUFBO0lBRUYsRUFBRSxDQUFDLGtCQUFrQixFQUFFO1FBQ3JCLE1BQU0sQ0FBQyxjQUFjLENBQUMsVUFBVSxDQUFDLG1CQUFtQixDQUFDLENBQUMsSUFBSSxDQUFDLENBQU8sVUFBVTtZQUMxRSxPQUFPLENBQUMsR0FBRyxDQUFDLFVBQVUsQ0FBQyxNQUFNLENBQUMsQ0FBQTtRQUNoQyxDQUFDLENBQUEsQ0FBQyxDQUFBO0lBQ0osQ0FBQyxDQUFDLENBQUE7QUFDSixDQUFDLENBQUMsQ0FBQSJ9
|
42
test/test.passthrough.ts
Normal file
42
test/test.passthrough.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
tap.test('should handle passthrough for interactive commands', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test with a simple echo command that doesn't need input
|
||||
const result = await testSmartshell.execPassthrough('echo "Testing passthrough"');
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Testing passthrough');
|
||||
});
|
||||
|
||||
tap.test('should handle streaming passthrough', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test streaming passthrough with a simple command
|
||||
const streamingResult = await testSmartshell.execStreamingPassthrough('echo "Testing streaming passthrough"');
|
||||
const finalResult = await streamingResult.finalPromise;
|
||||
|
||||
expect(finalResult.exitCode).toEqual(0);
|
||||
expect(finalResult.stdout).toContain('Testing streaming passthrough');
|
||||
});
|
||||
|
||||
tap.test('should allow normal exec without passthrough', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Regular exec should still work as before
|
||||
const result = await testSmartshell.exec('echo "Normal exec"');
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Normal exec');
|
||||
});
|
||||
|
||||
export default tap.start();
|
146
test/test.pty.ts
Normal file
146
test/test.pty.ts
Normal file
@@ -0,0 +1,146 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
// Helper to check if node-pty is available
|
||||
const isPtyAvailable = async (): Promise<boolean> => {
|
||||
try {
|
||||
await import('node-pty');
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
tap.test('PTY: should handle bash read with prompts correctly', async (tools) => {
|
||||
const ptyAvailable = await isPtyAvailable();
|
||||
if (!ptyAvailable) {
|
||||
console.log('Skipping PTY test - node-pty not installed');
|
||||
return;
|
||||
}
|
||||
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// This test should work with PTY (bash read with prompt)
|
||||
const interactive = await testSmartshell.execInteractiveControlPty("bash -c 'read -p \"Enter name: \" name && echo \"Hello, $name\"'");
|
||||
|
||||
// Send input programmatically
|
||||
await interactive.sendLine('TestUser');
|
||||
|
||||
// Wait for completion
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Enter name:'); // Prompt should be visible with PTY
|
||||
expect(result.stdout).toContain('Hello, TestUser');
|
||||
});
|
||||
|
||||
tap.test('PTY: should handle terminal colors and escape sequences', async (tools) => {
|
||||
const ptyAvailable = await isPtyAvailable();
|
||||
if (!ptyAvailable) {
|
||||
console.log('Skipping PTY test - node-pty not installed');
|
||||
return;
|
||||
}
|
||||
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// ls --color=auto should produce colors in PTY mode
|
||||
const result = await testSmartshell.execInteractiveControlPty('ls --color=always /tmp');
|
||||
const finalResult = await result.finalPromise;
|
||||
|
||||
expect(finalResult.exitCode).toEqual(0);
|
||||
// Check for ANSI escape sequences (colors) in output
|
||||
const hasColors = /\x1b\[[0-9;]*m/.test(finalResult.stdout);
|
||||
expect(hasColors).toEqual(true);
|
||||
});
|
||||
|
||||
tap.test('PTY: should handle interactive password prompt simulation', async (tools) => {
|
||||
const ptyAvailable = await isPtyAvailable();
|
||||
if (!ptyAvailable) {
|
||||
console.log('Skipping PTY test - node-pty not installed');
|
||||
return;
|
||||
}
|
||||
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Simulate a password prompt scenario
|
||||
const interactive = await testSmartshell.execStreamingInteractiveControlPty(
|
||||
"bash -c 'read -s -p \"Password: \" pass && echo && echo \"Got password of length ${#pass}\"'"
|
||||
);
|
||||
|
||||
await tools.delayFor(100);
|
||||
await interactive.sendLine('secretpass');
|
||||
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Password:');
|
||||
expect(result.stdout).toContain('Got password of length 10');
|
||||
});
|
||||
|
||||
tap.test('PTY: should handle terminal size options', async (tools) => {
|
||||
const ptyAvailable = await isPtyAvailable();
|
||||
if (!ptyAvailable) {
|
||||
console.log('Skipping PTY test - node-pty not installed');
|
||||
return;
|
||||
}
|
||||
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Check terminal size using stty
|
||||
const result = await testSmartshell.execInteractiveControlPty('stty size');
|
||||
const finalResult = await result.finalPromise;
|
||||
|
||||
expect(finalResult.exitCode).toEqual(0);
|
||||
// Default size should be 30 rows x 120 cols as set in _execCommandPty
|
||||
expect(finalResult.stdout).toContain('30 120');
|
||||
});
|
||||
|
||||
tap.test('PTY: should handle Ctrl+C (SIGINT) properly', async (tools) => {
|
||||
const ptyAvailable = await isPtyAvailable();
|
||||
if (!ptyAvailable) {
|
||||
console.log('Skipping PTY test - node-pty not installed');
|
||||
return;
|
||||
}
|
||||
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Start a long-running process
|
||||
const streaming = await testSmartshell.execStreamingInteractiveControlPty('sleep 10');
|
||||
|
||||
// Send interrupt after a short delay
|
||||
await tools.delayFor(100);
|
||||
await streaming.keyboardInterrupt();
|
||||
|
||||
const result = await streaming.finalPromise;
|
||||
// Process should exit with non-zero code due to interrupt
|
||||
expect(result.exitCode).not.toEqual(0);
|
||||
});
|
||||
|
||||
tap.test('Regular pipe mode should still work alongside PTY', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Regular mode should work without PTY
|
||||
const interactive = await testSmartshell.execInteractiveControl('echo "Pipe mode works"');
|
||||
const result = await interactive.finalPromise;
|
||||
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Pipe mode works');
|
||||
});
|
||||
|
||||
export default tap.start();
|
104
test/test.silent.ts
Normal file
104
test/test.silent.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
let testSmartshell: smartshell.Smartshell;
|
||||
|
||||
tap.test('setup for silent execution tests', async () => {
|
||||
testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
expect(testSmartshell).toBeInstanceOf(smartshell.Smartshell);
|
||||
});
|
||||
|
||||
tap.test('execSilent should capture output without printing to console', async () => {
|
||||
const result = await testSmartshell.execSilent('echo "Hidden from console"');
|
||||
expect(result.stdout).toContain('Hidden from console');
|
||||
expect(result.exitCode).toEqual(0);
|
||||
});
|
||||
|
||||
tap.test('execSilent should capture multi-line output', async () => {
|
||||
const result = await testSmartshell.execSilent('echo "Line 1" && echo "Line 2" && echo "Line 3"');
|
||||
const lines = result.stdout.trim().split('\n');
|
||||
expect(lines).toHaveLength(3);
|
||||
expect(lines[0]).toEqual('Line 1');
|
||||
expect(lines[1]).toEqual('Line 2');
|
||||
expect(lines[2]).toEqual('Line 3');
|
||||
});
|
||||
|
||||
tap.test('execSilent should capture error output', async () => {
|
||||
const result = await testSmartshell.execSilent('echo "This works" && exit 1');
|
||||
expect(result.stdout).toContain('This works');
|
||||
expect(result.exitCode).toEqual(1);
|
||||
});
|
||||
|
||||
tap.test('execSilent should parse command output programmatically', async () => {
|
||||
// Test that we can programmatically process the captured output
|
||||
const result = await testSmartshell.execSilent('echo "apple,banana,cherry"');
|
||||
const items = result.stdout.trim().split(',');
|
||||
expect(items).toHaveLength(3);
|
||||
expect(items[0]).toEqual('apple');
|
||||
expect(items[1]).toEqual('banana');
|
||||
expect(items[2]).toEqual('cherry');
|
||||
});
|
||||
|
||||
tap.test('execStrictSilent should capture output and throw on error', async () => {
|
||||
// Test successful command
|
||||
const successResult = await testSmartshell.execStrictSilent('echo "Success"');
|
||||
expect(successResult.stdout).toContain('Success');
|
||||
expect(successResult.exitCode).toEqual(0);
|
||||
|
||||
// Test that it throws on error
|
||||
let errorThrown = false;
|
||||
try {
|
||||
await testSmartshell.execStrictSilent('echo "Error output" && exit 1');
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
}
|
||||
expect(errorThrown).toBeTrue();
|
||||
});
|
||||
|
||||
tap.test('execStreamingSilent should capture streaming output without console display', async () => {
|
||||
const streamingResult = await testSmartshell.execStreamingSilent('echo "Line 1" && sleep 0.1 && echo "Line 2"');
|
||||
|
||||
let capturedData = '';
|
||||
streamingResult.childProcess.stdout.on('data', (data) => {
|
||||
capturedData += data.toString();
|
||||
});
|
||||
|
||||
await streamingResult.finalPromise;
|
||||
expect(capturedData).toContain('Line 1');
|
||||
expect(capturedData).toContain('Line 2');
|
||||
});
|
||||
|
||||
tap.test('execAndWaitForLineSilent should wait for pattern without console output', async () => {
|
||||
// This should complete without printing to console
|
||||
await testSmartshell.execAndWaitForLineSilent('echo "Starting..." && echo "Ready to go"', /Ready to go/);
|
||||
});
|
||||
|
||||
tap.test('execSilent should handle commands with quotes', async () => {
|
||||
const result = await testSmartshell.execSilent('echo "Hello World"');
|
||||
expect(result.stdout.trim()).toEqual('Hello World');
|
||||
});
|
||||
|
||||
tap.test('execSilent should capture large output', async () => {
|
||||
// Generate 100 lines of output
|
||||
const result = await testSmartshell.execSilent('for i in {1..100}; do echo "Line $i"; done');
|
||||
const lines = result.stdout.trim().split('\n');
|
||||
expect(lines).toHaveLength(100);
|
||||
expect(lines[0]).toEqual('Line 1');
|
||||
expect(lines[99]).toEqual('Line 100');
|
||||
});
|
||||
|
||||
tap.test('execSilent vs exec output comparison', async () => {
|
||||
// Both should capture the same output, but exec prints to console
|
||||
const silentResult = await testSmartshell.execSilent('echo "Test output"');
|
||||
const normalResult = await testSmartshell.exec('echo "Test output"');
|
||||
|
||||
expect(silentResult.stdout).toEqual(normalResult.stdout);
|
||||
expect(silentResult.exitCode).toEqual(normalResult.exitCode);
|
||||
});
|
||||
|
||||
export default tap.start({
|
||||
throwOnError: true,
|
||||
});
|
54
test/test.simpleInteractive.ts
Normal file
54
test/test.simpleInteractive.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
tap.test('should send input to cat command', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Use cat which simply echoes what it receives
|
||||
const interactive = await testSmartshell.execInteractiveControl('cat');
|
||||
|
||||
// Send some text and close stdin
|
||||
await interactive.sendLine('Hello World');
|
||||
interactive.endInput(); // Close stdin properly
|
||||
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Hello World');
|
||||
});
|
||||
|
||||
tap.test('should work with simple echo', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// This should work without any input
|
||||
const interactive = await testSmartshell.execInteractiveControl('echo "Direct test"');
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Direct test');
|
||||
});
|
||||
|
||||
tap.test('should handle streaming with input control', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test with streaming and cat
|
||||
const streaming = await testSmartshell.execStreamingInteractiveControl('cat');
|
||||
|
||||
await streaming.sendLine('Line 1');
|
||||
await streaming.sendLine('Line 2');
|
||||
streaming.endInput(); // Close stdin
|
||||
|
||||
const result = await streaming.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Line 1');
|
||||
expect(result.stdout).toContain('Line 2');
|
||||
});
|
||||
|
||||
export default tap.start();
|
150
test/test.spawn.ts
Normal file
150
test/test.spawn.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartshell from '../ts/index.js';
|
||||
|
||||
tap.test('execSpawn should execute commands with args array (shell:false)', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test basic command with args
|
||||
const result = await testSmartshell.execSpawn('echo', ['Hello', 'World']);
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Hello World');
|
||||
});
|
||||
|
||||
tap.test('execSpawn should handle command not found errors', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let errorThrown = false;
|
||||
try {
|
||||
await testSmartshell.execSpawn('nonexistentcommand123', ['arg1']);
|
||||
} catch (error) {
|
||||
errorThrown = true;
|
||||
expect(error.code).toEqual('ENOENT');
|
||||
}
|
||||
expect(errorThrown).toBeTrue();
|
||||
});
|
||||
|
||||
tap.test('execSpawn should properly escape arguments', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Test that shell metacharacters are treated as literals
|
||||
const result = await testSmartshell.execSpawn('echo', ['$HOME', '&&', 'ls']);
|
||||
expect(result.exitCode).toEqual(0);
|
||||
// Should output literal strings, not expanded/executed
|
||||
expect(result.stdout).toContain('$HOME && ls');
|
||||
});
|
||||
|
||||
tap.test('execSpawn streaming should work', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const streaming = await testSmartshell.execSpawnStreaming('echo', ['Streaming test']);
|
||||
const result = await streaming.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Streaming test');
|
||||
});
|
||||
|
||||
tap.test('execSpawn interactive control should work', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const interactive = await testSmartshell.execSpawnInteractiveControl('cat', []);
|
||||
|
||||
await interactive.sendLine('Input line');
|
||||
interactive.endInput();
|
||||
|
||||
const result = await interactive.finalPromise;
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('Input line');
|
||||
});
|
||||
|
||||
tap.test('execSpawn should capture stderr', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// ls on non-existent directory should produce stderr
|
||||
const result = await testSmartshell.execSpawn('ls', ['/nonexistent/directory/path']);
|
||||
expect(result.exitCode).not.toEqual(0);
|
||||
expect(result.stderr).toBeTruthy();
|
||||
expect(result.stderr).toContain('No such file or directory');
|
||||
});
|
||||
|
||||
tap.test('execSpawn with timeout should terminate process', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const start = Date.now();
|
||||
const result = await testSmartshell.execSpawn('sleep', ['10'], { timeout: 100 });
|
||||
const duration = Date.now() - start;
|
||||
|
||||
// Process should be terminated by timeout
|
||||
expect(duration).toBeLessThan(500);
|
||||
expect(result.exitCode).not.toEqual(0);
|
||||
expect(result.signal).toBeTruthy(); // Should have been killed by signal
|
||||
});
|
||||
|
||||
tap.test('execSpawn with maxBuffer should truncate output', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
// Generate large output
|
||||
const result = await testSmartshell.execSpawn('bash', ['-c', 'for i in {1..1000}; do echo "Line $i with some padding text to make it longer"; done'], {
|
||||
maxBuffer: 1024, // Very small buffer
|
||||
});
|
||||
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(result.stdout).toContain('[Output truncated - exceeded maxBuffer]');
|
||||
});
|
||||
|
||||
tap.test('execSpawn with onData callback should stream data', async (tools) => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
let dataReceived = '';
|
||||
const result = await testSmartshell.execSpawn('echo', ['Test data'], {
|
||||
onData: (chunk) => {
|
||||
dataReceived += chunk.toString();
|
||||
}
|
||||
});
|
||||
|
||||
expect(result.exitCode).toEqual(0);
|
||||
expect(dataReceived).toContain('Test data');
|
||||
});
|
||||
|
||||
tap.test('execSpawn with signal should report signal in result', async () => {
|
||||
const testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
|
||||
const streaming = await testSmartshell.execSpawnStreaming('sleep', ['10']);
|
||||
|
||||
// Send SIGTERM after a short delay
|
||||
setTimeout(() => streaming.terminate(), 100);
|
||||
|
||||
const result = await streaming.finalPromise;
|
||||
expect(result.exitCode).not.toEqual(0);
|
||||
expect(result.signal).toEqual('SIGTERM');
|
||||
});
|
||||
|
||||
export default tap.start();
|
77
test/test.ts
77
test/test.ts
@@ -1,40 +1,57 @@
|
||||
import { expect, tap } from 'tapbundle'
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
|
||||
import * as smartshell from '../dist/index'
|
||||
import * as smartshell from '../ts/index.js';
|
||||
import * as smartpromise from '@push.rocks/smartpromise';
|
||||
|
||||
let testSmartshell: smartshell.Smartshell
|
||||
let testSmartshell: smartshell.Smartshell;
|
||||
|
||||
|
||||
tap.test('smartshell should run async', async () => {
|
||||
this.timeout(1000000)
|
||||
return smartshell.exec('npm -v').then((execResult) => {
|
||||
expect(execResult.stdout).to.match(/[0-9\.]*/)
|
||||
})
|
||||
})
|
||||
tap.test('smartshell should run async and silent', async () => {
|
||||
return smartshell.execSilent('npm -v').then((execResult) => {
|
||||
expect(execResult.stdout).to.match(/[0-9\.]*/)
|
||||
})
|
||||
})
|
||||
tap.test('smartshell should stream a shell execution', async () => {
|
||||
let execStreamingResponse = smartshell.execStreaming('npm -v')
|
||||
execStreamingResponse.childProcess.stdout.on('data', (data) => {
|
||||
console.log('Received ' + data)
|
||||
})
|
||||
return execStreamingResponse.finalPromise
|
||||
})
|
||||
tap.test('smartshell should create a Smartshell instance', async () => {
|
||||
testSmartshell = new smartshell.Smartshell({
|
||||
executor: 'bash',
|
||||
sourceFilePaths: []
|
||||
})
|
||||
expect(testSmartshell).to.be.instanceof(smartshell.Smartshell)
|
||||
})
|
||||
sourceFilePaths: [],
|
||||
});
|
||||
expect(testSmartshell).toBeInstanceOf(smartshell.Smartshell);
|
||||
});
|
||||
|
||||
tap.test('smartshell should run async', async () => {
|
||||
let execResult = await testSmartshell.exec('npm -v');
|
||||
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).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) => {
|
||||
done.resolve(data);
|
||||
});
|
||||
let data = await done.promise;
|
||||
expect(data).toMatch(/[0-9\.]*/);
|
||||
await execStreamingResponse.finalPromise;
|
||||
});
|
||||
|
||||
tap.test('it should execute and wait for a line in the output', async () => {
|
||||
await testSmartshell.execAndWaitForLine('echo "5.0.4"', /5.0.4/);
|
||||
});
|
||||
|
||||
tap.test('smartshell should run async', async () => {
|
||||
return testSmartshell.execSilent('sleep 1 && npm -v').then(async (execResult) => {
|
||||
console.log(execResult.stdout)
|
||||
})
|
||||
})
|
||||
console.log(execResult.stdout);
|
||||
});
|
||||
});
|
||||
|
||||
tap.start()
|
||||
tap.test('should be able to find git', async () => {
|
||||
await testSmartshell.exec('git --version');
|
||||
});
|
||||
|
||||
tap.test('should spawn an interactive cli', async () => {
|
||||
await testSmartshell.execInteractive('echo "hi"');
|
||||
});
|
||||
|
||||
tap.start({
|
||||
throwOnError: true,
|
||||
});
|
||||
|
8
ts/00_commitinfo_data.ts
Normal file
8
ts/00_commitinfo_data.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @push.rocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartshell',
|
||||
version: '3.3.0',
|
||||
description: 'A library for executing shell commands using promises.'
|
||||
}
|
103
ts/classes.shellenv.ts
Normal file
103
ts/classes.shellenv.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
export type TExecutor = 'sh' | 'bash';
|
||||
|
||||
export interface IShellEnvContructorOptions {
|
||||
executor: TExecutor;
|
||||
sourceFilePaths?: string[];
|
||||
pathDirectories?: string[];
|
||||
}
|
||||
|
||||
export class ShellEnv {
|
||||
executor: TExecutor;
|
||||
sourceFileArray: string[] = [];
|
||||
pathDirArray: string[] = [];
|
||||
|
||||
/**
|
||||
* constructor for the shellenv
|
||||
*/
|
||||
constructor(optionsArg: IShellEnvContructorOptions) {
|
||||
this.executor = optionsArg.executor;
|
||||
|
||||
// add sourcefiles
|
||||
if (optionsArg.sourceFilePaths) {
|
||||
this.sourceFileArray = this.sourceFileArray.concat(optionsArg.sourceFilePaths);
|
||||
}
|
||||
|
||||
// add pathDirectories
|
||||
if (optionsArg.pathDirectories) {
|
||||
this.pathDirArray = this.pathDirArray.concat(optionsArg.pathDirectories);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* imports path into the shell from env if available and returns it with
|
||||
*/
|
||||
private _setPath(commandStringArg: string): string {
|
||||
let commandResult = commandStringArg;
|
||||
let commandPaths: string[] = [];
|
||||
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;
|
||||
});
|
||||
|
||||
commandResult = `PATH=${commandPaths.join(':')} && ${commandStringArg}`;
|
||||
return commandResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* add files that are going to be sourced when running a command
|
||||
* @param sourceFilePathsArray
|
||||
*/
|
||||
addSourceFiles(sourceFilePathsArray: string[]) {
|
||||
for (let sourceFilePath of sourceFilePathsArray) {
|
||||
this.sourceFileArray.push(sourceFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* cleans the source files array
|
||||
*/
|
||||
cleanSourceFiles() {
|
||||
this.sourceFileArray = [];
|
||||
}
|
||||
|
||||
public createEnvExecString(commandArg: string): string {
|
||||
let commandResult = '';
|
||||
let sourceString = '';
|
||||
|
||||
// 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 += ` && `;
|
||||
|
||||
switch (this.executor) {
|
||||
case 'bash':
|
||||
commandResult = `bash -c '${pathString}${sourceString}${commandArg}'`;
|
||||
break;
|
||||
case 'sh':
|
||||
commandResult = `${pathString}${sourceString}${commandArg}`;
|
||||
break;
|
||||
}
|
||||
commandResult = this._setPath(commandResult);
|
||||
return commandResult;
|
||||
}
|
||||
}
|
38
ts/classes.shelllog.ts
Normal file
38
ts/classes.shelllog.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
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 {
|
||||
public logStore = Buffer.from('');
|
||||
|
||||
/**
|
||||
* 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 = (() => {
|
||||
if (!Buffer.isBuffer(dataArg)) {
|
||||
return Buffer.from(dataArg);
|
||||
}
|
||||
return dataArg;
|
||||
})();
|
||||
this.logStore = Buffer.concat([this.logStore, dataBuffer]);
|
||||
}
|
||||
|
||||
public logAndAdd(dataArg: string | Buffer): void {
|
||||
this.writeToConsole(dataArg);
|
||||
this.addToBuffer(dataArg);
|
||||
}
|
||||
}
|
55
ts/classes.smartexecution.ts
Normal file
55
ts/classes.smartexecution.ts
Normal 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();
|
||||
}
|
||||
}
|
||||
}
|
873
ts/classes.smartshell.ts
Normal file
873
ts/classes.smartshell.ts
Normal file
@@ -0,0 +1,873 @@
|
||||
import * as plugins from './plugins.js';
|
||||
import { ShellEnv } from './classes.shellenv.js';
|
||||
import type { IShellEnvContructorOptions, TExecutor } from './classes.shellenv.js';
|
||||
import { ShellLog } from './classes.shelllog.js';
|
||||
import * as cp from 'child_process';
|
||||
|
||||
// -- interfaces --
|
||||
export interface IExecResult {
|
||||
exitCode: number;
|
||||
stdout: string;
|
||||
signal?: NodeJS.Signals;
|
||||
stderr?: string;
|
||||
}
|
||||
|
||||
export interface IExecResultInteractive extends IExecResult {
|
||||
sendInput: (input: string) => Promise<void>;
|
||||
sendLine: (line: string) => Promise<void>;
|
||||
endInput: () => void;
|
||||
finalPromise: Promise<IExecResult>;
|
||||
}
|
||||
|
||||
export interface IExecResultStreaming {
|
||||
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;
|
||||
}
|
||||
|
||||
interface IExecOptions {
|
||||
commandString: string;
|
||||
silent?: boolean;
|
||||
strict?: boolean;
|
||||
streaming?: boolean;
|
||||
interactive?: boolean;
|
||||
passthrough?: boolean;
|
||||
interactiveControl?: boolean;
|
||||
usePty?: boolean;
|
||||
ptyCols?: number;
|
||||
ptyRows?: number;
|
||||
ptyTerm?: string;
|
||||
ptyShell?: string;
|
||||
maxBuffer?: number;
|
||||
onData?: (chunk: Buffer | string) => void;
|
||||
timeout?: number;
|
||||
debug?: boolean;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface ISpawnOptions extends Omit<IExecOptions, 'commandString'> {
|
||||
command: string;
|
||||
args?: string[];
|
||||
}
|
||||
|
||||
export class Smartshell {
|
||||
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 | void> {
|
||||
if (options.interactive) {
|
||||
return await this._execInteractive({ commandString: options.commandString });
|
||||
}
|
||||
return await this._execCommand(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes an interactive command.
|
||||
*/
|
||||
private async _execInteractive(options: Pick<IExecOptions, 'commandString'>): 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,
|
||||
});
|
||||
|
||||
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: process.cwd(),
|
||||
env: options.env || process.env,
|
||||
detached: false,
|
||||
signal: options.signal,
|
||||
});
|
||||
|
||||
this.smartexit.addProcess(execChildProcess);
|
||||
|
||||
// Handle timeout
|
||||
let timeoutHandle: NodeJS.Timeout | null = null;
|
||||
if (options.timeout) {
|
||||
timeoutHandle = setTimeout(() => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Timeout reached for process ${execChildProcess.pid}, terminating...`);
|
||||
}
|
||||
execChildProcess.kill('SIGTERM');
|
||||
}, options.timeout);
|
||||
}
|
||||
|
||||
// Connect stdin if passthrough is enabled (but not for interactive control)
|
||||
if (options.passthrough && !options.interactiveControl && execChildProcess.stdin) {
|
||||
process.stdin.pipe(execChildProcess.stdin);
|
||||
}
|
||||
|
||||
// Create input methods for interactive control
|
||||
const sendInput = async (input: string): Promise<void> => {
|
||||
if (!execChildProcess.stdin) {
|
||||
throw new Error('stdin is not available for this process');
|
||||
}
|
||||
if (execChildProcess.stdin.destroyed || !execChildProcess.stdin.writable) {
|
||||
throw new Error('stdin has been destroyed or is not writable');
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
execChildProcess.stdin.write(input, 'utf8', (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const sendLine = async (line: string): Promise<void> => {
|
||||
return sendInput(line + '\n');
|
||||
};
|
||||
|
||||
const endInput = (): void => {
|
||||
if (execChildProcess.stdin && !execChildProcess.stdin.destroyed) {
|
||||
execChildProcess.stdin.end();
|
||||
}
|
||||
};
|
||||
|
||||
// Capture stdout and stderr output
|
||||
execChildProcess.stdout.on('data', (data) => {
|
||||
if (!options.silent) {
|
||||
shellLogInstance.writeToConsole(data);
|
||||
}
|
||||
|
||||
if (options.onData) {
|
||||
options.onData(data);
|
||||
}
|
||||
|
||||
if (!bufferExceeded) {
|
||||
shellLogInstance.addToBuffer(data);
|
||||
if (shellLogInstance.logStore.length > maxBuffer) {
|
||||
bufferExceeded = true;
|
||||
shellLogInstance.logStore = Buffer.from('[Output truncated - exceeded maxBuffer]');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
execChildProcess.stderr.on('data', (data) => {
|
||||
if (!options.silent) {
|
||||
shellLogInstance.writeToConsole(data);
|
||||
}
|
||||
|
||||
const dataStr = data.toString();
|
||||
stderrBuffer += dataStr;
|
||||
|
||||
if (options.onData) {
|
||||
options.onData(data);
|
||||
}
|
||||
|
||||
if (!bufferExceeded) {
|
||||
shellLogInstance.addToBuffer(data);
|
||||
if (shellLogInstance.logStore.length > maxBuffer) {
|
||||
bufferExceeded = true;
|
||||
shellLogInstance.logStore = Buffer.from('[Output truncated - exceeded maxBuffer]');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Wrap child process termination into a Promise
|
||||
const childProcessEnded: Promise<IExecResult> = new Promise((resolve, reject) => {
|
||||
const handleExit = (code: number | null, signal: NodeJS.Signals | null) => {
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
this.smartexit.removeProcess(execChildProcess);
|
||||
|
||||
// Safely unpipe stdin when process ends if passthrough was enabled
|
||||
if (options.passthrough && !options.interactiveControl) {
|
||||
try {
|
||||
if (execChildProcess.stdin && !execChildProcess.stdin.destroyed) {
|
||||
process.stdin.unpipe(execChildProcess.stdin);
|
||||
}
|
||||
} catch (err) {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Error unpiping stdin: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const exitCode = typeof code === 'number' ? code : (signal ? 1 : 0);
|
||||
const execResult: IExecResult = {
|
||||
exitCode,
|
||||
stdout: shellLogInstance.logStore.toString(),
|
||||
signal: signal || undefined,
|
||||
stderr: stderrBuffer,
|
||||
};
|
||||
|
||||
if (options.strict && exitCode !== 0) {
|
||||
const errorMsg = signal
|
||||
? `Command "${options.command}" terminated by signal ${signal}`
|
||||
: `Command "${options.command}" exited with code ${exitCode}`;
|
||||
reject(new Error(errorMsg));
|
||||
} else {
|
||||
resolve(execResult);
|
||||
}
|
||||
};
|
||||
|
||||
execChildProcess.once('exit', handleExit);
|
||||
execChildProcess.once('error', (error) => {
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
this.smartexit.removeProcess(execChildProcess);
|
||||
|
||||
// Safely unpipe stdin when process errors if passthrough was enabled
|
||||
if (options.passthrough && !options.interactiveControl && execChildProcess.stdin) {
|
||||
try {
|
||||
if (!execChildProcess.stdin.destroyed) {
|
||||
process.stdin.unpipe(execChildProcess.stdin);
|
||||
}
|
||||
} catch (err) {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Error unpiping stdin on error: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
|
||||
// If interactive control is enabled but not streaming, return interactive interface
|
||||
if (options.interactiveControl && !options.streaming) {
|
||||
return {
|
||||
exitCode: 0, // Will be updated when process ends
|
||||
stdout: '', // Will be updated when process ends
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
finalPromise: childProcessEnded,
|
||||
} as IExecResultInteractive;
|
||||
}
|
||||
|
||||
// If streaming mode is enabled, return a streaming interface
|
||||
if (options.streaming) {
|
||||
return {
|
||||
childProcess: execChildProcess,
|
||||
finalPromise: childProcessEnded,
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
kill: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGKILL on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGKILL');
|
||||
},
|
||||
terminate: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGTERM on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGTERM');
|
||||
},
|
||||
keyboardInterrupt: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGINT on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGINT');
|
||||
},
|
||||
customSignal: async (signal: plugins.smartexit.TProcessSignal) => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with custom signal ${signal} on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, signal);
|
||||
},
|
||||
} as IExecResultStreaming;
|
||||
}
|
||||
|
||||
// For non-streaming mode, wait for the process to complete
|
||||
return await childProcessEnded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a command and returns either a non-streaming result or a streaming interface.
|
||||
*/
|
||||
private async _execCommand(options: IExecOptions): Promise<IExecResult | IExecResultStreaming | IExecResultInteractive> {
|
||||
const commandToExecute = this.shellEnv.createEnvExecString(options.commandString);
|
||||
const shellLogInstance = new ShellLog();
|
||||
let stderrBuffer = '';
|
||||
const maxBuffer = options.maxBuffer || 200 * 1024 * 1024; // Default 200MB
|
||||
let bufferExceeded = false;
|
||||
|
||||
// Handle PTY mode if requested
|
||||
if (options.usePty) {
|
||||
return await this._execCommandPty(options, commandToExecute, shellLogInstance);
|
||||
}
|
||||
|
||||
const execChildProcess = cp.spawn(commandToExecute, [], {
|
||||
shell: true,
|
||||
cwd: process.cwd(),
|
||||
env: options.env || process.env,
|
||||
detached: false,
|
||||
signal: options.signal,
|
||||
});
|
||||
|
||||
this.smartexit.addProcess(execChildProcess);
|
||||
|
||||
// Handle timeout
|
||||
let timeoutHandle: NodeJS.Timeout | null = null;
|
||||
if (options.timeout) {
|
||||
timeoutHandle = setTimeout(() => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Timeout reached for process ${execChildProcess.pid}, terminating...`);
|
||||
}
|
||||
execChildProcess.kill('SIGTERM');
|
||||
}, options.timeout);
|
||||
}
|
||||
|
||||
// Connect stdin if passthrough is enabled (but not for interactive control)
|
||||
if (options.passthrough && !options.interactiveControl && execChildProcess.stdin) {
|
||||
process.stdin.pipe(execChildProcess.stdin);
|
||||
}
|
||||
|
||||
// Create input methods for interactive control
|
||||
const sendInput = async (input: string): Promise<void> => {
|
||||
if (!execChildProcess.stdin) {
|
||||
throw new Error('stdin is not available for this process');
|
||||
}
|
||||
if (execChildProcess.stdin.destroyed || !execChildProcess.stdin.writable) {
|
||||
throw new Error('stdin has been destroyed or is not writable');
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
execChildProcess.stdin.write(input, 'utf8', (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const sendLine = async (line: string): Promise<void> => {
|
||||
return sendInput(line + '\n');
|
||||
};
|
||||
|
||||
const endInput = (): void => {
|
||||
if (execChildProcess.stdin && !execChildProcess.stdin.destroyed) {
|
||||
execChildProcess.stdin.end();
|
||||
}
|
||||
};
|
||||
|
||||
// Capture stdout and stderr output
|
||||
execChildProcess.stdout.on('data', (data) => {
|
||||
if (!options.silent) {
|
||||
shellLogInstance.writeToConsole(data);
|
||||
}
|
||||
|
||||
if (options.onData) {
|
||||
options.onData(data);
|
||||
}
|
||||
|
||||
if (!bufferExceeded) {
|
||||
shellLogInstance.addToBuffer(data);
|
||||
if (shellLogInstance.logStore.length > maxBuffer) {
|
||||
bufferExceeded = true;
|
||||
shellLogInstance.logStore = Buffer.from('[Output truncated - exceeded maxBuffer]');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
execChildProcess.stderr.on('data', (data) => {
|
||||
if (!options.silent) {
|
||||
shellLogInstance.writeToConsole(data);
|
||||
}
|
||||
|
||||
const dataStr = data.toString();
|
||||
stderrBuffer += dataStr;
|
||||
|
||||
if (options.onData) {
|
||||
options.onData(data);
|
||||
}
|
||||
|
||||
if (!bufferExceeded) {
|
||||
shellLogInstance.addToBuffer(data);
|
||||
if (shellLogInstance.logStore.length > maxBuffer) {
|
||||
bufferExceeded = true;
|
||||
shellLogInstance.logStore = Buffer.from('[Output truncated - exceeded maxBuffer]');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Wrap child process termination into a Promise
|
||||
const childProcessEnded: Promise<IExecResult> = new Promise((resolve, reject) => {
|
||||
const handleExit = (code: number | null, signal: NodeJS.Signals | null) => {
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
this.smartexit.removeProcess(execChildProcess);
|
||||
|
||||
// Safely unpipe stdin when process ends if passthrough was enabled
|
||||
if (options.passthrough && !options.interactiveControl) {
|
||||
try {
|
||||
if (execChildProcess.stdin && !execChildProcess.stdin.destroyed) {
|
||||
process.stdin.unpipe(execChildProcess.stdin);
|
||||
}
|
||||
} catch (err) {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Error unpiping stdin: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const exitCode = typeof code === 'number' ? code : (signal ? 1 : 0);
|
||||
const execResult: IExecResult = {
|
||||
exitCode,
|
||||
stdout: shellLogInstance.logStore.toString(),
|
||||
signal: signal || undefined,
|
||||
stderr: stderrBuffer,
|
||||
};
|
||||
|
||||
if (options.strict && exitCode !== 0) {
|
||||
const errorMsg = signal
|
||||
? `Command "${options.commandString}" terminated by signal ${signal}`
|
||||
: `Command "${options.commandString}" exited with code ${exitCode}`;
|
||||
reject(new Error(errorMsg));
|
||||
} else {
|
||||
resolve(execResult);
|
||||
}
|
||||
};
|
||||
|
||||
execChildProcess.once('exit', handleExit);
|
||||
execChildProcess.once('error', (error) => {
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
this.smartexit.removeProcess(execChildProcess);
|
||||
|
||||
// Safely unpipe stdin when process errors if passthrough was enabled
|
||||
if (options.passthrough && !options.interactiveControl && execChildProcess.stdin) {
|
||||
try {
|
||||
if (!execChildProcess.stdin.destroyed) {
|
||||
process.stdin.unpipe(execChildProcess.stdin);
|
||||
}
|
||||
} catch (err) {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Error unpiping stdin on error: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
|
||||
// If interactive control is enabled but not streaming, return interactive interface
|
||||
if (options.interactiveControl && !options.streaming) {
|
||||
return {
|
||||
exitCode: 0, // Will be updated when process ends
|
||||
stdout: '', // Will be updated when process ends
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
finalPromise: childProcessEnded,
|
||||
} as IExecResultInteractive;
|
||||
}
|
||||
|
||||
// If streaming mode is enabled, return a streaming interface
|
||||
if (options.streaming) {
|
||||
return {
|
||||
childProcess: execChildProcess,
|
||||
finalPromise: childProcessEnded,
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
kill: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGKILL on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGKILL');
|
||||
},
|
||||
terminate: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGTERM on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGTERM');
|
||||
},
|
||||
keyboardInterrupt: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with SIGINT on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, 'SIGINT');
|
||||
},
|
||||
customSignal: async (signal: plugins.smartexit.TProcessSignal) => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Running tree kill with custom signal ${signal} on process ${execChildProcess.pid}`);
|
||||
}
|
||||
await plugins.smartexit.SmartExit.killTreeByPid(execChildProcess.pid, signal);
|
||||
},
|
||||
} as IExecResultStreaming;
|
||||
}
|
||||
|
||||
// For non-streaming mode, wait for the process to complete.
|
||||
return await childProcessEnded;
|
||||
}
|
||||
|
||||
public async exec(commandString: string): Promise<IExecResult> {
|
||||
const result = await this._exec({ commandString });
|
||||
// Type assertion is safe here because non-streaming, non-interactive exec always returns IExecResult
|
||||
return result as IExecResult;
|
||||
}
|
||||
|
||||
public async execSilent(commandString: string): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString, silent: true })) as IExecResult;
|
||||
}
|
||||
|
||||
public async execStrict(commandString: string): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString, strict: true })) as IExecResult;
|
||||
}
|
||||
|
||||
public async execStrictSilent(commandString: string): Promise<IExecResult> {
|
||||
return (await this._exec({ commandString, silent: true, strict: true })) as IExecResult;
|
||||
}
|
||||
|
||||
public async execStreaming(commandString: string, silent: boolean = false): Promise<IExecResultStreaming> {
|
||||
return (await this._exec({ commandString, silent, streaming: true })) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execStreamingSilent(commandString: string): Promise<IExecResultStreaming> {
|
||||
return (await this._exec({ commandString, silent: true, streaming: true })) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execInteractive(commandString: string): Promise<void> {
|
||||
await this._exec({ commandString, interactive: true });
|
||||
}
|
||||
|
||||
public async execPassthrough(commandString: string): Promise<IExecResult> {
|
||||
return await this._exec({ commandString, passthrough: true }) as IExecResult;
|
||||
}
|
||||
|
||||
public async execStreamingPassthrough(commandString: string): Promise<IExecResultStreaming> {
|
||||
return await this._exec({ commandString, streaming: true, passthrough: true }) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execInteractiveControl(commandString: string): Promise<IExecResultInteractive> {
|
||||
return await this._exec({ commandString, interactiveControl: true }) as IExecResultInteractive;
|
||||
}
|
||||
|
||||
public async execStreamingInteractiveControl(commandString: string): Promise<IExecResultStreaming> {
|
||||
return await this._exec({ commandString, streaming: true, interactiveControl: true }) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
public async execInteractiveControlPty(commandString: string): Promise<IExecResultInteractive> {
|
||||
return await this._exec({ commandString, interactiveControl: true, usePty: true }) as IExecResultInteractive;
|
||||
}
|
||||
|
||||
public async execStreamingInteractiveControlPty(commandString: string): Promise<IExecResultStreaming> {
|
||||
return await this._exec({ commandString, streaming: true, interactiveControl: true, usePty: true }) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a command with args array (shell:false) for security
|
||||
* This is the recommended API for untrusted input
|
||||
*/
|
||||
public async execSpawn(command: string, args: string[] = [], options: Omit<ISpawnOptions, 'command' | 'args'> = {}): Promise<IExecResult> {
|
||||
const result = await this._execSpawn({ command, args, ...options });
|
||||
// Type assertion is safe here because non-streaming, non-interactive exec always returns IExecResult
|
||||
return result as IExecResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a command with args array in streaming mode
|
||||
*/
|
||||
public async execSpawnStreaming(command: string, args: string[] = [], options: Omit<ISpawnOptions, 'command' | 'args' | 'streaming'> = {}): Promise<IExecResultStreaming> {
|
||||
return await this._execSpawn({ command, args, streaming: true, ...options }) as IExecResultStreaming;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a command with args array with interactive control
|
||||
*/
|
||||
public async execSpawnInteractiveControl(command: string, args: string[] = [], options: Omit<ISpawnOptions, 'command' | 'args' | 'interactiveControl'> = {}): Promise<IExecResultInteractive> {
|
||||
return await this._execSpawn({ command, args, interactiveControl: true, ...options }) as IExecResultInteractive;
|
||||
}
|
||||
|
||||
public async execAndWaitForLine(
|
||||
commandString: string,
|
||||
regex: RegExp,
|
||||
silent: boolean = false,
|
||||
options: { timeout?: number; terminateOnMatch?: boolean } = {}
|
||||
): Promise<void> {
|
||||
const execStreamingResult = await this.execStreaming(commandString, silent);
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let matched = false;
|
||||
let timeoutHandle: NodeJS.Timeout | null = null;
|
||||
|
||||
// Set up timeout if specified
|
||||
if (options.timeout) {
|
||||
timeoutHandle = setTimeout(async () => {
|
||||
if (!matched) {
|
||||
matched = true;
|
||||
// Remove listener to prevent memory leak
|
||||
execStreamingResult.childProcess.stdout.removeAllListeners('data');
|
||||
await execStreamingResult.terminate();
|
||||
reject(new Error(`Timeout waiting for pattern after ${options.timeout}ms`));
|
||||
}
|
||||
}, options.timeout);
|
||||
}
|
||||
|
||||
const dataHandler = async (chunk: Buffer | string) => {
|
||||
const data = typeof chunk === 'string' ? chunk : chunk.toString();
|
||||
if (!matched && regex.test(data)) {
|
||||
matched = true;
|
||||
|
||||
// Clear timeout if set
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
|
||||
// Remove listener to prevent memory leak
|
||||
execStreamingResult.childProcess.stdout.removeListener('data', dataHandler);
|
||||
|
||||
// Terminate process if requested
|
||||
if (options.terminateOnMatch) {
|
||||
await execStreamingResult.terminate();
|
||||
await execStreamingResult.finalPromise;
|
||||
}
|
||||
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
|
||||
execStreamingResult.childProcess.stdout.on('data', dataHandler);
|
||||
|
||||
// Also resolve/reject when process ends
|
||||
execStreamingResult.finalPromise.then(() => {
|
||||
if (!matched) {
|
||||
matched = true;
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
reject(new Error('Process ended without matching pattern'));
|
||||
}
|
||||
}).catch((err) => {
|
||||
if (!matched) {
|
||||
matched = true;
|
||||
if (timeoutHandle) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public async execAndWaitForLineSilent(commandString: string, regex: RegExp, options?: { timeout?: number; terminateOnMatch?: boolean }): Promise<void> {
|
||||
return this.execAndWaitForLine(commandString, regex, true, options);
|
||||
}
|
||||
|
||||
private nodePty: any = null;
|
||||
|
||||
private async lazyLoadNodePty(): Promise<any> {
|
||||
if (this.nodePty) {
|
||||
return this.nodePty;
|
||||
}
|
||||
|
||||
try {
|
||||
// Try to load node-pty if available
|
||||
// @ts-ignore - node-pty is optional
|
||||
this.nodePty = await import('node-pty');
|
||||
return this.nodePty;
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
'node-pty is required for PTY support but is not installed.\n' +
|
||||
'Please install it as an optional dependency:\n' +
|
||||
' pnpm add --save-optional node-pty\n' +
|
||||
'Note: node-pty requires compilation and may have platform-specific requirements.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async _execCommandPty(
|
||||
options: IExecOptions,
|
||||
commandToExecute: string,
|
||||
shellLogInstance: ShellLog
|
||||
): Promise<IExecResult | IExecResultStreaming | IExecResultInteractive> {
|
||||
const pty = await this.lazyLoadNodePty();
|
||||
|
||||
// Platform-aware shell selection
|
||||
let shell: string;
|
||||
let shellArgs: string[];
|
||||
|
||||
if (options.ptyShell) {
|
||||
// User-provided shell override
|
||||
shell = options.ptyShell;
|
||||
shellArgs = ['-c', commandToExecute];
|
||||
} else if (process.platform === 'win32') {
|
||||
// Windows: Use PowerShell by default, or cmd as fallback
|
||||
const powershell = process.env.PROGRAMFILES
|
||||
? `${process.env.PROGRAMFILES}\\PowerShell\\7\\pwsh.exe`
|
||||
: 'powershell.exe';
|
||||
|
||||
// Check if PowerShell Core exists, otherwise use Windows PowerShell
|
||||
const fs = await import('fs');
|
||||
if (fs.existsSync(powershell)) {
|
||||
shell = powershell;
|
||||
shellArgs = ['-NoProfile', '-NonInteractive', '-Command', commandToExecute];
|
||||
} else if (process.env.COMSPEC) {
|
||||
shell = process.env.COMSPEC;
|
||||
shellArgs = ['/d', '/s', '/c', commandToExecute];
|
||||
} else {
|
||||
shell = 'cmd.exe';
|
||||
shellArgs = ['/d', '/s', '/c', commandToExecute];
|
||||
}
|
||||
} else {
|
||||
// POSIX: Use SHELL env var or bash as default
|
||||
shell = process.env.SHELL || '/bin/bash';
|
||||
shellArgs = ['-c', commandToExecute];
|
||||
}
|
||||
|
||||
// Create PTY process
|
||||
const ptyProcess = pty.spawn(shell, shellArgs, {
|
||||
name: options.ptyTerm || 'xterm-256color',
|
||||
cols: options.ptyCols || 120,
|
||||
rows: options.ptyRows || 30,
|
||||
cwd: process.cwd(),
|
||||
env: options.env || process.env,
|
||||
});
|
||||
|
||||
// Add to smartexit (wrap in a minimal object with pid)
|
||||
this.smartexit.addProcess({ pid: ptyProcess.pid } as any);
|
||||
|
||||
// Handle output (stdout and stderr are combined in PTY)
|
||||
ptyProcess.onData((data: string) => {
|
||||
if (!options.silent) {
|
||||
shellLogInstance.writeToConsole(data);
|
||||
}
|
||||
shellLogInstance.addToBuffer(data);
|
||||
});
|
||||
|
||||
// Wrap PTY termination into a Promise
|
||||
const childProcessEnded: Promise<IExecResult> = new Promise((resolve, reject) => {
|
||||
ptyProcess.onExit(({ exitCode, signal }: { exitCode: number; signal?: number }) => {
|
||||
this.smartexit.removeProcess({ pid: ptyProcess.pid } as any);
|
||||
|
||||
const execResult: IExecResult = {
|
||||
exitCode: exitCode ?? (signal ? 1 : 0),
|
||||
stdout: shellLogInstance.logStore.toString(),
|
||||
};
|
||||
|
||||
if (options.strict && exitCode !== 0) {
|
||||
reject(new Error(`Command "${options.commandString}" exited with code ${exitCode}`));
|
||||
} else {
|
||||
resolve(execResult);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Create input methods for PTY
|
||||
const sendInput = async (input: string): Promise<void> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
ptyProcess.write(input);
|
||||
resolve();
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const sendLine = async (line: string): Promise<void> => {
|
||||
// Use \r for PTY (carriage return is typical for terminal line discipline)
|
||||
return sendInput(line + '\r');
|
||||
};
|
||||
|
||||
const endInput = (): void => {
|
||||
// Send EOF (Ctrl+D) to PTY
|
||||
ptyProcess.write('\x04');
|
||||
};
|
||||
|
||||
// If interactive control is enabled but not streaming, return interactive interface
|
||||
if (options.interactiveControl && !options.streaming) {
|
||||
return {
|
||||
exitCode: 0, // Will be updated when process ends
|
||||
stdout: '', // Will be updated when process ends
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
finalPromise: childProcessEnded,
|
||||
} as IExecResultInteractive;
|
||||
}
|
||||
|
||||
// If streaming mode is enabled, return a streaming interface
|
||||
if (options.streaming) {
|
||||
return {
|
||||
childProcess: { pid: ptyProcess.pid } as any, // Minimal compatibility object
|
||||
finalPromise: childProcessEnded,
|
||||
sendInput,
|
||||
sendLine,
|
||||
endInput,
|
||||
kill: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Killing PTY process ${ptyProcess.pid}`);
|
||||
}
|
||||
ptyProcess.kill();
|
||||
},
|
||||
terminate: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Terminating PTY process ${ptyProcess.pid}`);
|
||||
}
|
||||
ptyProcess.kill('SIGTERM');
|
||||
},
|
||||
keyboardInterrupt: async () => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Sending SIGINT to PTY process ${ptyProcess.pid}`);
|
||||
}
|
||||
ptyProcess.kill('SIGINT');
|
||||
},
|
||||
customSignal: async (signal: plugins.smartexit.TProcessSignal) => {
|
||||
if (options.debug) {
|
||||
console.log(`[smartshell] Sending ${signal} to PTY process ${ptyProcess.pid}`);
|
||||
}
|
||||
ptyProcess.kill(signal as any);
|
||||
},
|
||||
} as IExecResultStreaming;
|
||||
}
|
||||
|
||||
// For non-streaming mode, wait for the process to complete
|
||||
return await childProcessEnded;
|
||||
}
|
||||
}
|
@@ -1,2 +1,3 @@
|
||||
export * from './smartshell.wrap'
|
||||
export * from './smartshell.classes.smartshell'
|
||||
export * from './classes.smartshell.js';
|
||||
export * from './classes.smartexecution.js';
|
||||
export { which } from './plugins.js';
|
||||
|
6
ts/plugins.ts
Normal file
6
ts/plugins.ts
Normal 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 };
|
@@ -1,65 +0,0 @@
|
||||
import * as plugins from './smartshell.plugins'
|
||||
import * as smartshellWrap from './smartshell.wrap'
|
||||
|
||||
export type TExecutor = 'sh' | 'bash'
|
||||
|
||||
export interface ISmartshellContructorOptions {
|
||||
executor: TExecutor
|
||||
sourceFilePaths: string[]
|
||||
|
||||
}
|
||||
|
||||
export class Smartshell {
|
||||
executor: TExecutor
|
||||
sourceFileArray: string[] = []
|
||||
constructor (optionsArg: ISmartshellContructorOptions) {
|
||||
this.executor = optionsArg.executor
|
||||
for (let sourceFilePath of optionsArg.sourceFilePaths) {
|
||||
this.sourceFileArray.push(sourceFilePath)
|
||||
}
|
||||
}
|
||||
|
||||
addSourceFiles(sourceFilePathsArray: string[]) {
|
||||
for(let sourceFilePath of sourceFilePathsArray) {
|
||||
this.sourceFileArray.push(sourceFilePath)
|
||||
}
|
||||
}
|
||||
|
||||
cleanSourceFiles () {
|
||||
this.sourceFileArray = []
|
||||
}
|
||||
|
||||
/**
|
||||
* executes silently and returns IExecResult
|
||||
* @param commandArg
|
||||
*/
|
||||
async execSilent (commandArg: string) {
|
||||
let execCommand = this.createExecString(commandArg)
|
||||
return await smartshellWrap.execSilent(execCommand)
|
||||
}
|
||||
|
||||
/**
|
||||
* executes and returns IExecResult
|
||||
* @param commandArg
|
||||
*/
|
||||
async exec (commandArg: string) {
|
||||
let execCommand = this.createExecString(commandArg)
|
||||
return await smartshellWrap.exec(execCommand)
|
||||
}
|
||||
|
||||
/**
|
||||
* creates the final sourcing string
|
||||
* @param commandArg
|
||||
*/
|
||||
private createExecString (commandArg): string {
|
||||
if (this.executor === 'bash') {
|
||||
let sourceString = ''
|
||||
for (let sourceFilePath of this.sourceFileArray) {
|
||||
sourceString = sourceString + `source ${sourceFilePath} && `
|
||||
}
|
||||
return `bash -c '${sourceString} ${commandArg}'`
|
||||
} else {
|
||||
return commandArg
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,9 +0,0 @@
|
||||
import * as shelljs from 'shelljs'
|
||||
import * as smartq from 'smartq'
|
||||
import * as which from 'which'
|
||||
|
||||
export {
|
||||
shelljs,
|
||||
smartq,
|
||||
which
|
||||
}
|
@@ -1,98 +0,0 @@
|
||||
import * as plugins from './smartshell.plugins'
|
||||
|
||||
// interfaces
|
||||
import { ChildProcess } from 'child_process'
|
||||
import { Deferred } from 'smartq'
|
||||
|
||||
/**
|
||||
* interface for ExecResult
|
||||
*/
|
||||
export interface IExecResult {
|
||||
exitCode: number,
|
||||
stdout: string
|
||||
}
|
||||
|
||||
/**
|
||||
* interface for streaming ExecResult
|
||||
*/
|
||||
export interface IExecResultStreaming {
|
||||
childProcess: ChildProcess,
|
||||
finalPromise: Promise<IExecResult>
|
||||
}
|
||||
|
||||
/**
|
||||
* executes a given command async
|
||||
* @param commandStringArg
|
||||
*/
|
||||
export let exec = (commandStringArg: string): Promise<IExecResult> => {
|
||||
let done = plugins.smartq.defer<IExecResult>()
|
||||
plugins.shelljs.exec(commandStringArg, { async: true }, (code, stdout, stderr) => {
|
||||
done.resolve({
|
||||
exitCode: code,
|
||||
stdout: stdout
|
||||
})
|
||||
})
|
||||
return done.promise
|
||||
}
|
||||
|
||||
/**
|
||||
* executes a given command async and silent
|
||||
* @param commandStringArg
|
||||
*/
|
||||
export let execSilent = (commandStringArg: string) => {
|
||||
let done = plugins.smartq.defer<IExecResult>()
|
||||
plugins.shelljs.exec(commandStringArg, { async: true, silent: true }, (code, stdout, stderr) => {
|
||||
done.resolve({
|
||||
exitCode: code,
|
||||
stdout: stdout
|
||||
})
|
||||
})
|
||||
return done.promise
|
||||
}
|
||||
|
||||
/**
|
||||
* executes a command and allws you to stream output
|
||||
*/
|
||||
export let execStreaming = (commandStringArg: string) => {
|
||||
let childProcessEnded = plugins.smartq.defer<IExecResult>()
|
||||
let execChildProcess = plugins.shelljs.exec(commandStringArg, {async: true, silent: true}, (code, stdout, stderr) => {
|
||||
childProcessEnded.resolve({
|
||||
exitCode: code,
|
||||
stdout: stdout
|
||||
})
|
||||
})
|
||||
return {
|
||||
childProcess: execChildProcess,
|
||||
finalPromise: childProcessEnded.promise
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* executes a command and returns promise that will be fullfilled once an putput line matches RegexArg
|
||||
* @param commandStringArg
|
||||
* @param regexArg
|
||||
*/
|
||||
export let execAndWaitForLine = (commandStringArg: string, regexArg: RegExp) => {
|
||||
let done = plugins.smartq.defer()
|
||||
let execStreamingResult = execStreaming(commandStringArg)
|
||||
execStreamingResult.childProcess.on('data', (stdOutChunk: string) => {
|
||||
if (regexArg.test(stdOutChunk)) {
|
||||
done.resolve()
|
||||
}
|
||||
})
|
||||
return done.promise
|
||||
}
|
||||
|
||||
/**
|
||||
* get a path
|
||||
*/
|
||||
export let which = (cmd: string): Promise<string> => {
|
||||
let done = plugins.smartq.defer()
|
||||
plugins.which(cmd, (err, path: string) => {
|
||||
if (err) {
|
||||
done.reject(err)
|
||||
}
|
||||
done.resolve(path)
|
||||
})
|
||||
return done.promise
|
||||
}
|
14
tsconfig.json
Normal file
14
tsconfig.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"useDefineForClassFields": false,
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"esModuleInterop": true,
|
||||
"verbatimModuleSyntax": true
|
||||
},
|
||||
"exclude": [
|
||||
"dist_*/**/*.d.ts"
|
||||
]
|
||||
}
|
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"extends": "tslint-config-standard"
|
||||
}
|
304
yarn.lock
304
yarn.lock
@@ -1,304 +0,0 @@
|
||||
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
|
||||
# yarn lockfile v1
|
||||
|
||||
|
||||
"@types/chai-as-promised@0.0.29":
|
||||
version "0.0.29"
|
||||
resolved "https://registry.yarnpkg.com/@types/chai-as-promised/-/chai-as-promised-0.0.29.tgz#43d52892aa998e185a3de3e2477edb8573be1d77"
|
||||
dependencies:
|
||||
"@types/chai" "*"
|
||||
"@types/promises-a-plus" "*"
|
||||
|
||||
"@types/chai-string@^1.1.30":
|
||||
version "1.1.30"
|
||||
resolved "https://registry.yarnpkg.com/@types/chai-string/-/chai-string-1.1.30.tgz#4d8744b31a5a2295fc01c981ed1e2d4c8a070f0a"
|
||||
dependencies:
|
||||
"@types/chai" "*"
|
||||
|
||||
"@types/chai@*", "@types/chai@^3.4.35":
|
||||
version "3.5.2"
|
||||
resolved "https://registry.yarnpkg.com/@types/chai/-/chai-3.5.2.tgz#c11cd2817d3a401b7ba0f5a420f35c56139b1c1e"
|
||||
|
||||
"@types/node@*":
|
||||
version "8.0.1"
|
||||
resolved "https://registry.yarnpkg.com/@types/node/-/node-8.0.1.tgz#89c271e0c3b9ebb6a3756dd601336970b6228b77"
|
||||
|
||||
"@types/promises-a-plus@*":
|
||||
version "0.0.27"
|
||||
resolved "https://registry.yarnpkg.com/@types/promises-a-plus/-/promises-a-plus-0.0.27.tgz#c64651134614c84b8f5d7114ce8901d36a609780"
|
||||
|
||||
"@types/shelljs@^0.6.0":
|
||||
version "0.6.0"
|
||||
resolved "https://registry.yarnpkg.com/@types/shelljs/-/shelljs-0.6.0.tgz#090b705c102ce7fc5c0c5ea9b524418ff15840df"
|
||||
dependencies:
|
||||
"@types/node" "*"
|
||||
|
||||
"@types/shelljs@^0.7.2":
|
||||
version "0.7.2"
|
||||
resolved "https://registry.yarnpkg.com/@types/shelljs/-/shelljs-0.7.2.tgz#c2bdb3fe80cd7a3da08750ca898ae44c589671f3"
|
||||
dependencies:
|
||||
"@types/node" "*"
|
||||
|
||||
"@types/which@^1.0.28":
|
||||
version "1.0.28"
|
||||
resolved "https://registry.yarnpkg.com/@types/which/-/which-1.0.28.tgz#016e387629b8817bed653fe32eab5d11279c8df6"
|
||||
|
||||
ansi-256-colors@^1.1.0:
|
||||
version "1.1.0"
|
||||
resolved "https://registry.yarnpkg.com/ansi-256-colors/-/ansi-256-colors-1.1.0.tgz#910de50efcc7c09e3d82f2f87abd6b700c18818a"
|
||||
|
||||
assertion-error@^1.0.1:
|
||||
version "1.0.2"
|
||||
resolved "https://registry.yarnpkg.com/assertion-error/-/assertion-error-1.0.2.tgz#13ca515d86206da0bac66e834dd397d87581094c"
|
||||
|
||||
balanced-match@^1.0.0:
|
||||
version "1.0.0"
|
||||
resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767"
|
||||
|
||||
beautycolor@^1.0.7:
|
||||
version "1.0.7"
|
||||
resolved "https://registry.yarnpkg.com/beautycolor/-/beautycolor-1.0.7.tgz#a4715738ac4c8221371e9cbeb5a6cc6d11ecbf7c"
|
||||
dependencies:
|
||||
ansi-256-colors "^1.1.0"
|
||||
typings-global "^1.0.14"
|
||||
|
||||
bindings@^1.2.1:
|
||||
version "1.2.1"
|
||||
resolved "https://registry.yarnpkg.com/bindings/-/bindings-1.2.1.tgz#14ad6113812d2d37d72e67b4cacb4bb726505f11"
|
||||
|
||||
brace-expansion@^1.1.7:
|
||||
version "1.1.8"
|
||||
resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.8.tgz#c07b211c7c952ec1f8efd51a77ef0d1d3990a292"
|
||||
dependencies:
|
||||
balanced-match "^1.0.0"
|
||||
concat-map "0.0.1"
|
||||
|
||||
chai-as-promised@^6.0.0:
|
||||
version "6.0.0"
|
||||
resolved "https://registry.yarnpkg.com/chai-as-promised/-/chai-as-promised-6.0.0.tgz#1a02a433a6f24dafac63b9c96fa1684db1aa8da6"
|
||||
dependencies:
|
||||
check-error "^1.0.2"
|
||||
|
||||
chai-string@^1.3.0:
|
||||
version "1.4.0"
|
||||
resolved "https://registry.yarnpkg.com/chai-string/-/chai-string-1.4.0.tgz#359140c051d36a4e4b1a5fc6b910152f438a8d49"
|
||||
|
||||
chai@^3.5.0:
|
||||
version "3.5.0"
|
||||
resolved "https://registry.yarnpkg.com/chai/-/chai-3.5.0.tgz#4d02637b067fe958bdbfdd3a40ec56fef7373247"
|
||||
dependencies:
|
||||
assertion-error "^1.0.1"
|
||||
deep-eql "^0.1.3"
|
||||
type-detect "^1.0.0"
|
||||
|
||||
check-error@^1.0.2:
|
||||
version "1.0.2"
|
||||
resolved "https://registry.yarnpkg.com/check-error/-/check-error-1.0.2.tgz#574d312edd88bb5dd8912e9286dd6c0aed4aac82"
|
||||
|
||||
concat-map@0.0.1:
|
||||
version "0.0.1"
|
||||
resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b"
|
||||
|
||||
deep-eql@^0.1.3:
|
||||
version "0.1.3"
|
||||
resolved "https://registry.yarnpkg.com/deep-eql/-/deep-eql-0.1.3.tgz#ef558acab8de25206cd713906d74e56930eb69f2"
|
||||
dependencies:
|
||||
type-detect "0.1.1"
|
||||
|
||||
early@^2.1.1:
|
||||
version "2.1.1"
|
||||
resolved "https://registry.yarnpkg.com/early/-/early-2.1.1.tgz#841e23254ea5dc54d8afaeee82f5ab65c00ee23c"
|
||||
dependencies:
|
||||
beautycolor "^1.0.7"
|
||||
smartq "^1.1.1"
|
||||
typings-global "^1.0.16"
|
||||
|
||||
es6-error@^4.0.2:
|
||||
version "4.0.2"
|
||||
resolved "https://registry.yarnpkg.com/es6-error/-/es6-error-4.0.2.tgz#eec5c726eacef51b7f6b73c20db6e1b13b069c98"
|
||||
|
||||
fs.realpath@^1.0.0:
|
||||
version "1.0.0"
|
||||
resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f"
|
||||
|
||||
glob@^7.0.0:
|
||||
version "7.1.2"
|
||||
resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.2.tgz#c19c9df9a028702d678612384a6552404c636d15"
|
||||
dependencies:
|
||||
fs.realpath "^1.0.0"
|
||||
inflight "^1.0.4"
|
||||
inherits "2"
|
||||
minimatch "^3.0.4"
|
||||
once "^1.3.0"
|
||||
path-is-absolute "^1.0.0"
|
||||
|
||||
inflight@^1.0.4:
|
||||
version "1.0.6"
|
||||
resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9"
|
||||
dependencies:
|
||||
once "^1.3.0"
|
||||
wrappy "1"
|
||||
|
||||
inherits@2:
|
||||
version "2.0.3"
|
||||
resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de"
|
||||
|
||||
interpret@^1.0.0:
|
||||
version "1.0.3"
|
||||
resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.0.3.tgz#cbc35c62eeee73f19ab7b10a801511401afc0f90"
|
||||
|
||||
isexe@^2.0.0:
|
||||
version "2.0.0"
|
||||
resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10"
|
||||
|
||||
leakage@^0.3.0:
|
||||
version "0.3.0"
|
||||
resolved "https://registry.yarnpkg.com/leakage/-/leakage-0.3.0.tgz#15d698abdc76bbc6439601f4f3020e77e2d50c39"
|
||||
dependencies:
|
||||
es6-error "^4.0.2"
|
||||
left-pad "^1.1.3"
|
||||
memwatch-next "^0.3.0"
|
||||
minimist "^1.2.0"
|
||||
pretty-bytes "^4.0.2"
|
||||
|
||||
left-pad@^1.1.3:
|
||||
version "1.1.3"
|
||||
resolved "https://registry.yarnpkg.com/left-pad/-/left-pad-1.1.3.tgz#612f61c033f3a9e08e939f1caebeea41b6f3199a"
|
||||
|
||||
memwatch-next@^0.3.0:
|
||||
version "0.3.0"
|
||||
resolved "https://registry.yarnpkg.com/memwatch-next/-/memwatch-next-0.3.0.tgz#2111050f9a906e0aa2d72a4ec0f0089c78726f8f"
|
||||
dependencies:
|
||||
bindings "^1.2.1"
|
||||
nan "^2.3.2"
|
||||
|
||||
minimatch@^3.0.4:
|
||||
version "3.0.4"
|
||||
resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083"
|
||||
dependencies:
|
||||
brace-expansion "^1.1.7"
|
||||
|
||||
minimist@^1.2.0:
|
||||
version "1.2.0"
|
||||
resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284"
|
||||
|
||||
nan@^2.3.2:
|
||||
version "2.6.2"
|
||||
resolved "https://registry.yarnpkg.com/nan/-/nan-2.6.2.tgz#e4ff34e6c95fdfb5aecc08de6596f43605a7db45"
|
||||
|
||||
once@^1.3.0:
|
||||
version "1.4.0"
|
||||
resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1"
|
||||
dependencies:
|
||||
wrappy "1"
|
||||
|
||||
path-is-absolute@^1.0.0:
|
||||
version "1.0.1"
|
||||
resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f"
|
||||
|
||||
path-parse@^1.0.5:
|
||||
version "1.0.5"
|
||||
resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.5.tgz#3c1adf871ea9cd6c9431b6ea2bd74a0ff055c4c1"
|
||||
|
||||
pretty-bytes@^4.0.2:
|
||||
version "4.0.2"
|
||||
resolved "https://registry.yarnpkg.com/pretty-bytes/-/pretty-bytes-4.0.2.tgz#b2bf82e7350d65c6c33aa95aaa5a4f6327f61cd9"
|
||||
|
||||
rechoir@^0.6.2:
|
||||
version "0.6.2"
|
||||
resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.6.2.tgz#85204b54dba82d5742e28c96756ef43af50e3384"
|
||||
dependencies:
|
||||
resolve "^1.1.6"
|
||||
|
||||
resolve@^1.1.6:
|
||||
version "1.3.3"
|
||||
resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.3.3.tgz#655907c3469a8680dc2de3a275a8fdd69691f0e5"
|
||||
dependencies:
|
||||
path-parse "^1.0.5"
|
||||
|
||||
semver@^5.3.0:
|
||||
version "5.3.0"
|
||||
resolved "https://registry.yarnpkg.com/semver/-/semver-5.3.0.tgz#9b2ce5d3de02d17c6012ad326aa6b4d0cf54f94f"
|
||||
|
||||
shelljs@^0.7.6, shelljs@^0.7.8:
|
||||
version "0.7.8"
|
||||
resolved "https://registry.yarnpkg.com/shelljs/-/shelljs-0.7.8.tgz#decbcf874b0d1e5fb72e14b164a9683048e9acb3"
|
||||
dependencies:
|
||||
glob "^7.0.0"
|
||||
interpret "^1.0.0"
|
||||
rechoir "^0.6.2"
|
||||
|
||||
smartchai@^1.0.3:
|
||||
version "1.0.3"
|
||||
resolved "https://registry.yarnpkg.com/smartchai/-/smartchai-1.0.3.tgz#de6d010bb8b5aef24cb70b31a5f5334e8c41b72f"
|
||||
dependencies:
|
||||
"@types/chai" "^3.4.35"
|
||||
"@types/chai-as-promised" "0.0.29"
|
||||
"@types/chai-string" "^1.1.30"
|
||||
chai "^3.5.0"
|
||||
chai-as-promised "^6.0.0"
|
||||
chai-string "^1.3.0"
|
||||
|
||||
smartdelay@^1.0.3:
|
||||
version "1.0.3"
|
||||
resolved "https://registry.yarnpkg.com/smartdelay/-/smartdelay-1.0.3.tgz#5fd44dad77262d110702f0293efa80c072cfb579"
|
||||
dependencies:
|
||||
smartq "^1.1.1"
|
||||
typings-global "^1.0.16"
|
||||
|
||||
smartq@^1.1.0, smartq@^1.1.1:
|
||||
version "1.1.1"
|
||||
resolved "https://registry.yarnpkg.com/smartq/-/smartq-1.1.1.tgz#efb358705260d41ae18aef7ffd815f7b6fe17dd3"
|
||||
dependencies:
|
||||
typed-promisify "^0.3.0"
|
||||
typings-global "^1.0.14"
|
||||
|
||||
smartshell@^1.0.6:
|
||||
version "1.0.6"
|
||||
resolved "https://registry.yarnpkg.com/smartshell/-/smartshell-1.0.6.tgz#27b1c79029784abe72ac7e91fe698b7ebecc6629"
|
||||
dependencies:
|
||||
"@types/shelljs" "^0.6.0"
|
||||
"@types/which" "^1.0.28"
|
||||
shelljs "^0.7.6"
|
||||
smartq "^1.1.0"
|
||||
which "^1.2.12"
|
||||
|
||||
tapbundle@^1.0.14:
|
||||
version "1.0.14"
|
||||
resolved "https://registry.yarnpkg.com/tapbundle/-/tapbundle-1.0.14.tgz#75827e335fcb02216f0267a26a26d702ddc02e3c"
|
||||
dependencies:
|
||||
early "^2.1.1"
|
||||
leakage "^0.3.0"
|
||||
smartchai "^1.0.3"
|
||||
smartdelay "^1.0.3"
|
||||
smartq "^1.1.1"
|
||||
typings-global "^1.0.16"
|
||||
|
||||
type-detect@0.1.1:
|
||||
version "0.1.1"
|
||||
resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-0.1.1.tgz#0ba5ec2a885640e470ea4e8505971900dac58822"
|
||||
|
||||
type-detect@^1.0.0:
|
||||
version "1.0.0"
|
||||
resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-1.0.0.tgz#762217cc06db258ec48908a1298e8b95121e8ea2"
|
||||
|
||||
typed-promisify@^0.3.0:
|
||||
version "0.3.0"
|
||||
resolved "https://registry.yarnpkg.com/typed-promisify/-/typed-promisify-0.3.0.tgz#1ba0af5e444c87d8047406f18ce49092a1191853"
|
||||
|
||||
typings-global@^1.0.14, typings-global@^1.0.16, typings-global@^1.0.19:
|
||||
version "1.0.19"
|
||||
resolved "https://registry.yarnpkg.com/typings-global/-/typings-global-1.0.19.tgz#3376a72d4de1e5541bf5702248ff64c3e6ea316c"
|
||||
dependencies:
|
||||
semver "^5.3.0"
|
||||
smartshell "^1.0.6"
|
||||
|
||||
which@^1.2.12, which@^1.2.14:
|
||||
version "1.2.14"
|
||||
resolved "https://registry.yarnpkg.com/which/-/which-1.2.14.tgz#9a87c4378f03e827cecaf1acdf56c736c01c14e5"
|
||||
dependencies:
|
||||
isexe "^2.0.0"
|
||||
|
||||
wrappy@1:
|
||||
version "1.0.2"
|
||||
resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"
|
Reference in New Issue
Block a user