Compare commits

..

22 Commits

Author SHA1 Message Date
2896cc396f 1.6.2
Some checks failed
Default (tags) / security (push) Failing after 1s
Default (tags) / test (push) Failing after 1s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-10-17 06:43:36 +00:00
e76ad2fb58 fix(ts/index): Use cli.js as the spawned CLI entry point instead of cli.child.js 2025-10-17 06:43:36 +00:00
6b6ecee0ed 1.6.1
Some checks failed
Default (tags) / security (push) Failing after 1s
Default (tags) / test (push) Failing after 1s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-10-17 06:26:00 +00:00
e5b57c894b fix(plugins): Export child_process.spawn from plugins and use plugins.spawn in spawnPath to remove direct require and unify process spawning 2025-10-17 06:26:00 +00:00
ec2db7af72 1.6.0
Some checks failed
Default (tags) / security (push) Failing after 1s
Default (tags) / test (push) Failing after 1s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-10-17 06:15:33 +00:00
9b5668eccb feat(core): Add spawnPath child-process API with timeout/abort/terminate support, export native types, and expand README 2025-10-17 06:15:33 +00:00
528a56c358 1.5.0
Some checks failed
Default (tags) / security (push) Failing after 1s
Default (tags) / test (push) Failing after 1s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-10-16 20:49:03 +00:00
7fb2389e3a feat(core): Add cwd option and child-process execution for custom working directory; implement signal-forwarding child runner; update docs and bump package version to 1.4.0 2025-10-16 20:49:03 +00:00
e9ae00f5e9 1.3.4
Some checks failed
Default (tags) / security (push) Failing after 1s
Default (tags) / test (push) Failing after 1s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-10-13 21:28:27 +00:00
4cd8bf5c1a fix(docs): Update README with expanded docs and examples; add pnpm and CI tooling configs 2025-10-13 21:28:27 +00:00
2bba5f75e6 1.3.3 2024-10-27 19:46:14 +01:00
74bb4a9837 fix(core): removed unused import statement in ts/plugins.ts 2024-10-27 19:46:13 +01:00
3286776b48 1.3.2 2024-10-27 19:45:58 +01:00
bec80e6862 fix(core): Replace ts-node with tsx for module handling 2024-10-27 19:45:57 +01:00
c2e406964d 1.3.1 2024-10-27 19:22:45 +01:00
c3e3b2d050 fix(core): Add console.log to show ts-node options in use 2024-10-27 19:22:45 +01:00
3a68f74c4e 1.3.0 2024-10-27 19:11:55 +01:00
8f4292f402 feat(ci): Add Gitea workflows for build and release. 2024-10-27 19:11:55 +01:00
61a82f0d03 1.2.49 2024-06-24 12:06:14 +02:00
2c8f262c0a fix(core): Minor maintenance updates with version bump 2024-06-24 12:06:13 +02:00
bd5ec7ca76 1.2.48 2024-06-24 12:05:44 +02:00
857882807f fix(dependencies): Update TypeScript dependency version 2024-06-24 12:05:44 +02:00
15 changed files with 4716 additions and 580 deletions

View File

@@ -0,0 +1,66 @@
name: Default (not tags)
on:
push:
tags-ignore:
- '**'
env:
IMAGE: code.foss.global/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build

View File

@@ -0,0 +1,124 @@
name: Default (tags)
on:
push:
tags:
- '*'
env:
IMAGE: code.foss.global/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @ship.zone/npmci
npmci npm prepare
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
pnpm install -g @git.zone/tsdoc
npmci command tsdoc
continue-on-error: true

1
.serena/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/cache

67
.serena/project.yml Normal file
View File

@@ -0,0 +1,67 @@
# 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: "tsrun"

View File

