Compare commits

...

46 Commits

Author SHA1 Message Date
8c1b306313 v3.2.0
Some checks failed
Default (tags) / security (push) Successful in 33s
Default (tags) / test (push) Failing after 4m5s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2026-02-24 19:02:39 +00:00
a893e7a771 feat(bundle): add configurable bundle output modes and bundler options (support base64ts, production builds, includeFiles, maxLineLength) and route non-default outputs to a CustomBundleHandler 2026-02-24 19:02:39 +00:00
c330420eea v3.1.0
Some checks failed
Default (tags) / security (push) Successful in 41s
Default (tags) / test (push) Failing after 4m2s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2026-02-05 14:58:27 +00:00
df8b164434 feat(dev-server): add no-cache headers to built-in development server; update docs and bump dependencies 2026-02-05 14:58:27 +00:00
6af321647d v3.0.1
Some checks failed
Default (tags) / security (push) Successful in 34s
Default (tags) / test (push) Failing after 4m3s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2026-01-24 11:39:18 +00:00
47cd9adc8e fix(deps): downgrade @push.rocks/smartinteract to ^2.0.16 2026-01-24 11:39:18 +00:00
721dc3b22c v3.0.0
Some checks failed
Default (tags) / security (push) Successful in 40s
Default (tags) / test (push) Failing after 4m3s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2026-01-24 11:29:55 +00:00
9fb3f6a872 BREAKING CHANGE(tswatch): refactor tswatch to a config-driven design (load config from npmextra.json) and add interactive init wizard; change TsWatch public API and enhance Watcher behavior 2026-01-24 11:29:55 +00:00
5a702055f4 v2.3.13
Some checks failed
Default (tags) / security (push) Successful in 51s
Default (tags) / test (push) Failing after 40s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-11 21:19:20 +00:00
ebcfbc88b2 fix(@push.rocks/smartwatch): Update @push.rocks/smartwatch dependency to ^6.3.0 2025-12-11 21:19:20 +00:00
cd76756e89 v2.3.12
Some checks failed
Default (tags) / security (push) Successful in 41s
Default (tags) / test (push) Failing after 40s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-11 19:15:36 +00:00
c269f4f7e1 fix(smartwatch): Bump @push.rocks/smartwatch from ^6.2.4 to ^6.2.5 2025-12-11 19:15:36 +00:00
88595335ea v2.3.11
Some checks failed
Default (tags) / security (push) Failing after 18s
Default (tags) / test (push) Failing after 49s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-11 17:14:05 +00:00
313362b795 fix(typedserver): Add cross-origin security headers to element mode dev server 2025-12-11 17:14:05 +00:00
0bb76f32b8 v2.3.10
Some checks failed
Default (tags) / security (push) Successful in 44s
Default (tags) / test (push) Failing after 40s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-11 11:39:43 +00:00
5c7bf83f74 fix(dependencies): Bump dependency versions: @types/node to ^25.0.0 and @push.rocks/smartwatch to ^6.2.4 2025-12-11 11:39:43 +00:00
57caa96a85 v2.3.9
Some checks failed
Default (tags) / security (push) Successful in 44s
Default (tags) / test (push) Failing after 46s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-11 09:12:31 +00:00
eb64501767 fix(smartwatch): Bump @push.rocks/smartwatch dependency to ^6.2.3 2025-12-11 09:12:31 +00:00
3f90dfd1db v2.3.8
Some checks failed
Default (tags) / security (push) Successful in 48s
Default (tags) / test (push) Failing after 38s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-11 08:40:45 +00:00
b5552a7f34 fix(@push.rocks/smartwatch): Bump @push.rocks/smartwatch dependency to ^6.2.2 2025-12-11 08:40:45 +00:00
814cc70a29 v2.3.7
Some checks failed
Default (tags) / security (push) Successful in 49s
Default (tags) / test (push) Failing after 40s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-10 17:18:08 +00:00
8508eee439 fix(smartwatch): Bump @push.rocks/smartwatch dependency to ^6.2.1 2025-12-10 17:18:08 +00:00
592e1f35b2 v2.3.6
Some checks failed
Default (tags) / security (push) Successful in 49s
Default (tags) / test (push) Failing after 39s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-10 14:31:55 +00:00
94fa31a5c8 fix(dependencies): Bump @types/node to ^24.10.2 and @push.rocks/smartwatch to ^6.2.0 2025-12-10 14:31:55 +00:00
6b8ce469d2 v2.3.5
Some checks failed
Default (tags) / security (push) Successful in 44s
Default (tags) / test (push) Failing after 41s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-08 19:35:32 +00:00
bb1038baa0 fix(dependencies): Update @push.rocks/smartwatch dependency to ^6.1.1 2025-12-08 19:35:32 +00:00
a3db29edd7 v2.3.4
Some checks failed
Default (tags) / security (push) Successful in 1m54s
Default (tags) / test (push) Failing after 40s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-08 17:54:39 +00:00
2c8ed46c9e fix(dependencies.@push.rocks/smartwatch): Bump @push.rocks/smartwatch dependency to ^6.1.0 2025-12-08 17:54:39 +00:00
6c30d35de7 v2.3.3
Some checks failed
Default (tags) / security (push) Successful in 50s
Default (tags) / test (push) Failing after 1m49s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-08 17:07:20 +00:00
3cdd5302f8 fix(dependencies): Bump dependencies: @api.global/typedserver to ^7.11.1 and @push.rocks/smartwatch to ^6.0.0 2025-12-08 17:07:20 +00:00
42bba057cb v2.3.2
Some checks failed
Default (tags) / security (push) Successful in 48s
Default (tags) / test (push) Failing after 39s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-08 15:57:12 +00:00
b9cddaa3f3 fix(smartwatch): Bump @push.rocks/smartwatch dependency to ^5.1.0 2025-12-08 15:57:12 +00:00
9ecf007767 v2.3.1
Some checks failed
Default (tags) / security (push) Successful in 30s
Default (tags) / test (push) Failing after 37s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-08 12:31:38 +00:00
660a480317 fix(element): Enable SPA fallback in element dev server 2025-12-08 12:31:38 +00:00
ec268802ca v2.3.0
Some checks failed
Default (tags) / security (push) Successful in 49s
Default (tags) / test (push) Failing after 39s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-08 12:27:52 +00:00
6415a459d2 feat(typedserver): Enable compression for element development server and update @api.global/typedserver dependency 2025-12-08 12:27:52 +00:00
01bde87067 v2.2.5
Some checks failed
Default (tags) / security (push) Successful in 50s
Default (tags) / test (push) Failing after 40s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-08 11:32:12 +00:00
4f4c4a7538 fix(typedserver): Update @api.global/typedserver to ^7.10.2 and remove deprecated compression options from TypedServer initialization 2025-12-08 11:32:12 +00:00
0dee896201 v2.2.4
Some checks failed
Default (tags) / security (push) Successful in 53s
Default (tags) / test (push) Failing after 41s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-04 16:15:38 +00:00
29f7283f7a fix(dependencies): Bump dependency versions: @api.global/typedserver, @git.zone/tsbundle, @push.rocks/smartfs, @push.rocks/taskbuffer 2025-12-04 16:15:38 +00:00
3eb99e1f08 v2.2.3
Some checks failed
Default (tags) / security (push) Successful in 48s
Default (tags) / test (push) Failing after 37s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-04 08:30:05 +00:00
ad41fe876d fix(tswatch.classes.watcher): Convert directory watch paths to glob patterns for smartwatch compatibility 2025-12-04 08:30:05 +00:00
d6f3381e71 v2.2.2
Some checks failed
Default (tags) / security (push) Successful in 41s
Default (tags) / test (push) Failing after 39s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-01 12:03:00 +00:00
bcbf6fc139 fix(core): Replace smartchok/smartfile with smartwatch/smartfs, update watcher and plugins, and bump dependencies 2025-12-01 12:03:00 +00:00
f73ca7ac2f fix(exports): correct package.json exports field syntax
Some checks failed
Default (tags) / security (push) Successful in 32s
Default (tags) / test (push) Successful in 52s
Default (tags) / release (push) Failing after 57s
Default (tags) / metadata (push) Successful in 57s
2025-07-29 17:50:59 +00:00
75acc4b768 feat(exports): modernize package exports and expose watcher class
Some checks failed
Default (tags) / security (push) Successful in 49s
Default (tags) / test (push) Successful in 1m7s
Default (tags) / release (push) Failing after 1m18s
Default (tags) / metadata (push) Successful in 1m26s
2025-07-29 17:46:28 +00:00
18 changed files with 5835 additions and 4225 deletions

View File

