@dtsx/bun 0.0.0-stage → 0.11.40

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,149 @@
1
- # Temporary Holding Version
1
+ # @dtsx/bun
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 Bun Bundler plugin for automatic TypeScript declaration file generation using dtsx.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ bun add @dtsx/bun -d
9
+ # or
10
+ npm install @dtsx/bun --save-dev
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```typescript
16
+ // build.ts
17
+ import { dts } from '@dtsx/bun'
18
+
19
+ await Bun.build({
20
+ entrypoints: ['src/index.ts'],
21
+ outdir: 'dist',
22
+ plugins: [
23
+ dts({
24
+ // Options
25
+ }),
26
+ ],
27
+ })
28
+ ```
29
+
30
+ ## Options
31
+
32
+ | Option | Type | Default | Description |
33
+ |--------|------|---------|-------------|
34
+ | `trigger` | `'build' \| 'watch' \| 'both'` | `'build'` | When to generate declarations |
35
+ | `entryPointsOnly` | `boolean` | `true` | Only generate for entry points |
36
+ | `declarationDir` | `string` | Bun outdir | Output directory for declarations |
37
+ | `bundle` | `boolean` | `false` | Bundle all declarations into one file |
38
+ | `bundleOutput` | `string` | `'index.d.ts'` | Bundled output filename |
39
+ | `exclude` | `(string \| RegExp)[]` | `[]` | Patterns to exclude |
40
+ | `include` | `(string \| RegExp)[]` | `[]` | Patterns to include |
41
+ | `emitOnError` | `boolean` | `true` | Emit even with type errors |
42
+
43
+ ## Examples
44
+
45
+ ### Basic Usage
46
+
47
+ ```typescript
48
+ import { dts } from '@dtsx/bun'
49
+
50
+ await Bun.build({
51
+ entrypoints: ['src/index.ts'],
52
+ outdir: 'dist',
53
+ plugins: [dts()],
54
+ })
55
+ ```
56
+
57
+ ### With Bundled Declarations
58
+
59
+ ```typescript
60
+ import { dts } from '@dtsx/bun'
61
+
62
+ await Bun.build({
63
+ entrypoints: ['src/index.ts'],
64
+ outdir: 'dist',
65
+ plugins: [
66
+ dts({
67
+ bundle: true,
68
+ bundleOutput: 'types.d.ts',
69
+ }),
70
+ ],
71
+ })
72
+ ```
73
+
74
+ ### Multiple Entry Points
75
+
76
+ ```typescript
77
+ import { dts } from '@dtsx/bun'
78
+
79
+ await Bun.build({
80
+ entrypoints: ['src/index.ts', 'src/utils.ts'],
81
+ outdir: 'dist',
82
+ plugins: [
83
+ dts({
84
+ entryPointsOnly: true,
85
+ }),
86
+ ],
87
+ })
88
+ ```
89
+
90
+ ### With Callbacks
91
+
92
+ ```typescript
93
+ import { dts } from '@dtsx/bun'
94
+
95
+ await Bun.build({
96
+ entrypoints: ['src/index.ts'],
97
+ outdir: 'dist',
98
+ plugins: [
99
+ dts({
100
+ onStart: () => {
101
+ console.log('Starting declaration generation...')
102
+ },
103
+ onSuccess: (stats) => {
104
+ console.log(`Generated ${stats.totalFiles} files in ${stats.totalTime}ms`)
105
+ },
106
+ onError: (error) => {
107
+ console.error('Failed to generate declarations:', error.message)
108
+ },
109
+ }),
110
+ ],
111
+ })
112
+ ```
113
+
114
+ ### Filter Files
115
+
116
+ ```typescript
117
+ import { dts } from '@dtsx/bun'
118
+
119
+ await Bun.build({
120
+ entrypoints: ['src/index.ts'],
121
+ outdir: 'dist',
122
+ plugins: [
123
+ dts({
124
+ include: [/src\/lib/],
125
+ exclude: ['test', /\.spec\.ts$/],
126
+ }),
127
+ ],
128
+ })
129
+ ```
130
+
131
+ ### Custom Output Directory
132
+
133
+ ```typescript
134
+ import { dts } from '@dtsx/bun'
135
+
136
+ await Bun.build({
137
+ entrypoints: ['src/index.ts'],
138
+ outdir: 'dist',
139
+ plugins: [
140
+ dts({
141
+ declarationDir: 'types',
142
+ }),
143
+ ],
144
+ })
145
+ ```
146
+
147
+ ## License
148
+
149
+ MIT
@@ -0,0 +1,94 @@
1
+ import type { BunPlugin } from 'bun';
2
+ import type { DtsGenerationOption, GenerationStats } from '@dtsx/dtsx';
3
+ export type { DtsGenerationOption, GenerationStats };
4
+ /**
5
+ * Creates a Bun plugin for generating TypeScript declaration files
6
+ * @param options - Configuration options for DTS generation
7
+ * @returns BunPlugin instance
8
+ */
9
+ export declare function dts(options?: PluginConfig): BunPlugin;
10
+ /**
11
+ * Create a watch mode plugin that regenerates on file changes
12
+ */
13
+ export declare function dtsWatch(options?: PluginConfig): BunPlugin;
14
+ /**
15
+ * Create a plugin that only validates types without generating
16
+ */
17
+ export declare function dtsCheck(options: Omit<PluginConfig, 'outdir'>): BunPlugin;
18
+ /**
19
+ * Clear the incremental cache
20
+ */
21
+ export declare function clearCache(cacheDir?: string): void;
22
+ /**
23
+ * Error codes for categorizing plugin errors
24
+ */
25
+ export declare const PluginErrorCodes: {
26
+ readonly CONFIG_ERROR: 'CONFIG_ERROR';
27
+ readonly GENERATION_ERROR: 'GENERATION_ERROR';
28
+ readonly FILE_ERROR: 'FILE_ERROR';
29
+ readonly CACHE_ERROR: 'CACHE_ERROR';
30
+ readonly TIMEOUT_ERROR: 'TIMEOUT_ERROR'
31
+ };
32
+ /**
33
+ * Build event payload
34
+ */
35
+ export declare interface BuildEvent {
36
+ type: BuildEventType
37
+ timestamp: number
38
+ data: BuildEventData
39
+ }
40
+ /**
41
+ * Configuration interface extending DtsGenerationOption with build-specific properties
42
+ */
43
+ export declare interface PluginConfig extends DtsGenerationOption {
44
+ build?: {
45
+ config: {
46
+ root?: string
47
+ outdir?: string
48
+ entrypoints?: string[]
49
+ target?: 'bun' | 'browser' | 'node'
50
+ }
51
+ }
52
+ onSuccess?: (stats: GenerationStats) => void | Promise<void>
53
+ onError?: (error: DtsxPluginError) => void | Promise<void>
54
+ failOnError?: boolean
55
+ incremental?: boolean
56
+ cacheDir?: string
57
+ on?: Partial<Record<BuildEventType, BuildEventListener>>
58
+ timeout?: number
59
+ continueOnError?: boolean
60
+ verbose?: boolean
61
+ }
62
+ export type PluginErrorCode = typeof PluginErrorCodes[keyof typeof PluginErrorCodes];
63
+ /**
64
+ * Build event types
65
+ */
66
+ export type BuildEventType = 'start' | 'progress' | 'file' | 'complete' | 'error';
67
+ export type BuildEventData = | { type: 'start', files: string[], config: DtsGenerationOption }
68
+ | { type: 'progress', processed: number, total: number, currentFile: string }
69
+ | { type: 'file', file: string, outputFile: string, duration: number, cached: boolean }
70
+ | { type: 'complete', stats: GenerationStats, duration: number, fromCache: number }
71
+ | { type: 'error', error: DtsxPluginError, file?: string }
72
+ /**
73
+ * Event listener function
74
+ */
75
+ export type BuildEventListener = (_event: BuildEvent) => void | Promise<void>;
76
+ /**
77
+ * Custom error class for bun-plugin-dtsx
78
+ */
79
+ export declare class DtsxPluginError extends Error {
80
+ readonly code: PluginErrorCode;
81
+ readonly context?: Record<string, unknown>;
82
+ readonly cause?: Error;
83
+ constructor(message: string, code: PluginErrorCode, context?: Record<string, unknown>, cause?: Error);
84
+ toJSON(): Record<string, unknown>;
85
+ }
86
+ /**
87
+ * Event emitter for build events
88
+ */
89
+ declare class BuildEventEmitter {
90
+ private listeners;
91
+ on(type: BuildEventType, listener: BuildEventListener): void;
92
+ emit(type: BuildEventType, data: BuildEventData): Promise<void>;
93
+ }
94
+ export default dts;
package/dist/index.js ADDED
@@ -0,0 +1,267 @@
1
+ // @bun
2
+ // src/index.ts
3
+ import process from "process";
4
+ import { dirname, relative, resolve, sep } from "path";
5
+ import { clearBuildCache } from "@dtsx/dtsx/cache";
6
+ import { generate } from "@dtsx/dtsx/generator";
7
+ var PluginErrorCodes = {
8
+ CONFIG_ERROR: "CONFIG_ERROR",
9
+ GENERATION_ERROR: "GENERATION_ERROR",
10
+ FILE_ERROR: "FILE_ERROR",
11
+ CACHE_ERROR: "CACHE_ERROR",
12
+ TIMEOUT_ERROR: "TIMEOUT_ERROR"
13
+ };
14
+
15
+ class DtsxPluginError extends Error {
16
+ code;
17
+ context;
18
+ cause;
19
+ constructor(message, code, context, cause) {
20
+ super(message);
21
+ this.name = "DtsxPluginError";
22
+ this.code = code;
23
+ this.context = context;
24
+ this.cause = cause;
25
+ if (Error.captureStackTrace) {
26
+ Error.captureStackTrace(this, this.constructor);
27
+ }
28
+ }
29
+ toJSON() {
30
+ return {
31
+ name: this.name,
32
+ code: this.code,
33
+ message: this.message,
34
+ context: this.context,
35
+ stack: this.stack
36
+ };
37
+ }
38
+ }
39
+
40
+ class BuildEventEmitter {
41
+ listeners = new Map;
42
+ on(type, listener) {
43
+ const existing = this.listeners.get(type) || [];
44
+ existing.push(listener);
45
+ this.listeners.set(type, existing);
46
+ }
47
+ async emit(type, data) {
48
+ const event = {
49
+ type,
50
+ timestamp: Date.now(),
51
+ data
52
+ };
53
+ const listeners = this.listeners.get(type) || [];
54
+ for (const listener of listeners) {
55
+ await listener(event);
56
+ }
57
+ }
58
+ }
59
+ var cleanedOutdirs = new Set;
60
+ function dts(options = {}) {
61
+ const {
62
+ onSuccess,
63
+ onError,
64
+ failOnError = true,
65
+ incremental = false,
66
+ cacheDir = ".dtsx-cache",
67
+ on,
68
+ timeout = 60000,
69
+ continueOnError = false,
70
+ verbose = false,
71
+ ...dtsOptions
72
+ } = options;
73
+ const emitter = new BuildEventEmitter;
74
+ if (on) {
75
+ for (const [type, listener] of Object.entries(on)) {
76
+ if (listener) {
77
+ emitter.on(type, listener);
78
+ }
79
+ }
80
+ }
81
+ return {
82
+ name: "bun-plugin-dtsx",
83
+ async setup(build) {
84
+ const startTime = Date.now();
85
+ try {
86
+ const config = normalizeConfig({ ...dtsOptions, incremental, cacheDir }, build);
87
+ if (config.clean) {
88
+ const outdirPath = resolve(config.cwd ?? process.cwd(), config.outdir ?? "./dist");
89
+ if (cleanedOutdirs.has(outdirPath)) {
90
+ config.clean = false;
91
+ } else {
92
+ cleanedOutdirs.add(outdirPath);
93
+ }
94
+ }
95
+ await emitter.emit("start", {
96
+ type: "start",
97
+ files: config.entrypoints || [],
98
+ config
99
+ });
100
+ if (verbose) {
101
+ console.log("[bun-plugin-dtsx] Starting declaration generation...");
102
+ if (incremental) {
103
+ console.log("[bun-plugin-dtsx] Incremental mode enabled");
104
+ }
105
+ }
106
+ const generateWithTimeout = async () => {
107
+ return new Promise((resolvePromise, rejectPromise) => {
108
+ const timeoutId = setTimeout(() => {
109
+ rejectPromise(new DtsxPluginError(`Generation timed out after ${timeout}ms`, "TIMEOUT_ERROR", { timeout }));
110
+ }, timeout);
111
+ generate(config).then((stats) => {
112
+ clearTimeout(timeoutId);
113
+ resolvePromise(stats);
114
+ }).catch((err) => {
115
+ clearTimeout(timeoutId);
116
+ rejectPromise(err);
117
+ });
118
+ });
119
+ };
120
+ const stats = await generateWithTimeout();
121
+ const duration = Date.now() - startTime;
122
+ const fromCache = Math.max(0, stats.filesProcessed - stats.filesGenerated - stats.filesFailed);
123
+ await emitter.emit("complete", {
124
+ type: "complete",
125
+ stats,
126
+ duration,
127
+ fromCache
128
+ });
129
+ if (verbose) {
130
+ console.log(`[bun-plugin-dtsx] Generation complete in ${duration}ms`);
131
+ if (fromCache > 0) {
132
+ console.log(`[bun-plugin-dtsx] ${fromCache} files served from cache`);
133
+ }
134
+ }
135
+ if (onSuccess) {
136
+ await onSuccess(stats);
137
+ }
138
+ } catch (error) {
139
+ const pluginError = wrapError(error);
140
+ await emitter.emit("error", {
141
+ type: "error",
142
+ error: pluginError
143
+ });
144
+ if (onError) {
145
+ await onError(pluginError);
146
+ } else {
147
+ console.error("[bun-plugin-dtsx] Error generating declarations:");
148
+ console.error(` Code: ${pluginError.code}`);
149
+ console.error(` Message: ${pluginError.message}`);
150
+ if (pluginError.context) {
151
+ console.error(` Context: ${JSON.stringify(pluginError.context)}`);
152
+ }
153
+ if (verbose && pluginError.stack) {
154
+ console.error(` Stack: ${pluginError.stack}`);
155
+ }
156
+ }
157
+ if (failOnError && !continueOnError) {
158
+ throw pluginError;
159
+ }
160
+ }
161
+ }
162
+ };
163
+ }
164
+ function wrapError(error) {
165
+ if (error instanceof DtsxPluginError) {
166
+ return error;
167
+ }
168
+ if (error instanceof Error) {
169
+ let code = "GENERATION_ERROR";
170
+ if (error.message.includes("config") || error.message.includes("Config")) {
171
+ code = "CONFIG_ERROR";
172
+ } else if (error.message.includes("file") || error.message.includes("File") || error.message.includes("ENOENT")) {
173
+ code = "FILE_ERROR";
174
+ }
175
+ return new DtsxPluginError(error.message, code, { originalError: error.name }, error);
176
+ }
177
+ return new DtsxPluginError(String(error), "GENERATION_ERROR");
178
+ }
179
+ function commonParentDir(paths) {
180
+ const dirs = paths.map((p) => dirname(p).split(sep));
181
+ let common = dirs[0];
182
+ for (const parts of dirs.slice(1)) {
183
+ let i = 0;
184
+ while (i < common.length && i < parts.length && common[i] === parts[i])
185
+ i++;
186
+ common = common.slice(0, i);
187
+ }
188
+ return common.join(sep) || sep;
189
+ }
190
+ function normalizeConfig(options, build) {
191
+ const cwd = options.cwd || process.cwd();
192
+ const bunEntrypoints = build?.config?.entrypoints;
193
+ const outdir = options.outdir || options.build?.config.outdir || build?.config.outdir || "./dist";
194
+ let root = options.root || options.build?.config.root || build?.config.root;
195
+ if (!root && bunEntrypoints?.length) {
196
+ const ancestor = commonParentDir(bunEntrypoints.map((ep) => resolve(cwd, ep)));
197
+ root = relative(cwd, ancestor) || ".";
198
+ }
199
+ root = root || "./src";
200
+ let entrypoints = options.entrypoints;
201
+ if (!entrypoints) {
202
+ if (bunEntrypoints?.length) {
203
+ const resolvedRoot = resolve(cwd, root);
204
+ const inside = [];
205
+ for (const ep of bunEntrypoints) {
206
+ const resolved = resolve(cwd, ep);
207
+ if (resolved === resolvedRoot || resolved.startsWith(resolvedRoot + sep)) {
208
+ inside.push(relative(resolvedRoot, resolved));
209
+ } else {
210
+ console.warn(`[bun-plugin-dtsx] Skipping entrypoint outside root "${root}": ${ep}`);
211
+ }
212
+ }
213
+ entrypoints = inside.length ? inside : ["index.ts"];
214
+ } else {
215
+ entrypoints = ["index.ts"];
216
+ }
217
+ }
218
+ return {
219
+ ...options,
220
+ cwd,
221
+ root,
222
+ entrypoints,
223
+ outdir,
224
+ clean: options.clean ?? true,
225
+ tsconfigPath: options.tsconfigPath,
226
+ moduleSpecifierMode: options.moduleSpecifierMode ?? ((build?.config.target ?? options.build?.config.target) === "node" ? "node" : "preserve")
227
+ };
228
+ }
229
+ function dtsWatch(options = {}) {
230
+ return dts({
231
+ ...options,
232
+ incremental: true,
233
+ verbose: options.verbose ?? true
234
+ });
235
+ }
236
+ function dtsCheck(options) {
237
+ return {
238
+ name: "bun-plugin-dtsx-check",
239
+ async setup(build) {
240
+ const config = normalizeConfig({ ...options, outdir: "" }, build);
241
+ try {
242
+ await generate({ ...config, clean: false });
243
+ } catch (error) {
244
+ const pluginError = wrapError(error);
245
+ if (options.onError) {
246
+ await options.onError(pluginError);
247
+ }
248
+ if (options.failOnError !== false) {
249
+ throw pluginError;
250
+ }
251
+ }
252
+ }
253
+ };
254
+ }
255
+ function clearCache(cacheDir = ".dtsx-cache") {
256
+ clearBuildCache(resolve(cacheDir));
257
+ }
258
+ var src_default = dts;
259
+ export {
260
+ DtsxPluginError,
261
+ PluginErrorCodes,
262
+ clearCache,
263
+ src_default as default,
264
+ dts,
265
+ dtsCheck,
266
+ dtsWatch
267
+ };
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@dtsx/bun",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "type": "module",
4
+ "sideEffects": false,
5
+ "version": "0.11.40",
6
+ "description": "A Bun Bundler plugin that auto generates your DTS types extremely fast.",
7
+ "author": "Chris Breuer <chris@ow3.org>",
8
+ "license": "MIT",
9
+ "homepage": "https://github.com/stacksjs/dtsx/tree/main/packages/bun-plugin#readme",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/stacksjs/dtsx.git"
13
+ },
14
+ "bugs": {
15
+ "url": "https://github.com/stacksjs/dtsx/issues"
16
+ },
17
+ "keywords": [
18
+ "dts",
19
+ "dtsx",
20
+ "emit",
21
+ "generation",
22
+ "typescript",
23
+ "types",
24
+ "auto",
25
+ "stacks",
26
+ "bun",
27
+ "plugin",
28
+ "package"
29
+ ],
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js"
34
+ },
35
+ "./*": {
36
+ "import": "./dist/*"
37
+ }
38
+ },
39
+ "module": "./dist/index.js",
40
+ "types": "./dist/index.d.ts",
41
+ "files": [
42
+ "LICENSE.md",
43
+ "README.md",
44
+ "dist"
45
+ ],
46
+ "scripts": {
47
+ "build": "bun build.ts",
48
+ "prepublishOnly": "bun run build",
49
+ "test": "bun test",
50
+ "typecheck": "bun tsc --noEmit",
51
+ "lint": "bun x --bun pickier .",
52
+ "lint:fix": "bun x --bun pickier . --fix"
53
+ },
54
+ "dependencies": {
55
+ "@dtsx/dtsx": "0.11.40"
56
+ }
57
+ }