@@ -1,5 +1,82 @@
# Changelog
## 2025-10-17 - 1.6.2 - fix(ts/index)
Use cli.js as the spawned CLI entry point instead of cli.child.js
- Replace references to ../cli.child.js with ../cli.js in ts/index.ts (runInChildProcess and spawnPath) to ensure child processes spawn the correct CLI entry point.
- This change fixes child process spawning failures caused by referencing a non-existent cli.child.js file.
- Add local .claude/settings.local.json (local runner/editor permissions configuration).
## 2025-10-17 - 1.6.1 - fix(plugins)
Export child_process.spawn from plugins and use plugins.spawn in spawnPath to remove direct require and unify process spawning
- Exported spawn from ts/plugins.ts so native child_process.spawn is available via the plugins module
- Removed require('child_process') from ts/index.ts and switched to plugins.spawn when spawning child processes in spawnPath
- No public API changes; this unifies internal imports and fixes inconsistent spawn usage that could cause runtime issues
## 2025-10-17 - 1.6.0 - feat(core)
Add spawnPath child-process API with timeout/abort/terminate support, export native types, and expand README
- Implement spawnPath(filePath, fromFileUrl?, options?) in ts/index.ts producing an ITsrunChildProcess with childProcess, stdout, stderr, exitCode, kill() and terminate()
- Introduce ISpawnOptions (cwd, env, args, stdio, timeout, signal) and ITsrunChildProcess interfaces for robust process control
- Handle timeouts (auto SIGTERM), AbortSignal cancellation, and graceful terminate() (SIGTERM then SIGKILL after 5s)
- Export Node types ChildProcess and Readable from ts/plugins.ts for improved typings
- Greatly expand README: add badges, table of contents, detailed API docs and examples for runPath, runCli and spawnPath, and troubleshooting guidance
- Add local .claude/settings.local.json (environment/settings file)
## 2025-10-16 - 1.5.0 - feat(core)
Add cwd option and child-process execution for custom working directory; implement signal-forwarding child runner; update docs and bump package version to 1.4.0
- Introduce IRunOptions with cwd support to runPath/runCli
- When cwd is provided, runCli now spawns a child process (runInChildProcess) to execute the script in the specified working directory
- runInChildProcess preserves node execArgv, inherits env and stdio, forwards signals (SIGINT, SIGTERM, SIGHUP) and propagates child exit codes/signals
- Update README with documentation and examples for running scripts with a custom working directory and parallel execution
- Bump package version to 1.4.0
## 2025-10-13 - 1.3.4 - fix(docs)
Update README with expanded docs and examples; add pnpm and CI tooling configs
- Rewrite and expand README: clearer intro, installation, CLI and programmatic usage examples, features and examples, and updated package/project links.
- Add packageManager entry to package.json to record pnpm version/hash (pnpm@10.18.1+sha512...).
- Add pnpm-workspace.yaml with onlyBuiltDependencies for esbuild.
- Add .serena/project.yml and .serena/.gitignore for project metadata and Serena tooling configuration.
- Add .claude/settings.local.json to configure local agent permissions.
- No functional TypeScript source changes in this commit (runtime implementations remain as placeholders).
## 2024-10-27 - 1.3.3 - fix(core)
removed unused import statement in ts/plugins.ts
- Cleanup: Removed an unused import statement for tsImport from tsx/esm/api
## 2024-10-27 - 1.3.2 - fix(core)
Replace ts-node with tsx for module handling
- Removed ts-node and its loader, using tsx for module imports
- Simplified import logic by replacing tsx register API call
- Updated dependencies in package.json by removing ts-node and typescript
## 2024-10-27 - 1.3.1 - fix(core)
Add console.log to show ts-node options in use
- Added a console log statement in the ts/loader.ts to display the default ts-node options being used.
## 2024-10-27 - 1.3.0 - feat(ci)
Add Gitea workflows for build and release.
- Added .gitea/workflows/default_nottags.yaml for non-tag events.
- Added .gitea/workflows/default_tags.yaml for tag-based events.
- Updated build scripts in package.json to use pnpm.
- Refactored imports and exports in TypeScript source for better modularity.
## 2024-06-24 - 1.2.49 - fix(core)
Minor maintenance updates with version bump
## 2024-06-24 - 1.2.48 - fix(dependencies)
Update TypeScript dependency version
- Updated TypeScript from version 5.4.5 to 5.5.2 to include latest features and fixes.
## 2024-06-24 - 1.2.47 - fix(core)
Remove GitLab CI configuration and update dependencies

View File

