Compare commits

..

10 Commits

Author SHA1 Message Date
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
11 changed files with 4519 additions and 791 deletions

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,41 @@
# Changelog
## 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.

View File

@@ -1,6 +1,6 @@
{
"name": "@git.zone/tsrun",
"version": "1.3.0",
"version": "1.5.0",
"description": "run typescript programs efficiently",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
@@ -25,8 +25,7 @@
"dependencies": {
"@push.rocks/smartfile": "^11.0.21",
"@push.rocks/smartshell": "^3.0.5",
"ts-node": "^10.9.2",
"typescript": "5.5.2"
"tsx": "^4.19.2"
},
"private": false,
"files": [
@@ -51,5 +50,6 @@
"bugs": {
"url": "https://gitlab.com/gitzone/tsrun/issues"
},
"homepage": "https://gitlab.com/gitzone/tsrun#readme"
"homepage": "https://gitlab.com/gitzone/tsrun#readme",
"packageManager": "pnpm@10.18.1+sha512.77a884a165cbba2d8d1c19e3b4880eee6d2fcabd0d879121e282196b80042351d5eb3ca0935fa599da1dc51265cc68816ad2bddd2a2de5ea9fdf92adbec7cd34"
}

4821
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

217
readme.md
View File

@@ -1,50 +1,203 @@
# @gitzone/tsrun
# @git.zone/tsrun
run typescript programs efficiently
> Run TypeScript files instantly, without the compilation hassle ⚡
## Availabililty and Links
Execute TypeScript programs on-the-fly with zero configuration. Perfect for scripts, prototyping, and development workflows.
- [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/)
## What is tsrun?
## Status for master
**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.
| 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) |
## 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.
Import tsrun in your code for dynamic TypeScript execution:
## Legal
```typescript
import { runPath, runCli } from '@git.zone/tsrun';
> MIT licensed | **©** [Task Venture Capital GmbH](https://task.vc)
> | By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
// Run a TypeScript file from an absolute or relative path
await runPath('./scripts/myScript.ts');
// Run with path resolution relative to a file URL
await runPath('./myScript.ts', import.meta.url);
// Run in CLI mode programmatically (respects process.argv)
await runCli('./myScript.ts');
```
## 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.
## 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
## 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
## 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)
## 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.3.0',
version: '1.5.0',
description: 'run typescript programs efficiently'
}

View File

@@ -1,14 +1,24 @@
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 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 +32,66 @@ 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.child.js relative to this file
const cliChildPath = plugins.path.join(__dirname, '../cli.child.js');
// Build args: [Node flags, entry point, script path, script args]
const args = [
...process.execArgv, // Preserve --inspect, etc.
cliChildPath,
...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();
}
});
});
};

View File

@@ -1,26 +0,0 @@
import * as paths from './paths.js';
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,
paths: plugins.smartfile.fs.toObjectSync(plugins.path.join(paths.cwd, 'tsconfig.json'))
?.compilerOptions?.paths,
} as CompilerOptions,
esm: true,
skipIgnore: true,
transpileOnly: true,
};
export const { resolve, load, getFormat, transformSource } = plugins.tsNode.createEsmHooks(
plugins.tsNode.register(defaultTsNodeOptions),
) as any;

View File

@@ -9,8 +9,3 @@ import * as smartfile from '@push.rocks/smartfile';
import * as smartshell from '@push.rocks/smartshell';
export { smartfile, smartshell };
// third party scope
import * as tsNode from 'ts-node';
export { tsNode };