@@ -1,5 +1,161 @@
# Changelog # Changelog
## 2026-02-24 - 3.2.0 - feat(bundle)
add configurable bundle output modes and bundler options (support base64ts, production builds, includeFiles, maxLineLength) and route non-default outputs to a CustomBundleHandler
- Added new ITswatchConfig fields: outputMode, bundler, production, includeFiles, maxLineLength
- tswatch now creates a CustomBundleHandler and uses it when outputMode is not 'bundle' (e.g. base64ts)
- Default bundling path now reads bundler and production from bundleConfig (defaults to 'esbuild' and false)
- Bumped dependency @git.zone/tsbundle to ^2.9.0
## 2026-02-05 - 3.1.0 - feat(dev-server)
add no-cache headers to built-in development server; update docs and bump dependencies
- Introduce noCache: true in ts/tswatch.classes.tswatch.ts to send Cache-Control: no-store, no-cache during development (prevents browser caching).
- Update documentation to describe no-caching behavior (readme.md and readme.hints.md).
- Bump dependencies: @git.zone/tstest ^3.1.8, @types/node ^25.2.1, @push.rocks/npmextra ^5.3.3, @push.rocks/taskbuffer ^4.2.0.
## 2026-01-24 - 3.0.1 - fix(deps)
downgrade @push.rocks/smartinteract to ^2.0.16
- package.json: @push.rocks/smartinteract ^2.1.0 -> ^2.0.16
## 2026-01-24 - 3.0.0 - BREAKING CHANGE(tswatch)
refactor tswatch to a config-driven design (load config from npmextra.json) and add interactive init wizard; change TsWatch public API and enhance Watcher behavior
- Switch to config-driven operation: configuration read from npmextra.json under the key @git.zone/tswatch
- Added ConfigHandler for loading/merging presets and new TswatchInit interactive wizard (runInit) to create/save configuration
- Changed TsWatch constructor to accept ITswatchConfig and added TsWatch.fromConfig(cwd?) for loading from npmextra.json
- Significant public API change: previous watchmode string-based constructor/behavior removed/rewired — consumers must migrate to new config-based usage (breaking change)
- Watcher refactor: Watcher.fromConfig, named watchers, array/single path support, debounce, restart/queue handling, runOnStart, safer start/stop behavior and execution tracking
- New TypeScript interfaces: interfaces.config.ts (ITswatchConfig, IWatcherConfig, IServerConfig, IBundleConfig); removed/changed old watchmodes types
- CLI updated to use configuration if present or launch the init wizard; added init command
- Updated tests to cover ConfigHandler, Watcher, and TsWatch config-driven behavior
- Updated dependencies and plugin usage (added @push.rocks/npmextra, @push.rocks/smartinteract; bumped several @git.zone and @push.rocks package versions)
## 2025-12-11 - 2.3.13 - fix(@push.rocks/smartwatch)
Update @push.rocks/smartwatch dependency to ^6.3.0
- Bump @push.rocks/smartwatch from ^6.2.5 to ^6.3.0 in package.json
- Dependency-only change; no source files modified
## 2025-12-11 - 2.3.12 - fix(smartwatch)
Bump @push.rocks/smartwatch from ^6.2.4 to ^6.2.5
- Updated dependency @push.rocks/smartwatch to ^6.2.5 in package.json
- No source code changes; dependency version bump only
## 2025-12-11 - 2.3.11 - fix(typedserver)
Add cross-origin security headers to element mode dev server
- Set crossOriginOpenerPolicy to 'same-origin' and crossOriginEmbedderPolicy to 'require-corp' on the TypedServer used in element mode.
- Improves security and enables cross-origin isolation (e.g. for SharedArrayBuffer) during local development.
- Applies to the development server serving ./dist_watch/ on port 3002.
## 2025-12-11 - 2.3.10 - fix(dependencies)
Bump dependency versions: @types/node to ^25.0.0 and @push.rocks/smartwatch to ^6.2.4
- Update devDependency @types/node from ^24.10.2 to ^25.0.0
- Update dependency @push.rocks/smartwatch from ^6.2.3 to ^6.2.4
## 2025-12-11 - 2.3.9 - fix(smartwatch)
Bump @push.rocks/smartwatch dependency to ^6.2.3
- Updated dependency @push.rocks/smartwatch from ^6.2.2 to ^6.2.3
- No source code changes; dependency version bump only
## 2025-12-11 - 2.3.8 - fix(@push.rocks/smartwatch)
Bump @push.rocks/smartwatch dependency to ^6.2.2
- package.json: updated @push.rocks/smartwatch from ^6.2.1 to ^6.2.2
## 2025-12-10 - 2.3.7 - fix(smartwatch)
Bump @push.rocks/smartwatch dependency to ^6.2.1
- Updated dependency @push.rocks/smartwatch from ^6.2.0 to ^6.2.1 in package.json
## 2025-12-10 - 2.3.6 - fix(dependencies)
Bump @types/node to ^24.10.2 and @push.rocks/smartwatch to ^6.2.0
- Dev dependency @types/node updated from ^24.10.1 to ^24.10.2
- Dependency @push.rocks/smartwatch updated from ^6.1.1 to ^6.2.0
## 2025-12-08 - 2.3.5 - fix(dependencies)
Update @push.rocks/smartwatch dependency to ^6.1.1
- Bump @push.rocks/smartwatch from ^6.1.0 to ^6.1.1 in package.json
- Only package.json changed; no source code modifications
## 2025-12-08 - 2.3.4 - fix(dependencies.@push.rocks/smartwatch)
Bump @push.rocks/smartwatch dependency to ^6.1.0
- Updated package.json dependency @push.rocks/smartwatch from ^6.0.0 to ^6.1.0
## 2025-12-08 - 2.3.3 - fix(dependencies)
Bump dependencies: @api.global/typedserver to ^7.11.1 and @push.rocks/smartwatch to ^6.0.0
- Updated @api.global/typedserver from ^7.11.0 to ^7.11.1 (patch).
- Updated @push.rocks/smartwatch from ^5.1.0 to ^6.0.0 (major). Verify compatibility as this may include breaking changes in that dependency.
- Change is limited to package.json (dependency version updates).
## 2025-12-08 - 2.3.2 - fix(smartwatch)
Bump @push.rocks/smartwatch dependency to ^5.1.0
- Updated dependency @push.rocks/smartwatch from ^5.0.0 to ^5.1.0 in package.json
## 2025-12-08 - 2.3.1 - fix(element)
Enable SPA fallback in element dev server
- Add spaFallback: true to the TypedServer configuration used in element mode.
- Improves developer experience for single-page apps by serving the index file for unknown routes during development and supporting client-side routing.
## 2025-12-08 - 2.3.0 - feat(typedserver)
Enable compression for element development server and update @api.global/typedserver dependency
- Enable HTTP compression (compression: true) for the element mode development server (TypedServer) to improve asset delivery during development.
- Bump dependency @api.global/typedserver from ^7.10.2 to ^7.11.0 in package.json.
## 2025-12-08 - 2.2.5 - fix(typedserver)
Update @api.global/typedserver to ^7.10.2 and remove deprecated compression options from TypedServer initialization
- Bump @api.global/typedserver dependency from ^7.4.1 to ^7.10.2.
- Remove enableCompression and preferredCompressionMethod options when creating TypedServer in element mode to be compatible with the newer API.
## 2025-12-04 - 2.2.4 - fix(dependencies)
Bump dependency versions: @api.global/typedserver, @git.zone/tsbundle, @push.rocks/smartfs, @push.rocks/taskbuffer
- Upgrade @api.global/typedserver from ^3.0.80 to ^7.4.1
- Upgrade @git.zone/tsbundle from ^2.6.2 to ^2.6.3
- Upgrade @push.rocks/smartfs from ^1.1.3 to ^1.2.0
- Upgrade @push.rocks/taskbuffer from ^3.4.0 to ^3.5.0
## 2025-12-04 - 2.2.3 - fix(tswatch.classes.watcher)
Convert directory watch paths to glob patterns for smartwatch compatibility
- Watcher: convert directory paths to recursive glob patterns before adding them to Smartwatch so directories are watched recursively (e.g. /path/to/dir/ -> /path/to/dir/**/*).
- Readme: added migration note explaining that directory paths are converted to glob patterns for smartwatch compatibility.
## 2025-12-01 - 2.2.2 - fix(core)
Replace smartchok/smartfile with smartwatch/smartfs, update watcher and plugins, and bump dependencies
- Replaced @push.rocks/smartchok with @push.rocks/smartwatch and updated Watcher to use Smartwatch (add/start/stop/getObservableFor).
- Replaced @push.rocks/smartfile with @push.rocks/smartfs and added SmartFs usage (SmartFsProviderNode) plus a listFolders helper used by TsWatch.
- Updated tswatch.plugins.ts to export smartfs and smartwatch and removed smartchok/smartfile exports.
- Updated tswatch.classes.watcher.ts and tswatch.classes.tswatch.ts to use the new smartwatch/smartfs APIs and adjusted directory listing and watcher logic accordingly.
- Bumped several devDependencies and dependencies in package.json (tsbuild, tstest, @api.global/typedserver, @git.zone/tsbundle, @git.zone/tsrun, @push.rocks/* packages).
- Documentation updates: readme.md and readme.hints.md include migration notes and Issue Reporting & Security section.
## 2025-07-29 - 2.2.1 - fix(exports)
Fix package.json exports field syntax
- Fixed exports field syntax from "./" to "." for proper module resolution
## 2025-07-29 - 2.2.0 - feat(exports)
Modernize package exports and expose watcher class
- Updated package.json to use modern exports field instead of main/typings
- Exposed TsWatch watcher class through index exports
## 2025-07-29 - 2.1.3 - fix(documentation) ## 2025-07-29 - 2.1.3 - fix(documentation)
Update and align documentation with internal CLI and project structure Update and align documentation with internal CLI and project structure

View File

@@ -1,9 +1,5 @@
{ {
"npmci": { "@git.zone/cli": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
},
"gitzone": {
"projectType": "npm", "projectType": "npm",
"module": { "module": {
"githost": "code.foss.global", "githost": "code.foss.global",
@@ -34,9 +30,19 @@
"node.js", "node.js",
"development server" "development server"
] ]
},
"release": {
"registries": [
"https://verdaccio.lossless.digital",
"https://registry.npmjs.org"
],
"accessLevel": "public"
} }
}, },
"tsdoc": { "@git.zone/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" "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"
},
"@ship.zone/szci": {
"npmGlobalTools": []
} }
} }

View File

@@ -1,10 +1,11 @@
{ {
"name": "@git.zone/tswatch", "name": "@git.zone/tswatch",
"version": "2.1.5", "version": "3.2.0",
"private": false, "private": false,
"description": "A development tool for automatically watching and re-compiling TypeScript projects upon detecting file changes, enhancing developer workflows.", "description": "A development tool for automatically watching and re-compiling TypeScript projects upon detecting file changes, enhancing developer workflows.",
"main": "dist_ts/index.js", "exports": {
"typings": "dist_ts/index.d.ts", ".": "./dist_ts/index.js"
},
"type": "module", "type": "module",
"author": "Lossless GmbH", "author": "Lossless GmbH",
"license": "MIT", "license": "MIT",
@@ -17,24 +18,26 @@
"buildDocs": "tsdoc" "buildDocs": "tsdoc"
}, },
"devDependencies": { "devDependencies": {
"@git.zone/tsbuild": "^2.6.4", "@git.zone/tsbuild": "^4.1.2",
"@git.zone/tstest": "^2.3.2", "@git.zone/tstest": "^3.1.8",
"@types/node": "^22" "@types/node": "^25.2.1"
}, },
"dependencies": { "dependencies": {
"@api.global/typedserver": "^3.0.74", "@api.global/typedserver": "^8.3.0",
"@git.zone/tsbundle": "^2.5.1", "@git.zone/tsbundle": "^2.9.0",
"@git.zone/tsrun": "^1.3.3", "@git.zone/tsrun": "^2.0.1",
"@push.rocks/early": "^4.0.4", "@push.rocks/early": "^4.0.4",
"@push.rocks/lik": "^6.2.2", "@push.rocks/lik": "^6.2.2",
"@push.rocks/smartchok": "^1.1.1", "@push.rocks/npmextra": "^5.3.3",
"@push.rocks/smartcli": "^4.0.11", "@push.rocks/smartcli": "^4.0.20",
"@push.rocks/smartdelay": "^3.0.5", "@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/smartfile": "^11.2.5", "@push.rocks/smartfs": "^1.3.1",
"@push.rocks/smartlog": "^3.1.8", "@push.rocks/smartinteract": "^2.0.16",
"@push.rocks/smartlog": "^3.1.10",
"@push.rocks/smartlog-destination-local": "^9.0.2", "@push.rocks/smartlog-destination-local": "^9.0.2",
"@push.rocks/smartshell": "^3.2.3", "@push.rocks/smartshell": "^3.3.0",
"@push.rocks/taskbuffer": "^3.1.7" "@push.rocks/smartwatch": "^6.3.0",
"@push.rocks/taskbuffer": "^4.2.0"
}, },
"files": [ "files": [
"ts/**/*", "ts/**/*",

8068
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,44 +1,94 @@
# tswatch Project Hints # tswatch Project Hints
## Core Architecture ## Core Architecture (v3.x - Config-Driven)
- tswatch is a TypeScript file watcher with multiple operation modes
- Main class `TsWatch` orchestrates different watch modes
- `Watcher` class handles individual file watching and command execution
## Available Watch Modes tswatch is now a config-driven TypeScript file watcher. Configuration is read from `npmextra.json` under the key `@git.zone/tswatch`.
1. **npm/node** (default): Runs `npm test` on changes
2. **test**: Runs `npm run test2` on changes ### Key Classes
3. **element**: Web component development with dev server on port 3002
4. **service**: Runs `npm run startTs` for service projects - **TsWatch**: Main orchestrator class, accepts `ITswatchConfig`
5. **website**: Full website mode with bundling and asset processing - **Watcher**: Handles individual file watching with debouncing and restart modes
6. **echo**: Test mode that runs `npm -v` (for testing) - **ConfigHandler**: Loads and manages configuration from npmextra.json
- **TswatchInit**: Interactive wizard for creating configuration
### Configuration Structure
```json
{
"@git.zone/tswatch": {
"watchers": [
{
"name": "backend",
"watch": "./ts/**/*",
"command": "npm run startTs",
"restart": true,
"debounce": 300,
"runOnStart": true
}
],
"server": {
"enabled": true,
"port": 3002,
"serveDir": "./dist_watch/",
"liveReload": true
},
"bundles": [
{
"name": "frontend",
"from": "./html/index.ts",
"to": "./dist_watch/bundle.js",
"watchPatterns": ["./ts_web/**/*"],
"triggerReload": true
}
],
"preset": "element"
}
}
```
### Available Presets
- **npm**: Watch ts/ and test/, run `npm test`
- **test**: Watch ts/ and test/, run `npm run test2`
- **service**: Watch ts/, run `npm run startTs` with restart
- **element**: Dev server on 3002, bundle ts_web, watch html
- **website**: Full stack with backend restart + frontend bundling + assets
### CLI Commands
- `tswatch` - Run with config (or launch wizard if no config)
- `tswatch init` - Force run the configuration wizard
## Key Implementation Details ## Key Implementation Details
- Uses `@push.rocks/smartchok` for file watching
- Uses `@push.rocks/smartwatch` (v6.x) for file watching - class is `Smartwatch`
- Uses `@push.rocks/smartfs` (v1.x) for filesystem operations
- Uses `@push.rocks/npmextra` for reading npmextra.json config
- Uses `@push.rocks/smartinteract` for the init wizard
- Uses `@git.zone/tsbundle` for bundling with esbuild - Uses `@git.zone/tsbundle` for bundling with esbuild
- Uses `@api.global/typedserver` for development server in element mode - Uses `@api.global/typedserver` for development server
- Element/website modes watch multiple `ts*/` directories
- All modes support both command execution and function callbacks
## CLI Entry Points ### Watcher Features
- `cli.js` -> Main CLI entry point
- `ts/tswatch.cli.ts` -> CLI implementation with smartcli
- Default command triggers npm mode
## Project Structure Expectations - **Debouncing**: Configurable delay before executing (default: 300ms)
- `ts/` - Backend TypeScript files - **Restart mode**: Kill previous process before restarting (configurable)
- `ts_web/` - Frontend TypeScript files (element/website modes) - **Named watchers**: All watchers have names for clear logging
- `html/` - HTML templates (element/website modes) - **Multiple watch patterns**: Can watch multiple glob patterns
- `assets/` - Static assets (website mode only)
- `dist_watch/` - Output for element mode
- `dist_serve/` - Output for website mode
## Development Server Details ### Server Features
- Port: 3002
- Features: CORS, gzip compression, live reload injection
- Only available in element mode via `typedserver` property
## Common Issues to Watch For - Port configurable (default: 3002)
- The test mode runs `test2` script, not `test` - CORS enabled
- Website mode restarts the entire server process on backend changes - Gzip compression
- Element mode rebuilds and reloads on any ts* folder change - Live reload injection (configurable)
- SPA fallback support
- No-cache headers (prevents browser caching during development)
## Project Structure
- `ts/tswatch.classes.tswatch.ts` - Main TsWatch class
- `ts/tswatch.classes.watcher.ts` - Watcher class with debounce/restart
- `ts/tswatch.classes.confighandler.ts` - Config loading
- `ts/tswatch.init.ts` - Interactive init wizard
- `ts/tswatch.cli.ts` - CLI entry point
- `ts/interfaces/interfaces.config.ts` - Type definitions

484
readme.md
View File

@@ -1,229 +1,411 @@
# @git.zone/tswatch # @git.zone/tswatch
A TypeScript file watcher that automatically recompiles and executes your project when files change. Designed to streamline development workflows for various TypeScript project types. A powerful, config-driven TypeScript file watcher that automatically recompiles and executes your project when files change. Built for modern TypeScript development with zero-config presets and deep customization options.
## Features ## Issue Reporting and Security
- 🔄 **Automatic recompilation** on file changes For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
- 🚀 **Multiple project modes**: npm packages, web elements, services, and websites
- 🌐 **Built-in development server** with live reload for web projects
-**Fast bundling** with esbuild integration
- 🛠️ **Flexible CLI and programmatic API**
- 📦 **Zero configuration** for standard project structures
## Prerequisites ## ✨ Features
- Node.js (v14 or higher) - 🔄 **Config-driven architecture** - Define watchers, bundles, and dev server in `npmextra.json`
- pnpm (recommended) or npm - **Zero-config presets** - Get started instantly with `npm`, `element`, `service`, `website`, and `test` presets
- 🧙 **Interactive wizard** - Run `tswatch init` to generate configuration interactively
- 🌐 **Built-in dev server** - Live reload, CORS, compression, SPA fallback out of the box
- 📦 **Smart bundling** - TypeScript, HTML, and assets with esbuild integration
- 🔁 **Debounced execution** - Configurable debounce prevents command spam
- 🛑 **Process management** - Automatic restart or queue mode for long-running commands
- 🎯 **Glob patterns** - Watch any files with flexible pattern matching
## Installation ## 📦 Installation
Install `@git.zone/tswatch` globally or as a development dependency:
```bash ```bash
# Global installation # Global installation (recommended for CLI usage)
pnpm install -g @git.zone/tswatch pnpm install -g @git.zone/tswatch
# As a dev dependency # As a dev dependency
pnpm install --save-dev @git.zone/tswatch pnpm install --save-dev @git.zone/tswatch
``` ```
## Quick Start ## 🚀 Quick Start
### Using the Wizard
```bash ```bash
# Watch and run tests on changes (default behavior) # Run the interactive wizard to create your configuration
tswatch tswatch init
# Watch a web element project with dev server
tswatch element
# Watch a service project
tswatch service
``` ```
## CLI Commands The wizard will guide you through creating a `npmextra.json` configuration with your chosen preset or custom watchers.
### `tswatch` or `tswatch npm` ### Using Presets
Watches TypeScript files and runs `npm test` on changes. This is the default mode.
If you already have a configuration, just run:
```bash ```bash
tswatch tswatch
# or explicitly
tswatch npm
``` ```
### `tswatch element` This reads your config from `npmextra.json` under the `@git.zone/tswatch` key and starts watching.
Sets up a development environment for web components/elements:
- Starts a dev server on port 3002 ## ⚙️ Configuration
- Bundles TypeScript to `dist_watch/`
- Enables live reload tswatch uses `npmextra.json` for configuration. Add your config under the `@git.zone/tswatch` key:
- Watches all `ts*/` folders
```json
{
"@git.zone/tswatch": {
"preset": "npm"
}
}
```
### Available Presets
| Preset | Description |
|--------|-------------|
| `npm` | Watch `ts/` and `test/`, run `npm test` on changes |
| `test` | Watch `ts/` and `test/`, run `npm run test2` on changes |
| `service` | Watch `ts/`, restart `npm run startTs` (ideal for backend services) |
| `element` | Dev server on port 3002 + bundling for web components |
| `website` | Full-stack: backend + frontend bundling + asset processing |
### Full Configuration Schema
```json
{
"@git.zone/tswatch": {
"preset": "element",
"server": {
"enabled": true,
"port": 3002,
"serveDir": "./dist_watch/",
"liveReload": true
},
"bundles": [
{
"name": "main-bundle",
"from": "./ts_web/index.ts",
"to": "./dist_watch/bundle.js",
"watchPatterns": ["./ts_web/**/*"],
"triggerReload": true
},
{
"name": "html",
"from": "./html/index.html",
"to": "./dist_watch/index.html",
"watchPatterns": ["./html/**/*"],
"triggerReload": true
}
],
"watchers": [
{
"name": "backend-build",
"watch": "./ts/**/*",
"command": "npm run build",
"restart": false,
"debounce": 300,
"runOnStart": true
},
{
"name": "tests",
"watch": ["./ts/**/*", "./test/**/*"],
"command": "npm test",
"restart": true,
"debounce": 300,
"runOnStart": true
}
]
}
}
```
### Configuration Options
#### `ITswatchConfig`
| Option | Type | Description |
|--------|------|-------------|
| `preset` | `string` | Use a preset: `npm`, `test`, `service`, `element`, `website` |
| `watchers` | `IWatcherConfig[]` | Array of watcher configurations |
| `server` | `IServerConfig` | Development server configuration |
| `bundles` | `IBundleConfig[]` | Bundle configurations |
#### `IWatcherConfig`
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `name` | `string` | *required* | Name for logging purposes |
| `watch` | `string \| string[]` | *required* | Glob pattern(s) to watch |
| `command` | `string` | - | Shell command to execute on changes |
| `restart` | `boolean` | `true` | Kill previous process before restarting |
| `debounce` | `number` | `300` | Debounce delay in milliseconds |
| `runOnStart` | `boolean` | `true` | Run the command immediately on start |
#### `IServerConfig`
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `enabled` | `boolean` | *required* | Whether the server is enabled |
| `port` | `number` | `3002` | Server port |
| `serveDir` | `string` | `./dist_watch/` | Directory to serve |
| `liveReload` | `boolean` | `true` | Inject live reload script |
#### `IBundleConfig`
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `name` | `string` | - | Name for logging purposes |
| `from` | `string` | *required* | Entry point file |
| `to` | `string` | *required* | Output file |
| `watchPatterns` | `string[]` | - | Additional patterns to watch |
| `triggerReload` | `boolean` | `true` | Trigger server reload after bundling |
## 🛠️ CLI Commands
### `tswatch`
Runs with configuration from `npmextra.json`. If no config exists, launches the interactive wizard.
```bash ```bash
tswatch element tswatch
``` ```
### `tswatch service` ### `tswatch init`
Watches TypeScript files in `./ts/` and runs `npm run startTs` on changes. Ideal for backend services.
Force-run the configuration wizard (creates or overwrites existing config).
```bash ```bash
tswatch service tswatch init
``` ```
### `tswatch website` ## 💻 Programmatic API
Full website development mode:
- Bundles TypeScript files to `dist_serve/`
- Processes HTML files
- Handles assets
- Runs `npm run startTs` for server-side code
```bash ### Basic Usage with Config
tswatch website
```
### `tswatch test`
Runs `npm run test2` whenever files change. Useful for projects with custom test scripts.
```bash
tswatch test
```
## Project Structure
tswatch expects certain project structures depending on the mode:
### NPM/Node Projects
```
project/
├── ts/ # TypeScript source files
├── test/ # Test files
└── package.json # With "test" script
```
### Element Projects
```
project/
├── ts/ # Backend TypeScript
├── ts_web/ # Frontend TypeScript
├── html/ # HTML templates
│ └── index.ts # Entry point
└── dist_watch/ # Output directory (auto-created)
```
### Website Projects
```
project/
├── ts/ # Backend TypeScript
├── ts_web/ # Frontend TypeScript
│ └── index.ts # Entry point
├── html/ # HTML files
│ └── index.html
├── assets/ # Static assets
└── dist_serve/ # Output directory
```
## Programmatic API
### Basic Usage
```typescript ```typescript
import { TsWatch } from '@git.zone/tswatch'; import { TsWatch } from '@git.zone/tswatch';
// Create and start a watcher // Create TsWatch with inline configuration
const watcher = new TsWatch('node'); const watcher = new TsWatch({
watchers: [
{
name: 'my-watcher',
watch: './src/**/*',
command: 'npm run build',
restart: true,
debounce: 300,
runOnStart: true,
},
],
});
await watcher.start(); await watcher.start();
// Stop when done // Later: stop watching
await watcher.stop(); await watcher.stop();
``` ```
### Custom Watchers ### Load from Config File
```typescript
import { TsWatch } from '@git.zone/tswatch';
// Load configuration from npmextra.json
const watcher = TsWatch.fromConfig();
if (watcher) {
await watcher.start();
}
```
### Using ConfigHandler
```typescript
import { ConfigHandler } from '@git.zone/tswatch';
const configHandler = new ConfigHandler();
// Check if config exists
if (configHandler.hasConfig()) {
const config = configHandler.loadConfig();
console.log(config);
}
// Get available presets
const presets = configHandler.getPresetNames();
console.log(presets); // ['npm', 'test', 'service', 'element', 'website']
// Get a specific preset
const npmPreset = configHandler.getPreset('npm');
```
### Using Watcher Directly
For more granular control, use the `Watcher` class:
```typescript ```typescript
import { Watcher } from '@git.zone/tswatch'; import { Watcher } from '@git.zone/tswatch';
const customWatcher = new Watcher({ // Create from config object
filePathToWatch: './src', const watcher = Watcher.fromConfig({
commandToExecute: 'npm run build', name: 'my-watcher',
timeout: 5000 // Optional timeout in ms watch: ['./src/**/*', './lib/**/*'],
command: 'npm run compile',
restart: true,
}); });
await customWatcher.start(); await watcher.start();
``` ```
### Using Function Callbacks ### Using Function Callbacks
```typescript ```typescript
import { Watcher } from '@git.zone/tswatch';
const watcher = new Watcher({ const watcher = new Watcher({
filePathToWatch: './src', name: 'custom-handler',
filePathToWatch: './src/**/*',
functionToCall: async () => { functionToCall: async () => {
console.log('Files changed!'); console.log('Files changed! Running custom logic...');
// Your custom logic here // Your custom build/test/deploy logic here
} },
debounce: 500,
runOnStart: true,
}); });
await watcher.start();
``` ```
## Development Server ## 📁 Project Structures
Element mode includes a built-in development server: ### NPM Package / Node.js Library
```
project/
├── ts/ # TypeScript source files
├── test/ # Test files
├── package.json # With "test" script
└── npmextra.json # tswatch config
```
Config:
```json
{
"@git.zone/tswatch": {
"preset": "npm"
}
}
```
### Backend Service
```
project/
├── ts/ # TypeScript source files
├── package.json # With "startTs" script
└── npmextra.json
```
Config:
```json
{
"@git.zone/tswatch": {
"preset": "service"
}
}
```
### Web Component / Element
```
project/
├── ts/ # Backend TypeScript (optional)
├── ts_web/ # Frontend TypeScript
├── html/
│ ├── index.ts # Web entry point
│ └── index.html
├── dist_watch/ # Output (auto-created)
└── npmextra.json
```
Config:
```json
{
"@git.zone/tswatch": {
"preset": "element"
}
}
```
Access your project at `http://localhost:3002`
### Full-Stack Website
```
project/
├── ts/ # Backend TypeScript
├── ts_web/ # Frontend TypeScript
│ └── index.ts
├── html/
│ └── index.html
├── assets/ # Static assets
├── dist_serve/ # Output
└── npmextra.json
```
Config:
```json
{
"@git.zone/tswatch": {
"preset": "website"
}
}
```
## 🌐 Development Server
The built-in development server (enabled in `element` and `website` presets) features:
- **Live Reload** - Automatically refreshes browser on changes
- **No Caching** - Prevents browser caching during development (sends `Cache-Control: no-store, no-cache` headers)
- **CORS** - Cross-origin requests enabled
- **Compression** - Gzip compression for faster loading
- **SPA Fallback** - Single-page application routing support
- **Security Headers** - Cross-origin isolation headers
Default configuration:
- **Port**: 3002 - **Port**: 3002
- **Features**: CORS enabled, gzip compression, live reload - **Serve Directory**: `./dist_watch/`
- **Serve directory**: `./dist_watch/` - **Live Reload**: Enabled
Access your project at `http://localhost:3002` when running in element mode. ## 🔧 Configuration Tips
## Configuration Tips 1. **Use presets for common workflows** - They're battle-tested and cover most use cases
2. **Customize with explicit config** - Override preset defaults by adding explicit `watchers`, `bundles`, or `server` config
1. **TypeScript Config**: Ensure your `tsconfig.json` is properly configured for your target environment 3. **Debounce wisely** - Default 300ms works well; increase for slower builds
2. **Package Scripts**: Define appropriate scripts in `package.json`: 4. **Use `restart: false`** for one-shot commands (like builds) and `restart: true` for long-running processes (like servers)
- `test`: For npm mode
- `startTs`: For service/website modes
- `build`: For general compilation
3. **File Organization**: Keep TypeScript files in `ts/` (backend) and `ts_web/` (frontend) directories
## Common Use Cases
### Developing a Node.js Library
```bash
tswatch npm
```
Automatically runs tests when you modify source files.
### Building a Web Component
```bash
tswatch element
```
Get instant feedback with live reload while developing custom elements.
### Creating a Backend Service
```bash
tswatch service
```
Automatically restart your service on code changes.
### Full-Stack Web Application
```bash
tswatch website
```
Handle both frontend and backend compilation with asset processing.
## License and Legal Information ## 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. This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file. **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 ### 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. This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
### Company Information ### Company Information
Task Venture Capital GmbH Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany 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. For any legal inquiries or further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works. 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

@@ -1,20 +1,105 @@
// tslint:disable-next-line: no-implicit-dependencies
import { expect, tap } from '@git.zone/tstest/tapbundle'; import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as tswatch from '../ts/index.js'; import * as tswatch from '../ts/index.js';
let testTsWatchInstance: tswatch.TsWatch; // ============================================
// ConfigHandler Tests
// ============================================
tap.test('should create a valid TsWatch instance', async () => { tap.test('ConfigHandler: should return all preset names', async () => {
testTsWatchInstance = new tswatch.TsWatch('echo'); const configHandler = new tswatch.ConfigHandler();
const presetNames = configHandler.getPresetNames();
expect(presetNames).toContain('npm');
expect(presetNames).toContain('test');
expect(presetNames).toContain('service');
expect(presetNames).toContain('element');
expect(presetNames).toContain('website');
expect(presetNames.length).toEqual(5);
}); });
tap.test('should start the tswatch instance', async () => { tap.test('ConfigHandler: should return npm preset with watchers', async () => {
await testTsWatchInstance.start(); const configHandler = new tswatch.ConfigHandler();
const preset = configHandler.getPreset('npm');
expect(preset).toBeTruthy();
expect(preset.watchers).toBeTruthy();
expect(preset.watchers.length).toBeGreaterThan(0);
expect(preset.watchers[0].name).toEqual('npm-test');
expect(preset.watchers[0].command).toEqual('npm run test');
}); });
tap.test('should stop the instance', async (tools) => { tap.test('ConfigHandler: should return element preset with server', async () => {
tools.delayFor(2000); const configHandler = new tswatch.ConfigHandler();
testTsWatchInstance.stop(); const preset = configHandler.getPreset('element');
expect(preset).toBeTruthy();
expect(preset.server).toBeTruthy();
expect(preset.server.enabled).toBeTrue();
expect(preset.server.port).toEqual(3002);
expect(preset.bundles).toBeTruthy();
expect(preset.bundles.length).toBeGreaterThan(0);
}); });
tap.start(); tap.test('ConfigHandler: should return null for invalid preset', async () => {
const configHandler = new tswatch.ConfigHandler();
const preset = configHandler.getPreset('invalid');
expect(preset).toBeNull();
});
tap.test('ConfigHandler: should return correct config key', async () => {
const configHandler = new tswatch.ConfigHandler();
expect(configHandler.getConfigKey()).toEqual('@git.zone/tswatch');
});
// ============================================
// Watcher Tests
// ============================================
tap.test('Watcher: should create from config with defaults', async () => {
const watcher = tswatch.Watcher.fromConfig({
name: 'test-watcher',
watch: './ts/**/*',
command: 'echo test',
});
expect(watcher).toBeInstanceOf(tswatch.Watcher);
});
tap.test('Watcher: should handle array watch patterns', async () => {
const watcher = tswatch.Watcher.fromConfig({
name: 'multi-watch',
watch: ['./ts/**/*', './test/**/*'],
command: 'echo test',
});
expect(watcher).toBeInstanceOf(tswatch.Watcher);
});
// ============================================
// TsWatch Tests
// ============================================
let testTsWatch: tswatch.TsWatch;
tap.test('TsWatch: should create with minimal config', async () => {
testTsWatch = new tswatch.TsWatch({
watchers: [
{
name: 'echo-test',
watch: './ts/**/*',
command: 'echo "test"',
runOnStart: false,
},
],
});
expect(testTsWatch).toBeInstanceOf(tswatch.TsWatch);
expect(testTsWatch.config.watchers).toBeTruthy();
expect(testTsWatch.config.watchers.length).toEqual(1);
});
tap.test('TsWatch: should start and populate watcherMap', async () => {
await testTsWatch.start();
expect(testTsWatch.watcherMap.getArray().length).toBeGreaterThan(0);
});
tap.test('TsWatch: should stop cleanly', async (tools) => {
await tools.delayFor(500);
await testTsWatch.stop();
});
export default tap.start();

View File

@@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@git.zone/tswatch', name: '@git.zone/tswatch',
version: '2.1.3', version: '3.2.0',
description: 'A development tool for automatically watching and re-compiling TypeScript projects upon detecting file changes, enhancing developer workflows.' description: 'A development tool for automatically watching and re-compiling TypeScript projects upon detecting file changes, enhancing developer workflows.'
} }