@@ -1,6 +1,6 @@
{
"name": "@git.zone/tsrun",
"version": "1.2.47",
"version": "1.6.2",
"description": "run typescript programs efficiently",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
@@ -11,9 +11,9 @@
"tsrun": "./cli.js"
},
"scripts": {
"test": "(tsbuild && node ./cli.js test/test.js sayhello)",
"test": "(pnpm run build && node ./cli.js test/test.js sayhello)",
"format": "(gitzone format)",
"build": "(tsbuild)",
"build": "(tsbuild --web --allowimplicitany)",
"buildDocs": "tsdoc"
},
"devDependencies": {
@@ -25,8 +25,7 @@
"dependencies": {
"@push.rocks/smartfile": "^11.0.21",
"@push.rocks/smartshell": "^3.0.5",
"ts-node": "^10.9.2",
"typescript": "5.4.5"
"tsx": "^4.19.2"
},
"private": false,
"files": [
@@ -43,5 +42,14 @@
],
"browserslist": [
"last 1 chrome versions"
]
],
"repository": {
"type": "git",
"url": "git+https://gitlab.com/gitzone/tsrun.git"
},
"bugs": {
"url": "https://gitlab.com/gitzone/tsrun/issues"
},
"homepage": "https://gitlab.com/gitzone/tsrun#readme",
"packageManager": "pnpm@10.18.1+sha512.77a884a165cbba2d8d1c19e3b4880eee6d2fcabd0d879121e282196b80042351d5eb3ca0935fa599da1dc51265cc68816ad2bddd2a2de5ea9fdf92adbec7cd34"
}

4125
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

2
pnpm-workspace.yaml Normal file
View File

@@ -0,0 +1,2 @@
onlyBuiltDependencies:
- esbuild

494
readme.md
View File

