@dtsx/tsup 0.0.0-stage → 0.11.39

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 CHANGED
@@ -1,3 +1,236 @@
1
- # Temporary Holding Version
1
+ # @dtsx/tsup
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A tsup plugin for automatic TypeScript declaration file generation using dtsx.
4
+
5
+ ## Supported tsup versions
6
+
7
+ The plugin supports tsup `>=8.3.6 <8.5.1` and requires `@swc/core` as a peer.
8
+ These dependencies are checked together in strict consumers of the normally
9
+ packed plugin. tsup 8.5.1 and 9.0.0 publish declarations that import a missing
10
+ `./types.cts` file; this range avoids advertising a broken SDK contract.
11
+ The SWC peer supplies the types referenced by tsup 8.5.0's public declarations.
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ bun add @dtsx/tsup -d
17
+ # or
18
+ npm install @dtsx/tsup --save-dev
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ### Basic Usage
24
+
25
+ ```typescript
26
+ // tsup.config.ts
27
+ import { defineConfig } from 'tsup'
28
+ import { dtsxPlugin } from '@dtsx/tsup'
29
+
30
+ export default defineConfig({
31
+ entry: ['src/index.ts'],
32
+ format: ['esm', 'cjs'],
33
+ dts: false, // Disable tsup's dts, use dtsx instead
34
+ plugins: [
35
+ dtsxPlugin(),
36
+ ],
37
+ })
38
+ ```
39
+
40
+ ### Using the Helper
41
+
42
+ ```typescript
43
+ // tsup.config.ts
44
+ import { defineConfig } from '@dtsx/tsup'
45
+
46
+ export default defineConfig({
47
+ entry: ['src/index.ts'],
48
+ format: ['esm', 'cjs'],
49
+ dtsx: {
50
+ // dtsx options
51
+ bundle: true,
52
+ },
53
+ })
54
+ ```
55
+
56
+ ### Quick Config
57
+
58
+ ```typescript
59
+ // tsup.config.ts
60
+ import { createTsupConfig } from '@dtsx/tsup'
61
+
62
+ export default createTsupConfig('src/index.ts', {
63
+ bundle: true,
64
+ bundleOutput: 'types.d.ts',
65
+ })
66
+ ```
67
+
68
+ ## Options
69
+
70
+ | Option | Type | Default | Description |
71
+ |--------|------|---------|-------------|
72
+ | `trigger` | `'buildStart' \| 'buildEnd'` | `'buildEnd'` | When to generate declarations |
73
+ | `entryPointsOnly` | `boolean` | `true` | Only generate for entry points |
74
+ | `declarationDir` | `string` | tsup outDir | Output directory for declarations |
75
+ | `bundle` | `boolean` | `false` | Bundle all declarations into one file |
76
+ | `bundleOutput` | `string` | `'index.d.ts'` | Bundled output filename |
77
+ | `exclude` | `(string \| RegExp)[]` | `[]` | Patterns to exclude |
78
+ | `include` | `(string \| RegExp)[]` | `[]` | Patterns to include |
79
+ | `skipIfTsupDts` | `boolean` | `true` | Skip if tsup dts is enabled |
80
+
81
+ ## Examples
82
+
83
+ ### With Bundled Declarations
84
+
85
+ ```typescript
86
+ // tsup.config.ts
87
+ import { defineConfig } from 'tsup'
88
+ import { dtsxPlugin } from '@dtsx/tsup'
89
+
90
+ export default defineConfig({
91
+ entry: ['src/index.ts'],
92
+ format: ['esm', 'cjs'],
93
+ dts: false,
94
+ plugins: [
95
+ dtsxPlugin({
96
+ bundle: true,
97
+ bundleOutput: 'types.d.ts',
98
+ }),
99
+ ],
100
+ })
101
+ ```
102
+
103
+ ### Multiple Entry Points
104
+
105
+ ```typescript
106
+ // tsup.config.ts
107
+ import { defineConfig } from 'tsup'
108
+ import { dtsxPlugin } from '@dtsx/tsup'
109
+
110
+ export default defineConfig({
111
+ entry: {
112
+ index: 'src/index.ts',
113
+ utils: 'src/utils.ts',
114
+ types: 'src/types.ts',
115
+ },
116
+ format: ['esm', 'cjs'],
117
+ dts: false,
118
+ plugins: [
119
+ dtsxPlugin({
120
+ entryPointsOnly: true,
121
+ }),
122
+ ],
123
+ })
124
+ ```
125
+
126
+ ### With Callbacks
127
+
128
+ ```typescript
129
+ // tsup.config.ts
130
+ import { defineConfig } from 'tsup'
131
+ import { dtsxPlugin } from '@dtsx/tsup'
132
+
133
+ export default defineConfig({
134
+ entry: ['src/index.ts'],
135
+ format: ['esm'],
136
+ dts: false,
137
+ plugins: [
138
+ dtsxPlugin({
139
+ onStart: () => {
140
+ console.log('Starting declaration generation...')
141
+ },
142
+ onSuccess: (stats) => {
143
+ console.log(`Generated ${stats.totalFiles} files in ${stats.totalTime}ms`)
144
+ },
145
+ onError: (error) => {
146
+ console.error('Failed:', error.message)
147
+ },
148
+ }),
149
+ ],
150
+ })
151
+ ```
152
+
153
+ ### Generate Before Build
154
+
155
+ ```typescript
156
+ // tsup.config.ts
157
+ import { defineConfig } from 'tsup'
158
+ import { dtsxPlugin } from '@dtsx/tsup'
159
+
160
+ export default defineConfig({
161
+ entry: ['src/index.ts'],
162
+ format: ['esm'],
163
+ dts: false,
164
+ plugins: [
165
+ dtsxPlugin({
166
+ trigger: 'buildStart', // Generate before build
167
+ }),
168
+ ],
169
+ })
170
+ ```
171
+
172
+ ### Filter Files
173
+
174
+ ```typescript
175
+ // tsup.config.ts
176
+ import { defineConfig } from 'tsup'
177
+ import { dtsxPlugin } from '@dtsx/tsup'
178
+
179
+ export default defineConfig({
180
+ entry: ['src/index.ts'],
181
+ format: ['esm'],
182
+ dts: false,
183
+ plugins: [
184
+ dtsxPlugin({
185
+ include: [/src\/lib/],
186
+ exclude: ['test', /\.spec\.ts$/],
187
+ }),
188
+ ],
189
+ })
190
+ ```
191
+
192
+ ### Custom Output Directory
193
+
194
+ ```typescript
195
+ // tsup.config.ts
196
+ import { defineConfig } from 'tsup'
197
+ import { dtsxPlugin } from '@dtsx/tsup'
198
+
199
+ export default defineConfig({
200
+ entry: ['src/index.ts'],
201
+ outDir: 'dist',
202
+ dts: false,
203
+ plugins: [
204
+ dtsxPlugin({
205
+ declarationDir: 'types', // Outputs to types/ instead of dist/
206
+ }),
207
+ ],
208
+ })
209
+ ```
210
+
211
+ ## Why Use dtsx Instead of tsup's Built-in dts
212
+
213
+ 1. **Faster**: dtsx is optimized for speed and can be significantly faster for large projects
214
+ 2. **More Options**: Bundling, filtering, callbacks, and more
215
+ 3. **Better Control**: Fine-grained control over declaration generation
216
+ 4. **Incremental Support**: Only regenerate changed files
217
+
218
+ ## Compatibility
219
+
220
+ - tsup 6.x, 7.x, 8.x
221
+ - Node.js 18+
222
+ - Bun 1.0+
223
+
224
+ ## TypeScript Configuration
225
+
226
+ The plugin automatically detects your `tsconfig.json`. You can also specify a custom path:
227
+
228
+ ```typescript
229
+ dtsxPlugin({
230
+ tsconfigPath: './tsconfig.build.json',
231
+ })
232
+ ```
233
+
234
+ ## License
235
+
236
+ MIT
@@ -0,0 +1,39 @@
1
+ import type { DtsGenerationOption, GenerationStats } from '@dtsx/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
+
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 { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, relative, resolve } from "node:path";
4
+ import { generate } from "@dtsx/dtsx";
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
+ createTsupConfig,
241
+ src_default as default,
242
+ defineConfig,
243
+ dtsxPlugin
244
+ };
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@dtsx/tsup",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "type": "module",
4
+ "version": "0.11.39",
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
+ "@dtsx/dtsx": "0.11.39"
53
+ },
54
+ "peerDependencies": {
55
+ "tsup": ">=8.3.6 <8.5.1",
56
+ "@swc/core": "^1.16.22"
57
+ }
58
+ }