View File

@@ -1,5 +1,11 @@
import * as early from '@push.rocks/early'; import * as early from '@push.rocks/early';
early.start('tswatch'); early.start('tswatch');
export * from './tswatch.classes.tswatch.js'; export * from './tswatch.classes.tswatch.js';
export * from './tswatch.classes.watcher.js';
export * from './tswatch.classes.confighandler.js';
export * from './tswatch.cli.js'; export * from './tswatch.cli.js';
export * from './tswatch.init.js';
export * from './interfaces/index.js';
early.stop(); early.stop();

View File

@@ -1 +1 @@
export * from './interfaces.watchmodes.js'; export * from './interfaces.config.js';

View File

@@ -0,0 +1,71 @@
/**
* Configuration for a single watcher
*/
export interface IWatcherConfig {
/** Name for this watcher (used in logging) */
name: string;
/** Glob pattern(s) to watch */
watch: string | string[];
/** Shell command to execute on changes */
command?: string;
/** If true, kill previous process before restarting (default: true) */
restart?: boolean;
/** Debounce delay in ms (default: 300) */
debounce?: number;
/** If true, run the command immediately on start (default: true) */
runOnStart?: boolean;
}
/**
* Configuration for the development server
*/
export interface IServerConfig {
/** Whether the server is enabled */
enabled: boolean;
/** Server port (default: 3002) */
port?: number;
/** Directory to serve (default: ./dist_watch/) */
serveDir?: string;
/** Whether to inject live reload script (default: true) */
liveReload?: boolean;
}
/**
* Configuration for a bundle operation
*/
export interface IBundleConfig {
/** Name for this bundle (used in logging) */
name?: string;
/** Entry point file */
from: string;
/** Output file */
to: string;
/** Additional patterns to watch that trigger this bundle */
watchPatterns?: string[];
/** If true, trigger server reload after bundling (default: true) */
triggerReload?: boolean;
/** Output mode: 'bundle' writes JS, 'base64ts' writes base64-encoded TS (default: 'bundle') */
outputMode?: 'bundle' | 'base64ts';
/** Bundler to use (default: 'esbuild') */
bundler?: 'esbuild' | 'rolldown' | 'rspack';
/** Whether to produce a production build (default: false) */
production?: boolean;
/** Files to include alongside the bundle */
includeFiles?: (string | { from: string; to: string })[];
/** Max chars per line for base64ts output. 0 or undefined = unlimited */
maxLineLength?: number;
}
/**
* Main tswatch configuration
*/
export interface ITswatchConfig {
/** Array of watcher configurations */
watchers?: IWatcherConfig[];
/** Development server configuration */
server?: IServerConfig;
/** Bundle configurations */
bundles?: IBundleConfig[];
/** Use a preset configuration (overridden by explicit watchers/server/bundles) */
preset?: 'element' | 'website' | 'npm' | 'service' | 'test';
}