@@ -1,47 +1,477 @@
# @gitzone/tsrun
run typescript programs efficiently
# @git.zone/tsrun
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@gitzone/tsrun)
* [gitlab.com (source)](https://gitlab.com/gitzone/tsrun)
* [github.com (source mirror)](https://github.com/gitzone/tsrun)
* [docs (typedoc)](https://gitzone.gitlab.io/tsrun/)
[![npm version](https://img.shields.io/npm/v/@git.zone/tsrun.svg)](https://www.npmjs.com/package/@git.zone/tsrun)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-%3E%3D3.x-blue)](https://www.typescriptlang.org/)
[![Node.js](https://img.shields.io/badge/Node.js-%3E%3D16.x-green)](https://nodejs.org/)
## Status for master
> Run TypeScript files instantly, without the compilation hassle ⚡
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/gitzone/tsrun/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/gitzone/tsrun/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@gitzone/tsrun)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/gitzone/tsrun)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@gitzone/tsrun)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@gitzone/tsrun)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@gitzone/tsrun)](https://lossless.cloud)
Execute TypeScript programs on-the-fly with zero configuration. Perfect for scripts, prototyping, and development workflows.
## Table of Contents
- [What is tsrun?](#what-is-tsrun)
- [Installation](#installation)
- [Usage](#usage)
- [CLI Usage](#-cli-usage)
- [Programmatic API](#-programmatic-api)
- [Features](#features)
- [Why tsrun?](#why-tsrun)
- [Common Use Cases](#common-use-cases)
- [API Reference](#api-reference)
- [Examples](#examples)
- [Package Information](#package-information)
- [Requirements](#requirements)
- [Troubleshooting](#troubleshooting)
- [License and Legal Information](#license-and-legal-information)
## What is tsrun?
**tsrun** is a lightweight TypeScript execution tool that lets you run `.ts` files directly—no build step required. It's like running JavaScript with `node`, but for TypeScript. Under the hood, tsrun uses [tsx](https://github.com/esbuild-kit/tsx) for lightning-fast execution while keeping your workflow simple and efficient.
## Installation
```bash
npm install -g @git.zone/tsrun
```
Or as a project dependency:
```bash
npm install --save-dev @git.zone/tsrun
```
## Usage
Use TypeScript for best in class instellisense.
### 🚀 CLI Usage
To simply run a TypeScript file on the fly type
Simply run any TypeScript file:
```typescript
tsrun myfiletorun.ts
```bash
tsrun myScript.ts
```
There are options available:
Pass arguments to your script transparently:
- `--web` will inject browser types. this is useful when testing code with polyfills on node, but that is meant for the browser later on.
```bash
tsrun myScript.ts --config production --verbose
```
## Contribution
All arguments are passed through to your TypeScript program, just as if you were running it with `node`.
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
### 💻 Programmatic API
For further information read the linked docs at the top of this readme.
tsrun provides three powerful functions for different execution needs:
## Legal
> MIT licensed | **©** [Task Venture Capital GmbH](https://task.vc)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
#### runPath() - Simple Execution
Wait for a script to complete. Perfect for sequential workflows.
```typescript
import { runPath } from '@git.zone/tsrun';
// Run a TypeScript file (absolute or relative path)
await runPath('./scripts/build.ts');
// With path resolution relative to a file URL
await runPath('./build.ts', import.meta.url);
// With custom working directory
await runPath('./build.ts', import.meta.url, { cwd: '/path/to/project' });
```
#### runCli() - CLI Mode
Run with process.argv integration, as if invoked from command line.
```typescript
import { runCli } from '@git.zone/tsrun';
// Respects process.argv for argument passing
await runCli('./script.ts');
```
#### spawnPath() - Advanced Control
Full process control with stdio access, timeouts, and cancellation.
```typescript
import { spawnPath } from '@git.zone/tsrun';
// Returns immediately with process handle
const proc = spawnPath('./task.ts', import.meta.url, {
timeout: 30000,
cwd: '/path/to/project',
env: { NODE_ENV: 'production' },
args: ['--verbose']
});
// Access stdout/stderr streams
proc.stdout?.on('data', (chunk) => console.log(chunk.toString()));
// Wait for completion
const exitCode = await proc.exitCode;
```
## Features
**Zero Configuration** - Just point and shoot. No tsconfig tweaking required.
**Fast Execution** - Powered by tsx for near-instant TypeScript execution.
🔄 **Transparent Arguments** - Command line arguments pass through seamlessly to your scripts.
📦 **Dual Interface** - Use as a CLI tool or import as a library in your code.
🎯 **TypeScript Native** - Full TypeScript support with excellent IntelliSense.
🔀 **Custom Working Directory** - Execute scripts with different cwds for parallel multi-project workflows.
🎛️ **Advanced Process Control** - Full control with spawnPath() for stdio access, timeouts, and cancellation.
## Why tsrun?
Sometimes you just want to run a TypeScript file without setting up a build pipeline, configuring webpack, or waiting for `tsc` to compile. That's where tsrun shines:
- **Quick Scripts**: Write and run TypeScript scripts as easily as bash scripts
- **Prototyping**: Test ideas without project setup overhead
- **Development Workflows**: Integrate TypeScript execution into your tooling
- **CI/CD**: Run TypeScript-based build scripts without pre-compilation
## Common Use Cases
### Development Scripts
```typescript
// scripts/dev-setup.ts
import { runPath } from '@git.zone/tsrun';
console.log('Setting up development environment...');
await runPath('./install-deps.ts', import.meta.url);
await runPath('./init-db.ts', import.meta.url);
await runPath('./seed-data.ts', import.meta.url);
console.log('✓ Development environment ready!');
```
### Multi-Project Builds
```typescript
// build-all-projects.ts
import { runPath } from '@git.zone/tsrun';
const projects = [
'/workspace/frontend',
'/workspace/backend',
'/workspace/shared'
];
await Promise.all(
projects.map(cwd =>
runPath('./build.ts', import.meta.url, { cwd })
)
);
```
### Long-Running Tasks with Monitoring
```typescript
// monitor-task.ts
import { spawnPath } from '@git.zone/tsrun';
const proc = spawnPath('./data-migration.ts', import.meta.url, {
timeout: 300000, // 5 minutes max
env: { LOG_LEVEL: 'verbose' }
});
let lineCount = 0;
proc.stdout?.on('data', (chunk) => {
lineCount++;
if (lineCount % 100 === 0) {
console.log(`Processed ${lineCount} lines...`);
}
});
try {
await proc.exitCode;
console.log('Migration completed successfully!');
} catch (error) {
console.error('Migration failed:', error.message);
process.exit(1);
}
```
## API Reference
Choose the right function for your use case:
| Function | Use When | Returns | Execution Mode |
|----------|----------|---------|----------------|
| `runPath()` | Simple script execution, sequential workflows | Promise (waits) | In-process (or child with cwd) |
| `runCli()` | Need process.argv integration | Promise (waits) | In-process |
| `spawnPath()` | Need process control, stdio access, timeout/cancel | Process handle | Child process |
**Quick decision guide:**
- 🎯 **Need to wait for completion?** → Use `runPath()` or `runCli()`
- 🎛️ **Need to capture output or control process?** → Use `spawnPath()`
-**Running multiple scripts in parallel?** → Use `runPath()` with custom `cwd` or `spawnPath()`
- ⏱️ **Need timeout or cancellation?** → Use `spawnPath()`
## Examples
### Simple Script
```typescript
// hello.ts
console.log('Hello from TypeScript! 🎉');
const greet = (name: string): string => {
return `Welcome, ${name}!`;
};
console.log(greet('Developer'));
```
Run it:
```bash
tsrun hello.ts
# Output:
# Hello from TypeScript! 🎉
# Welcome, Developer!
```
### With Command Line Arguments
```typescript
// deploy.ts
const environment = process.argv[2] || 'development';
const verbose = process.argv.includes('--verbose');
console.log(`Deploying to ${environment}...`);
if (verbose) {
console.log('Verbose mode enabled');
}
```
Run it:
```bash
tsrun deploy.ts production --verbose
# Output:
# Deploying to production...
# Verbose mode enabled
```
### Programmatic Execution
```typescript
// runner.ts
import { runPath } from '@git.zone/tsrun';
const scripts = [
'./scripts/setup.ts',
'./scripts/migrate.ts',
'./scripts/seed.ts'
];
for (const script of scripts) {
console.log(`Running ${script}...`);
await runPath(script, import.meta.url);
console.log(`✓ ${script} completed`);
}
```
### Running with Custom Working Directory
Execute TypeScript files with a different working directory using the `cwd` option. This is especially useful for parallel execution across multiple projects:
```typescript
import { runPath } from '@git.zone/tsrun';
// Run with custom cwd
await runPath('./build.ts', undefined, { cwd: '/path/to/project-a' });
// Parallel execution with different cwds (safe and isolated)
await Promise.all([
runPath('./deploy.ts', undefined, { cwd: '/projects/frontend' }),
runPath('./deploy.ts', undefined, { cwd: '/projects/backend' }),
runPath('./deploy.ts', undefined, { cwd: '/projects/api' })
]);
```
**How it works:**
- When `cwd` is provided, the script executes in a **child process** for complete isolation
- Without `cwd`, execution happens **in-process** (faster, less overhead)
- Child processes inherit all environment variables and stdio connections
- Perfect for running the same script across multiple project directories
**Notes:**
- Output from parallel executions may interleave on the console
- Each child process runs with its own isolated working directory
- Exit codes and signals are properly forwarded
### Advanced Process Control with spawnPath()
For advanced use cases requiring full process control, stdio access, or timeout/cancellation support, use `spawnPath()`. Unlike `runPath()` which waits for completion, `spawnPath()` returns immediately with a process handle.
```typescript
import { spawnPath } from '@git.zone/tsrun';
// Basic spawning with output capture
const proc = spawnPath('./build.ts', import.meta.url);
proc.stdout?.on('data', (chunk) => {
console.log('Output:', chunk.toString());
});
proc.stderr?.on('data', (chunk) => {
console.error('Error:', chunk.toString());
});
const exitCode = await proc.exitCode;
console.log(`Process exited with code ${exitCode}`);
```
**With timeout and custom environment:**
```typescript
const proc = spawnPath('./long-running-task.ts', import.meta.url, {
timeout: 30000, // Kill after 30 seconds
cwd: '/path/to/project',
env: {
NODE_ENV: 'production',
API_KEY: 'secret'
},
args: ['--mode', 'fast']
});
try {
const exitCode = await proc.exitCode;
console.log('Task completed:', exitCode);
} catch (error) {
console.error('Task failed or timed out:', error.message);
}
```
**AbortController integration:**
```typescript
const controller = new AbortController();
const proc = spawnPath('./task.ts', import.meta.url, {
signal: controller.signal
});
// Cancel after 5 seconds
setTimeout(() => controller.abort(), 5000);
try {
await proc.exitCode;
} catch (error) {
console.log('Process was aborted');
}
```
**Graceful termination:**
```typescript
const proc = spawnPath('./server.ts', import.meta.url);
// Later: gracefully shut down
// Sends SIGTERM, waits 5s, then SIGKILL if still running
await proc.terminate();
```
**Key differences from runPath():**
| Feature | runPath() | spawnPath() |
|---------|-----------|-------------|
| Returns | Promise (waits) | Process handle (immediate) |
| Default execution | In-process (unless cwd) | Always child process |
| stdio | 'inherit' (transparent) | 'pipe' (capturable) |
| Process control | Limited | Full (streams, signals, timeout) |
| Use case | Simple script execution | Complex process management |
## Package Information
- **npmjs**: [@git.zone/tsrun](https://www.npmjs.com/package/@git.zone/tsrun)
- **Source**: [git.zone](https://git.zone/lossless/tsrun) | [GitLab Mirror](https://gitlab.com/gitzone/tsrun) | [GitHub Mirror](https://github.com/gitzone/tsrun)
- **Documentation**: [TypeDoc](https://gitzone.gitlab.io/tsrun/)
## Requirements
- **Node.js**: >= 16.x
- **TypeScript**: >= 3.x (automatically handled by tsx)
## Troubleshooting
### Common Issues
**"Cannot find module" errors**
Make sure you're using absolute paths or paths relative to `import.meta.url`:
```typescript
// ❌ Wrong - relative to cwd
await runPath('./script.ts');
// ✅ Correct - relative to current file
await runPath('./script.ts', import.meta.url);
```
**Process hangs or doesn't complete**
When using `spawnPath()`, make sure to await the `exitCode` promise:
```typescript
const proc = spawnPath('./script.ts', import.meta.url);
// Don't forget to await!
await proc.exitCode;
```
**Timeout not working**
Timeouts only work with `spawnPath()`, not with `runPath()`:
```typescript
// ❌ Wrong - timeout is ignored
await runPath('./script.ts', import.meta.url, { timeout: 5000 });
// ✅ Correct - use spawnPath for timeout support
const proc = spawnPath('./script.ts', import.meta.url, { timeout: 5000 });
await proc.exitCode;
```
**Environment variables not available**
The `env` option automatically merges with `process.env` - your custom values override parent values:
```typescript
// Parent env is automatically inherited
spawnPath('./script.ts', import.meta.url, {
env: {
CUSTOM_VAR: 'value' // Added to parent env
}
});
// Script will see both process.env AND CUSTOM_VAR
```
## 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.

View File

@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@git.zone/tsrun',
version: '1.2.47',
version: '1.6.2',
description: 'run typescript programs efficiently'
}

View File

@@ -1,14 +1,82 @@
import * as plugins from './plugins.js';
const __dirname = plugins.path.dirname(plugins.url.fileURLToPath(import.meta.url));
export const runPath = async (pathArg: string, fromFileUrl?: string) => {
export interface IRunOptions {
cwd?: string;
}
export interface ISpawnOptions {
/** Working directory for the child process */
cwd?: string;
/** Environment variables (merged with parent's env) */
env?: Record<string, string>;
/** Additional CLI arguments to pass to the script */
args?: string[];
/**
* Stdio configuration
* - 'pipe': Create pipes for stdin/stdout/stderr (default)
* - 'inherit': Use parent's stdio
* - Array: Custom configuration per stream
*/
stdio?: 'pipe' | 'inherit' | ['pipe' | 'inherit' | 'ignore', 'pipe' | 'inherit' | 'ignore', 'pipe' | 'inherit' | 'ignore'];
/**
* Optional timeout in milliseconds
* If provided, process is automatically killed after timeout
*/
timeout?: number;
/**
* AbortSignal for cancellation support
* Allows external cancellation of the process
*/
signal?: AbortSignal;
}
export interface ITsrunChildProcess {
/** Direct access to Node's ChildProcess object */
childProcess: plugins.ChildProcess;
/** Readable stream for stdout (null if stdio is 'inherit') */
stdout: plugins.Readable | null;
/** Readable stream for stderr (null if stdio is 'inherit') */
stderr: plugins.Readable | null;
/** Promise that resolves with the exit code when process ends */
exitCode: Promise<number>;
/**
* Send signal to process
* Returns true if signal was sent successfully
*/
kill(signal?: NodeJS.Signals): boolean;
/**
* Gracefully terminate the process
* Tries SIGTERM first, waits 5s, then SIGKILL if still running
* Returns a promise that resolves when process is terminated
*/
terminate(): Promise<void>;
}
export const runPath = async (pathArg: string, fromFileUrl?: string, options?: IRunOptions) => {
pathArg = fromFileUrl
? plugins.path.join(plugins.path.dirname(plugins.url.fileURLToPath(fromFileUrl)), pathArg)
: pathArg;
await runCli(pathArg);
await runCli(pathArg, options);
};
export const runCli = async (pathArg?: string) => {
export const runCli = async (pathArg?: string, options?: IRunOptions) => {
// CRITICAL: Branch BEFORE splicing argv to avoid corruption
if (options?.cwd) {
return runInChildProcess(pathArg, options.cwd);
}
// Existing in-process execution
// contents of argv array
// process.argv[0] -> node Executable
// process.argv[1] -> tsrun executable
@@ -22,21 +90,186 @@ export const runCli = async (pathArg?: string) => {
// thus when pathArg is specifed -> we only splice 2
pathArg ? process.argv.splice(0, 2) : process.argv.splice(0, 3); // this ensures transparent arguments for the child process
// lets setup things for execution
const smartshellInstance = new plugins.smartshell.Smartshell({
executor: 'bash',
const tsx = await import('tsx/esm/api');
const unregister = tsx.register();
await import(absolutePathToTsFile);
};
const runInChildProcess = async (pathArg: string | undefined, cwd: string): Promise<void> => {
const { spawn } = await import('child_process');
// Resolve cli.js relative to this file
const cliPath = plugins.path.join(__dirname, '../cli.js');
// Build args: [Node flags, entry point, script path, script args]
const args = [
...process.execArgv, // Preserve --inspect, etc.
cliPath,
...process.argv.slice(2) // Original CLI args (not spliced)
];
return new Promise((resolve, reject) => {
const child = spawn(process.execPath, args, {
cwd: cwd,
env: process.env,
stdio: 'inherit',
shell: false,
windowsHide: false
});
const tsNodeLoaderPath = plugins.path.join(__dirname, 'loader.js');
// note: -> reduce on emtpy array does not work
// thus check needed before reducing the argv array
smartshellInstance.exec(
`node --loader ${tsNodeLoaderPath} ${absolutePathToTsFile} ${
process.argv.length > 0
? process.argv.reduce((prevArg, currentArg) => {
return prevArg + ' ' + currentArg;
})
: ''
}`
);
// Signal forwarding with cleanup
const signalHandler = (signal: NodeJS.Signals) => {
try { child.kill(signal); } catch {}
};
const signals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM', 'SIGHUP'];
signals.forEach(sig => process.on(sig, signalHandler));
child.on('error', (err) => {
signals.forEach(sig => process.off(sig, signalHandler));
reject(err);
});
child.on('close', (code, signal) => {
// Clean up signal handlers
signals.forEach(sig => process.off(sig, signalHandler));
if (signal) {
// Child was terminated by signal
// On POSIX: try to exit with same signal
// On Windows: exit with convention (128 + signal number)
try {
process.kill(process.pid, signal);
} catch {
// Fallback to exit code
const signalExitCode = signal === 'SIGINT' ? 130 : 128;
process.exit(signalExitCode);
}
} else if (code !== null && code !== 0) {
process.exit(code);
} else {
resolve();
}
});
});
};
export const spawnPath = (
filePath: string,
fromFileUrl?: string | URL,
options?: ISpawnOptions
): ITsrunChildProcess => {
// 1. Resolve path (similar to runPath)
const resolvedPath = fromFileUrl
? plugins.path.join(
plugins.path.dirname(
plugins.url.fileURLToPath(
typeof fromFileUrl === 'string' ? fromFileUrl : fromFileUrl.href
)
),
filePath
)
: filePath;
// 2. Build spawn args
const cliPath = plugins.path.join(__dirname, '../cli.js');
const args = [
...process.execArgv,
cliPath,
resolvedPath,
...(options?.args || [])
];
// 3. Build spawn options
const spawnOptions = {
cwd: options?.cwd || process.cwd(),
env: { ...process.env, ...options?.env },
stdio: options?.stdio || 'pipe',
shell: false,
windowsHide: false
};
// 4. Spawn child process
const child = plugins.spawn(process.execPath, args, spawnOptions);
// 5. Set up timeout if provided
let timeoutId: NodeJS.Timeout | undefined;
let timeoutTriggered = false;
if (options?.timeout) {
timeoutId = setTimeout(() => {
timeoutTriggered = true;
child.kill('SIGTERM');
}, options.timeout);
}
// 6. Set up AbortSignal if provided
let abortHandler: (() => void) | undefined;
if (options?.signal) {
abortHandler = () => {
child.kill('SIGTERM');
};
options.signal.addEventListener('abort', abortHandler);
}
// 7. Create exitCode promise
const exitCodePromise = new Promise<number>((resolve, reject) => {
child.on('close', (code: number | null, signal: NodeJS.Signals | null) => {
if (timeoutId) clearTimeout(timeoutId);
if (abortHandler && options?.signal) {
options.signal.removeEventListener('abort', abortHandler);
}
if (timeoutTriggered) {
reject(new Error(`Process killed: timeout of ${options?.timeout}ms exceeded`));
} else if (options?.signal?.aborted) {
reject(new Error('Process killed: aborted by signal'));
} else if (signal) {
reject(new Error(`Process killed with signal ${signal}`));
} else {
resolve(code || 0);
}
});
child.on('error', (err: Error) => {
if (timeoutId) clearTimeout(timeoutId);
if (abortHandler && options?.signal) {
options.signal.removeEventListener('abort', abortHandler);
}
reject(err);
});
});
// 8. Implement terminate() method
const terminate = async (): Promise<void> => {
return new Promise((resolve) => {
if (child.killed) {
resolve();
return;
}
child.kill('SIGTERM');
const killTimeout = setTimeout(() => {
if (!child.killed) {
child.kill('SIGKILL');
}
}, 5000);
child.on('close', () => {
clearTimeout(killTimeout);
resolve();
});
});
};
// 9. Return ITsrunChildProcess object
return {
childProcess: child,
stdout: child.stdout,
stderr: child.stderr,
exitCode: exitCodePromise,
kill: (signal?: NodeJS.Signals) => child.kill(signal),
terminate
};
};

View File

@@ -1,23 +0,0 @@
import * as plugins from './plugins.js';
import type { CompilerOptions } from 'typescript';
const defaultTsNodeOptions: plugins.tsNode.CreateOptions = {
compilerOptions: {
lib: ['dom'],
target: <any>'es2022', // Script Target should be a string -> 2 is for ES2015
experimentalDecorators: true,
useDefineForClassFields: false,
esModuleInterop: true,
strictNullChecks: false,
moduleResolution: <any>'nodenext',
module: <any>'nodenext',
verbatimModuleSyntax: true,
} as CompilerOptions,
esm: true,
skipIgnore: true,
transpileOnly: true,
};
export const { resolve, load, getFormat, transformSource } = plugins.tsNode.createEsmHooks(
plugins.tsNode.register(defaultTsNodeOptions)
) as any;

1
ts/paths.ts Normal file
View File

@@ -0,0 +1 @@
export const cwd = process.cwd();

View File

@@ -1,15 +1,15 @@
// node native
import * as path from 'path';
import * as url from 'url';
import { spawn } from 'child_process';
import type { ChildProcess } from 'child_process';
import type { Readable } from 'stream';
export { path, url };
export { path, url, spawn };
export type { ChildProcess, Readable };
// @pushrocks scope
import * as smartfile from '@push.rocks/smartfile';
import * as smartshell from '@push.rocks/smartshell';
export { smartshell };
// third party scope
import * as tsNode from 'ts-node';
export { tsNode };
export { smartfile, smartshell };

View File

@@ -3,7 +3,12 @@
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "nodenext"
}
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}