@dtsx/dtsx 0.0.0-stage → 0.11.38
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +21 -0
- package/README.md +442 -2
- package/dist/bin/cli.d.ts +1 -0
- package/dist/bin/cli.js +12 -0
- package/dist/chunk-082w7zvy.js +4 -0
- package/dist/chunk-0k0fhq13.js +19 -0
- package/dist/chunk-0rmbc5zp.js +3 -0
- package/dist/chunk-0yg5mcrf.js +3 -0
- package/dist/chunk-0zfzhn19.js +31 -0
- package/dist/chunk-189nn4fc.js +3 -0
- package/dist/chunk-1j6092xz.js +7 -0
- package/dist/chunk-1qtghb2x.js +3 -0
- package/dist/chunk-2436cnmb.js +3 -0
- package/dist/chunk-2qd3axyx.js +5 -0
- package/dist/chunk-32qexm3w.js +3 -0
- package/dist/chunk-3fbt79hx.js +3 -0
- package/dist/chunk-3t57mzvf.js +3 -0
- package/dist/chunk-42j9cfte.js +3 -0
- package/dist/chunk-4fygcxtb.js +4 -0
- package/dist/chunk-50h54rax.js +177 -0
- package/dist/chunk-5hyv43ps.js +12 -0
- package/dist/chunk-6yvk3q1e.js +3 -0
- package/dist/chunk-73dzve1s.js +3 -0
- package/dist/chunk-7tremqhs.js +14 -0
- package/dist/chunk-83qnrx0m.js +7 -0
- package/dist/chunk-88gwzbew.js +4 -0
- package/dist/chunk-8d3sdkv4.js +24 -0
- package/dist/chunk-8tzd98q8.js +22 -0
- package/dist/chunk-96atbsd3.js +3 -0
- package/dist/chunk-9gts9ymh.js +3 -0
- package/dist/chunk-9menejdz.js +3 -0
- package/dist/chunk-a7nvyxpg.js +6 -0
- package/dist/chunk-ag1b6d30.js +3 -0
- package/dist/chunk-asws39qs.js +31 -0
- package/dist/chunk-bnry23ve.js +4 -0
- package/dist/chunk-bxc2herz.js +9 -0
- package/dist/chunk-cpmqa8kd.js +4 -0
- package/dist/chunk-cv29b4zb.js +7 -0
- package/dist/chunk-cyr45de1.js +8 -0
- package/dist/chunk-d0bazr3p.js +3 -0
- package/dist/chunk-danfamyx.js +3 -0
- package/dist/chunk-davy89dj.js +8 -0
- package/dist/chunk-e29rp5xj.js +7 -0
- package/dist/chunk-eba562w8.js +9 -0
- package/dist/chunk-ebjafajx.js +62 -0
- package/dist/chunk-ft2zk7jx.js +3 -0
- package/dist/chunk-g2120ysy.js +3 -0
- package/dist/chunk-ghfd34r7.js +3 -0
- package/dist/chunk-gspsxc9d.js +34 -0
- package/dist/chunk-h3n6256r.js +3 -0
- package/dist/chunk-hnqm1zb3.js +5 -0
- package/dist/chunk-htgy94y3.js +2 -0
- package/dist/chunk-hv8bx8xx.js +102 -0
- package/dist/chunk-hzn9kmq7.js +3 -0
- package/dist/chunk-ja7bp731.js +3 -0
- package/dist/chunk-jcckwgb9.js +3 -0
- package/dist/chunk-kfk554fj.js +3 -0
- package/dist/chunk-kkshxyex.js +18 -0
- package/dist/chunk-kpbz61yy.js +4 -0
- package/dist/chunk-mkakbjvs.js +3 -0
- package/dist/chunk-mwyjxjqa.js +3 -0
- package/dist/chunk-p023fhce.js +8 -0
- package/dist/chunk-p9vfxn8g.js +3 -0
- package/dist/chunk-pga5m4wm.js +3 -0
- package/dist/chunk-pjqzkgzk.js +6 -0
- package/dist/chunk-qzjzw9p2.js +3 -0
- package/dist/chunk-rbx6q1r0.js +18 -0
- package/dist/chunk-rkstz4w1.js +6 -0
- package/dist/chunk-rz060wxt.js +6 -0
- package/dist/chunk-sd8bywh9.js +21 -0
- package/dist/chunk-sv8h007a.js +3 -0
- package/dist/chunk-t4va49p3.js +10 -0
- package/dist/chunk-tka2m4af.js +7 -0
- package/dist/chunk-v6fwy63g.js +3 -0
- package/dist/chunk-v93389xm.js +3 -0
- package/dist/chunk-vf3ybe5r.js +3 -0
- package/dist/chunk-vkahj2ab.js +10 -0
- package/dist/chunk-wnqg6hem.js +27 -0
- package/dist/chunk-xa6rsd4b.js +29 -0
- package/dist/chunk-xfjfhe9d.js +3 -0
- package/dist/chunk-xwpn40p0.js +6 -0
- package/dist/chunk-y1g6v96c.js +10 -0
- package/dist/chunk-y5k0szq6.js +3 -0
- package/dist/chunk-yay68832.js +3 -0
- package/dist/chunk-yrv6z221.js +3 -0
- package/dist/chunk-yx1jy7fx.js +37 -0
- package/dist/chunk-zgcdx773.js +4 -0
- package/dist/chunk-zk3w5sqv.js +4 -0
- package/dist/chunk-zq93f8ca.js +5 -0
- package/dist/src/augmentation-graph.d.ts +11 -0
- package/dist/src/augmentation-graph.js +2 -0
- package/dist/src/binding-patterns.d.ts +18 -0
- package/dist/src/binding-patterns.js +2 -0
- package/dist/src/branded-types.d.ts +159 -0
- package/dist/src/branded-types.js +2 -0
- package/dist/src/bundle-linker.d.ts +38 -0
- package/dist/src/bundle-linker.js +2 -0
- package/dist/src/bundler.d.ts +55 -0
- package/dist/src/bundler.js +2 -0
- package/dist/src/cache.d.ts +53 -0
- package/dist/src/cache.js +2 -0
- package/dist/src/call-signatures.d.ts +1 -0
- package/dist/src/call-signatures.js +2 -0
- package/dist/src/checker.d.ts +107 -0
- package/dist/src/circular.d.ts +82 -0
- package/dist/src/circular.js +2 -0
- package/dist/src/compat.d.ts +114 -0
- package/dist/src/compat.js +2 -0
- package/dist/src/computed-keys.d.ts +12 -0
- package/dist/src/computed-keys.js +2 -0
- package/dist/src/concurrency.d.ts +4 -0
- package/dist/src/concurrency.js +2 -0
- package/dist/src/config.d.ts +35 -0
- package/dist/src/config.js +2 -0
- package/dist/src/dangling-refs.d.ts +11 -0
- package/dist/src/dangling-refs.js +2 -0
- package/dist/src/declaration-project.d.ts +33 -0
- package/dist/src/declaration-project.js +2 -0
- package/dist/src/declaration-publication.d.ts +15 -0
- package/dist/src/declaration-publication.js +2 -0
- package/dist/src/declaration-references.d.ts +19 -0
- package/dist/src/declaration-references.js +2 -0
- package/dist/src/diff.d.ts +82 -0
- package/dist/src/diff.js +2 -0
- package/dist/src/docs.d.ts +97 -0
- package/dist/src/docs.js +2 -0
- package/dist/src/enum-declarations.d.ts +6 -0
- package/dist/src/enum-declarations.js +2 -0
- package/dist/src/errors.d.ts +113 -0
- package/dist/src/errors.js +2 -0
- package/dist/src/extractor/directives.d.ts +5 -0
- package/dist/src/extractor/directives.js +2 -0
- package/dist/src/extractor/extract.d.ts +10 -0
- package/dist/src/extractor/extract.js +2 -0
- package/dist/src/extractor/hash.d.ts +1 -0
- package/dist/src/extractor/hash.js +2 -0
- package/dist/src/extractor/scanner.d.ts +32 -0
- package/dist/src/extractor/scanner.js +2 -0
- package/dist/src/extractor.d.ts +5 -0
- package/dist/src/extractor.js +2 -0
- package/dist/src/formats.d.ts +50 -0
- package/dist/src/formats.js +2 -0
- package/dist/src/formatter.d.ts +61 -0
- package/dist/src/formatter.js +2 -0
- package/dist/src/function-properties.d.ts +3 -0
- package/dist/src/function-properties.js +2 -0
- package/dist/src/generator.d.ts +18 -0
- package/dist/src/generator.js +2 -0
- package/dist/src/global-types.d.ts +17 -0
- package/dist/src/global-types.js +2 -0
- package/dist/src/import-sorter.d.ts +99 -0
- package/dist/src/import-sorter.js +2 -0
- package/dist/src/incremental.d.ts +103 -0
- package/dist/src/incremental.js +2 -0
- package/dist/src/index.d.ts +62 -0
- package/dist/src/index.js +2 -0
- package/dist/src/inferred-imports.d.ts +4 -0
- package/dist/src/inferred-imports.js +2 -0
- package/dist/src/json-config.d.ts +2 -0
- package/dist/src/json-config.js +2 -0
- package/dist/src/lexical.d.ts +6 -0
- package/dist/src/lexical.js +2 -0
- package/dist/src/logger.d.ts +57 -0
- package/dist/src/logger.js +2 -0
- package/dist/src/lsp.d.ts +333 -0
- package/dist/src/lsp.js +2 -0
- package/dist/src/memory.d.ts +127 -0
- package/dist/src/memory.js +2 -0
- package/dist/src/merger.d.ts +38 -0
- package/dist/src/merger.js +2 -0
- package/dist/src/module-graph.d.ts +70 -0
- package/dist/src/module-graph.js +2 -0
- package/dist/src/module-references.d.ts +30 -0
- package/dist/src/module-references.js +2 -0
- package/dist/src/native-checker.d.ts +55 -0
- package/dist/src/native-checker.js +2 -0
- package/dist/src/native-engine.d.ts +16 -0
- package/dist/src/native-engine.js +2 -0
- package/dist/src/native-extractor.d.ts +9 -0
- package/dist/src/native-extractor.js +2 -0
- package/dist/src/native-generation.d.ts +20 -0
- package/dist/src/native-generation.js +2 -0
- package/dist/src/native-project.d.ts +35 -0
- package/dist/src/native-project.js +2 -0
- package/dist/src/optimizer.d.ts +56 -0
- package/dist/src/optimizer.js +2 -0
- package/dist/src/output-normalizer.d.ts +123 -0
- package/dist/src/output-normalizer.js +2 -0
- package/dist/src/parallel-processor.d.ts +63 -0
- package/dist/src/parallel-processor.js +2 -0
- package/dist/src/parameters.d.ts +5 -0
- package/dist/src/parameters.js +2 -0
- package/dist/src/parser.d.ts +68 -0
- package/dist/src/parser.js +2 -0
- package/dist/src/plugins/bun.d.ts +58 -0
- package/dist/src/plugins/bun.js +2 -0
- package/dist/src/plugins/esbuild.d.ts +63 -0
- package/dist/src/plugins/esbuild.js +2 -0
- package/dist/src/plugins/index.d.ts +16 -0
- package/dist/src/plugins/index.js +2 -0
- package/dist/src/plugins/tsdown.d.ts +30 -0
- package/dist/src/plugins/tsdown.js +2 -0
- package/dist/src/plugins/tsup.d.ts +53 -0
- package/dist/src/plugins/tsup.js +2 -0
- package/dist/src/plugins/vite.d.ts +49 -0
- package/dist/src/plugins/vite.js +2 -0
- package/dist/src/plugins/webpack.d.ts +69 -0
- package/dist/src/plugins/webpack.js +2 -0
- package/dist/src/plugins.d.ts +88 -0
- package/dist/src/plugins.js +2 -0
- package/dist/src/process-source.d.ts +28 -0
- package/dist/src/process-source.js +2 -0
- package/dist/src/processor/cache.d.ts +18 -0
- package/dist/src/processor/cache.js +2 -0
- package/dist/src/processor/comments.d.ts +9 -0
- package/dist/src/processor/comments.js +2 -0
- package/dist/src/processor/declarations.d.ts +37 -0
- package/dist/src/processor/declarations.js +2 -0
- package/dist/src/processor/import-usage.d.ts +6 -0
- package/dist/src/processor/import-usage.js +2 -0
- package/dist/src/processor/imports.d.ts +68 -0
- package/dist/src/processor/imports.js +2 -0
- package/dist/src/processor/index.d.ts +33 -0
- package/dist/src/processor/index.js +2 -0
- package/dist/src/processor/type-inference.d.ts +116 -0
- package/dist/src/processor/type-inference.js +2 -0
- package/dist/src/processor.d.ts +5 -0
- package/dist/src/processor.js +2 -0
- package/dist/src/profiling.d.ts +114 -0
- package/dist/src/profiling.js +2 -0
- package/dist/src/return-type-scope.d.ts +3 -0
- package/dist/src/return-type-scope.js +2 -0
- package/dist/src/security.d.ts +100 -0
- package/dist/src/security.js +2 -0
- package/dist/src/source-cache.d.ts +16 -0
- package/dist/src/source-cache.js +2 -0
- package/dist/src/sourcemap.d.ts +137 -0
- package/dist/src/sourcemap.js +2 -0
- package/dist/src/stx.d.ts +20 -0
- package/dist/src/stx.js +2 -0
- package/dist/src/syntax-validator.d.ts +7 -0
- package/dist/src/syntax-validator.js +2 -0
- package/dist/src/tracking.d.ts +95 -0
- package/dist/src/tracking.js +2 -0
- package/dist/src/transformers.d.ts +188 -0
- package/dist/src/transformers.js +2 -0
- package/dist/src/tree-shaker.d.ts +69 -0
- package/dist/src/tree-shaker.js +2 -0
- package/dist/src/tsconfig.d.ts +8 -0
- package/dist/src/tsconfig.js +2 -0
- package/dist/src/type-mappings.d.ts +145 -0
- package/dist/src/type-mappings.js +2 -0
- package/dist/src/types.d.ts +230 -0
- package/dist/src/types.js +1 -0
- package/dist/src/utils.d.ts +63 -0
- package/dist/src/utils.js +2 -0
- package/dist/src/value-inference.d.ts +6 -0
- package/dist/src/value-inference.js +2 -0
- package/dist/src/vue.d.ts +108 -0
- package/dist/src/vue.js +2 -0
- package/dist/src/watcher.d.ts +64 -0
- package/dist/src/watcher.js +2 -0
- package/dist/src/worker-thread.d.ts +1 -0
- package/dist/src/worker-thread.js +2 -0
- package/dist/src/worker.d.ts +98 -0
- package/dist/src/worker.js +2 -0
- package/dist/src/workspace.d.ts +62 -0
- package/dist/src/workspace.js +2 -0
- package/native/README.md +6 -0
- package/native/darwin-arm64/libzig-dtsx.dylib +0 -0
- package/native/darwin-x64/libzig-dtsx.dylib +0 -0
- package/native/freebsd-x64/libzig-dtsx.so +0 -0
- package/native/linux-arm64/libzig-dtsx.so +0 -0
- package/native/linux-x64/libzig-dtsx.so +0 -0
- package/native/windows-x64/zig-dtsx.dll +0 -0
- package/package.json +120 -4
package/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Open Web Foundation
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,443 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center"><img src="https://github.com/stacksjs/dtsx/blob/main/.github/art/cover.jpg?raw=true" alt="Social Card of this repo"></p>
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://npmjs.com/package/@dtsx/dtsx)
|
|
4
|
+
[](https://github.com/stacksjs/dtsx/actions?query=workflow%3Aci)
|
|
5
|
+
[](http://commitizen.github.io/cz-cli/)
|
|
6
|
+
<!-- [![npm downloads][npm-downloads-src]][npm-downloads-href] -->
|
|
7
|
+
<!-- [![Codecov][codecov-src]][codecov-href] -->
|
|
8
|
+
|
|
9
|
+
# dtsx
|
|
10
|
+
|
|
11
|
+
> A blazing-fast TypeScript declaration file (.d.ts) generator with advanced features like incremental builds, watch mode, bundling, and IDE integration.
|
|
12
|
+
|
|
13
|
+
## Features
|
|
14
|
+
|
|
15
|
+
- ⚡ Extremely fast .d.ts generation
|
|
16
|
+
- 🔄 Watch mode with incremental builds
|
|
17
|
+
- 📦 Declaration bundling support
|
|
18
|
+
- 🔌 Plugin system for custom transformations
|
|
19
|
+
- 🧩 Monorepo/workspace support
|
|
20
|
+
- 🛠️ IDE integration via LSP
|
|
21
|
+
- ⚙️ Highly configurable
|
|
22
|
+
- 🪶 Lightweight library
|
|
23
|
+
- 🤖 Cross-platform binary
|
|
24
|
+
|
|
25
|
+
## Install
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
bun install -d @dtsx/dtsx
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
> [!NOTE]
|
|
32
|
+
> dtsx was published as `@stacksjs/dtsx` up to v0.11.36. Install `@dtsx/dtsx` instead and change imports from `@stacksjs/dtsx` to `@dtsx/dtsx`; the API, CLI and config are unchanged. See [Migrating from @stacksjs/dtsx](https://github.com/stacksjs/dtsx/blob/main/docs/MIGRATION.md#from-stacksjsdtsx).
|
|
33
|
+
|
|
34
|
+
> _@npmjs.com, please allow us to use the `dtsx` package name 🙏_
|
|
35
|
+
|
|
36
|
+
<!-- _Alternatively, you can install:_
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
brew install dtsx # wip
|
|
40
|
+
pkgx install dtsx # wip
|
|
41
|
+
``` -->
|
|
42
|
+
|
|
43
|
+
## Get Started
|
|
44
|
+
|
|
45
|
+
There are two ways of using this ".d.ts generation" tool: _as a library or as a CLI._
|
|
46
|
+
|
|
47
|
+
_dtsx works out of the box — no `isolatedDeclarations` required. It infers sound types directly from your source values, preserving original values via `@defaultValue` JSDoc. If you do enable `isolatedDeclarations`, dtsx treats annotations as authoritative, skips initializers for concrete types, and only reads broad containers to preserve `@defaultValue` documentation._
|
|
48
|
+
|
|
49
|
+
```json
|
|
50
|
+
{
|
|
51
|
+
"compilerOptions": {
|
|
52
|
+
"isolatedDeclarations": true // optional — dtsx works great without it
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Library
|
|
58
|
+
|
|
59
|
+
Given the npm package is installed, you can use the `generate` function to generate TypeScript declaration files from your project.
|
|
60
|
+
|
|
61
|
+
### Usage
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import type { DtsGenerationOptions } from '@dtsx/dtsx'
|
|
65
|
+
import { generate } from '@dtsx/dtsx'
|
|
66
|
+
|
|
67
|
+
const options: DtsGenerationOptions = {
|
|
68
|
+
cwd: './', // default: process.cwd()
|
|
69
|
+
root: './src', // default: './src'
|
|
70
|
+
entrypoints: ['**/*.{ts,tsx,mts,cts,vue,stx}'], // default
|
|
71
|
+
outdir: './dist', // default: './dist'
|
|
72
|
+
clean: true, // default: false
|
|
73
|
+
verbose: true, // default: false
|
|
74
|
+
keepComments: true, // default: true
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
await generate(options)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### STX Components
|
|
81
|
+
|
|
82
|
+
`.stx` entrypoints support Vue-style script blocks, Blade-style `@ts` blocks,
|
|
83
|
+
typed and runtime `defineProps`, `props as Props`, and legacy `$props.name`
|
|
84
|
+
contracts. dtsx emits the default component as
|
|
85
|
+
`DefineComponent<Props>` from `@stacksjs/stx` in semantic and isolated modes.
|
|
86
|
+
|
|
87
|
+
### Configuration File
|
|
88
|
+
|
|
89
|
+
Library usage can also be configured using a `dts.config.ts` _(or `dts.config.js`)_ file which is automatically loaded when running the `./dtsx` _(or `bunx dtsx`)_ command. It is also loaded when the `generate` function is called, unless custom options are provided.
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
// dts.config.ts (or dts.config.js)
|
|
93
|
+
import { defineConfig } from '@dtsx/dtsx'
|
|
94
|
+
|
|
95
|
+
export default defineConfig({
|
|
96
|
+
cwd: './',
|
|
97
|
+
root: './src',
|
|
98
|
+
entrypoints: ['**/*.ts'],
|
|
99
|
+
outdir: './dist',
|
|
100
|
+
keepComments: true,
|
|
101
|
+
clean: true,
|
|
102
|
+
verbose: true,
|
|
103
|
+
|
|
104
|
+
// Advanced options
|
|
105
|
+
watch: false, // Enable watch mode
|
|
106
|
+
incremental: false, // Enable incremental builds
|
|
107
|
+
parallel: false, // Enable parallel processing
|
|
108
|
+
concurrency: 4, // Number of parallel workers
|
|
109
|
+
|
|
110
|
+
// Bundling
|
|
111
|
+
bundle: false, // Bundle all declarations into one file
|
|
112
|
+
bundleOutput: 'index.d.ts', // Output filename when bundling
|
|
113
|
+
|
|
114
|
+
// Output formatting
|
|
115
|
+
prettier: false, // Use Prettier for formatting
|
|
116
|
+
indentStyle: 'spaces', // 'spaces' or 'tabs'
|
|
117
|
+
indentSize: 2, // Number of spaces
|
|
118
|
+
|
|
119
|
+
// Plugins
|
|
120
|
+
plugins: [],
|
|
121
|
+
})
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
_You may also run:_
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
./dtsx generate
|
|
128
|
+
|
|
129
|
+
# if the package is installed, you can also run
|
|
130
|
+
# bunx dtsx generate
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## CLI
|
|
134
|
+
|
|
135
|
+
The `dtsx` CLI provides a comprehensive set of commands for generating and managing TypeScript declaration files.
|
|
136
|
+
|
|
137
|
+
### Commands
|
|
138
|
+
|
|
139
|
+
#### Generate Declarations
|
|
140
|
+
|
|
141
|
+
Generate declaration files using the default options:
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
dtsx generate
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
_Or use custom options:_
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
# Generate declarations for specific entry points
|
|
151
|
+
dtsx generate --entrypoints src/index.ts,src/utils.ts --outdir dist/types
|
|
152
|
+
|
|
153
|
+
# Generate declarations with custom configuration
|
|
154
|
+
dtsx generate --root ./lib --outdir ./types --clean
|
|
155
|
+
|
|
156
|
+
# Enable incremental builds
|
|
157
|
+
dtsx generate --incremental
|
|
158
|
+
|
|
159
|
+
# Enable parallel processing
|
|
160
|
+
dtsx generate --parallel --concurrency 8
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
#### Watch Mode
|
|
164
|
+
|
|
165
|
+
Watch for file changes and automatically regenerate declarations:
|
|
166
|
+
|
|
167
|
+
```bash
|
|
168
|
+
dtsx watch
|
|
169
|
+
|
|
170
|
+
# Watch with custom options
|
|
171
|
+
dtsx watch --root ./src --outdir ./dist --debounce 300
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
#### Bundle Declarations
|
|
175
|
+
|
|
176
|
+
Bundle multiple declaration files into a single file:
|
|
177
|
+
|
|
178
|
+
```bash
|
|
179
|
+
# Bundle declarations using the generate command with --bundle flag
|
|
180
|
+
dtsx generate --bundle --bundle-output index.d.ts
|
|
181
|
+
|
|
182
|
+
# Or with custom output directory
|
|
183
|
+
dtsx generate --outdir ./dist --bundle --bundle-output types.d.ts
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
#### Workspace/Monorepo Support
|
|
187
|
+
|
|
188
|
+
Generate declarations for all packages in a monorepo:
|
|
189
|
+
|
|
190
|
+
```bash
|
|
191
|
+
dtsx workspace
|
|
192
|
+
|
|
193
|
+
# Specify packages directory
|
|
194
|
+
dtsx workspace --packages ./packages
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
#### Type Checking
|
|
198
|
+
|
|
199
|
+
Run type checking with isolated declarations support:
|
|
200
|
+
|
|
201
|
+
```bash
|
|
202
|
+
dtsx check
|
|
203
|
+
|
|
204
|
+
# Check specific files
|
|
205
|
+
dtsx check --files "src/**/*.ts"
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
#### Circular Dependency Detection
|
|
209
|
+
|
|
210
|
+
Detect circular dependencies in your TypeScript files:
|
|
211
|
+
|
|
212
|
+
```bash
|
|
213
|
+
dtsx circular
|
|
214
|
+
|
|
215
|
+
# Output as JSON or DOT (Graphviz) format
|
|
216
|
+
dtsx circular --format json
|
|
217
|
+
dtsx circular --format dot
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
#### Generate Documentation
|
|
221
|
+
|
|
222
|
+
Generate API documentation from your TypeScript files:
|
|
223
|
+
|
|
224
|
+
```bash
|
|
225
|
+
dtsx docs
|
|
226
|
+
|
|
227
|
+
# Specify output format
|
|
228
|
+
dtsx docs --format markdown
|
|
229
|
+
dtsx docs --format html
|
|
230
|
+
dtsx docs --format json
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
#### Optimize Declarations
|
|
234
|
+
|
|
235
|
+
Optimize and tree-shake declaration files:
|
|
236
|
+
|
|
237
|
+
```bash
|
|
238
|
+
dtsx optimize
|
|
239
|
+
|
|
240
|
+
# Optimize specific files
|
|
241
|
+
dtsx optimize --files "dist/**/*.d.ts"
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
#### Convert Types
|
|
245
|
+
|
|
246
|
+
Convert TypeScript types to different schema formats:
|
|
247
|
+
|
|
248
|
+
```bash
|
|
249
|
+
dtsx convert --format zod
|
|
250
|
+
dtsx convert --format json-schema
|
|
251
|
+
dtsx convert --format valibot
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
#### LSP Server
|
|
255
|
+
|
|
256
|
+
Start the Language Server Protocol server for IDE integration:
|
|
257
|
+
|
|
258
|
+
```bash
|
|
259
|
+
dtsx lsp
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
#### Read from Stdin
|
|
263
|
+
|
|
264
|
+
Accept TypeScript code from stdin:
|
|
265
|
+
|
|
266
|
+
```bash
|
|
267
|
+
echo "export function foo(): string { return 'bar' }" | dtsx stdin
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
### CLI Options
|
|
271
|
+
|
|
272
|
+
#### Global Options
|
|
273
|
+
|
|
274
|
+
- `--cwd <path>`: Set the current working directory _(default: current directory)_
|
|
275
|
+
- `--verbose`: Enable verbose output _(default: false)_
|
|
276
|
+
- `--help`: Show help information
|
|
277
|
+
- `--version`: Show version number
|
|
278
|
+
|
|
279
|
+
#### Generate Options
|
|
280
|
+
|
|
281
|
+
- `--root <path>`: Specify the root directory of the project _(default: './src')_
|
|
282
|
+
- `--entrypoints <files>`: Define entry point files _(comma-separated, default: `**/*.{ts,tsx,mts,cts,vue,stx}`)_
|
|
283
|
+
- `--outdir <path>`: Set the output directory for generated .d.ts files _(default: './dist')_
|
|
284
|
+
- `--keep-comments`: Keep comments in generated .d.ts files _(default: true)_
|
|
285
|
+
- `--clean`: Clean output directory before generation _(default: false)_
|
|
286
|
+
- `--tsconfig <path>`: Specify the path to tsconfig.json _(default: 'tsconfig.json')_
|
|
287
|
+
- `--incremental`: Enable incremental builds _(default: false)_
|
|
288
|
+
- `--parallel`: Enable parallel processing _(default: false)_
|
|
289
|
+
- `--concurrency <n>`: Number of parallel workers _(default: 4)_
|
|
290
|
+
- `--dry-run`: Show what would be generated without writing files
|
|
291
|
+
- `--diff`: Show differences from existing .d.ts files
|
|
292
|
+
- `--validate`: Validate generated .d.ts against TypeScript compiler
|
|
293
|
+
- `--stats`: Show generation statistics
|
|
294
|
+
- `--progress`: Show progress during generation
|
|
295
|
+
- `--output-format <format>`: Output format: 'text' or 'json' _(default: 'text')_
|
|
296
|
+
|
|
297
|
+
#### Watch Options
|
|
298
|
+
|
|
299
|
+
- `--debounce <ms>`: Debounce delay in milliseconds _(default: 100)_
|
|
300
|
+
|
|
301
|
+
#### Bundle Options (use with generate command)
|
|
302
|
+
|
|
303
|
+
- `--bundle`: Enable bundling of declarations into a single file
|
|
304
|
+
- `--bundle-output <file>`: Output filename when bundling _(default: 'index.d.ts')_
|
|
305
|
+
|
|
306
|
+
To learn more, head over to the [documentation](https://dtsx.stacksjs.org/).
|
|
307
|
+
|
|
308
|
+
## Build Tool Integration
|
|
309
|
+
|
|
310
|
+
dtsx provides plugins for popular build tools:
|
|
311
|
+
|
|
312
|
+
### Vite
|
|
313
|
+
|
|
314
|
+
```ts
|
|
315
|
+
// vite.config.ts
|
|
316
|
+
import { dts } from '@dtsx/dtsx/vite'
|
|
317
|
+
|
|
318
|
+
export default {
|
|
319
|
+
plugins: [dts()],
|
|
320
|
+
}
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
### esbuild
|
|
324
|
+
|
|
325
|
+
```ts
|
|
326
|
+
// build.ts
|
|
327
|
+
import { dtsx } from '@dtsx/dtsx/esbuild'
|
|
328
|
+
|
|
329
|
+
await esbuild.build({
|
|
330
|
+
plugins: [dtsx()],
|
|
331
|
+
})
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
### webpack
|
|
335
|
+
|
|
336
|
+
```ts
|
|
337
|
+
// webpack.config.js
|
|
338
|
+
const { DtsxWebpackPlugin } = require('@dtsx/dtsx/webpack')
|
|
339
|
+
|
|
340
|
+
module.exports = {
|
|
341
|
+
plugins: [new DtsxWebpackPlugin()],
|
|
342
|
+
}
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
### tsdown
|
|
346
|
+
|
|
347
|
+
```ts
|
|
348
|
+
// tsdown.config.ts
|
|
349
|
+
import { dts } from '@dtsx/dtsx/tsdown'
|
|
350
|
+
import { defineConfig } from 'tsdown'
|
|
351
|
+
|
|
352
|
+
export default defineConfig({
|
|
353
|
+
entry: ['src/index.ts'],
|
|
354
|
+
plugins: [dts()],
|
|
355
|
+
})
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
DTSX replaces tsdown's built-in declaration generator. It supports ESM/CJS output, named entries and watch rebuilds without requiring a TypeScript compiler at runtime. The bundled DTSX package has no required npm dependencies; tsdown is a development dependency of the consuming project. Bundled declaration maps are not supported.
|
|
359
|
+
|
|
360
|
+
Run `bun run benchmark:tsdown --output tsdown-benchmark.json` from this repository for a comparison with tsdown's own declaration generator, including fresh output and strict type controls.
|
|
361
|
+
|
|
362
|
+
### tsup
|
|
363
|
+
|
|
364
|
+
```ts
|
|
365
|
+
// tsup.config.ts
|
|
366
|
+
import { dtsxPlugin } from '@dtsx/dtsx/tsup'
|
|
367
|
+
|
|
368
|
+
export default {
|
|
369
|
+
plugins: [dtsxPlugin()],
|
|
370
|
+
}
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
### Bun
|
|
374
|
+
|
|
375
|
+
```ts
|
|
376
|
+
// build.ts
|
|
377
|
+
import { dts } from 'bun-plugin-dtsx'
|
|
378
|
+
|
|
379
|
+
await Bun.build({
|
|
380
|
+
plugins: [dts()],
|
|
381
|
+
})
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
## Documentation
|
|
385
|
+
|
|
386
|
+
- [Architecture Guide](../../ARCHITECTURE.md) - How dtsx works internally
|
|
387
|
+
- [Contributing Guide](../../CONTRIBUTING.md) - How to contribute to dtsx
|
|
388
|
+
- [Performance Guide](../../PERFORMANCE.md) - Tips for optimizing large codebases
|
|
389
|
+
- [Migration Guide](../../MIGRATION.md) - Migrating from other tools
|
|
390
|
+
- [Troubleshooting](../../TROUBLESHOOTING.md) - Common issues and solutions
|
|
391
|
+
|
|
392
|
+
## Testing
|
|
393
|
+
|
|
394
|
+
```bash
|
|
395
|
+
bun test
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
## Changelog
|
|
399
|
+
|
|
400
|
+
Please see our [releases](https://github.com/stacksjs/stacks/releases) page for more information on what has changed recently.
|
|
401
|
+
|
|
402
|
+
## Contributing
|
|
403
|
+
|
|
404
|
+
Please review the [Contributing Guide](https://github.com/stacksjs/contributing) for details.
|
|
405
|
+
|
|
406
|
+
## Community
|
|
407
|
+
|
|
408
|
+
For help, discussion about best practices, or any other conversation that would benefit from being searchable:
|
|
409
|
+
|
|
410
|
+
[Discussions on GitHub](https://github.com/stacksjs/stacks/discussions)
|
|
411
|
+
|
|
412
|
+
For casual chit-chat with others using this package:
|
|
413
|
+
|
|
414
|
+
[Join the Stacks Discord Server](https://stacksjs.com/discord)
|
|
415
|
+
|
|
416
|
+
## Postcardware
|
|
417
|
+
|
|
418
|
+
"Software that is free, but hopes for a postcard." We love receiving postcards from around the world showing where `dtsx` is being used! We showcase them on our website too.
|
|
419
|
+
|
|
420
|
+
Our address: Stacks.js, 12665 Village Ln #2306, Playa Vista, CA 90094, United States 🌎
|
|
421
|
+
|
|
422
|
+
## Sponsors
|
|
423
|
+
|
|
424
|
+
We would like to extend our thanks to the following sponsors for funding Stacks development. If you are interested in becoming a sponsor, please reach out to us.
|
|
425
|
+
|
|
426
|
+
- [JetBrains](https://www.jetbrains.com/)
|
|
427
|
+
- [The Solana Foundation](https://solana.com/)
|
|
428
|
+
|
|
429
|
+
## Credits
|
|
430
|
+
|
|
431
|
+
- [Chris Breuer](https://github.com/chrisbbreuer)
|
|
432
|
+
- [All Contributors](../../contributors)
|
|
433
|
+
|
|
434
|
+
## License
|
|
435
|
+
|
|
436
|
+
The MIT License (MIT). Please see [LICENSE](https://github.com/stacksjs/dtsx/tree/main/LICENSE.md) for more information.
|
|
437
|
+
|
|
438
|
+
Made with 💙
|
|
439
|
+
|
|
440
|
+
<!-- Badges -->
|
|
441
|
+
|
|
442
|
+
<!-- [codecov-src]: https://img.shields.io/codecov/c/gh/stacksjs/dtsx/main?style=flat-square
|
|
443
|
+
[codecov-href]: https://codecov.io/gh/stacksjs/dtsx -->
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/bin/cli.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// @bun
|
|
3
|
+
import n from"process";var U=n.argv[2];if(U==="stdin"||U==="emit"||U==="--project"){if(U==="stdin"){let{processSource:e}=await import("../src/process-source.js"),t=[];for await(let f of n.stdin)t.push(f);let o=Buffer.concat(t).toString("utf-8");if(o.trim())n.stdout.write(e(o,"stdin.ts")),n.stdout.write(`
|
|
4
|
+
`)}else if(U==="--project"){let{readdirSync:e,readFileSync:t,writeFileSync:o,mkdirSync:f}=await import("fs"),p=typeof globalThis.Bun<"u",a=p?globalThis.Bun:null,l=n.argv.slice(3),y="",w="",h=!1;for(let s=0;s<l.length;s++)if(l[s]==="--outdir"&&l[s+1])w=l[s+1],s++;else if(l[s]==="--isolated-declarations")h=!0;else if(!y)y=l[s];f(w,{recursive:!0});let m=e(y).filter((s)=>s.endsWith(".ts")&&!s.endsWith(".d.ts")),i=m.length,u=Array(i),c=Array(i);for(let s=0;s<i;s++)u[s]=`${y}/${m[s]}`,c[s]=`${w}/${m[s].slice(0,-3)}.d.ts`;let g=["bun"],k=16777216,{nativeEngineAvailable:P}=await import("../src/native-engine.js"),x=!1;if(p&&i>=256&&!P()){let s=0;for(let E=0;E<i&&!x;E++)s+=a.file(u[E]).size,x=s>=k}let C=!1,b=null;if(x){let s=null;try{let{createWorkerPool:E,calculateOptimalBatchSize:L}=await import("../src/worker.js"),{cpus:I}=await import("os"),F=Math.max(1,I().length-1),T=Math.min(64,Math.max(8,L(i,F)*2)),d=i>=256,S=!0,W=i>=256;if(!d&&i>=256){b=Array(i);for(let j=0;j<i;j++)b[j]=a.file(u[j]).text()}let _=Math.ceil(i/T),X=Math.min(_,Math.max(2,F*2));s=E({maxWorkers:F,initialWorkers:F,recycleAfter:Math.max(100,_+1)}),await s.init();let Z=s,Y=0,q=Date.now(),ee=async()=>{for(;;){let j=Y++;if(j>=_)return;let M=j*T;if(M>=i)return;let G=Math.min(i,M+T)-M,z;if(W){let B=Array(G),A=Array(G),R;if(d)for(let v=0;v<G;v++){let O=M+v;B[v]=u[O],A[v]=c[O]}else{let v=Array(G);for(let O=0;O<G;O++){let J=M+O;B[O]=u[J],A[O]=c[J],v[O]=b?b[J]:a.file(u[J]).text()}R=await Promise.all(v)}z=await Z.submit({id:`batch-${q}-${j}`,type:"process-batch",filePath:B[0]||"",filePaths:B,sources:R,outPaths:A,writeOutput:!0,config:{keepComments:!0,importOrder:g,isolatedDeclarations:h}})}else{let B=Array(G);if(d)for(let A=0;A<G;A++){let R=M+A;B[A]={filePath:u[R],outPath:c[R]}}else{let A=Array(G);for(let v=0;v<G;v++){let O=M+v;A[v]=b?b[O]:a.file(u[O]).text()}let R=await Promise.all(A);for(let v=0;v<G;v++){let O=M+v;B[v]={filePath:u[O],sourceCode:R[v],outPath:c[O]}}}z=await Z.submit({id:`batch-${q}-${j}`,type:"process-batch",filePath:u[M]||"",files:B,writeOutput:!0,config:{keepComments:!0,importOrder:g,isolatedDeclarations:h}})}if(!z.success)throw Error(z.error||`Worker batch failed for ${u[M]}`);if(z.batchResults?.length){let B=z.batchResults[0];throw Error(B?.error||z.error||`Worker failed for ${u[M]}`)}}},H=[];for(let j=0;j<X;j++)H.push(ee());await Promise.all(H),C=!0}catch{C=!1}finally{if(s)await s.shutdown()}}if(!C){let{scanDeclarations:s}=await import("../src/extractor/scanner.js"),{processDeclarations:E}=await import("../src/processor.js"),{emitNatively:L}=await import("../src/process-source.js"),I=Array(i);if(p){let d=b?await Promise.all(b):await Promise.all(u.map((S)=>a.file(S).text()));for(let S=0;S<i;S++)I[S]=d[S]}else for(let d=0;d<i;d++)I[d]=t(u[d],"utf-8");let F=Array(i),T={filePath:"",sourceCode:"",declarations:[]};for(let d=0;d<i;d++){let S=L(I[d],m[d],!0,g,h);if(S!==null){F[d]=S;continue}let W=s(I[d],m[d],!0,h);T.filePath=m[d],T.sourceCode=I[d],T.declarations=W,F[d]=E(W,T,!0,g)}if(p){let d=Array(i);for(let S=0;S<i;S++)d[S]=a.write(c[S],F[S]);await Promise.all(d)}else for(let d=0;d<i;d++)o(c[d],F[d])}}else{let{processSource:e}=await import("../src/process-source.js"),{readFileSync:t,writeFileSync:o,mkdirSync:f}=await import("fs"),p=typeof globalThis.Bun<"u",a=p?globalThis.Bun:null,l=n.argv[3],y=p?await a.file(l).text():t(l,"utf-8"),w=n.argv[4];if(w){let{dirname:h}=await import("path");f(h(w),{recursive:!0});let m=`${e(y,l)}
|
|
5
|
+
`;if(p)await a.write(w,m);else o(w,m)}else n.stdout.write(e(y,l)),n.stdout.write(`
|
|
6
|
+
`)}n.exit(0)}var{resolve:N}=await import("path"),{CLI:te}=await import("../chunk-asws39qs.js"),{version:Q}=await import("../chunk-htgy94y3.js"),{getConfig:oe}=await import("../src/config.js"),{generate:re,processSource:ne,watch:se}=await import("../src/generator.js"),D=new te("dtsx"),r={cwd:n.cwd(),root:"./src",entrypoints:["**/*.ts"],outdir:"./dist",keepComments:!0,clean:!1,tsconfigPath:"tsconfig.json",verbose:!1,importOrder:["bun"],dryRun:!1,stats:!1,continueOnError:!1,logLevel:"info",exclude:[],outputFormat:"text",progress:!1,diff:!1,validate:!1,parallel:!1,concurrency:4};function V(e){if(e===void 0)return;let t=(Array.isArray(e)?e:[e]).flatMap((o)=>String(o).split(",")).map((o)=>o.trim()).filter(Boolean);return t.length>0?[...new Set(t)]:void 0}D.command("generate","Generate TypeScript declaration files").option("--cwd <path>","Current working directory",{default:r.cwd}).option("--root <path>","Root directory of the project",{default:r.root}).option("--entrypoints <files>",`Entry point files; repeat the flag or comma-separate (default: ${r.entrypoints?.join(",")})`,{type:[String]}).option("--outdir <path>","Output directory for generated .d.ts files",{default:r.outdir}).option("--keep-comments","Keep comments in generated .d.ts files",{default:r.keepComments}).option("--clean","Clean output directory before generation",{default:r.clean}).option("--tsconfig <path>","Path to tsconfig.json",{default:r.tsconfigPath}).option("--module-specifier-mode <mode>","Declaration module specifiers: preserve or node").option("--verbose","Enable verbose logging",{default:r.verbose}).option("--import-order <patterns>","Import order priority patterns (comma-separated)",{default:r.importOrder?.join(","),type:[String]}).option("--dry-run","Show what would be generated without writing files",{default:r.dryRun}).option("--stats","Show statistics after generation",{default:r.stats}).option("--continue-on-error","Continue processing other files if one fails",{default:r.continueOnError}).option("--log-level <level>","Log level (debug, info, warn, error, silent)",{default:r.logLevel}).option("--exclude <patterns>","Glob patterns to exclude (comma-separated)",{default:r.exclude?.join(","),type:[String]}).option("--output-format <format>","Output format: text or json",{default:r.outputFormat}).option("--progress","Show progress during generation",{default:r.progress}).option("--diff","Show diff of changes compared to existing files",{default:r.diff}).option("--validate","Validate generated .d.ts files against TypeScript",{default:r.validate}).option("--parallel","Process files in parallel",{default:r.parallel}).option("--concurrency <number>","Number of concurrent workers (with --parallel)",{default:r.concurrency}).option("--declaration-map","Generate declaration map files (.d.ts.map)",{default:!1}).option("--bundle","Bundle all declarations into a single output file",{default:!1}).option("--bundle-output <file>","Output filename when bundling (relative to outdir)",{default:"index.d.ts"}).option("--config <path>","Path to config file (dtsx.config.ts)",{default:""}).option("--incremental","Enable incremental builds (only regenerate changed files)",{default:!1}).option("--clear-cache","Clear the incremental build cache before generating",{default:!1}).option("--indent-style <style>","Indentation style: spaces or tabs",{default:"spaces"}).option("--indent-size <size>","Number of spaces for indentation",{default:2}).option("--prettier","Use Prettier for output formatting if available",{default:!1}).example("dtsx generate").example("dtsx generate --entrypoints src/index.ts,src/utils.ts --outdir dist/types").example("dtsx generate --entrypoints index.ts --entrypoints mime/index.ts --root src").example('dtsx generate --import-order "node:,bun,@myorg/"').example("dtsx generate --dry-run --stats").example('dtsx generate --exclude "**/*.test.ts,**/__tests__/**"').example("dtsx generate --stats --output-format json").example("dtsx generate --bundle --bundle-output types.d.ts").action(async(e)=>{try{let t=N(e.cwd||r.cwd),o=await oe(t),f={entrypoints:V(e.entrypoints)??o.entrypoints??r.entrypoints,cwd:t,root:N(e.root||o.root||r.root),outdir:N(e.outdir||o.outdir||r.outdir),tsconfigPath:N(e.tsconfigPath||o.tsconfigPath||r.tsconfigPath),moduleSpecifierMode:e.moduleSpecifierMode??o.moduleSpecifierMode??r.moduleSpecifierMode,keepComments:e.keepComments??o.keepComments??r.keepComments,clean:e.clean??o.clean??r.clean,verbose:e.verbose??o.verbose??r.verbose,importOrder:V(e.importOrder)??o.importOrder??r.importOrder,dryRun:e.dryRun??o.dryRun??r.dryRun,stats:e.stats??o.stats??r.stats,continueOnError:e.continueOnError??o.continueOnError??r.continueOnError,logLevel:e.logLevel??o.logLevel??r.logLevel,exclude:e.exclude?e.exclude.flatMap((a)=>a.split(",").map((l)=>l.trim()).filter(Boolean)):o.exclude||r.exclude,outputFormat:e.outputFormat??o.outputFormat??r.outputFormat,progress:e.progress??o.progress??r.progress,diff:e.diff??o.diff??r.diff,validate:e.validate??o.validate??r.validate,parallel:e.parallel??o.parallel??r.parallel,concurrency:Number(e.concurrency)||o.concurrency||r.concurrency,declarationMap:e.declarationMap??o.declarationMap??!1,bundle:e.bundle??o.bundle??!1,bundleOutput:e.bundleOutput??o.bundleOutput??"index.d.ts",incremental:e.incremental??o.incremental??!1,cacheDir:o.cacheDir,clearCache:e.clearCache??!1,indentStyle:e.indentStyle??o.indentStyle??"spaces",indentSize:Number(e.indentSize)||o.indentSize||2,prettier:e.prettier??o.prettier??!1,plugins:o.plugins},p=await re(f);if(p.filesFailed>0&&p.filesGenerated===0)n.exit(1);else if(p.filesFailed>0)n.exit(2)}catch(t){if(console.error(`Error generating .d.ts files: ${t instanceof Error?t.message:String(t)}`),e.verbose&&t instanceof Error&&t.stack)console.error(t.stack);n.exit(1)}});D.command("watch","Watch for changes and regenerate .d.ts files").option("--cwd <path>","Current working directory",{default:r.cwd}).option("--root <path>","Root directory of the project",{default:r.root}).option("--entrypoints <files>",`Entry point files; repeat the flag or comma-separate (default: ${r.entrypoints?.join(",")})`,{type:[String]}).option("--outdir <path>","Output directory for generated .d.ts files",{default:r.outdir}).option("--keep-comments","Keep comments in generated .d.ts files",{default:r.keepComments}).option("--exclude <patterns>","Glob patterns to exclude (comma-separated)",{default:r.exclude?.join(","),type:[String]}).option("--log-level <level>","Log level (debug, info, warn, error, silent)",{default:r.logLevel}).example("dtsx watch").example("dtsx watch --root src --outdir dist/types").action(async(e)=>{try{let t={entrypoints:V(e.entrypoints)??r.entrypoints,cwd:N(e.cwd||r.cwd),root:N(e.root||r.root),outdir:N(e.outdir||r.outdir),keepComments:e.keepComments??r.keepComments,exclude:e.exclude?e.exclude.flatMap((o)=>o.split(",").map((f)=>f.trim()).filter(Boolean)):r.exclude,logLevel:e.logLevel??r.logLevel};await se(t)}catch(t){console.error("Error in watch mode:",t),n.exit(1)}});D.command("stdin","Process TypeScript from stdin and output .d.ts to stdout").option("--keep-comments","Keep comments in generated .d.ts files",{default:!0}).option("--import-order <patterns>","Import order priority patterns (comma-separated)",{default:"bun",type:[String]}).example(`echo "export const foo: string = 'bar'" | dtsx stdin`).example("cat src/index.ts | dtsx stdin").action(async(e)=>{try{let t=[];for await(let a of n.stdin)t.push(a);let o=Buffer.concat(t).toString("utf-8");if(!o.trim())console.error("Error: No input received from stdin"),n.exit(1);let f=["bun"];if(e.importOrder){if(Array.isArray(e.importOrder))f=e.importOrder.flatMap((a)=>a.split(",").map((l)=>l.trim()).filter(Boolean));else if(typeof e.importOrder==="string")f=e.importOrder.split(",").map((a)=>a.trim()).filter(Boolean)}let p=ne(o,"stdin.ts",e.keepComments??!0,f);console.log(p)}catch(t){console.error("Error processing stdin:",t),n.exit(1)}});D.command("optimize","Optimize declaration files").option("--files <patterns>","Glob patterns for .d.ts files to optimize",{default:"**/*.d.ts",type:[String]}).option("--outdir <path>","Output directory (defaults to in-place)",{default:""}).option("--remove-unused-imports","Remove unused type imports",{default:!0}).option("--deduplicate","Remove duplicate declarations",{default:!0}).option("--merge-interfaces","Merge interface declarations with same name",{default:!0}).option("--inline-types","Inline simple type aliases",{default:!1}).option("--remove-empty","Remove empty interfaces",{default:!0}).option("--sort","Sort declarations alphabetically",{default:!1}).option("--sort-imports","Sort imports",{default:!0}).option("--minify","Minify output (remove whitespace)",{default:!1}).option("--remove-comments","Remove comments",{default:!1}).example('dtsx optimize --files "dist/**/*.d.ts"').example("dtsx optimize --minify --remove-comments").action(async(e)=>{try{let{optimizeFile:t}=await import("../src/optimizer.js"),{Glob:o}=await Promise.resolve(globalThis.Bun),{resolve:f,join:p,relative:a,dirname:l,basename:y}=await import("path"),{mkdirSync:w,copyFileSync:h,existsSync:m}=await import("fs"),i=n.cwd(),u=e.files||["**/*.d.ts"],c=[];for(let x of u){let C=new o(x);for await(let b of C.scan({cwd:i,absolute:!0,onlyFiles:!0}))if(b.endsWith(".d.ts")&&!b.includes("node_modules"))c.push(b)}if(c.length===0)console.error("No .d.ts files found"),n.exit(1);console.log(`Optimizing ${c.length} declaration files...`);let g=0,k=0;for(let x of c){let C=x;if(e.outdir){let E=a(i,x);C=p(f(e.outdir),E);let L=l(C);if(!m(L))w(L,{recursive:!0});h(x,C)}let b=await t(C,{removeUnusedImports:e.removeUnusedImports??!0,deduplicateDeclarations:e.deduplicate??!0,mergeInterfaces:e.mergeInterfaces??!0,inlineSimpleTypes:e.inlineTypes??!1,removeEmptyInterfaces:e.removeEmpty??!0,sortDeclarations:e.sort??!1,sortImports:e.sortImports??!0,minify:e.minify??!1,removeComments:e.removeComments??!1});k+=b.originalSize,g+=b.savings;let s=a(i,C);console.log(` ${s}: ${b.originalSize}B -> ${b.optimizedSize}B (-${b.savingsPercent}%)`)}let P=k>0?Math.round(g/k*100):0;console.log(`
|
|
7
|
+
Total: ${k}B -> ${k-g}B (-${P}%)`)}catch(t){console.error("Error optimizing files:",t),n.exit(1)}});D.command("docs","Generate API documentation from source files").option("--root <path>","Root directory to scan for source files",{default:"./src"}).option("--outdir <path>","Output directory for documentation",{default:"./docs"}).option("--format <format>","Output format: markdown or html",{default:"markdown"}).option("--title <title>","Documentation title",{default:"API Documentation"}).option("--include-private","Include private members (prefixed with _)",{default:!1}).option("--include-internal","Include internal members (@internal)",{default:!1}).option("--group-by-category","Group entries by @category tag",{default:!1}).option("--source-url <url>","Base URL for source links").example("dtsx docs").example("dtsx docs --format html --outdir ./api-docs").example('dtsx docs --group-by-category --title "My API"').action(async(e)=>{try{let{generateDocs:t}=await import("../src/docs.js"),{Glob:o}=await Promise.resolve(globalThis.Bun),{resolve:f}=await import("path"),p=f(e.root||"./src"),a=new o("**/*.ts"),l=[];for await(let y of a.scan({cwd:p,absolute:!0,onlyFiles:!0}))if(!y.endsWith(".d.ts")&&!y.includes("node_modules"))l.push(y);if(l.length===0)console.error("No TypeScript files found"),n.exit(1);console.log(`Found ${l.length} source files`),await t(l,{format:e.format||"markdown",outdir:f(e.outdir||"./docs"),title:e.title||"API Documentation",includePrivate:e.includePrivate??!1,includeInternal:e.includeInternal??!1,groupByCategory:e.groupByCategory??!1,includeSourceLinks:!!e.sourceUrl,sourceBaseUrl:e.sourceUrl})}catch(t){console.error("Error generating documentation:",t),n.exit(1)}});D.command("workspace","Generate declarations for all projects in a monorepo/workspace").option("--cwd <path>","Workspace root directory",{default:n.cwd()}).option("--parallel","Process projects in parallel",{default:!1}).option("--continue-on-error","Continue if a project fails",{default:!0}).option("--log-level <level>","Log level (debug, info, warn, error, silent)",{default:"info"}).example("dtsx workspace").example("dtsx workspace --cwd /path/to/monorepo").action(async(e)=>{try{let{generateMonorepo:t,generateFromPackageWorkspaces:o}=await import("../src/workspace.js"),{existsSync:f}=await import("fs"),{join:p,resolve:a}=await import("path"),l=a(e.cwd||n.cwd()),y=p(l,"tsconfig.json"),w;if(f(y))w=await t(l,{logLevel:e.logLevel||"info",continueOnError:e.continueOnError??!0});else w=await o(l,{logLevel:e.logLevel||"info",continueOnError:e.continueOnError??!0});if(!w.success)n.exit(1)}catch(t){console.error("Error generating workspace declarations:",t),n.exit(1)}});D.command("lsp","Start the Language Server Protocol server for IDE integration").example("dtsx lsp").action(async()=>{let{startLSPServer:e}=await import("../src/lsp.js");e()});D.command("check","Type check TypeScript files or validate generated declarations").option("--files <patterns>","Glob patterns for files to check",{default:"**/*.ts",type:[String]}).option("--declarations-only","Only check .d.ts files",{default:!1}).option("--tsconfig <path>","Path to tsconfig.json",{default:"tsconfig.json"}).option("--strict","Enable strict type checking",{default:!1}).option("--skip-lib-check","Skip checking library definitions",{default:!0}).option("--warnings-as-errors","Treat warnings as errors",{default:!1}).option("--max-errors <number>","Maximum errors before stopping",{default:0}).option("--isolated-declarations","Check if code follows isolated declarations best practices (recommended)",{default:!1}).option("--format <format>","Output format: text or json",{default:"text"}).example("dtsx check").example('dtsx check --files "src/**/*.ts" --strict').example('dtsx check --declarations-only --files "dist/**/*.d.ts"').example("dtsx check --isolated-declarations").action(async(e)=>{try{let{typeCheck:t,checkIsolatedDeclarations:o,formatTypeCheckResults:f}=await import("../chunk-5hyv43ps.js"),{Glob:p}=await Promise.resolve(globalThis.Bun),{resolve:a,relative:l}=await import("path"),y=n.cwd(),w=e.files||["**/*.ts"],h=[];for(let i of w){let u=new p(i);for await(let c of u.scan({cwd:y,absolute:!0,onlyFiles:!0}))if(!c.includes("node_modules"))if(e.declarationsOnly){if(c.endsWith(".d.ts"))h.push(c)}else h.push(c)}if(h.length===0)console.error("No files found to check"),n.exit(1);if(e.isolatedDeclarations){console.log(`Checking ${h.length} files for isolated declarations best practices...`);let i=await o(h,e.tsconfig?a(e.tsconfig):void 0),u=0,c=[];for(let[g,k]of i){let P=l(y,g);if(!k.compatible)if(u+=k.issues.length,e.format==="json")c.push({file:P,compatible:!1,issues:k.issues});else{console.log(`
|
|
8
|
+
\u2717 ${P}`);for(let x of k.issues)if(console.log(` ${x.line}:${x.column} - ${x.message}`),x.missingAnnotation)console.log(` Missing: ${x.missingAnnotation} type annotation`)}else if(e.format==="json")c.push({file:P,compatible:!0,issues:[]})}if(e.format==="json")console.log(JSON.stringify(c,null,2));else if(u>0)console.log(`
|
|
9
|
+
${h.length} files checked, ${u} recommendations found`),console.log("Tip: Adding explicit type annotations improves .d.ts accuracy");else console.log(`
|
|
10
|
+
${h.length} files checked, all follow isolated declarations best practices`);n.exit(u>0?1:0)}console.log(`Type checking ${h.length} files...`);let m=await t(h,{tsconfigPath:e.tsconfig?a(e.tsconfig):void 0,strict:e.strict??!1,declarationsOnly:e.declarationsOnly??!1,skipLibCheck:e.skipLibCheck??!0,warningsAsErrors:e.warningsAsErrors??!1,maxErrors:e.maxErrors||void 0});if(e.format==="json")console.log(JSON.stringify(m,null,2));else console.log(f(m));n.exit(m.success?0:1)}catch(t){console.error(t instanceof Error?`Error during type checking: ${t.message}`:`Error during type checking: ${String(t)}`),n.exit(1)}});D.command("convert","Convert TypeScript types to different schema formats").option("--files <patterns>","Glob patterns for TypeScript files",{default:"**/*.ts",type:[String]}).option("--format <format>","Output format: json-schema, zod, valibot, io-ts, yup, arktype",{default:"json-schema"}).option("--outdir <path>","Output directory for converted files",{default:"./schemas"}).option("--include-descriptions","Include JSDoc descriptions in output",{default:!0}).option("--all-optional","Make all properties optional",{default:!1}).option("--use-infer","Include inferred types (for Zod, Valibot, etc.)",{default:!0}).option("--json-schema-draft <version>","JSON Schema draft version: 2020-12, 2019-09, draft-07",{default:"2020-12"}).example("dtsx convert --format zod").example('dtsx convert --format json-schema --files "src/types/**/*.ts"').example("dtsx convert --format valibot --outdir ./validation").action(async(e)=>{try{let t=await import("../src/formats.js"),{extractDeclarations:o}=await import("../src/extractor.js"),{Glob:f}=await Promise.resolve(globalThis.Bun),{resolve:p,relative:a,join:l,dirname:y,basename:w}=await import("path"),{mkdirSync:h,existsSync:m,readFileSync:i,writeFileSync:u}=await import("fs"),c=n.cwd(),g=e.files||["**/*.ts"],k=e.format||"json-schema",P=p(e.outdir||"./schemas"),x=[];for(let s of g){let E=new f(s);for await(let L of E.scan({cwd:c,absolute:!0,onlyFiles:!0}))if(!L.endsWith(".d.ts")&&!L.includes("node_modules"))x.push(L)}if(x.length===0)console.error("No TypeScript files found"),n.exit(1);if(console.log(`Converting ${x.length} files to ${k} format...`),!m(P))h(P,{recursive:!0});let C=0,b=0;for(let s of x){let E=i(s,"utf-8"),I=o(E,s).filter((_)=>_.kind==="interface"||_.kind==="type");if(I.length===0)continue;let F=t.convertToFormat(I,{format:k,includeDescriptions:e.includeDescriptions??!0,allOptional:e.allOptional??!1,useInfer:e.useInfer??!0,jsonSchemaDraft:e.jsonSchemaDraft||"2020-12"}),T=a(c,s),d=w(s,".ts"),S=t.getFormatExtension(k),W=l(P,y(T),`${d}${S}`),K=y(W);if(!m(K))h(K,{recursive:!0});u(W,F),C+=I.length,b++,console.log(` ${a(c,W)} (${I.length} types)`)}console.log(`
|
|
11
|
+
Converted ${C} declarations from ${b} files`)}catch(t){console.error("Error converting files:",t),n.exit(1)}});D.command("circular","Detect circular dependencies in TypeScript files").option("--files <patterns>","Glob patterns for files to check",{default:"**/*.ts",type:[String]}).option("--root <path>","Root directory for resolution",{default:"."}).option("--ignore <patterns>","Glob patterns to ignore (comma-separated)",{default:"",type:[String]}).option("--types-only","Only report type-level cycles",{default:!1}).option("--max-depth <number>","Maximum depth for cycle detection",{default:100}).option("--include-node-modules","Include node_modules in analysis",{default:!1}).option("--format <format>","Output format: text, json, dot",{default:"text"}).option("--summary","Show graph summary statistics",{default:!1}).example("dtsx circular").example('dtsx circular --files "src/**/*.ts"').example('dtsx circular --ignore "**/*.test.ts,**/__tests__/**"').example("dtsx circular --format dot > deps.dot").example("dtsx circular --summary").action(async(e)=>{try{let{analyzeCircularDependencies:t,formatCircularAnalysis:o,getGraphSummary:f,exportGraphAsDot:p,exportGraphAsJson:a}=await import("../src/circular.js"),{Glob:l}=await Promise.resolve(globalThis.Bun),{resolve:y,relative:w}=await import("path"),h=n.cwd(),m=y(e.root||"."),i=e.files||["**/*.ts"],u=[];for(let g of i){let k=new l(g);for await(let P of k.scan({cwd:m,absolute:!0,onlyFiles:!0}))if(!P.endsWith(".d.ts")){if(!e.includeNodeModules&&P.includes("node_modules"))continue;u.push(P)}}if(u.length===0)console.error("No TypeScript files found"),n.exit(1);console.log(`Analyzing ${u.length} files for circular dependencies...`);let c=await t(u,{rootDir:m,ignore:e.ignore?.filter(Boolean),typesOnly:e.typesOnly??!1,maxDepth:e.maxDepth??100,includeNodeModules:e.includeNodeModules??!1});if(e.format==="json")console.log(a(c.graph,m));else if(e.format==="dot")console.log(p(c.graph,m));else if(console.log(o(c,m)),e.summary){let g=f(c.graph);if(console.log(`
|
|
12
|
+
--- Dependency Graph Summary ---`),console.log(`Total files: ${g.totalFiles}`),console.log(`Total dependencies: ${g.totalDependencies}`),console.log(`Average dependencies per file: ${g.avgDependencies.toFixed(2)}`),g.maxDependencies.count>0)console.log(`Most dependencies: ${w(m,g.maxDependencies.file)} (${g.maxDependencies.count})`);if(g.mostDepended.count>0)console.log(`Most depended on: ${w(m,g.mostDepended.file)} (${g.mostDepended.count} dependents)`);if(g.isolatedFiles.length>0)console.log(`Isolated files (no dependencies): ${g.isolatedFiles.length}`)}n.exit(c.hasCircular?1:0)}catch(t){console.error("Error analyzing dependencies:",t),n.exit(1)}});D.command("version","Show the version of dtsx").action(()=>{console.log(Q)});D.version(Q);D.help();D.parse();
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{p}from"./chunk-v6fwy63g.js";import{createHash as g}from"crypto";import{mkdir as y,readFile as l,stat as m,writeFile as v}from"fs/promises";import{dirname as C,join as o}from"path";var c="1.0.0",b=".dtsx-cache",d="manifest.json";class ei{config;manifest=null;dirty=!1;stats={totalEntries:0,hits:0,misses:0,hitRatio:0,sizeBytes:0,timeSavedMs:0};constructor(t={}){this.config={enabled:t.enabled??!0,cacheDir:t.cacheDir??b,format:t.format??"json",maxAge:t.maxAge??86400000,force:t.force??!1,validateCache:t.validateCache??!0}}async init(){if(!this.config.enabled)return;try{await y(this.config.cacheDir,{recursive:!0}),await this.loadManifest()}catch{this.manifest={version:c,entries:{},createdAt:Date.now(),updatedAt:Date.now()}}}async loadManifest(){let t=o(this.config.cacheDir,d);try{let e=await l(t,"utf-8");if(this.manifest=JSON.parse(e),this.manifest.version!==c){await this.clear();return}this.stats.totalEntries=Object.keys(this.manifest.entries).length}catch{this.manifest={version:c,entries:{},createdAt:Date.now(),updatedAt:Date.now()}}}async save(){if(!this.config.enabled||!this.manifest||!this.dirty)return;let t=o(this.config.cacheDir,d);this.manifest.updatedAt=Date.now(),await v(t,JSON.stringify(this.manifest,null,2)),this.dirty=!1}async get(t,e){if(!this.config.enabled||!this.manifest||this.config.force)return this.stats.misses++,null;let s=this.manifest.entries[t];if(!s)return this.stats.misses++,null;if(s.configHash!==e)return this.stats.misses++,null;if(Date.now()-s.cachedAt>this.config.maxAge)return this.stats.misses++,delete this.manifest.entries[t],this.dirty=!0,null;if(this.config.validateCache)try{let a=(await m(t)).mtimeMs;if(a!==s.mtime){let i=await l(t,"utf-8");if(this.hashContent(i)!==s.hash)return this.stats.misses++,null;s.mtime=a,this.dirty=!0}}catch{return this.stats.misses++,delete this.manifest.entries[t],this.dirty=!0,null}if(s.dependencies.length>0){if((await Promise.all(s.dependencies.map(async(a)=>{let i=this.manifest.entries[a];if(!i)return!0;try{return(await m(a)).mtimeMs===i.mtime}catch{return!1}}))).some((a)=>!a))return this.stats.misses++,null}return this.stats.hits++,this.stats.timeSavedMs+=50,this.updateHitRatio(),s}async set(t,e,s,r,a,i){if(!this.config.enabled||!this.manifest)return;let n=Date.now();try{n=(await m(t)).mtimeMs}catch{}let h={filePath:t,hash:this.hashContent(e),mtime:n,declarations:s,dtsContent:r,dependencies:a,cachedAt:Date.now(),configHash:i};if(!(t in this.manifest.entries))this.stats.totalEntries++;this.manifest.entries[t]=h,this.dirty=!0}invalidate(t){if(!this.manifest)return;delete this.manifest.entries[t],this.dirty=!0;for(let[e,s]of Object.entries(this.manifest.entries))if(s.dependencies.includes(t))delete this.manifest.entries[e]}async clear(){this.manifest={version:c,entries:{},createdAt:Date.now(),updatedAt:Date.now()},this.stats={totalEntries:0,hits:0,misses:0,hitRatio:0,sizeBytes:0,timeSavedMs:0},this.dirty=!0,await this.save()}getStats(){return{...this.stats}}hashContent(t){return String(p(t))}updateHitRatio(){let t=this.stats.hits+this.stats.misses;this.stats.hitRatio=t>0?this.stats.hits/t:0}static hashConfig(t){let e={outdir:t.outdir,clean:t.clean,tsconfigPath:t.tsconfigPath};return g("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16)}}function po(t,e){let s=[],r=[],a=[];return{async needsRebuild(i){return await t.get(i,e)===null},async getCachedDeclarations(i){let n=await t.get(i,e);if(n)return r.push(i),n.declarations;return null},async getCachedDts(i){let n=await t.get(i,e);if(n)return n.dtsContent;return null},async cacheResult(i,n,h,u,f=[]){await t.set(i,n,h,u,f,e),s.push(i)},skip(i){a.push(i)},getResult(){return{rebuilt:s,cached:r,skipped:a,stats:t.getStats()}},async save(){await t.save()}}}async function mo(t,e=604800000){let s=t.getStats();if(s.totalEntries>1000)return await t.clear(),s.totalEntries;return 0}function go(t){let e=[];return e.push("Incremental Build Results:"),e.push(` Rebuilt: ${t.rebuilt.length} files`),e.push(` From cache: ${t.cached.length} files`),e.push(` Skipped: ${t.skipped.length} files`),e.push(""),e.push("Cache Statistics:"),e.push(` Total entries: ${t.stats.totalEntries}`),e.push(` Hit ratio: ${(t.stats.hitRatio*100).toFixed(1)}%`),e.push(` Time saved: ~${t.stats.timeSavedMs}ms`),e.join(`
|
|
3
|
+
`)}function ho(t,e){let s=[],r=/import\s+(?:type\s+)?(?:.+(?:[\n\r\u2028\u2029]\s*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF])from\s+)?['"]([^'"]+)['"]/g,a;while((a=r.exec(t))!==null){let i=a[1];if(i.startsWith(".")){let n=o(C(e),i);s.push(n),s.push(`${n}.ts`),s.push(`${n}.tsx`),s.push(o(n,"index.ts")),s.push(o(n,"index.tsx"))}}return s}
|
|
4
|
+
export{ei,po,mo,go,ho};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var rn=["import","type","interface","enum","class","function","variable","export","module","namespace","unknown"],zr=["builtin","external","scoped","internal","parent","sibling","index","type"];function We(e,n={}){let{lineEnding:t="lf",trailingNewline:i=!0,maxBlankLines:u=1,trimTrailingWhitespace:a=!0,normalizeIndentation:l=!0,indent:x={style:"spaces",size:2},declarationOrder:f,importGrouping:p,preserveComments:d=!0,insertFinalNewline:b=!0}=n,r=e;if(r=sn(r,t),p?.enabled!==!1)r=ln(r,p||{});if(f)r=un(r,f);if(a)r=on(r);if(r=an(r,u),l)r=Hr(r,x);if(i||b)r=cn(r);return r}function sn(e,n){let t=e;if(e.indexOf("\r")!==-1){if(e.indexOf(`\r
|
|
3
|
+
`)!==-1)t=t.replace(/\r\n/g,`
|
|
4
|
+
`);if(t.indexOf("\r")!==-1)t=t.replace(/\r/g,`
|
|
5
|
+
`)}if(n==="crlf")t=t.replace(/\n/g,`\r
|
|
6
|
+
`);return t}function eo(e){let n=(e.match(/\r\n/g)||[]).length,t=(e.match(/(?<!\r)\n/g)||[]).length;if(n>t)return"crlf";return"lf"}function on(e){return e.split(`
|
|
7
|
+
`).map((n)=>n.replace(/[\t ]+$/,"")).join(`
|
|
8
|
+
`)}function an(e,n){let t=new RegExp(`\\n{${n+2},}`,"g");return e.replace(t,`
|
|
9
|
+
`.repeat(n+1))}function cn(e){return`${e.replace(/\s+$/,"")}
|
|
10
|
+
`}function Hr(e,n){let{style:t="spaces",size:i=2}=n,u=t==="tabs"?"\t":" ".repeat(i),a=e.split(`
|
|
11
|
+
`),l=[];for(let x of a){let f=x.match(/^([\t ]*)(.*)$/);if(!f){l.push(x);continue}let[,p,d]=f;if(!d){l.push("");continue}let b=p.replace(/\t/g," "),r=Math.floor(b.length/2);l.push(u.repeat(r)+d)}return l.join(`
|
|
12
|
+
`)}function ln(e,n){let{groups:t=zr,separateGroups:i=!0,alphabetize:u=!0}=n,a=e.split(`
|
|
13
|
+
`),l=[],x=[],f=-1;for(let s=0;s<a.length;s++){let c=a[s],o=E(c);if(o)l.push({line:c,source:o.source,group:o.group,isType:o.isType}),f=s;else if(l.length>0&&c.trim()==="")continue;else if(l.length>0||c.trim()!==""){if(l.length===0||s>f+1)x.push(c)}}if(l.length===0)return e;let p=new Map;for(let s of t)p.set(s,[]);for(let s of l)(p.get(s.group)||p.get("external")||[]).push(s);if(u)for(let[,s]of p)s.sort((c,o)=>{if(c.isType!==o.isType)return c.isType?1:-1;return c.source.localeCompare(o.source)});let d=[],b=null;for(let s of t){let c=p.get(s)||[];if(c.length===0)continue;if(i&&b!==null)d.push("");for(let o of c)d.push(o.line);b=s}let r=a.slice(0,a.findIndex((s)=>E(s)!==null)),m=x;while(m.length>0&&m[0].trim()==="")m.shift();return[...r,...d,"",...m].join(`
|
|
14
|
+
`)}function E(e){let n=e.trim(),t=n.match(/^import\s+(type\s+)?.*from\s+['"]([^'"]+)['"]/);if(!t){let a=n.match(/^import\s+['"]([^'"]+)['"]/);if(a)return{source:a[1],group:k(a[1]),isType:!1};return null}let i=!!t[1],u=t[2];return{source:u,group:i?"type":k(u),isType:i}}function k(e){if(e.startsWith("node:"))return"builtin";let n=["assert","buffer","child_process","cluster","crypto","dgram","dns","events","fs","http","https","net","os","path","querystring","readline","stream","url","util","zlib"];if(n.includes(e)||n.includes(e.split("/")[0]))return"builtin";if(e==="."||e==="./index"||e==="./index.js"||e==="./index.ts")return"index";if(e.startsWith("./"))return"sibling";if(e.startsWith("../"))return"parent";if(e.startsWith("@/")||e.startsWith("~/")||e.startsWith("#"))return"internal";if(e.startsWith("@"))return"scoped";return"external"}function un(e,n){let{kinds:t=rn,alphabetize:i=!1,groupExports:u=!0}=n,a=e.split(`
|
|
15
|
+
`),l=[],x=[],f=[],p=null,d=0,b=!0,r=!1,m=[];for(let o=0;o<a.length;o++){let g=a[o],h=g.trim(),y=d,z=h.startsWith("///"),I=y===0&&!z&&(h.startsWith("//")||h.startsWith("/*"));if(r||I){if(m.push(g),!r&&h.startsWith("/*")&&!h.includes("*/"))r=!0;else if(r&&h.includes("*/"))r=!1;continue}if(y===0&&m.length>0&&h===""){m.push(g);continue}d+=(g.match(/\{/g)||[]).length,d-=(g.match(/\}/g)||[]).length;let W=T(h);if(b&&W&&W.kind!=="import"&&!h.startsWith("//")&&!h.startsWith("/*"))b=!1;if(b){if(m.length>0){if(W?.kind==="import"||!W)x.push(...m),m.length=0}x.push(g);continue}if(W&&d<=1){if(p)l.push(p);p={lines:m.length>0?[...m,g]:[g],kind:W.kind,name:W.name,isExport:W.isExport},m.length=0}else if(p)p.lines.push(g);else{if(h==="")continue;f.push(g)}}if(p)l.push(p);if(m.length>0)f.push(...m);l.sort((o,g)=>{if(u&&o.isExport!==g.isExport)return o.isExport?-1:1;let h=t.indexOf(o.kind),y=t.indexOf(g.kind),z=h>=0?h:t.length,I=y>=0?y:t.length;if(z!==I)return z-I;if(i)return o.name.localeCompare(g.name);return 0});let s=[...x],c=null;for(let o of l){if(c!==null&&o.kind!==c)s.push("");s.push(...o.lines),c=o.kind}if(f.length>0)s.push(""),s.push(...f);return s.join(`
|
|
16
|
+
`)}function T(e){let n=e.startsWith("export "),t=n?e.slice(7):e;if(e.startsWith("import "))return{kind:"import",name:e.match(/from\s+['"]([^'"]+)['"]/)?.[1]||"",isExport:!1};if(t.startsWith("type ")||t.startsWith("declare type "))return{kind:"type",name:t.match(/type\s+(\w+)/)?.[1]||"",isExport:n};if(t.startsWith("interface ")||t.startsWith("declare interface "))return{kind:"interface",name:t.match(/interface\s+(\w+)/)?.[1]||"",isExport:n};if(t.startsWith("class ")||t.startsWith("abstract class ")||t.startsWith("declare class ")||t.startsWith("declare abstract class "))return{kind:"class",name:t.match(/class\s+(\w+)/)?.[1]||"",isExport:n};if(t.startsWith("enum ")||t.startsWith("const enum ")||t.startsWith("declare enum ")||t.startsWith("declare const enum "))return{kind:"enum",name:t.match(/enum\s+(\w+)/)?.[1]||"",isExport:n};if(t.startsWith("function ")||t.startsWith("async function ")||t.startsWith("declare function ")||t.startsWith("declare async function "))return{kind:"function",name:t.match(/function\s+(\w+)/)?.[1]||"",isExport:n};if(t.startsWith("const ")||t.startsWith("let ")||t.startsWith("var ")||t.startsWith("declare const ")||t.startsWith("declare let ")||t.startsWith("declare var "))return{kind:"variable",name:t.match(/(?:const|let|var)\s+(\w+)/)?.[1]||"",isExport:n};if(t.startsWith("namespace ")||t.startsWith("declare namespace "))return{kind:"namespace",name:t.match(/namespace\s+(\w+)/)?.[1]||"",isExport:n};if(t.startsWith("module ")||t.startsWith("declare module "))return{kind:"module",name:t.match(/module\s+['"]?(\w+)['"]?/)?.[1]||"",isExport:n};if(e.startsWith("export {")||e.startsWith("export *")||e.startsWith("export type {"))return{kind:"export",name:"",isExport:!0};return null}function to(e){let n=e.split(`
|
|
17
|
+
`),t=[];for(let i=0;i<n.length;i++){let u=n[i],a=u.trim();if(a.startsWith("/**")||a.startsWith("*")||a.startsWith("*/")){t.push(u);continue}if(a.startsWith("//")){t.push(u);continue}if(a.startsWith("/*")||a.endsWith("*/")){t.push(u);continue}t.push(u)}return t.join(`
|
|
18
|
+
`)}function no(e={}){return{normalize:(n)=>We(n,e),normalizeLineEndings:(n)=>sn(n,e.lineEnding||"lf"),removeTrailingWhitespace:on,normalizeBlankLines:(n)=>an(n,e.maxBlankLines||1),ensureTrailingNewline:cn,processImports:(n)=>ln(n,e.importGrouping||{}),orderDeclarations:(n)=>un(n,e.declarationOrder||{})}}var ro={default:{lineEnding:"lf",trailingNewline:!0,maxBlankLines:1,trimTrailingWhitespace:!0,normalizeIndentation:!0,indent:{style:"spaces",size:2},importGrouping:{enabled:!0,separateGroups:!0,alphabetize:!0}},minimal:{lineEnding:"lf",trailingNewline:!0,maxBlankLines:2,trimTrailingWhitespace:!0,normalizeIndentation:!1,importGrouping:{enabled:!1}},strict:{lineEnding:"lf",trailingNewline:!0,maxBlankLines:1,trimTrailingWhitespace:!0,normalizeIndentation:!0,indent:{style:"spaces",size:2},importGrouping:{enabled:!0,separateGroups:!0,alphabetize:!0},declarationOrder:{kinds:rn,alphabetize:!0,groupExports:!0}},windows:{lineEnding:"crlf",trailingNewline:!0,maxBlankLines:1,trimTrailingWhitespace:!0,normalizeIndentation:!0,indent:{style:"spaces",size:2},importGrouping:{enabled:!0,separateGroups:!0,alphabetize:!0}},tabs:{lineEnding:"lf",trailingNewline:!0,maxBlankLines:1,trimTrailingWhitespace:!0,normalizeIndentation:!0,indent:{style:"tabs",size:1},importGrouping:{enabled:!0,separateGroups:!0,alphabetize:!0}}};
|
|
19
|
+
export{rn,zr,We,sn,eo,on,an,cn,Hr,ln,un,to,no,ro};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{t}from"./chunk-1j6092xz.js";function q(r,i){if(i.kind!=="punctuation")return 0;let u=r.slice(i.start,i.end);if("([{<".includes(u))return 1;if(")]}".includes(u)||u===">"&&r[i.start-1]!=="=")return-1;return 0}function De(r){if(!r.includes("?"))return r;let i=r.trim(),u=i.startsWith("(")&&i.endsWith(")"),c=r.indexOf(i)+(u?1:0),o=u?i.slice(1,-1):i,a=[[]],x=0;for(let n of t(o)){if(n.kind==="punctuation"&&o[n.start]===","&&x===0)a.push([]);else a[a.length-1].push(n);x+=q(o,n)}let g=a.map((n)=>{let e=0,s=-1;for(let[T,p]of n.entries()){if(e===0&&p.kind==="punctuation"&&o[p.start]===":"){s=T;break}e+=q(o,p)}let d=s>0&&o[n[s-1].start]==="?"?n[s-1]:void 0,b=n[0]?o.slice(n[0].start,n[0].end):"",m=n[0]&&o.startsWith("...",n[0].start);return{tokens:n,colon:s,question:d,required:n.length>0&&!d&&!m&&b!=="this"}}),y=-1;for(let[n,e]of g.entries())if(e.required)y=n;let f=[];for(let[n,e]of g.entries()){if(n>=y||!e.question||e.colon<0)continue;let s=e.tokens[e.colon+1],d=e.tokens.at(-1);if(!s||!d)continue;f.push({start:c+e.question.start,end:c+e.question.end,text:""},{start:c+s.start,end:c+s.start,text:"("},{start:c+d.end,end:c+d.end,text:") | undefined"})}if(!f.length)return r;let l=[],h=0;for(let n of f)l.push(r.slice(h,n.start),n.text),h=n.end;return l.push(r.slice(h)),l.join("")}
|
|
3
|
+
export{De};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var ri=[{pattern:/^Promise<void>$/,replacement:"Promise<void>",priority:-1},{pattern:/^Record<string,\s*any>$/,replacement:"Record<string, unknown>",priority:0},{pattern:/^Array<([^<>]+)>$/,replacement:"$1[]",priority:0}],ii=[{pattern:/\bany\b/,replacement:"unknown",global:!0,priority:10},{pattern:/^object$/,replacement:"Record<string, unknown>",priority:10},{pattern:/^Function$/,replacement:"(...args: unknown[]) => unknown",priority:10}],si=[{pattern:/^(\w+)\[\]$/,replacement:"readonly $1[]",priority:5},{pattern:/^Array<(.+)>$/,replacement:"ReadonlyArray<$1>",priority:5},{pattern:/^Map<(.+),\s*(.+)>$/,replacement:"ReadonlyMap<$1, $2>",priority:5},{pattern:/^Set<(.+)>$/,replacement:"ReadonlySet<$1>",priority:5}],oi=[{pattern:/^Partial<Partial<(.+)>>$/,replacement:"Partial<$1>",priority:5},{pattern:/^Required<Required<(.+)>>$/,replacement:"Required<$1>",priority:5},{pattern:/^Pick<Omit<(.+),\s*(.+)>,\s*(.+)>$/,replacement:"Pick<$1, $3>",priority:5}];function ai(e){switch(e){case"strict":return ii;case"readonly":return si;case"simplified":return oi;case"nullable":return[{pattern:/^(.+)\s*\|\s*undefined$/,replacement:"$1 | undefined",priority:5}];case"branded":return[{pattern:/^string$/,replacement:"string",condition:(r)=>r.declarationKind==="variable"&&(r.declarationName?.includes("path")??!1),priority:5}];default:return[]}}var u=/[.*+?^${}()|[\]\\]/g,c=2048;class yn{rules;compiled=[];cache=new Map;constructor(e={rules:[]}){if(this.rules=[],e.includeDefaults!==!1)this.rules.push(...ri);if(e.presets)for(let r of e.presets)this.rules.push(...ai(r));this.rules.push(...e.rules),this.rules.sort((r,t)=>(t.priority||0)-(r.priority||0)),this.recompile()}recompile(){let e=Array(this.rules.length);for(let r=0;r<this.rules.length;r++){let t=this.rules[r],i=typeof t.pattern==="string"?new RegExp(t.pattern.replace(u,"\\$&"),t.global?"g":""):t.pattern;e[r]={rule:t,regex:i}}this.compiled=e}map(e,r={}){let i=!r.declarationName&&!r.declarationKind&&!r.filePath&&!r.isReturnType&&!r.isParameterType&&!r.isPropertyType?e:`${e}\x00${r.declarationName??""}\x00${r.declarationKind??""}\x00${r.filePath??""}\x00${r.isReturnType?"r":""}${r.isParameterType?"p":""}${r.isPropertyType?"P":""}`,l=this.cache.get(i);if(l!==void 0)return l;let a=e,o=null;for(let s=0;s<this.compiled.length;s++){let{rule:p,regex:n}=this.compiled[s];if(p.condition){if(!o)o={type:e,...r};if(!p.condition(o))continue}if(n.lastIndex=0,n.test(a)){if(n.lastIndex=0,a=a.replace(n,p.replacement),n.lastIndex=0,!p.global)break}}if(this.cache.size>=c){let s=Math.ceil(c*0.1),p=0;for(let n of this.cache.keys()){if(p++>=s)break;this.cache.delete(n)}}return this.cache.set(i,a),a}mapAll(e,r={}){return e.map((t)=>this.map(t,{...r,type:t}))}addRule(e){this.rules.push(e),this.rules.sort((r,t)=>(t.priority||0)-(r.priority||0)),this.recompile(),this.cache.clear()}removeRules(e){let r=this.rules.length;return this.rules=this.rules.filter((t)=>{let i=typeof t.pattern==="string"?t.pattern:t.pattern.source;if(e instanceof RegExp)e.lastIndex=0;return typeof e==="string"?i!==e:!e.test(i)}),this.recompile(),this.cache.clear(),r-this.rules.length}clearCache(){this.cache.clear()}getRules(){return this.rules}}function K(e={rules:[]}){return new yn(e)}var wo=K({rules:[]}),xo=K({rules:[],presets:["strict"]});function wt(e,r,t={}){return e.replace(/:\s*([^;,)\]}]+)/g,(i,l)=>`: ${r.map(l.trim(),t)}`)}var Co={makeReadonly:(e)=>{if(e.endsWith("[]"))return`readonly ${e}`;if(e.startsWith("Array<"))return e.replace("Array<","ReadonlyArray<");return e},makeNullable:(e)=>{if(e.includes("| null")||e.includes("| undefined"))return e;return`${e} | null`},makeOptional:(e)=>{if(e.includes("| undefined"))return e;return`${e} | undefined`},makeRequired:(e)=>e.replace(/\s*\|\s*null/g,"").replace(/\s*\|\s*undefined/g,"").trim(),promisify:(e)=>{if(e.startsWith("Promise<"))return e;return`Promise<${e}>`},unpromisify:(e)=>{let r=e.match(/^Promise<(.+)>$/);return r?r[1]:e},arrayify:(e)=>{if(e.endsWith("[]")||e.startsWith("Array<"))return e;return`${e}[]`},unarrayify:(e)=>{if(e.endsWith("[]"))return e.slice(0,-2);let r=e.match(/^(?:Readonly)?Array<(.+)>$/);return r?r[1]:e}};
|
|
3
|
+
export{ri,ii,si,oi,ai,yn,K,wo,xo,wt,Co};
|