tsup-plugin-dtsx 0.9.10

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 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 ADDED
@@ -0,0 +1,228 @@
1
+ # tsup-plugin-dtsx
2
+
3
+ A tsup plugin for automatic TypeScript declaration file generation using dtsx.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ bun add tsup-plugin-dtsx -d
9
+ # or
10
+ npm install tsup-plugin-dtsx --save-dev
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ### Basic Usage
16
+
17
+ ```typescript
18
+ // tsup.config.ts
19
+ import { defineConfig } from 'tsup'
20
+ import { dtsxPlugin } from 'tsup-plugin-dtsx'
21
+
22
+ export default defineConfig({
23
+ entry: ['src/index.ts'],
24
+ format: ['esm', 'cjs'],
25
+ dts: false, // Disable tsup's dts, use dtsx instead
26
+ plugins: [
27
+ dtsxPlugin(),
28
+ ],
29
+ })
30
+ ```
31
+
32
+ ### Using the Helper
33
+
34
+ ```typescript
35
+ // tsup.config.ts
36
+ import { defineConfig } from 'tsup-plugin-dtsx'
37
+
38
+ export default defineConfig({
39
+ entry: ['src/index.ts'],
40
+ format: ['esm', 'cjs'],
41
+ dtsx: {
42
+ // dtsx options
43
+ bundle: true,
44
+ },
45
+ })
46
+ ```
47
+
48
+ ### Quick Config
49
+
50
+ ```typescript
51
+ // tsup.config.ts
52
+ import { createTsupConfig } from 'tsup-plugin-dtsx'
53
+
54
+ export default createTsupConfig('src/index.ts', {
55
+ bundle: true,
56
+ bundleOutput: 'types.d.ts',
57
+ })
58
+ ```
59
+
60
+ ## Options
61
+
62
+ | Option | Type | Default | Description |
63
+ |--------|------|---------|-------------|
64
+ | `trigger` | `'buildStart' \| 'buildEnd'` | `'buildEnd'` | When to generate declarations |
65
+ | `entryPointsOnly` | `boolean` | `true` | Only generate for entry points |
66
+ | `declarationDir` | `string` | tsup outDir | Output directory for declarations |
67
+ | `bundle` | `boolean` | `false` | Bundle all declarations into one file |
68
+ | `bundleOutput` | `string` | `'index.d.ts'` | Bundled output filename |
69
+ | `exclude` | `(string \| RegExp)[]` | `[]` | Patterns to exclude |
70
+ | `include` | `(string \| RegExp)[]` | `[]` | Patterns to include |
71
+ | `skipIfTsupDts` | `boolean` | `true` | Skip if tsup dts is enabled |
72
+
73
+ ## Examples
74
+
75
+ ### With Bundled Declarations
76
+
77
+ ```typescript
78
+ // tsup.config.ts
79
+ import { defineConfig } from 'tsup'
80
+ import { dtsxPlugin } from 'tsup-plugin-dtsx'
81
+
82
+ export default defineConfig({
83
+ entry: ['src/index.ts'],
84
+ format: ['esm', 'cjs'],
85
+ dts: false,
86
+ plugins: [
87
+ dtsxPlugin({
88
+ bundle: true,
89
+ bundleOutput: 'types.d.ts',
90
+ }),
91
+ ],
92
+ })
93
+ ```
94
+
95
+ ### Multiple Entry Points
96
+
97
+ ```typescript
98
+ // tsup.config.ts
99
+ import { defineConfig } from 'tsup'
100
+ import { dtsxPlugin } from 'tsup-plugin-dtsx'
101
+
102
+ export default defineConfig({
103
+ entry: {
104
+ index: 'src/index.ts',
105
+ utils: 'src/utils.ts',
106
+ types: 'src/types.ts',
107
+ },
108
+ format: ['esm', 'cjs'],
109
+ dts: false,
110
+ plugins: [
111
+ dtsxPlugin({
112
+ entryPointsOnly: true,
113
+ }),
114
+ ],
115
+ })
116
+ ```
117
+
118
+ ### With Callbacks
119
+
120
+ ```typescript
121
+ // tsup.config.ts
122
+ import { defineConfig } from 'tsup'
123
+ import { dtsxPlugin } from 'tsup-plugin-dtsx'
124
+
125
+ export default defineConfig({
126
+ entry: ['src/index.ts'],
127
+ format: ['esm'],
128
+ dts: false,
129
+ plugins: [
130
+ dtsxPlugin({
131
+ onStart: () => {
132
+ console.log('Starting declaration generation...')
133
+ },
134
+ onSuccess: (stats) => {
135
+ console.log(`Generated ${stats.totalFiles} files in ${stats.totalTime}ms`)
136
+ },
137
+ onError: (error) => {
138
+ console.error('Failed:', error.message)
139
+ },
140
+ }),
141
+ ],
142
+ })
143
+ ```
144
+
145
+ ### Generate Before Build
146
+
147
+ ```typescript
148
+ // tsup.config.ts
149
+ import { defineConfig } from 'tsup'
150
+ import { dtsxPlugin } from 'tsup-plugin-dtsx'
151
+
152
+ export default defineConfig({
153
+ entry: ['src/index.ts'],
154
+ format: ['esm'],
155
+ dts: false,
156
+ plugins: [
157
+ dtsxPlugin({
158
+ trigger: 'buildStart', // Generate before build
159
+ }),
160
+ ],
161
+ })
162
+ ```
163
+
164
+ ### Filter Files
165
+
166
+ ```typescript
167
+ // tsup.config.ts
168
+ import { defineConfig } from 'tsup'
169
+ import { dtsxPlugin } from 'tsup-plugin-dtsx'
170
+
171
+ export default defineConfig({
172
+ entry: ['src/index.ts'],
173
+ format: ['esm'],
174
+ dts: false,
175
+ plugins: [
176
+ dtsxPlugin({
177
+ include: [/src\/lib/],
178
+ exclude: ['test', /\.spec\.ts$/],
179
+ }),
180
+ ],
181
+ })
182
+ ```
183
+
184
+ ### Custom Output Directory
185
+
186
+ ```typescript
187
+ // tsup.config.ts
188
+ import { defineConfig } from 'tsup'
189
+ import { dtsxPlugin } from 'tsup-plugin-dtsx'
190
+
191
+ export default defineConfig({
192
+ entry: ['src/index.ts'],
193
+ outDir: 'dist',
194
+ dts: false,
195
+ plugins: [
196
+ dtsxPlugin({
197
+ declarationDir: 'types', // Outputs to types/ instead of dist/
198
+ }),
199
+ ],
200
+ })
201
+ ```
202
+
203
+ ## Why Use dtsx Instead of tsup's Built-in dts?
204
+
205
+ 1. **Faster**: dtsx is optimized for speed and can be significantly faster for large projects
206
+ 2. **More Options**: Bundling, filtering, callbacks, and more
207
+ 3. **Better Control**: Fine-grained control over declaration generation
208
+ 4. **Incremental Support**: Only regenerate changed files
209
+
210
+ ## Compatibility
211
+
212
+ - tsup 6.x, 7.x, 8.x
213
+ - Node.js 18+
214
+ - Bun 1.0+
215
+
216
+ ## TypeScript Configuration
217
+
218
+ The plugin automatically detects your `tsconfig.json`. You can also specify a custom path:
219
+
220
+ ```typescript
221
+ dtsxPlugin({
222
+ tsconfigPath: './tsconfig.build.json',
223
+ })
224
+ ```
225
+
226
+ ## License
227
+
228
+ MIT
@@ -0,0 +1,39 @@
1
+ import type { DtsGenerationOption, GenerationStats } from '@stacksjs/dtsx';
2
+ import type { Options as TsupOptions } from 'tsup';
3
+ // Re-export types
4
+ export type { DtsGenerationOption, GenerationStats };
5
+ /**
6
+ * Create tsup plugin for dtsx declaration generation
7
+ */
8
+ export declare function dtsxPlugin(options?: DtsxTsupOptions): any;
9
+ /**
10
+ * Create a preset tsup config with dtsx integration
11
+ */
12
+ export declare function createTsupConfig(entry: string | string[] | Record<string, string>, options?: DtsxTsupOptions & {
13
+ /** Additional tsup options */
14
+ tsupOptions?: Partial<TsupOptions>
15
+ }): TsupOptions;
16
+ /**
17
+ * Define tsup config with dtsx (helper for tsup.config.ts)
18
+ */
19
+ export declare function defineConfig(options: TsupOptions & { dtsx?: DtsxTsupOptions }): TsupOptions;
20
+ /**
21
+ * Plugin configuration options
22
+ */
23
+ export declare interface DtsxTsupOptions extends Omit<Partial<DtsGenerationOption>, 'exclude' | 'include'> {
24
+ trigger?: 'buildStart' | 'buildEnd'
25
+ entryPointsOnly?: boolean
26
+ declarationDir?: string
27
+ bundle?: boolean
28
+ bundleOutput?: string
29
+ exclude?: (string | RegExp)[]
30
+ include?: (string | RegExp)[]
31
+ skipIfTsupDts?: boolean
32
+ declarationMap?: boolean
33
+ onSuccess?: (stats: GenerationStats) => void | Promise<void>
34
+ onError?: (error: Error) => void | Promise<void>
35
+ onStart?: () => void | Promise<void>
36
+ onProgress?: (current: number, total: number, file: string) => void
37
+ }
38
+ // Default export
39
+ export default dtsxPlugin;
package/dist/index.js ADDED
@@ -0,0 +1,244 @@
1
+ // src/index.ts
2
+ import { generate } from "@stacksjs/dtsx";
3
+ import { resolve, relative, join, dirname } from "node:path";
4
+ import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
5
+ var PLUGIN_NAME = "dtsx";
6
+ function dtsxPlugin(options = {}) {
7
+ const {
8
+ trigger = "buildEnd",
9
+ entryPointsOnly = true,
10
+ declarationDir,
11
+ bundle: bundleDeclarations = false,
12
+ bundleOutput = "index.d.ts",
13
+ exclude = [],
14
+ include = [],
15
+ skipIfTsupDts = true,
16
+ declarationMap = false,
17
+ onSuccess,
18
+ onError,
19
+ onStart,
20
+ onProgress,
21
+ ...dtsOptions
22
+ } = options;
23
+ const state = {
24
+ tsupOptions: null,
25
+ generatedFiles: new Set,
26
+ errors: []
27
+ };
28
+ return {
29
+ name: PLUGIN_NAME,
30
+ esbuildOptions(esbuildOptions, context) {
31
+ state.tsupOptions = context.options;
32
+ },
33
+ async buildStart() {
34
+ if (trigger !== "buildStart")
35
+ return;
36
+ if (skipIfTsupDts && state.tsupOptions?.dts) {
37
+ console.log(`[${PLUGIN_NAME}] Skipping - tsup dts is enabled`);
38
+ return;
39
+ }
40
+ await generateDeclarations();
41
+ },
42
+ async buildEnd() {
43
+ if (trigger !== "buildEnd")
44
+ return;
45
+ if (skipIfTsupDts && state.tsupOptions?.dts) {
46
+ console.log(`[${PLUGIN_NAME}] Skipping - tsup dts is enabled`);
47
+ return;
48
+ }
49
+ await generateDeclarations();
50
+ }
51
+ };
52
+ async function generateDeclarations() {
53
+ try {
54
+ await onStart?.();
55
+ let filesToProcess = getEntryPoints(state.tsupOptions);
56
+ filesToProcess = filterFiles(filesToProcess, include, exclude);
57
+ if (filesToProcess.length === 0) {
58
+ console.log(`[${PLUGIN_NAME}] No files to process`);
59
+ return;
60
+ }
61
+ console.log(`[${PLUGIN_NAME}] Generating declarations for ${filesToProcess.length} file(s)...`);
62
+ const outdir = declarationDir || state.tsupOptions?.outDir || "dist";
63
+ const config = normalizeConfig(dtsOptions, state.tsupOptions, outdir);
64
+ const stats = await generate({
65
+ ...config,
66
+ entrypoints: filesToProcess.map((f) => relative(config.cwd || process.cwd(), f))
67
+ });
68
+ state.generatedFiles = new Set;
69
+ if (bundleDeclarations && state.generatedFiles.size > 0) {
70
+ await bundleDeclarationsFiles(Array.from(state.generatedFiles), join(outdir, bundleOutput));
71
+ }
72
+ await onSuccess?.(stats);
73
+ console.log(`[${PLUGIN_NAME}] Generated ${state.generatedFiles.size} declaration file(s)`);
74
+ } catch (error) {
75
+ const err = error instanceof Error ? error : new Error(String(error));
76
+ state.errors.push(err);
77
+ if (onError) {
78
+ await onError(err);
79
+ } else {
80
+ console.error(`[${PLUGIN_NAME}] Error generating declarations:`, err.message);
81
+ }
82
+ }
83
+ }
84
+ }
85
+ function getEntryPoints(options) {
86
+ if (!options?.entry)
87
+ return [];
88
+ const entry = options.entry;
89
+ if (typeof entry === "string") {
90
+ return [resolve(entry)];
91
+ }
92
+ if (Array.isArray(entry)) {
93
+ return entry.map((e) => resolve(e));
94
+ }
95
+ if (typeof entry === "object") {
96
+ return Object.values(entry).map((e) => resolve(e));
97
+ }
98
+ return [];
99
+ }
100
+ function filterFiles(files, include, exclude) {
101
+ return files.filter((file) => {
102
+ if (!file.endsWith(".ts") && !file.endsWith(".tsx")) {
103
+ return false;
104
+ }
105
+ if (file.endsWith(".d.ts")) {
106
+ return false;
107
+ }
108
+ for (const pattern of exclude) {
109
+ if (typeof pattern === "string") {
110
+ if (file.includes(pattern))
111
+ return false;
112
+ } else if (pattern.test(file)) {
113
+ return false;
114
+ }
115
+ }
116
+ if (include.length > 0) {
117
+ for (const pattern of include) {
118
+ if (typeof pattern === "string") {
119
+ if (file.includes(pattern))
120
+ return true;
121
+ } else if (pattern.test(file)) {
122
+ return true;
123
+ }
124
+ }
125
+ return false;
126
+ }
127
+ return true;
128
+ });
129
+ }
130
+ function normalizeConfig(options, tsupOptions, outdir) {
131
+ const cwd = options.cwd || process.cwd();
132
+ let tsconfigPath = options.tsconfigPath || tsupOptions?.tsconfig;
133
+ if (!tsconfigPath) {
134
+ const defaultPaths = ["tsconfig.json", "tsconfig.build.json"];
135
+ for (const p of defaultPaths) {
136
+ if (existsSync(resolve(cwd, p))) {
137
+ tsconfigPath = p;
138
+ break;
139
+ }
140
+ }
141
+ }
142
+ return {
143
+ cwd,
144
+ root: options.root || "./src",
145
+ outdir,
146
+ tsconfigPath,
147
+ clean: options.clean ?? false,
148
+ keepComments: options.keepComments ?? true,
149
+ ...options
150
+ };
151
+ }
152
+ async function bundleDeclarationsFiles(files, outputPath) {
153
+ const contents = [
154
+ "/**",
155
+ " * Bundled TypeScript declarations",
156
+ ` * Generated by ${PLUGIN_NAME}`,
157
+ " */",
158
+ ""
159
+ ];
160
+ const imports = new Map;
161
+ const declarations = [];
162
+ for (const file of files) {
163
+ if (!existsSync(file))
164
+ continue;
165
+ const content = readFileSync(file, "utf-8");
166
+ const lines = content.split(`
167
+ `);
168
+ for (const line of lines) {
169
+ const trimmed = line.trim();
170
+ if (trimmed.startsWith("import ")) {
171
+ const match = trimmed.match(/from\s+['"]([^'"]+)['"]/);
172
+ if (match && !match[1].startsWith(".")) {
173
+ if (!imports.has(match[1])) {
174
+ imports.set(match[1], new Set);
175
+ }
176
+ const specMatch = trimmed.match(/\{([^}]+)\}/);
177
+ if (specMatch) {
178
+ specMatch[1].split(",").forEach((s) => {
179
+ imports.get(match[1]).add(s.trim());
180
+ });
181
+ }
182
+ }
183
+ continue;
184
+ }
185
+ if (trimmed.startsWith("import ") || trimmed === "")
186
+ continue;
187
+ declarations.push(line);
188
+ }
189
+ }
190
+ for (const [source, specifiers] of imports) {
191
+ if (specifiers.size > 0) {
192
+ contents.push(`import { ${Array.from(specifiers).join(", ")} } from '${source}';`);
193
+ }
194
+ }
195
+ if (imports.size > 0) {
196
+ contents.push("");
197
+ }
198
+ contents.push(...declarations);
199
+ const outDir = dirname(outputPath);
200
+ if (!existsSync(outDir)) {
201
+ mkdirSync(outDir, { recursive: true });
202
+ }
203
+ writeFileSync(outputPath, contents.join(`
204
+ `));
205
+ console.log(`[${PLUGIN_NAME}] Bundled declarations to ${outputPath}`);
206
+ }
207
+ function createTsupConfig(entry, options = {}) {
208
+ const { tsupOptions = {}, ...dtsxOptions } = options;
209
+ return {
210
+ entry,
211
+ format: ["esm", "cjs"],
212
+ splitting: false,
213
+ sourcemap: true,
214
+ clean: true,
215
+ dts: false,
216
+ esbuildPlugins: [],
217
+ ...tsupOptions,
218
+ plugins: [
219
+ ...tsupOptions.plugins || [],
220
+ dtsxPlugin(dtsxOptions)
221
+ ]
222
+ };
223
+ }
224
+ function defineConfig(options) {
225
+ const { dtsx: dtsxOptions, ...tsupOptions } = options;
226
+ if (dtsxOptions) {
227
+ return {
228
+ ...tsupOptions,
229
+ dts: false,
230
+ plugins: [
231
+ ...tsupOptions.plugins || [],
232
+ dtsxPlugin(dtsxOptions)
233
+ ]
234
+ };
235
+ }
236
+ return tsupOptions;
237
+ }
238
+ var src_default = dtsxPlugin;
239
+ export {
240
+ dtsxPlugin,
241
+ defineConfig,
242
+ src_default as default,
243
+ createTsupConfig
244
+ };
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "tsup-plugin-dtsx",
3
+ "type": "module",
4
+ "version": "0.9.10",
5
+ "description": "A tsup plugin that auto generates your DTS types extremely fast.",
6
+ "author": "Chris Breuer <chris@ow3.org>",
7
+ "license": "MIT",
8
+ "homepage": "https://github.com/stacksjs/dtsx/tree/main/packages/tsup-plugin#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/stacksjs/dtsx.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/stacksjs/dtsx/issues"
15
+ },
16
+ "keywords": [
17
+ "dts",
18
+ "dtsx",
19
+ "emit",
20
+ "generation",
21
+ "typescript",
22
+ "types",
23
+ "auto",
24
+ "stacks",
25
+ "tsup",
26
+ "plugin",
27
+ "package"
28
+ ],
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js"
33
+ },
34
+ "./*": {
35
+ "import": "./dist/*"
36
+ }
37
+ },
38
+ "module": "./dist/index.js",
39
+ "types": "./dist/index.d.ts",
40
+ "files": [
41
+ "LICENSE.md",
42
+ "README.md",
43
+ "dist"
44
+ ],
45
+ "scripts": {
46
+ "build": "bun build.ts",
47
+ "prepublishOnly": "bun run build",
48
+ "test": "bun test",
49
+ "typecheck": "bun tsc --noEmit"
50
+ },
51
+ "dependencies": {
52
+ "@stacksjs/dtsx": "0.9.10"
53
+ },
54
+ "peerDependencies": {
55
+ "tsup": "^8.5.1"
56
+ }
57
+ }