View File

@@ -1 +0,0 @@
export type TWatchModes = 'test' | 'node' | 'service' | 'element' | 'website' | 'echo';

View File

@@ -0,0 +1,185 @@
import * as plugins from './tswatch.plugins.js';
import * as paths from './tswatch.paths.js';
import * as interfaces from './interfaces/index.js';
const CONFIG_KEY = '@git.zone/tswatch';
/**
* Preset configurations matching legacy watch modes
*/
const presets: Record<string, interfaces.ITswatchConfig> = {
npm: {
watchers: [
{
name: 'npm-test',
watch: ['./ts/**/*', './test/**/*'],
command: 'npm run test',
restart: true,
debounce: 300,
runOnStart: true,
},
],
},
test: {
watchers: [
{
name: 'test2',
watch: ['./ts/**/*', './test/**/*'],
command: 'npm run test2',
restart: true,
debounce: 300,
runOnStart: true,
},
],
},
service: {
watchers: [
{
name: 'service',
watch: './ts/**/*',
command: 'npm run startTs',
restart: true,
debounce: 300,
runOnStart: true,
},
],
},
element: {
server: {
enabled: true,
port: 3002,
serveDir: './dist_watch/',
liveReload: true,
},
bundles: [
{
name: 'element-bundle',
from: './html/index.ts',
to: './dist_watch/bundle.js',
watchPatterns: ['./ts_web/**/*'],
triggerReload: true,
},
{
name: 'html',
from: './html/index.html',
to: './dist_watch/index.html',
watchPatterns: ['./html/**/*'],
triggerReload: true,
},
],
watchers: [
{
name: 'ts-build',
watch: './ts/**/*',
command: 'npm run build',
restart: false,
debounce: 300,
runOnStart: false,
},
],
},
website: {
bundles: [
{
name: 'website-bundle',
from: './ts_web/index.ts',
to: './dist_serve/bundle.js',
watchPatterns: ['./ts_web/**/*'],
triggerReload: false,
},
{
name: 'html',
from: './html/index.html',
to: './dist_serve/index.html',
watchPatterns: ['./html/**/*'],
triggerReload: false,
},
{
name: 'assets',
from: './assets/',
to: './dist_serve/assets/',
watchPatterns: ['./assets/**/*'],
triggerReload: false,
},
],
watchers: [
{
name: 'backend',
watch: './ts/**/*',
command: 'npm run startTs',
restart: true,
debounce: 300,
runOnStart: true,
},
],
},
};
/**
* Handles loading and managing tswatch configuration
*/
export class ConfigHandler {
private npmextra: plugins.npmextra.Npmextra;
private cwd: string;
constructor(cwdArg?: string) {
this.cwd = cwdArg || paths.cwd;
this.npmextra = new plugins.npmextra.Npmextra(this.cwd);
}
/**
* Check if a tswatch configuration exists
*/
public hasConfig(): boolean {
const config = this.npmextra.dataFor<interfaces.ITswatchConfig>(CONFIG_KEY, null);
return config !== null;
}
/**
* Load configuration from npmextra.json
* If a preset is specified, merge preset defaults with user overrides
*/
public loadConfig(): interfaces.ITswatchConfig | null {
const config = this.npmextra.dataFor<interfaces.ITswatchConfig>(CONFIG_KEY, null);
if (!config) {
return null;
}
// If a preset is specified, merge it with user config
if (config.preset && presets[config.preset]) {
const preset = presets[config.preset];
return {
...preset,
...config,
// Merge arrays instead of replacing
watchers: config.watchers || preset.watchers,
bundles: config.bundles || preset.bundles,
server: config.server !== undefined ? config.server : preset.server,
};
}
return config;
}
/**
* Get a preset configuration by name
*/
public getPreset(presetName: string): interfaces.ITswatchConfig | null {
return presets[presetName] || null;
}
/**
* Get all available preset names
*/
public getPresetNames(): string[] {
return Object.keys(presets);
}
/**
* Get the config key for npmextra.json
*/
public getConfigKey(): string {
return CONFIG_KEY;
}
}

