@dtsx/dtsx 0.0.0-stage → 0.11.37
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-0azm93j9.js +31 -0
- package/dist/chunk-0ke9xh7t.js +4 -0
- package/dist/chunk-1bpv3tck.js +10 -0
- package/dist/chunk-1e10w914.js +18 -0
- package/dist/chunk-1h6ycqza.js +6 -0
- package/dist/chunk-1j6092xz.js +7 -0
- package/dist/chunk-1pz7zxhc.js +3 -0
- package/dist/chunk-25vyhfzh.js +3 -0
- package/dist/chunk-2kwjbk55.js +3 -0
- package/dist/chunk-437g8zz6.js +177 -0
- package/dist/chunk-4f2mwn7p.js +5 -0
- package/dist/chunk-5hyv43ps.js +12 -0
- package/dist/chunk-5n0tfrpc.js +6 -0
- package/dist/chunk-60ssvwc8.js +4 -0
- package/dist/chunk-69dbf6de.js +3 -0
- package/dist/chunk-7610h2tf.js +3 -0
- package/dist/chunk-79nv7twc.js +14 -0
- package/dist/chunk-853ftm92.js +8 -0
- package/dist/chunk-90aptjh6.js +24 -0
- package/dist/chunk-acyj1dev.js +18 -0
- package/dist/chunk-asws39qs.js +31 -0
- package/dist/chunk-aw48mk3t.js +3 -0
- package/dist/chunk-bdxq6500.js +4 -0
- package/dist/chunk-bqabznps.js +7 -0
- package/dist/chunk-cen2t56g.js +3 -0
- package/dist/chunk-ckq8g1ck.js +4 -0
- package/dist/chunk-cs4gwz1k.js +27 -0
- package/dist/chunk-d43bpfk6.js +3 -0
- package/dist/chunk-dfye109x.js +3 -0
- package/dist/chunk-dv5hhg1a.js +3 -0
- package/dist/chunk-ezbp8tss.js +10 -0
- package/dist/chunk-fgbdm1y6.js +6 -0
- package/dist/chunk-fy97syc2.js +3 -0
- package/dist/chunk-g9d5r6a8.js +3 -0
- package/dist/chunk-ggbahdr2.js +4 -0
- package/dist/chunk-gpq2kggq.js +3 -0
- package/dist/chunk-gs7wfk8b.js +2 -0
- package/dist/chunk-gsb3ty07.js +3 -0
- package/dist/chunk-gsv5yc32.js +6 -0
- package/dist/chunk-h7k9wamx.js +3 -0
- package/dist/chunk-j6pfxvy8.js +3 -0
- package/dist/chunk-km8t8gqg.js +3 -0
- package/dist/chunk-knrtwppp.js +102 -0
- package/dist/chunk-m1khpcqb.js +3 -0
- package/dist/chunk-mt9219xc.js +7 -0
- package/dist/chunk-n2nyd0ck.js +3 -0
- package/dist/chunk-n37yj3xv.js +8 -0
- package/dist/chunk-n3p7wedp.js +3 -0
- package/dist/chunk-n6nw7sn2.js +7 -0
- package/dist/chunk-n94729d9.js +3 -0
- package/dist/chunk-nchp0pqa.js +3 -0
- package/dist/chunk-nn9tpxx3.js +3 -0
- package/dist/chunk-p2qz2nk2.js +3 -0
- package/dist/chunk-p7w9ydhe.js +9 -0
- package/dist/chunk-pga5m4wm.js +3 -0
- package/dist/chunk-psrgw9f8.js +19 -0
- package/dist/chunk-py7pj8aj.js +5 -0
- package/dist/chunk-pzedkn7z.js +4 -0
- package/dist/chunk-q0hn0ymb.js +6 -0
- package/dist/chunk-qnf4byak.js +3 -0
- package/dist/chunk-r4s18nn5.js +3 -0
- package/dist/chunk-r4zkf9ag.js +3 -0
- package/dist/chunk-rdzfdjkb.js +7 -0
- package/dist/chunk-rmdwvzgn.js +3 -0
- package/dist/chunk-s0mvstt0.js +3 -0
- package/dist/chunk-s6c98nad.js +29 -0
- package/dist/chunk-sjneg7p7.js +34 -0
- package/dist/chunk-sq34kkhy.js +3 -0
- package/dist/chunk-srg5qhch.js +22 -0
- package/dist/chunk-strqhcqs.js +3 -0
- package/dist/chunk-t1jtn2r0.js +10 -0
- package/dist/chunk-ttc5pr8y.js +37 -0
- package/dist/chunk-v44crx69.js +62 -0
- package/dist/chunk-v6fwy63g.js +3 -0
- package/dist/chunk-vae5wxar.js +3 -0
- package/dist/chunk-vtskg4r2.js +4 -0
- package/dist/chunk-w9av39jy.js +3 -0
- package/dist/chunk-wnk9yjw2.js +3 -0
- package/dist/chunk-wrnz0e76.js +4 -0
- package/dist/chunk-wzcwctba.js +9 -0
- package/dist/chunk-xb92nrsm.js +3 -0
- package/dist/chunk-xr1h3tv2.js +8 -0
- package/dist/chunk-xsf941gw.js +3 -0
- package/dist/chunk-z4mvkazp.js +21 -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 V=s,Y=0,Z=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 V.submit({id:`batch-${Z}-${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 V.submit({id:`batch-${Z}-${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]}`)}}},q=[];for(let j=0;j<X;j++)q.push(ee());await Promise.all(q),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:H}=await import("../chunk-gs7wfk8b.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 Q(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:Q(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: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:Q(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(H)});D.version(H);D.help();D.parse();
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{b,ae,Ot,f}from"./chunk-dfye109x.js";import{B}from"./chunk-pga5m4wm.js";import{R,M}from"./chunk-z4mvkazp.js";import{A,P}from"./chunk-mt9219xc.js";import{r}from"./chunk-qnf4byak.js";import{he}from"./chunk-xb92nrsm.js";import{e,I}from"./chunk-km8t8gqg.js";import{De,T,qn,V}from"./chunk-d43bpfk6.js";import{Tn}from"./chunk-cs4gwz1k.js";import{Ge,pt}from"./chunk-bqabznps.js";import{S}from"./chunk-v44crx69.js";import{me,J,G,ge}from"./chunk-853ftm92.js";import{Ve,_,q,mt,gt,ht,yt}from"./chunk-79nv7twc.js";import{K,pe}from"./chunk-s0mvstt0.js";import{ze,xt}from"./chunk-ezbp8tss.js";import{z}from"./chunk-acyj1dev.js";import{dn,_e}from"./chunk-p2qz2nk2.js";import{ye}from"./chunk-w9av39jy.js";import{je}from"./chunk-psrgw9f8.js";import{de}from"./chunk-wzcwctba.js";import{l}from"./chunk-t1jtn2r0.js";import{U,dt}from"./chunk-nn9tpxx3.js";import{mkdir as xe}from"fs/promises";import{availableParallelism as Pe}from"os";import{basename as fe,dirname as we,relative as H,resolve as oe}from"path";var re=new WeakMap,ce=new WeakMap;function ie(d){let a=re.get(d);if(!a)a=De(d),re.set(d,a),a.catch(()=>re.delete(d));return a}async function le(d,a,t,u,h,g=_){let o=fe(d)||"output.d.ts",w=H(we(d),a),W=`${o}.map`,Y=t.lastIndexOf(`
|
|
3
|
+
${Ve()}`),p=Y===-1?t:t.slice(0,Y),y=ht(p,o,w,u),C=`${d}.map`;return await g(C,JSON.stringify(y)),e.debug(` Generated source map: ${H(h,C)}`),W}async function s(d){let a=Date.now(),t={...S,...d};if(t.logLevel)I(t.logLevel);else if(t.verbose)I("debug");let u=new de;if(t.plugins&&t.plugins.length>0){for(let n of t.plugins)u.register(n),e.debug(`Registered plugin: ${n.name}`);t=await u.runOnStart(t)}if(t.moduleSpecifierMode!==void 0&&t.moduleSpecifierMode!=="preserve"&&t.moduleSpecifierMode!=="node")throw Error("moduleSpecifierMode must be preserve or node");if(await K(t),t.isolatedDeclarations===void 0)t.isolatedDeclarations=await q(t);let h=t.typeMappings?U(t.typeMappings):void 0,g=null,o={generationMode:t.isolatedDeclarations?"isolated":"semantic",filesProcessed:0,filesGenerated:0,filesFailed:0,filesValidated:0,validationErrors:0,declarationsFound:0,importsProcessed:0,exportsProcessed:0,durationMs:0,errors:[]},w=0;e.debug("Starting DTS generation..."),e.debug(`Using ${o.generationMode} declaration generation path`),e.debug("Config:",t);let W=await me(t,()=>ie(t)),Y=W.entryFiles,p=[...W.files],{resolver:y,reachability:C}=W;if(ce.set(t,new Set(p)),t.incremental){let n=W.getResolutionFingerprint();if(!t.isolatedDeclarations){let i=new Set(p),m=new Map;for(let v of p){let F=await f(v);m.set(v,_e(F));for(let ee of T(F,{includeImports:!0})){let O=y(ee.specifier,v).resolved;if(O&&!O.split(/[/\\]/).includes("node_modules")&&!i.has(O))i.add(O),m.set(O,_e(await f(O)))}}let c=[...m].sort(([v],[F])=>v.localeCompare(F));n=JSON.stringify([n,c])}if(g=new Ge(t,n),t.clearCache){if(e.debug("Clearing build cache..."),!t.dryRun)g.clear()}else if(g.load()){let m=g.getStats();e.debug(`Loaded build cache with ${m.entries} entries`)}else e.debug("No existing build cache found, starting fresh");if(!t.dryRun)pt(t.cwd)}if(g&&!t.dryRun){let n=g.prune(new Set(p),t.cwd);if(n>0)e.debug(`Pruned ${n} deleted files from cache`)}if(e.debug(`Found ${p.length} TypeScript files`),t.progress&&p.length>0){let n=t.parallel?"parallel":"sequential";e.info(`Processing ${p.length} files (${n})...`)}let L=new Map,N=new Map,E=async(n,i,m="lf")=>{N.set(n,{content:i,lineEnding:m})},D=async(n,i)=>{let m;try{let c=G(n,t),v=async(x)=>{if(!t.diff)return;try{let Q=await f(c),X=gt(Q,x,H(t.cwd,c));if(X)e.info(`
|
|
4
|
+
${X}`);else e.debug(`[no changes] ${c}`)}catch{e.info(`[new file] ${H(t.cwd,c)}`)}},F=(x)=>{if(!t.validate)return 0;let Q=mt(x,c);if(Q.isValid)return e.debug(`[validation] ${c} - OK`),0;e.warn(`[validation] ${H(t.cwd,c)} has ${Q.errors.length} error(s):`);for(let X of Q.errors){let se=` Line ${X.line}:${X.column}`;if(X.code)se+=` [${X.code}]`;if(se+=` - ${X.message}`,e.warn(se),X.suggestion)e.warn(` Suggestion: ${X.suggestion}`)}return Q.errors.length},ee=(x)=>{e.info(`[dry-run] Would generate: ${c}`),e.debug("--- Content preview ---"),e.debug(x.slice(0,500)+(x.length>500?`
|
|
5
|
+
...`:"")),e.debug("--- End preview ---")};if(g){let x=g.getCachedIfValid(n,t.cwd);if(x){if(t.bundle)L.set(n,x);await v(x);let Q=F(x);if(t.dryRun)ee(x);else{if(t.declarationMap)m=i??await f(n),await le(c,n,x,m,t.cwd,E);await E(c,x,t.lineEnding)}return e.debug(`[cached] ${H(t.cwd,c)}`),{success:!0,file:n,declarationCount:0,importCount:0,exportCount:0,cached:!0,validationErrorCount:Q}}}m=i??await f(n);let{content:O,declarationCount:Se,importCount:$e,exportCount:ve}=await be(n,m,t,u,h,W.augmentationImports.get(n));if(t.bundle)L.set(n,O);let j=O;if(t.prettier||t.indentStyle||t.indentSize){let x=await z(j,{usePrettier:t.prettier,builtIn:{indentSize:t.indentSize||2,useTabs:t.indentStyle==="tabs",normalizeWhitespace:!0,sortImports:!0,trailingNewline:!0}},c);j=x.content;for(let Q of x.warnings??[])e.warn(`[format] ${Q}`)}if(t.declarationMap){let x=`${fe(c)||"output.d.ts"}.map`;j=yt(j,x)}await v(j);let Ee=F(j);if(t.dryRun)ee(j);else{if(t.declarationMap&&m)await le(c,n,j,m,t.cwd,E);if(await E(c,j,t.lineEnding),g&&m)g.update(n,m,j,t.cwd);e.debug(`Generated: ${c}`)}return{success:!0,file:n,declarationCount:Se,importCount:$e,exportCount:ve,validationErrorCount:Ee}}catch(c){let v=ze(c,n,m);if(t.plugins&&t.plugins.length>0)await u.runOnError(c instanceof Error?c:Error(String(c)),n,m||"");return{success:!1,file:n,declarationCount:0,importCount:0,exportCount:0,dtsError:v,validationErrorCount:0}}},k=t.parallel||t.parallel!==!1&&p.length>=10,Z=B(t.concurrency,Pe?.()??8),te=new Map;if(k&&p.length>1){let n=p.map(async(i)=>{try{let m=await f(i);return{file:i,source:m}}catch{return{file:i,source:null}}});for(let i of await Promise.all(n))if(i.source!==null)te.set(i.file,i.source)}let ne=(n)=>{if(o.filesProcessed++,n.success){if(n.cached)w++;else o.filesGenerated++,o.declarationsFound+=n.declarationCount,o.importsProcessed+=n.importCount,o.exportsProcessed+=n.exportCount;if(t.validate){if(o.filesValidated++,n.validationErrorCount)o.validationErrors+=n.validationErrorCount}}else if(o.filesFailed++,n.dtsError){o.errors.push(n.dtsError);let i=xt(n.dtsError);if(t.continueOnError)e.warn(i);else throw e.error(i),Error(n.dtsError.message)}};if(k)for(let n=0;n<p.length;n+=Z){let i=p.slice(n,n+Z),m=await Promise.all(i.map((c)=>D(c,te.get(c))));for(let c of m)ne(c);if(t.progress){let c=Math.round(o.filesProcessed/p.length*100);e.info(`[${o.filesProcessed}/${p.length}] ${c}%`)}}else for(let n of p){let i=await D(n);if(ne(i),t.progress){let m=Math.round(o.filesProcessed/p.length*100),c=i.cached?"[cached]":"";e.info(`[${o.filesProcessed}/${p.length}] ${m}% - ${H(t.cwd,n)} ${c}`)}}if(!t.bundle){let n=[];if(C)for(let i of C.unresolved)n.push({from:i.from,specifier:i.specifier,reason:"missing"});if(t.autoIncludeReExports===!1&&p.length>0){let i=new Set(p);for(let m of p){let c;try{c=await f(m)}catch{continue}for(let v of T(c)){let F=y(v.specifier,m);if(!F.isRelative)continue;if(!F.resolved)n.push({from:m,specifier:v.specifier,reason:"missing"});else if(!/\.d\.(?:ts|mts|cts)$/.test(F.resolved)&&!i.has(F.resolved))n.push({from:m,specifier:v.specifier,reason:"not-emitted"})}}}if(n.length>0){let i=[];i.push(`Found ${n.length} re-export(s) pointing at siblings that won't be in the output:`);for(let c of n){let v=H(t.cwd,c.from);if(c.reason==="missing")i.push(` ${v} \u2192 '${c.specifier}' (path not found on disk)`);else i.push(` ${v} \u2192 '${c.specifier}' (resolved but not in entrypoints; set autoIncludeReExports: true or add to entrypoints)`)}let m=i.join(`
|
|
6
|
+
`);if(t.failOnUnresolvedReExport)throw Error(m);e.warn(m),e.warn('Generated .d.ts files reference modules that were not emitted \u2014 consumers will see "has no exported member" errors.')}}if(t.bundle&&(o.filesGenerated>0||w>0)&&Y.length>0)try{e.debug("Bundling declarations...");let n=Y.length===1&&!!t.bundleOutput;for(let i of Y){let m=await V([i],{includeImports:!0,resolveSpecifier:y}),c=new Set;for(let O of m.reachable){if(O.endsWith(".d.ts"))continue;if(O.includes("node_modules"))continue;c.add(O)}let v=p.filter((O)=>c.has(O));if(!v.includes(i))v.push(i);let F=Tn(i,v,L,{cwd:t.cwd,keepComments:t.keepComments});for(let O of new Set(F.warnings))e.warn(`[bundle] ${O}`);let ee=n?oe(t.cwd,t.outdir,t.bundleOutput):G(i,t);if(t.dryRun)e.info(`[dry-run] Would bundle ${F.files.length} files to: ${H(t.cwd,ee)}`);else await E(ee,F.content,t.lineEnding),e.debug(`Prepared ${F.files.length} bundled files for: ${H(t.cwd,ee)}`);if(n)break}}catch(n){let i=n instanceof Error?n.message:String(n);throw e.error(`Bundle failed: ${i}`),n}if(!t.dryRun)await pe(t,N);if(g&&!t.dryRun)g.save(),e.debug("Saved build cache");if(o.durationMs=Date.now()-a,t.stats)if(t.outputFormat==="json")console.log(JSON.stringify(o,null,2));else{if(e.info(`
|
|
7
|
+
--- Generation Statistics ---`),e.info(`Files processed: ${o.filesProcessed}`),e.info(`Files generated: ${o.filesGenerated}`),w>0)e.info(`Files cached: ${w}`);if(o.filesFailed>0)e.info(`Files failed: ${o.filesFailed}`);if(e.info(`Declarations found: ${o.declarationsFound}`),e.info(`Imports processed: ${o.importsProcessed}`),e.info(`Exports processed: ${o.exportsProcessed}`),o.filesValidated>0){if(e.info(`Files validated: ${o.filesValidated}`),o.validationErrors>0)e.info(`Validation errors: ${o.validationErrors}`)}if(e.info(`Duration: ${o.durationMs}ms`),o.errors.length>0){e.info(`
|
|
8
|
+
Errors:`);for(let n of o.errors){let i=` - ${n.file}`;if(n.location)i+=`:${n.location.line}:${n.location.column}`;if(n.code)i+=` [${n.code}]`;if(i+=`: ${n.message}`,e.info(i),n.suggestion)e.info(` Suggestion: ${n.suggestion}`)}}e.info(`-----------------------------
|
|
9
|
+
`)}if(t.plugins&&t.plugins.length>0)await u.runOnEnd(o);return e.debug("DTS generation complete!"),o}async function Me(d,a,t){let u=await ie(t),h=ge(a,t,u,ce.get(t));return qn(d,(g)=>h(g).emittedSpecifier)}async function co(d,a){re.delete(a),ce.delete(a);let t=await ie(a),u=await V([d],{includeImports:!0,resolveSpecifier:t}),h=await he([...u.sources.keys()],t,a.isolatedDeclarations??!1,u.sources);return(await Ce(d,a,void 0,h.get(oe(d)))).content}async function Ce(d,a,t,u){let h=await f(d),g=a.typeMappings?U(a.typeMappings):void 0;return be(d,h,a,t,g,u)}async function be(d,a,t,u,h,g){let o=a;if(u)o=await u.runOnBeforeFile(d,a);let w=new Map;if(!t.isolatedDeclarations){let E=await ie(t);for(let D of T(o,{includeImports:!0})){let k=E(D.specifier,d).resolved;if(k&&!k.split(/[/\\]/).includes("node_modules"))w.set(D.specifier,await f(k))}}let W=u?.hasDeclarationHooks()?null:Re(o,d,t,w,g);if(W!==null)return ue(W,d,o,t,u,h,Fe(W));let Y=w.size?dn(o,w):void 0,p=r(o,d,t.keepComments,t.isolatedDeclarations??!1,Y);if(u)p=await u.runOnDeclarations(d,o,p);let y=0,C=0;for(let E=0;E<p.length;E++){let D=p[E];if(D.kind==="import")y++;if(D.kind==="export"||D.isExported)C++}let N=l(p,{filePath:d,sourceCode:o,declarations:p,augmentationImports:g},t.keepComments,t.importOrder);return ue(N,d,o,t,u,h,{declarationCount:p.length,importCount:y,exportCount:C})}function Fe(d){let a=0,t=0,u=0;for(let h of d.split(`
|
|
10
|
+
`)){if(!h||h.startsWith(" ")||h.startsWith("\t")||h.startsWith("}")||h.startsWith("*")||h.startsWith("/"))continue;if(a++,h.startsWith("import "))t++;else if(h.startsWith("export "))u++}return{declarationCount:a,importCount:t,exportCount:u}}function Re(d,a,t,u,h){let g=t.importOrder??["bun"];if(g.length!==1||g[0]!=="bun")return null;let o=R(a)?M(d):A(a)?P(d):d;return ye(o,{keepComments:t.keepComments??!0,isolatedDeclarations:t.isolatedDeclarations??!1,sourceFile:a,inferenceSources:u,augmentationImports:h})}async function ue(d,a,t,u,h,g,o){let w=await Me(d,a,u);if(g)w=dt(w,g,{filePath:a});if(u.normalizeOutput===!0||u.declarationOrder)w=je(w,{lineEnding:"lf",declarationOrder:u.declarationOrder,indent:{style:u.indentStyle??"spaces",size:u.indentSize??2}});if(h)w=await h.runOnAfterFile(a,t,w);return{content:w,...o}}async function lo(d){let a={...S,...d};if(a.logLevel)I(a.logLevel);let t=oe(a.cwd,a.root),u=150,h=5,g=1e4,o={pendingChanges:new Set,debounceTimer:null,isProcessing:!1,errorCount:0,lastErrorTime:0};e.info(`Watching for changes in ${t}...`),e.info(`Press Ctrl+C to stop
|
|
11
|
+
`);try{await s(a),e.info(`[watch] Initial generation complete
|
|
12
|
+
`)}catch(y){let C=y instanceof Error?y.message:String(y);e.error(`[watch] Initial generation failed: ${C}`),e.info(`[watch] Continuing to watch for changes...
|
|
13
|
+
`)}async function w(){if(o.isProcessing||o.pendingChanges.size===0)return;let y=Date.now();if(o.errorCount>=h){if(y-o.lastErrorTime<g){e.warn(`[watch] Too many errors, pausing for ${Math.ceil((g-(y-o.lastErrorTime))/1000)}s...`);return}o.errorCount=0}o.isProcessing=!0;let C=Array.from(o.pendingChanges);o.pendingChanges.clear();let L=new Date().toLocaleTimeString();if(C.length===1)e.info(`
|
|
14
|
+
[${L}] File changed: ${C[0]}`);else e.info(`
|
|
15
|
+
[${L}] ${C.length} files changed`);let N=0,E=0;for(let D of C){let k=oe(t,D);try{let Z=a.exclude||[];if(J(k,Z,t)){e.debug(` Skipping excluded file: ${D}`);continue}if(!await ae(k).exists()){e.debug(` Skipping deleted file: ${D}`);continue}let ne=G(k,a),{content:n}=await Ce(k,a);await xe(we(ne),{recursive:!0}),await _(ne,n,a.lineEnding),e.info(` \u2713 ${H(a.cwd,ne)}`),N++}catch(Z){E++,o.errorCount++,o.lastErrorTime=Date.now();let te=ze(Z,k);if(e.error(` \u2717 ${D}: ${te.message}`),te.suggestion)e.error(` Suggestion: ${te.suggestion}`)}}if(C.length>1)e.info(` Done: ${N} generated, ${E} failed`);if(E===0)o.errorCount=0;if(o.isProcessing=!1,o.pendingChanges.size>0)o.debounceTimer=setTimeout(w,u)}function W(y){if(o.pendingChanges.add(y),o.debounceTimer)clearTimeout(o.debounceTimer);o.debounceTimer=setTimeout(w,u)}let p=Ot([b?"bun":"node","-e",`
|
|
16
|
+
const fs = require('fs');
|
|
17
|
+
|
|
18
|
+
const rootPath = '${t}';
|
|
19
|
+
|
|
20
|
+
fs.watch(rootPath, { recursive: true }, (eventType, filename) => {
|
|
21
|
+
if (filename && /.(?:[cm]?[jt]sx?|vue|stx)$/.test(filename) && !/.d.(?:ts|mts|cts)$/.test(filename)) {
|
|
22
|
+
console.log(\`CHANGED:\${filename}\`);
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
// Keep process alive
|
|
27
|
+
setInterval(() => {}, 1000);
|
|
28
|
+
`],{stdout:"pipe",stderr:"inherit"});if(b){let y=p.stdout.getReader(),C=new TextDecoder,L="";while(!0){let{done:N,value:E}=await y.read();if(N)break;L+=C.decode(E,{stream:!0});let D=L.split(`
|
|
29
|
+
`);L=D.pop()||"";for(let k of D)if(k.startsWith("CHANGED:")){let Z=k.slice(8);W(Z)}}}else{let y=p.stdout,C="";y.on("data",(L)=>{C+=L.toString();let N=C.split(`
|
|
30
|
+
`);C=N.pop()||"";for(let E of N)if(E.startsWith("CHANGED:")){let D=E.slice(8);W(D)}}),await p.exited}}
|
|
31
|
+
export{s,co,lo};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{r}from"./chunk-qnf4byak.js";import{existsSync as g,readFileSync as h,writeFileSync as b}from"fs";function d(t){let e=[],s=/\b([A-Z][a-zA-Z0-9]*)\b/g,o;while((o=s.exec(t))!==null){let i=o[1];if(!D(i))e.push(i)}return[...new Set(e)]}function D(t){return new Set(["Array","Object","String","Number","Boolean","Symbol","BigInt","Function","Promise","Map","Set","WeakMap","WeakSet","Date","RegExp","Error","TypeError","RangeError","SyntaxError","Partial","Required","Readonly","Pick","Omit","Record","Exclude","Extract","NonNullable","ReturnType","Parameters","ConstructorParameters","InstanceType","ThisType","Uppercase","Lowercase","Capitalize","Uncapitalize","Awaited","NoInfer","Generator","AsyncGenerator","IterableIterator","AsyncIterableIterator","PropertyKey","Iterable","AsyncIterable","ArrayLike","PromiseLike","ArrayBuffer","SharedArrayBuffer","DataView","Int8Array","Uint8Array","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"]).has(t)}function x(t){if(t.kind!=="type")return!1;let e=t.typeAnnotation||"";if(t.generics)return!1;if(e.includes("{")||e.includes("(")||e.includes("<"))return!1;return/^[\w\s|&]+$/.test(e)}function v(t){if(t.kind!=="interface")return!1;if(!t.members||t.members.length===0){if(!t.extends)return!0}return!1}function I(t,e){let s={...t,members:[...t.members||[],...e.members||[]],leadingComments:[...t.leadingComments||[],...e.leadingComments||[]]};if(t.extends&&e.extends){let o=t.extends.split(",").map((n)=>n.trim()),i=e.extends.split(",").map((n)=>n.trim());s.extends=[...new Set([...o,...i])].join(", ")}else s.extends=t.extends||e.extends;return s}function A(t){let e={import:0,interface:1,type:2,class:3,enum:4,function:5,variable:6,export:7};return[...t].sort((s,o)=>{let i=e[s.kind]??99,n=e[o.kind]??99;if(i!==n)return i-n;return s.name.localeCompare(o.name)})}function T(t){let e=[],s=[];for(let i=0;i<t.length;i++){let n=t[i];if(n.kind==="import")e.push(n);else s.push(n)}return[...[...e].sort((i,n)=>{let a=i.source||"",c=n.source||"",p=a.startsWith("node:")||a==="bun",m=c.startsWith("node:")||c==="bun";if(p&&!m)return-1;if(!p&&m)return 1;let l=!a.startsWith("."),u=!c.startsWith(".");if(l&&!u)return-1;if(!l&&u)return 1;return a.localeCompare(c)}),...s]}function S(t){let e=new Set;for(let i of t){if(i.kind==="import")continue;let n=i.text||"",a=i.typeAnnotation||"",c=i.returnType||"",p=i.extends||"",m=i.implements?.join(" ")||"",l=`${n} ${a} ${c} ${p} ${m}`;for(let u of d(l))e.add(u);if(i.members)for(let u of i.members){let f=`${u.typeAnnotation||""} ${u.returnType||""}`;for(let y of d(f))e.add(y)}if(i.parameters){for(let u of i.parameters)if(u.type)for(let f of d(u.type))e.add(f)}}let s=0;return{declarations:t.map((i)=>{if(i.kind!=="import"||!i.specifiers)return i;let n=i.specifiers.filter((a)=>{let c=a.alias||a.name;return e.has(c)});if(n.length===0){if(!i.isSideEffect)return s++,null}if(n.length<(i.specifiers?.length||0))return s+=(i.specifiers?.length||0)-n.length,{...i,specifiers:n};return i}).filter((i)=>i!==null),removed:s}}function k(t){let e=new Map,s=0;for(let o of t){if(o.kind==="import"){let n=`import:${o.source}`;if(e.has(n)){let a=e.get(n),c=[...a.specifiers||[],...o.specifiers||[]],p=Array.from(new Map(c.map((m)=>[m.alias||m.name,m])).values());e.set(n,{...a,specifiers:p}),s++}else e.set(n,o);continue}let i=`${o.kind}:${o.name}`;if(e.has(i))s++;else e.set(i,o)}return{declarations:Array.from(e.values()),removed:s}}function z(t){let e=new Map,s=[];for(let n of t)if(n.kind==="interface"){let a=n.name;if(!e.has(a))e.set(a,[]);e.get(a).push(n)}else s.push(n);let o=0,i=[];for(let[n,a]of e)if(a.length>1){let c=a[0];for(let p=1;p<a.length;p++)c=I(c,a[p]),o++;i.push(c)}else i.push(a[0]);return{declarations:[...s,...i],merged:o}}function w(t){let e=new Map,s=new Set;for(let n of t)if(x(n))e.set(n.name,n.typeAnnotation||""),s.add(n.name);if(e.size===0)return{declarations:t,inlined:0};function o(n){let a=n;for(let[c,p]of e){let m=new RegExp(`\\b${c}\\b`,"g");a=a.replace(m,p)}return a}return{declarations:t.filter((n)=>n.kind!=="type"||!s.has(n.name)).map((n)=>{if(n.typeAnnotation)n={...n,typeAnnotation:o(n.typeAnnotation)};if(n.returnType)n={...n,returnType:o(n.returnType)};if(n.extends)n={...n,extends:o(n.extends)};return n}),inlined:e.size}}function R(t){let e=t.length,s=t.filter((o)=>!v(o));return{declarations:s,removed:e-s.length}}function Dr(t,e={}){let s=[...t],o={originalSize:0,optimizedSize:0,savings:0,savingsPercent:0,removedImports:0,removedDeclarations:0,mergedInterfaces:0,inlinedTypes:0};if(e.removeUnusedImports){let{declarations:i,removed:n}=S(s);s=i,o.removedImports=n}if(e.deduplicateDeclarations){let{declarations:i,removed:n}=k(s);s=i,o.removedDeclarations+=n}if(e.mergeInterfaces){let{declarations:i,merged:n}=z(s);s=i,o.mergedInterfaces=n}if(e.removeEmptyInterfaces){let{declarations:i,removed:n}=R(s);s=i,o.removedDeclarations+=n}if(e.inlineSimpleTypes){let{declarations:i,inlined:n}=w(s);s=i,o.inlinedTypes=n}if(e.sortImports)s=T(s);if(e.sortDeclarations)s=A(s);return{declarations:s,result:o}}async function As(t,e={}){if(!g(t))throw Error(`File not found: ${t}`);let s=h(t,"utf-8"),o=Buffer.byteLength(s,"utf-8"),i=r(s,t,!e.removeComments),{declarations:n,result:a}=Dr(i,e),c=C(n,e);if(e.minify)c=Rr(c);let p=Buffer.byteLength(c,"utf-8");return a.originalSize=o,a.optimizedSize=p,a.savings=o-p,a.savingsPercent=Math.round(a.savings/o*100),b(t,c),a}function C(t,e){let s=[];for(let o of t){if(!e.removeComments&&o.leadingComments)for(let i of o.leadingComments)s.push(i);if(o.text)s.push(o.text);else s.push(E(o));s.push("")}return s.join(`
|
|
3
|
+
`)}function E(t){let e=[];if(t.isExported)e.push("export");if(t.isDefault)e.push("default");switch(t.kind){case"import":if(t.isTypeOnly)e.push("import type");else e.push("import");if(t.specifiers&&t.specifiers.length>0){let s=t.specifiers.map((o)=>{let i=o.isType?"type ":"";return o.alias?`${i}${o.name} as ${o.alias}`:`${i}${o.name}`}).join(", ");e.push(`{ ${s} }`)}e.push("from"),e.push(`'${t.source}'`);break;case"function":if(e.push("declare function"),e.push(t.name),t.generics)e.push(t.generics);if(e.push(`(${B(t.parameters)})`),t.returnType)e.push(`: ${t.returnType}`);break;case"variable":if(e.push("declare const"),e.push(t.name),t.typeAnnotation)e.push(`: ${t.typeAnnotation}`);break;case"interface":if(e.push("interface"),e.push(t.name),t.generics)e.push(t.generics);if(t.extends)e.push(`extends ${t.extends}`);if(e.push("{"),t.members)for(let s of t.members)e.push(` ${s.name}${s.typeAnnotation?`: ${s.typeAnnotation}`:""}`);e.push("}");break;case"type":if(e.push("type"),e.push(t.name),t.generics)e.push(t.generics);e.push("="),e.push(t.typeAnnotation||"unknown");break;case"class":if(e.push("declare class"),e.push(t.name),t.generics)e.push(t.generics);if(t.extends)e.push(`extends ${t.extends}`);if(t.implements?.length)e.push(`implements ${t.implements.join(", ")}`);e.push("{ }");break;case"enum":e.push("declare enum"),e.push(t.name),e.push("{ }");break;default:return t.text||""}return e.join(" ")}function B(t){if(!t)return"";return t.map((e)=>{let s="";if(e.rest)s+="...";if(s+=e.name,e.optional)s+="?";if(e.type)s+=`: ${e.type}`;return s}).join(", ")}function Rr(t){return t.replace(/(?<!\/\*\*)\/\/[^\n]*/g,"").replace(/^\s*[\r\n]/gm,"").replace(/ {2,}/g," ").replace(/\s*([{}[\]();,:])\s*/g,"$1").replace(/(\w)(\{)/g,"$1 $2").replace(/(\})([a-z])/gi,"$1 $2").replace(/(export|import|type|interface|class|function|const|let|var|extends|implements|declare)\s*/g,"$1 ").trim()}
|
|
4
|
+
export{Dr,As,Rr};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{r}from"./chunk-qnf4byak.js";import{existsSync as j,mkdirSync as N,readFileSync as z,writeFileSync as G}from"fs";import{dirname as K,relative as L,resolve as _}from"path";async function vi(t,e,n){let u=new Map,f=[],x=new Set,D=0,w=0,S=0,C=[];for(let i of t){let o=e.get(i);if(!o)continue;C.push({file:i,decls:r(o,i,n.keepComments)})}for(let{file:i,decls:o}of C){D+=o.length;for(let s of o)if(s.kind==="import"){w++;let c=s.source||"";if(c.startsWith("."))continue;if(!u.has(c))u.set(c,{source:c,specifiers:new Map,isTypeOnly:s.isTypeOnly||!1,isSideEffect:s.isSideEffect||!1});let l=u.get(c);if(s.specifiers)for(let h of s.specifiers){let W=h.alias||h.name;if(!l.specifiers.has(W))l.specifiers.set(W,{name:h.name,alias:h.alias,isType:h.isType||!1})}if(!s.isTypeOnly)l.isTypeOnly=!1}else if(s.isExported||s.kind==="export"){if(S++,s.kind==="export"&&s.source&&(s.source.startsWith(".")||s.source.startsWith("/")))continue;if(s.name&&x.has(s.name))continue;if(s.name)x.add(s.name);f.push({declaration:s,file:i})}}let a=[];a.push("/**"),a.push(" * Bundled TypeScript declarations"),a.push(` * Generated from ${t.length} source files`),a.push(" */"),a.push("");let T=n.importOrder||["bun"],y=Array.from(u.values()),p=Array(y.length);for(let i=0;i<y.length;i++){let o=y[i].source,s=T.length;for(let c=0;c<T.length;c++)if(o.startsWith(T[c])){s=c;break}p[i]=s}let g=y.map((i,o)=>o);g.sort((i,o)=>{let s=p[i],c=p[o];if(s!==c)return s-c;return y[i].source.localeCompare(y[o].source)});let b=g.map((i)=>y[i]);for(let i of b)if(i.isSideEffect)a.push(`import '${i.source}';`);else if(i.specifiers.size>0){let s=Array.from(i.specifiers.values()).map((l)=>{let h=l.isType?"type ":"";return l.alias?`${h}${l.name} as ${l.alias}`:`${h}${l.name}`}),c=i.isTypeOnly?"type ":"";a.push(`import ${c}{ ${s.join(", ")} } from '${i.source}';`)}if(b.length>0)a.push("");let m=new Map;for(let{declaration:i,file:o}of f){if(!m.has(o))m.set(o,[]);m.get(o).push(i)}for(let[i,o]of m){let s=L(n.cwd,i);a.push(`// From: ${s}`);for(let c of o){if(n.keepComments&&c.leadingComments)for(let l of c.leadingComments)a.push(l);a.push(F(c))}a.push("")}let d=a.join(`
|
|
3
|
+
`);return{content:d,files:t,declarationCount:D,importCount:w,exportCount:S,size:Buffer.byteLength(d,"utf8"),warnings:[]}}function F(t){if(t.text){let n=t.text.trim();if(t.isExported&&!n.startsWith("export"))n=`export ${n}`;if(!n.endsWith(";")&&!n.endsWith("}"))n+=";";return n}let e=[];if(t.isExported)e.push("export");if(t.isDefault)e.push("default");switch(t.kind){case"function":if(e.push("declare function"),e.push(t.name),t.generics)e.push(t.generics);if(e.push(`(${V(t.parameters)})`),t.returnType)e.push(`: ${t.returnType}`);break;case"variable":if(e.push("declare const"),e.push(t.name),t.typeAnnotation)e.push(`: ${t.typeAnnotation}`);break;case"interface":if(e.push("interface"),e.push(t.name),t.generics)e.push(t.generics);if(t.extends)e.push(`extends ${t.extends}`);if(e.push("{"),t.members)for(let n of t.members)e.push(` ${n.name}${n.typeAnnotation?`: ${n.typeAnnotation}`:""};`);e.push("}");break;case"type":if(e.push("type"),e.push(t.name),t.generics)e.push(t.generics);e.push("="),e.push(t.typeAnnotation||"unknown");break;case"class":if(e.push("declare class"),e.push(t.name),t.generics)e.push(t.generics);if(t.extends)e.push(`extends ${t.extends}`);if(t.implements&&t.implements.length>0)e.push(`implements ${t.implements.join(", ")}`);if(e.push("{"),t.members)for(let n of t.members)e.push(` ${F(n)}`);e.push("}");break;case"enum":if(e.push("declare enum"),e.push(t.name),e.push("{"),t.members){let n=t.members.map((u)=>u.value!==void 0?`${u.name} = ${u.value}`:u.name);e.push(` ${n.join(`,
|
|
4
|
+
`)}`)}e.push("}");break;default:return t.text||""}return e.join(" ")}function V(t){if(!t||t.length===0)return"";return t.map((e)=>{let n="";if(e.rest)n+="...";if(n+=e.name,e.optional)n+="?";if(e.type)n+=`: ${e.type}`;if(e.defaultValue)n+=` = ${e.defaultValue}`;return n}).join(", ")}async function Ft(t,e={}){let n=[],u=new Map,f=[],x=[],D=new Set,w=0,S=0,C=0;for(let p of t){if(!j(p)){n.push(`File not found: ${p}`);continue}let g=z(p,"utf-8");x.push(p);let b=g.split(`
|
|
5
|
+
`),m=[],d=0,i=!1;for(let o of b){let s=o.trim();if(!s&&!i)continue;if(s.startsWith("import ")){S++;let l=s.match(/import\s+(type\s+)?(?:\{([^}]+)\}|(\w+)|\*\s+as\s+(\w+))\s+from\s+['"]([^'"]+)['"]/);if(l){let[,h,W,q,H,A]=l;if(e.externals?.some((P)=>A.startsWith(P))){f.push(s);continue}if(A.startsWith("."))continue;if(!u.has(A))u.set(A,{source:A,specifiers:new Map,isTypeOnly:!!h,isSideEffect:!1});let E=u.get(A);if(W){let P=W.split(",").map((k)=>k.trim());for(let k of P){let[I,v]=k.split(/\s+as\s+/).map((M)=>M.trim()),R=I.startsWith("type "),O=R?I.replace("type ",""):I;E.specifiers.set(v||O,{name:O,alias:v!==O?v:void 0,isType:R})}}if(!h)E.isTypeOnly=!1}continue}if(/^(export\s+)?(declare\s+)?(interface|type|class|function|const|let|var|enum|namespace|module)\s/.test(s)){if(i=!0,m=[o],d=(o.match(/\{/g)||[]).length-(o.match(/\}/g)||[]).length,d===0&&(s.endsWith(";")||!s.includes("{"))){let l=B(s);if(!D.has(l)||!e.mergeDuplicates){if(D.add(l),f.push(o),w++,s.startsWith("export"))C++}i=!1,m=[]}}else if(i){if(m.push(o),d+=(o.match(/\{/g)||[]).length-(o.match(/\}/g)||[]).length,d<=0){let l=m.join(`
|
|
6
|
+
`),h=B(m[0]);if(!D.has(h)||!e.mergeDuplicates){if(D.add(h),f.push(l),w++,m[0].trim().startsWith("export"))C++}i=!1,m=[]}}else if(s.startsWith("export ")&&!s.includes("declare"))f.push(o),C++}}let a=[];if(e.banner)a.push(e.banner),a.push("");if(e.includeReferences&&e.references){for(let p of e.references)a.push(`/// <reference types="${p}" />`);a.push("")}let T=Array.from(u.values()).sort((p,g)=>p.source.localeCompare(g.source));for(let p of T)if(p.specifiers.size>0){let b=Array.from(p.specifiers.values()).map((d)=>{let i=d.isType?"type ":"";return d.alias?`${i}${d.name} as ${d.alias}`:`${i}${d.name}`}),m=p.isTypeOnly?"type ":"";a.push(`import ${m}{ ${b.join(", ")} } from '${p.source}';`)}if(T.length>0)a.push("");if(e.ambient&&e.moduleName){a.push(`declare module '${e.moduleName}' {`);for(let p of f){let g=p.split(`
|
|
7
|
+
`).map((b)=>` ${b.replace(/^(\s*)(export\s+)?declare\s+/,"$1$2")}`).join(`
|
|
8
|
+
`);a.push(g)}a.push("}")}else{if(e.sortDeclarations)f.sort((p,g)=>{let b=B(p),m=B(g);return b.localeCompare(m)});for(let p of f)a.push(p)}if(e.footer)a.push(""),a.push(e.footer);let y=a.join(`
|
|
9
|
+
`);return{content:y,files:x,declarationCount:w,importCount:S,exportCount:C,size:Buffer.byteLength(y,"utf-8"),warnings:n}}function B(t){let e=t.match(/(interface|type|class|function|const|let|var|enum|namespace|module)\s+(\w+)/);return e?`${e[1]}:${e[2]}`:t.trim()}async function Qn(t,e,n={}){let u=await Ft(t,n),f=K(e);if(!j(f))N(f,{recursive:!0});return G(e,u.content),u}function Si(t={}){return{bundle:(e)=>Ft(e,t),bundleAndWrite:(e,n)=>Qn(e,n,{...t,output:n})}}async function $i(t,e=process.cwd()){let n=Array.isArray(t)?t:[t],u=[];for(let f of n){if(f.includes("*"))continue;let x=_(e,f);if(j(x))u.push(x)}return u}
|
|
10
|
+
export{vi,Ft,Qn,Si,$i};
|