View File

@@ -3,204 +3,199 @@ import * as paths from './tswatch.paths.js';
import * as interfaces from './interfaces/index.js'; import * as interfaces from './interfaces/index.js';
import { Watcher } from './tswatch.classes.watcher.js'; import { Watcher } from './tswatch.classes.watcher.js';
import { ConfigHandler } from './tswatch.classes.confighandler.js';
import { logger } from './tswatch.logging.js'; import { logger } from './tswatch.logging.js';
/**
* TsWatch - Config-driven file watcher
*
* Reads configuration from npmextra.json under the key '@git.zone/tswatch'
* and sets up watchers, bundles, and dev server accordingly.
*/
export class TsWatch { export class TsWatch {
public watchmode: interfaces.TWatchModes; public config: interfaces.ITswatchConfig;
public watcherMap = new plugins.lik.ObjectMap<Watcher>(); public watcherMap = new plugins.lik.ObjectMap<Watcher>();
public typedserver: plugins.typedserver.TypedServer; public typedserver: plugins.typedserver.TypedServer | null = null;
constructor(watchmodeArg: interfaces.TWatchModes) { private tsbundle = new plugins.tsbundle.TsBundle();
this.watchmode = watchmodeArg; private customBundleHandler = new plugins.tsbundle.CustomBundleHandler();
private htmlHandler = new plugins.tsbundle.HtmlHandler();
private assetsHandler = new plugins.tsbundle.AssetsHandler();
constructor(configArg: interfaces.ITswatchConfig) {
this.config = configArg;
}
/**
* Create TsWatch from npmextra.json configuration
*/
public static fromConfig(cwdArg?: string): TsWatch | null {
const configHandler = new ConfigHandler(cwdArg);
const config = configHandler.loadConfig();
if (!config) {
return null;
}
return new TsWatch(config);
} }
/** /**
* starts the TsWatch instance * starts the TsWatch instance
*/ */
public async start() { public async start() {
const tsbundle = new plugins.tsbundle.TsBundle(); logger.log('info', 'Starting tswatch with config-driven mode');
const assetsHandler = new plugins.tsbundle.AssetsHandler();
const htmlHandler = new plugins.tsbundle.HtmlHandler();
switch (this.watchmode) {
case 'test':
/**
* this strategy runs test whenever there is a change in the ts directory
*/
this.watcherMap.add(
new Watcher({
filePathToWatch: paths.cwd,
commandToExecute: 'npm run test2',
timeout: null,
}),
);
break;
case 'node':
this.watcherMap.add(
new Watcher({
filePathToWatch: paths.cwd,
commandToExecute: 'npm run test',
timeout: null,
}),
);
break;
case 'element':
await (async () => {
/**
* this strategy runs a standard server and bundles the ts files to a dist_watch directory
*/
// lets create a standard server
logger.log(
'info',
'bundling TypeScript files to "dist_watch" Note: This is for development only!',
);
this.typedserver = new plugins.typedserver.TypedServer({
cors: true,
injectReload: true,
serveDir: plugins.path.join(paths.cwd, './dist_watch/'),
port: 3002,
enableCompression: true,
preferredCompressionMethod: 'gzip',
});
const bundleAndReloadElement = async () => { // Start server if configured
await tsbundle.build(paths.cwd, './html/index.ts', './dist_watch/bundle.js', { if (this.config.server?.enabled) {
bundler: 'esbuild', await this.startServer();
});
await this.typedserver.reload();
};
this.watcherMap.add(
new Watcher({
filePathToWatch: plugins.path.join(paths.cwd, './ts_web/'),
functionToCall: async () => {
await bundleAndReloadElement();
},
timeout: null,
}),
);
// lets get the other ts folders
let tsfolders = await plugins.smartfile.fs.listFolders(paths.cwd);
tsfolders = tsfolders.filter(
(itemArg) => itemArg.startsWith('ts') && itemArg !== 'ts_web',
);
const smartshellInstance = new plugins.smartshell.Smartshell({
executor: 'bash',
});
for (const tsfolder of tsfolders) {
logger.log('info', `creating watcher for folder ${tsfolder}`);
this.watcherMap.add(
new Watcher({
filePathToWatch: plugins.path.join(paths.cwd, `./${tsfolder}/`),
functionToCall: async () => {
logger.log('info', `building ${tsfolder}`);
await smartshellInstance.exec(`(cd ${paths.cwd} && npm run build)`);
await bundleAndReloadElement();
},
timeout: null,
}),
);
}
this.watcherMap.add(
new Watcher({
filePathToWatch: plugins.path.join(paths.cwd, './html/'),
functionToCall: async () => {
await htmlHandler.processHtml({
from: plugins.path.join(paths.cwd, './html/index.html'),
to: plugins.path.join(paths.cwd, './dist_watch/index.html'),
minify: false,
});
await bundleAndReloadElement();
},
timeout: null,
}),
);
})();
break;
case 'website':
await (async () => {
const websiteExecution = new plugins.smartshell.SmartExecution('npm run startTs');
const bundleAndReloadWebsite = async () => {
await tsbundle.build(paths.cwd, './ts_web/index.ts', './dist_serve/bundle.js', {
bundler: 'esbuild',
});
};
let tsfolders = await plugins.smartfile.fs.listFolders(paths.cwd);
tsfolders = tsfolders.filter(
(itemArg) => itemArg.startsWith('ts') && itemArg !== 'ts_web',
);
for (const tsfolder of tsfolders) {
this.watcherMap.add(
new Watcher({
filePathToWatch: plugins.path.join(paths.cwd, `./${tsfolder}/`),
functionToCall: async () => {
await websiteExecution.restart();
await bundleAndReloadWebsite();
},
timeout: null,
}),
);
}
this.watcherMap.add(
new Watcher({
filePathToWatch: plugins.path.join(paths.cwd, './ts_web/'),
functionToCall: async () => {
await bundleAndReloadWebsite();
},
timeout: null,
}),
);
this.watcherMap.add(
new Watcher({
filePathToWatch: plugins.path.join(paths.cwd, './html/'),
functionToCall: async () => {
await htmlHandler.processHtml({
from: plugins.path.join(paths.cwd, './html/index.html'),
to: plugins.path.join(paths.cwd, './dist_serve/index.html'),
minify: false,
});
await bundleAndReloadWebsite();
},
timeout: null,
}),
);
this.watcherMap.add(
new Watcher({
filePathToWatch: plugins.path.join(paths.cwd, './assets/'),
functionToCall: async () => {
await assetsHandler.processAssets();
await bundleAndReloadWebsite();
},
timeout: null,
}),
);
})();
break;
case 'service':
this.watcherMap.add(
new Watcher({
filePathToWatch: plugins.path.join(paths.cwd, './ts/'),
commandToExecute: 'npm run startTs',
timeout: null,
}),
);
break;
case 'echo':
const tsWatchInstanceEchoSomething = new Watcher({
filePathToWatch: plugins.path.join(paths.cwd, './ts'),
commandToExecute: 'npm -v',
timeout: null,
});
this.watcherMap.add(tsWatchInstanceEchoSomething);
break;
default:
break;
} }
this.watcherMap.forEach(async (watcher) => {
// Setup bundles and their watchers
if (this.config.bundles && this.config.bundles.length > 0) {
await this.setupBundles();
}
// Setup watchers from config
if (this.config.watchers && this.config.watchers.length > 0) {
await this.setupWatchers();
}
// Start all watchers
await this.watcherMap.forEach(async (watcher) => {
await watcher.start(); await watcher.start();
}); });
// Start server after watchers are ready
if (this.typedserver) { if (this.typedserver) {
await this.typedserver.start(); await this.typedserver.start();
logger.log('ok', `Dev server started on port ${this.config.server?.port || 3002}`);
}
}
/**
* Start the development server
*/
private async startServer() {
const serverConfig = this.config.server!;
const port = serverConfig.port || 3002;
const serveDir = serverConfig.serveDir || './dist_watch/';
logger.log('info', `Setting up dev server on port ${port}, serving ${serveDir}`);
this.typedserver = new plugins.typedserver.TypedServer({
cors: true,
injectReload: serverConfig.liveReload !== false,
serveDir: plugins.path.join(paths.cwd, serveDir),
port: port,
compression: true,
spaFallback: true,
noCache: true,
securityHeaders: {
crossOriginOpenerPolicy: 'same-origin',
crossOriginEmbedderPolicy: 'require-corp',
},
});
}
/**
* Setup bundle watchers
*/
private async setupBundles() {
for (const bundleConfig of this.config.bundles!) {
const name = bundleConfig.name || `bundle-${bundleConfig.from}`;
logger.log('info', `Setting up bundle: ${name}`);
// Determine what patterns to watch
const watchPatterns = bundleConfig.watchPatterns || [
plugins.path.dirname(bundleConfig.from) + '/**/*',
];
// Create the bundle function
const bundleFunction = async () => {
logger.log('info', `[${name}] bundling...`);
// Determine bundle type based on file extension
const fromPath = bundleConfig.from;
const toPath = bundleConfig.to;
if (fromPath.endsWith('.html')) {
// HTML processing
await this.htmlHandler.processHtml({
from: plugins.path.join(paths.cwd, fromPath),
to: plugins.path.join(paths.cwd, toPath),
minify: false,
});
} else if (fromPath.endsWith('/') || !fromPath.includes('.')) {
// Assets directory copy
await this.assetsHandler.processAssets();
} else if (bundleConfig.outputMode && bundleConfig.outputMode !== 'bundle') {
// Non-default outputMode (e.g. base64ts) — use CustomBundleHandler
await this.customBundleHandler.processSingleBundle({
from: bundleConfig.from,
to: bundleConfig.to,
outputMode: bundleConfig.outputMode,
bundler: bundleConfig.bundler || 'esbuild',
production: bundleConfig.production || false,
includeFiles: bundleConfig.includeFiles,
maxLineLength: bundleConfig.maxLineLength,
});
} else {
// Standard TypeScript bundling (default)
await this.tsbundle.build(paths.cwd, fromPath, toPath, {
bundler: bundleConfig.bundler || 'esbuild',
production: bundleConfig.production || false,
});
}
logger.log('ok', `[${name}] bundle complete`);
// Trigger reload if configured and server is running
if (bundleConfig.triggerReload !== false && this.typedserver) {
await this.typedserver.reload();
}
};
// Run initial bundle
await bundleFunction();
// Create watcher for this bundle
this.watcherMap.add(
new Watcher({
name: name,
filePathToWatch: watchPatterns.map((p) => plugins.path.join(paths.cwd, p)),
functionToCall: bundleFunction,
runOnStart: false, // Already ran above
debounce: 300,
}),
);
}
}
/**
* Setup watchers from config
*/
private async setupWatchers() {
for (const watcherConfig of this.config.watchers!) {
logger.log('info', `Setting up watcher: ${watcherConfig.name}`);
// Convert watch paths to absolute
const watchPaths = Array.isArray(watcherConfig.watch)
? watcherConfig.watch
: [watcherConfig.watch];
const absolutePaths = watchPaths.map((p) => plugins.path.join(paths.cwd, p));
this.watcherMap.add(
new Watcher({
name: watcherConfig.name,
filePathToWatch: absolutePaths,
commandToExecute: watcherConfig.command,
restart: watcherConfig.restart ?? true,
debounce: watcherConfig.debounce ?? 300,
runOnStart: watcherConfig.runOnStart ?? true,
}),
);
} }
} }
@@ -211,7 +206,7 @@ export class TsWatch {
if (this.typedserver) { if (this.typedserver) {
await this.typedserver.stop(); await this.typedserver.stop();
} }
this.watcherMap.forEach(async (watcher) => { await this.watcherMap.forEach(async (watcher) => {
await watcher.stop(); await watcher.stop();
}); });
} }

View File

@@ -1,11 +1,24 @@
import * as plugins from './tswatch.plugins.js'; import * as plugins from './tswatch.plugins.js';
import * as interfaces from './interfaces/index.js';
import { logger } from './tswatch.logging.js'; import { logger } from './tswatch.logging.js';
export interface IWatcherConstructorOptions { export interface IWatcherConstructorOptions {
filePathToWatch: string; /** Name for this watcher (used in logging) */
name?: string;
/** Path(s) to watch - can be a single path or array */
filePathToWatch: string | string[];
/** Shell command to execute on changes */
commandToExecute?: string; commandToExecute?: string;
/** Function to call on changes */
functionToCall?: () => Promise<any>; functionToCall?: () => Promise<any>;
/** Timeout for the watcher */
timeout?: number; timeout?: number;
/** If true, kill previous process before restarting (default: true) */
restart?: boolean;
/** Debounce delay in ms (default: 300) */
debounce?: number;
/** If true, run the command immediately on start (default: true) */
runOnStart?: boolean;
} }
/** /**
@@ -20,51 +33,150 @@ export class Watcher {
}); });
private currentExecution: plugins.smartshell.IExecResultStreaming; private currentExecution: plugins.smartshell.IExecResultStreaming;
private smartchokWatcher = new plugins.smartchok.Smartchok([]); private smartwatchInstance = new plugins.smartwatch.Smartwatch([]);
private options: IWatcherConstructorOptions; private options: IWatcherConstructorOptions;
private debounceTimer: NodeJS.Timeout | null = null;
private isExecuting = false;
private pendingExecution = false;
constructor(optionsArg: IWatcherConstructorOptions) { constructor(optionsArg: IWatcherConstructorOptions) {
this.options = optionsArg; this.options = {
restart: true,
debounce: 300,
runOnStart: true,
...optionsArg,
};
}
/**
* Create a Watcher from config
*/
public static fromConfig(config: interfaces.IWatcherConfig): Watcher {
const watchPaths = Array.isArray(config.watch) ? config.watch : [config.watch];
return new Watcher({
name: config.name,
filePathToWatch: watchPaths,
commandToExecute: config.command,
restart: config.restart ?? true,
debounce: config.debounce ?? 300,
runOnStart: config.runOnStart ?? true,
});
}
/**
* Get the watcher name for logging
*/
private getName(): string {
return this.options.name || 'unnamed';
} }
/** /**
* start the file * start the file
*/ */
public async start() { public async start() {
logger.log('info', `trying to start watcher for ${this.options.filePathToWatch}`); const name = this.getName();
logger.log('info', `[${name}] starting watcher`);
await this.setupCleanup(); await this.setupCleanup();
console.log(`Looking at ${this.options.filePathToWatch} for changes`);
this.smartchokWatcher.add([this.options.filePathToWatch]); // __dirname refers to the directory of this very file // Convert paths to glob patterns
await this.smartchokWatcher.start(); const paths = Array.isArray(this.options.filePathToWatch)
const changeObservable = await this.smartchokWatcher.getObservableFor('change'); ? this.options.filePathToWatch
changeObservable.subscribe(() => { : [this.options.filePathToWatch];
this.updateCurrentExecution();
const watchPatterns = paths.map((p) => {
// Convert directory path to glob pattern for smartwatch
if (p.endsWith('/')) {
return `${p}**/*`;
}
// If it's already a glob pattern, use as-is
if (p.includes('*')) {
return p;
}
// Otherwise assume it's a directory
return `${p}/**/*`;
}); });
await this.updateCurrentExecution();
logger.log('info', `watcher started for ${this.options.filePathToWatch}`); logger.log('info', `[${name}] watching patterns: ${watchPatterns.join(', ')}`);
this.smartwatchInstance.add(watchPatterns);
await this.smartwatchInstance.start();
const changeObservable = await this.smartwatchInstance.getObservableFor('change');
changeObservable.subscribe(() => {
this.handleChange();
});
// Run on start if configured
if (this.options.runOnStart) {
await this.executeCommand();
}
logger.log('info', `[${name}] watcher started`);
} }
/** /**
* updates the current execution * Handle file change with debouncing
*/ */
private async updateCurrentExecution() { private handleChange() {
if (this.options.commandToExecute) { const name = this.getName();
if (this.currentExecution) {
logger.log('ok', `reexecuting ${this.options.commandToExecute}`); // Clear existing debounce timer
this.currentExecution.kill(); if (this.debounceTimer) {
} else { clearTimeout(this.debounceTimer);
logger.log('ok', `executing ${this.options.commandToExecute} for the first time`); }
// Set new debounce timer
this.debounceTimer = setTimeout(async () => {
this.debounceTimer = null;
// If currently executing and not in restart mode, mark pending
if (this.isExecuting && !this.options.restart) {
logger.log('info', `[${name}] change detected, queuing execution`);
this.pendingExecution = true;
return;
} }
await this.executeCommand();
// If there was a pending execution, run it
if (this.pendingExecution) {
this.pendingExecution = false;
await this.executeCommand();
}
}, this.options.debounce);
}
/**
* Execute the command or function
*/
private async executeCommand() {
const name = this.getName();
if (this.options.commandToExecute) {
if (this.currentExecution && this.options.restart) {
logger.log('ok', `[${name}] restarting: ${this.options.commandToExecute}`);
this.currentExecution.kill();
} else if (!this.currentExecution) {
logger.log('ok', `[${name}] executing: ${this.options.commandToExecute}`);
}
this.isExecuting = true;
this.currentExecution = await this.smartshellInstance.execStreaming( this.currentExecution = await this.smartshellInstance.execStreaming(
this.options.commandToExecute, this.options.commandToExecute,
); );
} else {
console.log('no executionCommand set'); // Track when execution completes
this.currentExecution.childProcess.on('exit', () => {
this.isExecuting = false;
});
} }
if (this.options.functionToCall) { if (this.options.functionToCall) {
this.options.functionToCall(); this.isExecuting = true;
} else { try {
console.log('no functionToCall set.'); await this.options.functionToCall();
} finally {
this.isExecuting = false;
}
} }
} }
@@ -99,7 +211,10 @@ export class Watcher {
* stops the watcher * stops the watcher
*/ */
public async stop() { public async stop() {
await this.smartchokWatcher.stop(); if (this.debounceTimer) {
clearTimeout(this.debounceTimer);
}
await this.smartwatchInstance.stop();
if (this.currentExecution && !this.currentExecution.childProcess.killed) { if (this.currentExecution && !this.currentExecution.childProcess.killed) {
this.currentExecution.kill(); this.currentExecution.kill();
} }

View File

@@ -3,42 +3,48 @@ import * as paths from './tswatch.paths.js';
import { logger } from './tswatch.logging.js'; import { logger } from './tswatch.logging.js';
import { TsWatch } from './tswatch.classes.tswatch.js'; import { TsWatch } from './tswatch.classes.tswatch.js';
import { ConfigHandler } from './tswatch.classes.confighandler.js';
import { runInit } from './tswatch.init.js';
const tswatchCli = new plugins.smartcli.Smartcli(); const tswatchCli = new plugins.smartcli.Smartcli();
// standard behaviour will assume gitzone setup /**
tswatchCli.standardCommand().subscribe((argvArg) => { * Standard command (no args) - run with config or launch wizard
tswatchCli.triggerCommand('npm', {}); */
tswatchCli.standardCommand().subscribe(async (argvArg) => {
const configHandler = new ConfigHandler();
if (configHandler.hasConfig()) {
// Config exists - run with it
const tsWatch = TsWatch.fromConfig();
if (tsWatch) {
logger.log('info', 'Starting tswatch with configuration from npmextra.json');
await tsWatch.start();
} else {
logger.log('error', 'Failed to load configuration');
process.exit(1);
}
} else {
// No config - launch wizard
logger.log('info', 'No tswatch configuration found in npmextra.json');
const config = await runInit();
if (config) {
// Run with the newly created config
const tsWatch = new TsWatch(config);
await tsWatch.start();
}
}
}); });
tswatchCli.addCommand('element').subscribe(async (argvArg) => { /**
logger.log('info', `running watch task for a gitzone element project`); * Init command - force run wizard (overwrite existing config)
const tsWatch = new TsWatch('element'); */
await tsWatch.start(); tswatchCli.addCommand('init').subscribe(async (argvArg) => {
}); logger.log('info', 'Running tswatch configuration wizard');
const config = await runInit();
tswatchCli.addCommand('npm').subscribe(async (argvArg) => { if (config) {
logger.log('info', `running watch task for a gitzone element project`); logger.log('ok', 'Configuration created successfully');
const tsWatch = new TsWatch('node'); }
await tsWatch.start();
});
tswatchCli.addCommand('service').subscribe(async (argvArg) => {
logger.log('info', `running test task`);
const tsWatch = new TsWatch('service');
await tsWatch.start();
});
tswatchCli.addCommand('test').subscribe(async (argvArg) => {
logger.log('info', `running test task`);
const tsWatch = new TsWatch('test');
await tsWatch.start();
});
tswatchCli.addCommand('website').subscribe(async (argvArg) => {
logger.log('info', `running watch task for a gitzone website project`);
const tsWatch = new TsWatch('website');
await tsWatch.start();
}); });
export const runCli = async () => { export const runCli = async () => {

199
ts/tswatch.init.ts Normal file
View File

@@ -0,0 +1,199 @@
import * as plugins from './tswatch.plugins.js';
import * as paths from './tswatch.paths.js';
import * as interfaces from './interfaces/index.js';
import { ConfigHandler } from './tswatch.classes.confighandler.js';
import { logger } from './tswatch.logging.js';
const CONFIG_KEY = '@git.zone/tswatch';
/**
* Interactive init wizard for creating tswatch configuration
*/
export class TswatchInit {
private configHandler: ConfigHandler;
private smartInteract: plugins.smartinteract.SmartInteract;
constructor() {
this.configHandler = new ConfigHandler();
this.smartInteract = new plugins.smartinteract.SmartInteract([]);
}
/**
* Run the interactive init wizard
*/
public async run(): Promise<interfaces.ITswatchConfig | null> {
console.log('\n=== tswatch Configuration Wizard ===\n');
// Ask for template choice
const templateAnswer = await this.smartInteract.askQuestion({
name: 'template',
type: 'list',
message: 'Select a configuration template:',
default: 'npm',
choices: [
{ name: 'npm - Watch ts/ and test/, run npm test', value: 'npm' },
{ name: 'test - Watch ts/ and test/, run npm run test2', value: 'test' },
{ name: 'service - Watch ts/, restart npm run startTs', value: 'service' },
{ name: 'element - Dev server + bundling for web components', value: 'element' },
{ name: 'website - Full stack: backend + frontend + assets', value: 'website' },
{ name: 'custom - Configure watchers manually', value: 'custom' },
],
});
const template = templateAnswer.value as string;
let config: interfaces.ITswatchConfig;
if (template === 'custom') {
config = await this.runCustomWizard();
} else {
// Get preset config
const preset = this.configHandler.getPreset(template);
if (!preset) {
console.error(`Unknown template: ${template}`);
return null;
}
config = { ...preset, preset: template as interfaces.ITswatchConfig['preset'] };
}
// Save to npmextra.json
await this.saveConfig(config);
console.log('\nConfiguration saved to npmextra.json');
console.log('Run "tswatch" to start watching.\n');
return config;
}
/**
* Run custom configuration wizard
*/
private async runCustomWizard(): Promise<interfaces.ITswatchConfig> {
const config: interfaces.ITswatchConfig = {};
// Ask about server
const serverAnswer = await this.smartInteract.askQuestion({
name: 'enableServer',
type: 'confirm',
message: 'Enable development server?',
default: false,
});
if (serverAnswer.value) {
const portAnswer = await this.smartInteract.askQuestion({
name: 'port',
type: 'input',
message: 'Server port:',
default: '3002',
});
const serveDirAnswer = await this.smartInteract.askQuestion({
name: 'serveDir',
type: 'input',
message: 'Directory to serve:',
default: './dist_watch/',
});
config.server = {
enabled: true,
port: parseInt(portAnswer.value as string, 10),
serveDir: serveDirAnswer.value as string,
liveReload: true,
};
}
// Add watchers
config.watchers = [];
let addMore = true;
while (addMore) {
console.log('\n--- Add a watcher ---');
const nameAnswer = await this.smartInteract.askQuestion({
name: 'name',
type: 'input',
message: 'Watcher name:',
default: `watcher-${config.watchers.length + 1}`,
});
const watchAnswer = await this.smartInteract.askQuestion({
name: 'watch',
type: 'input',
message: 'Glob pattern(s) to watch (comma-separated):',
default: './ts/**/*',
});
const commandAnswer = await this.smartInteract.askQuestion({
name: 'command',
type: 'input',
message: 'Command to execute:',
default: 'npm run test',
});
const restartAnswer = await this.smartInteract.askQuestion({
name: 'restart',
type: 'confirm',
message: 'Restart command on each change (vs queue)?',
default: true,
});
// Parse watch patterns
const watchPatterns = (watchAnswer.value as string)
.split(',')
.map((p) => p.trim())
.filter((p) => p.length > 0);
config.watchers.push({
name: nameAnswer.value as string,
watch: watchPatterns.length === 1 ? watchPatterns[0] : watchPatterns,
command: commandAnswer.value as string,
restart: restartAnswer.value as boolean,
debounce: 300,
runOnStart: true,
});
const moreAnswer = await this.smartInteract.askQuestion({
name: 'addMore',
type: 'confirm',
message: 'Add another watcher?',
default: false,
});
addMore = moreAnswer.value as boolean;
}
return config;
}
/**
* Save configuration to npmextra.json
*/
private async saveConfig(config: interfaces.ITswatchConfig): Promise<void> {
const npmextraPath = plugins.path.join(paths.cwd, 'npmextra.json');
// Read existing npmextra.json if it exists
let existingConfig: Record<string, any> = {};
try {
const smartfsInstance = new plugins.smartfs.SmartFs(new plugins.smartfs.SmartFsProviderNode());
const content = await smartfsInstance.file(npmextraPath).encoding('utf8').read() as string;
existingConfig = JSON.parse(content);
} catch {
// File doesn't exist or is invalid, start fresh
}
// Update with new tswatch config
existingConfig[CONFIG_KEY] = config;
// Write back
const smartfsInstance = new plugins.smartfs.SmartFs(new plugins.smartfs.SmartFsProviderNode());
await smartfsInstance.file(npmextraPath).encoding('utf8').write(JSON.stringify(existingConfig, null, 2));
}
}
/**
* Run the init wizard
*/
export const runInit = async (): Promise<interfaces.ITswatchConfig | null> => {
const init = new TswatchInit();
return init.run();
};

View File

@@ -2,34 +2,38 @@
import * as path from 'path'; import * as path from 'path';
export { path }; export { path };
// @gitzone scope // @git.zone scope
import * as tsbundle from '@git.zone/tsbundle'; import * as tsbundle from '@git.zone/tsbundle';
export { tsbundle }; export { tsbundle };
// @apiglobal scope // @api.global scope
import * as typedserver from '@api.global/typedserver'; import * as typedserver from '@api.global/typedserver';
export { typedserver }; export { typedserver };
// @pushrocks scope // @push.rocks scope
import * as lik from '@push.rocks/lik'; import * as lik from '@push.rocks/lik';
import * as smartchok from '@push.rocks/smartchok'; import * as npmextra from '@push.rocks/npmextra';
import * as smartcli from '@push.rocks/smartcli'; import * as smartcli from '@push.rocks/smartcli';
import * as smartdelay from '@push.rocks/smartdelay'; import * as smartdelay from '@push.rocks/smartdelay';
import * as smartfile from '@push.rocks/smartfile'; import * as smartfs from '@push.rocks/smartfs';
import * as smartinteract from '@push.rocks/smartinteract';
import * as smartlog from '@push.rocks/smartlog'; import * as smartlog from '@push.rocks/smartlog';
import * as smartlogDestinationLocal from '@push.rocks/smartlog-destination-local'; import * as smartlogDestinationLocal from '@push.rocks/smartlog-destination-local';
import * as smartshell from '@push.rocks/smartshell'; import * as smartshell from '@push.rocks/smartshell';
import * as smartwatch from '@push.rocks/smartwatch';
import * as taskbuffer from '@push.rocks/taskbuffer'; import * as taskbuffer from '@push.rocks/taskbuffer';
export { export {
lik, lik,
smartchok, npmextra,
smartcli, smartcli,
smartdelay, smartdelay,
smartfile, smartfs,
smartinteract,
smartlog, smartlog,
smartlogDestinationLocal, smartlogDestinationLocal,
smartshell, smartshell,
smartwatch,
taskbuffer, taskbuffer,
}; };