@kubb/cli 5.0.0-beta.5 → 5.0.0-beta.51
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 +17 -10
- package/README.md +171 -51
- package/dist/Telemetry-BG80bcoQ.cjs +350 -0
- package/dist/Telemetry-BG80bcoQ.cjs.map +1 -0
- package/dist/Telemetry-CyBqvgcj.js +313 -0
- package/dist/Telemetry-CyBqvgcj.js.map +1 -0
- package/dist/{define-Bdn8j5VM.cjs → define-C4AB3POr.cjs} +2 -2
- package/dist/{define-Bdn8j5VM.cjs.map → define-C4AB3POr.cjs.map} +1 -1
- package/dist/{define-Ctii4bel.js → define-C63T4jp6.js} +2 -2
- package/dist/{define-Ctii4bel.js.map → define-C63T4jp6.js.map} +1 -1
- package/dist/{errors-CjPmyZHy.js → errors-BsemQCMn.js} +2 -2
- package/dist/{errors-CjPmyZHy.js.map → errors-BsemQCMn.js.map} +1 -1
- package/dist/{errors-CLCjoSg0.cjs → errors-DykI11xo.cjs} +2 -2
- package/dist/{errors-CLCjoSg0.cjs.map → errors-DykI11xo.cjs.map} +1 -1
- package/dist/generate-BRpukupe.cjs +82 -0
- package/dist/generate-BRpukupe.cjs.map +1 -0
- package/dist/generate-XeCSLYWp.js +83 -0
- package/dist/generate-XeCSLYWp.js.map +1 -0
- package/dist/index.cjs +22 -16
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +21 -15
- package/dist/index.js.map +1 -1
- package/dist/init-C156kkn3.cjs +53 -0
- package/dist/init-C156kkn3.cjs.map +1 -0
- package/dist/init-Djx-xXm2.js +53 -0
- package/dist/init-Djx-xXm2.js.map +1 -0
- package/dist/mcp--t_K4yMF.js +39 -0
- package/dist/mcp--t_K4yMF.js.map +1 -0
- package/dist/mcp-D4ZwcNDD.cjs +39 -0
- package/dist/mcp-D4ZwcNDD.cjs.map +1 -0
- package/dist/package-_PDiS5qW.js +6 -0
- package/dist/package-_PDiS5qW.js.map +1 -0
- package/dist/{package-BmYRU2hz.cjs → package-aN3cIOkh.cjs} +2 -2
- package/dist/package-aN3cIOkh.cjs.map +1 -0
- package/dist/run-7yQQ3lIR.js +51 -0
- package/dist/run-7yQQ3lIR.js.map +1 -0
- package/dist/{init-C5sZulT6.cjs → run-BtjzfTz3.cjs} +155 -85
- package/dist/run-BtjzfTz3.cjs.map +1 -0
- package/dist/{init-Cag3082g.js → run-C-omuksC.js} +147 -77
- package/dist/run-C-omuksC.js.map +1 -0
- package/dist/run-CDs_ebOt.cjs +1458 -0
- package/dist/run-CDs_ebOt.cjs.map +1 -0
- package/dist/run-CZEf3B3A.cjs +33 -0
- package/dist/run-CZEf3B3A.cjs.map +1 -0
- package/dist/run-CsBW0NRp.js +32 -0
- package/dist/run-CsBW0NRp.js.map +1 -0
- package/dist/run-YYlwMdeu.cjs +52 -0
- package/dist/run-YYlwMdeu.cjs.map +1 -0
- package/dist/run-aODbKkaY.js +1455 -0
- package/dist/run-aODbKkaY.js.map +1 -0
- package/dist/{shell-DLzN4fRo.js → shell-DsgkfUSW.js} +2 -2
- package/dist/{shell-DLzN4fRo.js.map → shell-DsgkfUSW.js.map} +1 -1
- package/dist/{shell-475fQKaX.cjs → shell-Lh-vLWwH.cjs} +2 -2
- package/dist/{shell-475fQKaX.cjs.map → shell-Lh-vLWwH.cjs.map} +1 -1
- package/dist/validate-DWdTJLGF.js +26 -0
- package/dist/validate-DWdTJLGF.js.map +1 -0
- package/dist/validate-sOD68Kma.cjs +26 -0
- package/dist/validate-sOD68Kma.cjs.map +1 -0
- package/package.json +14 -24
- package/src/Telemetry.ts +290 -0
- package/src/commands/generate.ts +27 -13
- package/src/commands/init.ts +34 -3
- package/src/commands/mcp.ts +28 -4
- package/src/commands/validate.ts +6 -4
- package/src/constants.ts +1 -81
- package/src/index.ts +7 -6
- package/src/loggers/clackLogger.ts +135 -201
- package/src/loggers/defineLogger.ts +59 -0
- package/src/loggers/plainLogger.ts +47 -102
- package/src/loggers/types.ts +6 -1
- package/src/loggers/utils.ts +164 -23
- package/src/runners/generate/run.ts +403 -0
- package/src/runners/generate/utils.ts +228 -0
- package/src/runners/init/run.ts +210 -0
- package/src/{utils/packageManager.ts → runners/init/utils.ts} +12 -2
- package/src/runners/mcp/run.ts +37 -0
- package/src/runners/validate/run.ts +63 -0
- package/dist/agent-BcUEl9yB.js +0 -56
- package/dist/agent-BcUEl9yB.js.map +0 -1
- package/dist/agent-CS45W0kL.cjs +0 -122
- package/dist/agent-CS45W0kL.cjs.map +0 -1
- package/dist/agent-CsMvXeqI.cjs +0 -58
- package/dist/agent-CsMvXeqI.cjs.map +0 -1
- package/dist/agent-IP0eLV3C.js +0 -118
- package/dist/agent-IP0eLV3C.js.map +0 -1
- package/dist/constants-B4iBDvCe.cjs +0 -148
- package/dist/constants-B4iBDvCe.cjs.map +0 -1
- package/dist/constants-DmPrkaz8.js +0 -95
- package/dist/constants-DmPrkaz8.js.map +0 -1
- package/dist/generate-7td_hs73.cjs +0 -65
- package/dist/generate-7td_hs73.cjs.map +0 -1
- package/dist/generate-BqeFFQGD.js +0 -66
- package/dist/generate-BqeFFQGD.js.map +0 -1
- package/dist/generate-CUd1dUY5.cjs +0 -1755
- package/dist/generate-CUd1dUY5.cjs.map +0 -1
- package/dist/generate-DVmGtwWe.js +0 -1752
- package/dist/generate-DVmGtwWe.js.map +0 -1
- package/dist/init-C5sZulT6.cjs.map +0 -1
- package/dist/init-Cag3082g.js.map +0 -1
- package/dist/init-CfAn19gC.js +0 -25
- package/dist/init-CfAn19gC.js.map +0 -1
- package/dist/init-CfsYoyGe.cjs +0 -25
- package/dist/init-CfsYoyGe.cjs.map +0 -1
- package/dist/mcp-BfORW-mY.cjs +0 -47
- package/dist/mcp-BfORW-mY.cjs.map +0 -1
- package/dist/mcp-BtOV6acy.js +0 -16
- package/dist/mcp-BtOV6acy.js.map +0 -1
- package/dist/mcp-CIbuLGMx.cjs +0 -16
- package/dist/mcp-CIbuLGMx.cjs.map +0 -1
- package/dist/mcp-DtQ5o0On.js +0 -46
- package/dist/mcp-DtQ5o0On.js.map +0 -1
- package/dist/package-BmYRU2hz.cjs.map +0 -1
- package/dist/package-DBU5ii-k.js +0 -6
- package/dist/package-DBU5ii-k.js.map +0 -1
- package/dist/telemetry-BU25EoI-.cjs +0 -282
- package/dist/telemetry-BU25EoI-.cjs.map +0 -1
- package/dist/telemetry-CaNU4-Bf.js +0 -245
- package/dist/telemetry-CaNU4-Bf.js.map +0 -1
- package/dist/validate-CQqM9siF.js +0 -25
- package/dist/validate-CQqM9siF.js.map +0 -1
- package/dist/validate-DBXLaLIn.cjs +0 -34
- package/dist/validate-DBXLaLIn.cjs.map +0 -1
- package/dist/validate-DI23zgmL.js +0 -33
- package/dist/validate-DI23zgmL.js.map +0 -1
- package/dist/validate-DwX4LzYq.cjs +0 -25
- package/dist/validate-DwX4LzYq.cjs.map +0 -1
- package/src/commands/agent/start.ts +0 -47
- package/src/commands/agent.ts +0 -8
- package/src/loggers/fileSystemLogger.ts +0 -138
- package/src/loggers/githubActionsLogger.ts +0 -379
- package/src/runners/agent.ts +0 -155
- package/src/runners/generate.ts +0 -333
- package/src/runners/init.ts +0 -296
- package/src/runners/mcp.ts +0 -51
- package/src/runners/validate.ts +0 -39
- package/src/types.ts +0 -11
- package/src/utils/Writables.ts +0 -17
- package/src/utils/executeHooks.ts +0 -45
- package/src/utils/flags.ts +0 -9
- package/src/utils/getConfig.ts +0 -10
- package/src/utils/getCosmiConfig.ts +0 -75
- package/src/utils/getSummary.ts +0 -68
- package/src/utils/runHook.ts +0 -91
- package/src/utils/telemetry.ts +0 -273
- package/src/utils/watcher.ts +0 -19
- /package/dist/{chunk-ByKO4r7w.cjs → chunk-Bx3C2hgW.cjs} +0 -0
- /package/dist/{chunk--u3MIqq1.js → chunk-C0LytTxp.js} +0 -0
|
@@ -0,0 +1,1458 @@
|
|
|
1
|
+
const require_chunk = require("./chunk-Bx3C2hgW.cjs");
|
|
2
|
+
const require_errors = require("./errors-DykI11xo.cjs");
|
|
3
|
+
const require_Telemetry = require("./Telemetry-BG80bcoQ.cjs");
|
|
4
|
+
const require_shell = require("./shell-Lh-vLWwH.cjs");
|
|
5
|
+
const require_package = require("./package-aN3cIOkh.cjs");
|
|
6
|
+
let node_util = require("node:util");
|
|
7
|
+
let node_events = require("node:events");
|
|
8
|
+
let node_crypto = require("node:crypto");
|
|
9
|
+
let node_child_process = require("node:child_process");
|
|
10
|
+
let node_fs = require("node:fs");
|
|
11
|
+
let node_path = require("node:path");
|
|
12
|
+
node_path = require_chunk.__toESM(node_path, 1);
|
|
13
|
+
let node_process = require("node:process");
|
|
14
|
+
node_process = require_chunk.__toESM(node_process, 1);
|
|
15
|
+
let _clack_prompts = require("@clack/prompts");
|
|
16
|
+
_clack_prompts = require_chunk.__toESM(_clack_prompts, 1);
|
|
17
|
+
let _kubb_core = require("@kubb/core");
|
|
18
|
+
let cosmiconfig = require("cosmiconfig");
|
|
19
|
+
let jiti = require("jiti");
|
|
20
|
+
let tinyexec = require("tinyexec");
|
|
21
|
+
//#region ../../internals/utils/src/asyncEventEmitter.ts
|
|
22
|
+
/**
|
|
23
|
+
* Typed `EventEmitter` that awaits all async listeners before resolving.
|
|
24
|
+
* Wraps Node's `EventEmitter` with full TypeScript event-map inference.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```ts
|
|
28
|
+
* const emitter = new AsyncEventEmitter<{ build: [name: string] }>()
|
|
29
|
+
* emitter.on('build', async (name) => { console.log(name) })
|
|
30
|
+
* await emitter.emit('build', 'petstore') // all listeners awaited
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
var AsyncEventEmitter = class {
|
|
34
|
+
/**
|
|
35
|
+
* Maximum number of listeners per event before Node emits a memory-leak warning.
|
|
36
|
+
* @default 10
|
|
37
|
+
*/
|
|
38
|
+
constructor(maxListener = 10) {
|
|
39
|
+
this.#emitter.setMaxListeners(maxListener);
|
|
40
|
+
}
|
|
41
|
+
#emitter = new node_events.EventEmitter();
|
|
42
|
+
/**
|
|
43
|
+
* Emits `eventName` and awaits all registered listeners sequentially.
|
|
44
|
+
* Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* ```ts
|
|
48
|
+
* await emitter.emit('build', 'petstore')
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
emit(eventName, ...eventArgs) {
|
|
52
|
+
const listeners = this.#emitter.listeners(eventName);
|
|
53
|
+
if (listeners.length === 0) return;
|
|
54
|
+
return this.#emitAll(eventName, listeners, eventArgs);
|
|
55
|
+
}
|
|
56
|
+
async #emitAll(eventName, listeners, eventArgs) {
|
|
57
|
+
for (const listener of listeners) try {
|
|
58
|
+
await listener(...eventArgs);
|
|
59
|
+
} catch (err) {
|
|
60
|
+
let serializedArgs;
|
|
61
|
+
try {
|
|
62
|
+
serializedArgs = JSON.stringify(eventArgs);
|
|
63
|
+
} catch {
|
|
64
|
+
serializedArgs = String(eventArgs);
|
|
65
|
+
}
|
|
66
|
+
throw new Error(`Error in async listener for "${eventName}" with eventArgs ${serializedArgs}`, { cause: require_errors.toError(err) });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Registers a persistent listener for `eventName`.
|
|
71
|
+
*
|
|
72
|
+
* @example
|
|
73
|
+
* ```ts
|
|
74
|
+
* emitter.on('build', async (name) => { console.log(name) })
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
77
|
+
on(eventName, handler) {
|
|
78
|
+
this.#emitter.on(eventName, handler);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Registers a one-shot listener that removes itself after the first invocation.
|
|
82
|
+
*
|
|
83
|
+
* @example
|
|
84
|
+
* ```ts
|
|
85
|
+
* emitter.onOnce('build', async (name) => { console.log(name) })
|
|
86
|
+
* ```
|
|
87
|
+
*/
|
|
88
|
+
onOnce(eventName, handler) {
|
|
89
|
+
const wrapper = (...args) => {
|
|
90
|
+
this.off(eventName, wrapper);
|
|
91
|
+
return handler(...args);
|
|
92
|
+
};
|
|
93
|
+
this.on(eventName, wrapper);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Removes a previously registered listener.
|
|
97
|
+
*
|
|
98
|
+
* @example
|
|
99
|
+
* ```ts
|
|
100
|
+
* emitter.off('build', handler)
|
|
101
|
+
* ```
|
|
102
|
+
*/
|
|
103
|
+
off(eventName, handler) {
|
|
104
|
+
this.#emitter.off(eventName, handler);
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Returns the number of listeners registered for `eventName`.
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```ts
|
|
111
|
+
* emitter.on('build', handler)
|
|
112
|
+
* emitter.listenerCount('build') // 1
|
|
113
|
+
* ```
|
|
114
|
+
*/
|
|
115
|
+
listenerCount(eventName) {
|
|
116
|
+
return this.#emitter.listenerCount(eventName);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Raises or lowers the per-event listener ceiling before Node warns about a memory leak.
|
|
120
|
+
* Set this above the expected listener count when many listeners attach by design.
|
|
121
|
+
*
|
|
122
|
+
* @example
|
|
123
|
+
* ```ts
|
|
124
|
+
* emitter.setMaxListeners(40)
|
|
125
|
+
* ```
|
|
126
|
+
*/
|
|
127
|
+
setMaxListeners(max) {
|
|
128
|
+
this.#emitter.setMaxListeners(max);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Returns the current per-event listener ceiling.
|
|
132
|
+
*/
|
|
133
|
+
getMaxListeners() {
|
|
134
|
+
return this.#emitter.getMaxListeners();
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Removes all listeners from every event channel.
|
|
138
|
+
*
|
|
139
|
+
* @example
|
|
140
|
+
* ```ts
|
|
141
|
+
* emitter.removeAll()
|
|
142
|
+
* ```
|
|
143
|
+
*/
|
|
144
|
+
removeAll() {
|
|
145
|
+
this.#emitter.removeAllListeners();
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
//#endregion
|
|
149
|
+
//#region ../../internals/utils/src/time.ts
|
|
150
|
+
/**
|
|
151
|
+
* Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.
|
|
152
|
+
* Rounds to 2 decimal places for sub-millisecond precision without noise.
|
|
153
|
+
*
|
|
154
|
+
* @example
|
|
155
|
+
* ```ts
|
|
156
|
+
* const start = process.hrtime()
|
|
157
|
+
* doWork()
|
|
158
|
+
* getElapsedMs(start) // 42.35
|
|
159
|
+
* ```
|
|
160
|
+
*/
|
|
161
|
+
function getElapsedMs(hrStart) {
|
|
162
|
+
const [seconds, nanoseconds] = process.hrtime(hrStart);
|
|
163
|
+
const ms = seconds * 1e3 + nanoseconds / 1e6;
|
|
164
|
+
return Math.round(ms * 100) / 100;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).
|
|
168
|
+
*
|
|
169
|
+
* @example
|
|
170
|
+
* ```ts
|
|
171
|
+
* formatMs(250) // '250ms'
|
|
172
|
+
* formatMs(1500) // '1.50s'
|
|
173
|
+
* formatMs(90000) // '1m 30.0s'
|
|
174
|
+
* ```
|
|
175
|
+
*/
|
|
176
|
+
function formatMs(ms) {
|
|
177
|
+
if (ms >= 6e4) return `${Math.floor(ms / 6e4)}m ${(ms % 6e4 / 1e3).toFixed(1)}s`;
|
|
178
|
+
if (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;
|
|
179
|
+
return `${Math.round(ms)}ms`;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Formats the elapsed time since `hrStart` as a human-readable string.
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* ```ts
|
|
186
|
+
* const start = process.hrtime()
|
|
187
|
+
* doWork()
|
|
188
|
+
* formatHrtime(start) // '1.50s'
|
|
189
|
+
* ```
|
|
190
|
+
*/
|
|
191
|
+
function formatHrtime(hrStart) {
|
|
192
|
+
return formatMs(getElapsedMs(hrStart));
|
|
193
|
+
}
|
|
194
|
+
//#endregion
|
|
195
|
+
//#region ../../internals/utils/src/colors.ts
|
|
196
|
+
/**
|
|
197
|
+
* Parses a CSS hex color string (`#RGB`) into its RGB channels.
|
|
198
|
+
* Falls back to `255` for any channel that cannot be parsed.
|
|
199
|
+
*/
|
|
200
|
+
function parseHex(color) {
|
|
201
|
+
const int = Number.parseInt(color.replace("#", ""), 16);
|
|
202
|
+
return Number.isNaN(int) ? {
|
|
203
|
+
r: 255,
|
|
204
|
+
g: 255,
|
|
205
|
+
b: 255
|
|
206
|
+
} : {
|
|
207
|
+
r: int >> 16 & 255,
|
|
208
|
+
g: int >> 8 & 255,
|
|
209
|
+
b: int & 255
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Returns a function that wraps a string in a 24-bit ANSI true-color escape sequence
|
|
214
|
+
* for the given hex color.
|
|
215
|
+
*/
|
|
216
|
+
function hex(color) {
|
|
217
|
+
const { r, g, b } = parseHex(color);
|
|
218
|
+
return (text) => `\x1b[38;2;${r};${g};${b}m${text}\x1b[0m`;
|
|
219
|
+
}
|
|
220
|
+
function gradient(colorStops, text) {
|
|
221
|
+
const chars = text.split("");
|
|
222
|
+
return chars.map((char, i) => {
|
|
223
|
+
const t = chars.length <= 1 ? 0 : i / (chars.length - 1);
|
|
224
|
+
const seg = Math.min(Math.floor(t * (colorStops.length - 1)), colorStops.length - 2);
|
|
225
|
+
const lt = t * (colorStops.length - 1) - seg;
|
|
226
|
+
const from = parseHex(colorStops[seg]);
|
|
227
|
+
const to = parseHex(colorStops[seg + 1]);
|
|
228
|
+
return `\x1b[38;2;${Math.round(from.r + (to.r - from.r) * lt)};${Math.round(from.g + (to.g - from.g) * lt)};${Math.round(from.b + (to.b - from.b) * lt)}m${char}\x1b[0m`;
|
|
229
|
+
}).join("");
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* ANSI color functions for each part of the Kubb mascot illustration.
|
|
233
|
+
*/
|
|
234
|
+
const palette = {
|
|
235
|
+
/**
|
|
236
|
+
* Top cap of the skittle.
|
|
237
|
+
*/
|
|
238
|
+
lid: hex("#F55A17"),
|
|
239
|
+
/**
|
|
240
|
+
* Upper wood body.
|
|
241
|
+
*/
|
|
242
|
+
woodTop: hex("#F5A217"),
|
|
243
|
+
/**
|
|
244
|
+
* Middle wood body.
|
|
245
|
+
*/
|
|
246
|
+
woodMid: hex("#F58517"),
|
|
247
|
+
/**
|
|
248
|
+
* Base wood body.
|
|
249
|
+
*/
|
|
250
|
+
woodBase: hex("#B45309"),
|
|
251
|
+
/**
|
|
252
|
+
* Eye whites.
|
|
253
|
+
*/
|
|
254
|
+
eye: hex("#FFFFFF"),
|
|
255
|
+
/**
|
|
256
|
+
* Highlight accent.
|
|
257
|
+
*/
|
|
258
|
+
highlight: hex("#adadc6"),
|
|
259
|
+
/**
|
|
260
|
+
* Cheek blush.
|
|
261
|
+
*/
|
|
262
|
+
blush: hex("#FDA4AF")
|
|
263
|
+
};
|
|
264
|
+
/**
|
|
265
|
+
* Generates the Kubb mascot welcome banner as an ANSI-colored string.
|
|
266
|
+
*
|
|
267
|
+
* @example
|
|
268
|
+
* ```ts
|
|
269
|
+
* console.log(getIntro({ title: 'kubb.config.ts', description: 'generating…', version: '5.0.0', areEyesOpen: true }))
|
|
270
|
+
* ```
|
|
271
|
+
*/
|
|
272
|
+
function getIntro({ title, description, version, areEyesOpen }) {
|
|
273
|
+
const kubbVersion = gradient([
|
|
274
|
+
"#F58517",
|
|
275
|
+
"#F5A217",
|
|
276
|
+
"#F55A17"
|
|
277
|
+
], `KUBB v${version}`);
|
|
278
|
+
const eyeTop = areEyesOpen ? palette.eye("█▀█") : palette.eye("───");
|
|
279
|
+
const eyeBottom = areEyesOpen ? palette.eye("▀▀▀") : palette.eye("───");
|
|
280
|
+
return `
|
|
281
|
+
${palette.lid("▄▄▄▄▄▄▄▄▄▄▄▄▄")}
|
|
282
|
+
${palette.woodTop("█ ")}${palette.highlight("▄▄")}${palette.woodTop(" ")}${palette.highlight("▄▄")}${palette.woodTop(" █")} ${kubbVersion}
|
|
283
|
+
${palette.woodMid("█ ")}${eyeTop}${palette.woodMid(" ")}${eyeTop}${palette.woodMid(" █")} ${(0, node_util.styleText)("gray", title)}
|
|
284
|
+
${palette.woodMid("█ ")}${eyeBottom}${palette.woodMid(" ")}${palette.blush("◡")}${palette.woodMid(" ")}${eyeBottom}${palette.woodMid(" █")} ${(0, node_util.styleText)("yellow", "➜")} ${(0, node_util.styleText)("white", description)}
|
|
285
|
+
${palette.woodBase("▀▀▀▀▀▀▀▀▀▀▀▀▀")}
|
|
286
|
+
`;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Formats a millisecond duration with a threshold-based ANSI color.
|
|
290
|
+
* `≤ 500 ms` → green · `≤ 1 000 ms` → yellow · `> 1 000 ms` → red.
|
|
291
|
+
*
|
|
292
|
+
* @example
|
|
293
|
+
* ```ts
|
|
294
|
+
* formatMsWithColor(200) // '\x1b[32m200ms\x1b[39m'
|
|
295
|
+
* formatMsWithColor(800) // '\x1b[33m800ms\x1b[39m'
|
|
296
|
+
* formatMsWithColor(1500) // '\x1b[31m1.50s\x1b[39m'
|
|
297
|
+
* ```
|
|
298
|
+
*/
|
|
299
|
+
function formatMsWithColor(ms) {
|
|
300
|
+
const formatted = formatMs(ms);
|
|
301
|
+
if (ms <= 500) return (0, node_util.styleText)("green", formatted);
|
|
302
|
+
if (ms <= 1e3) return (0, node_util.styleText)("yellow", formatted);
|
|
303
|
+
return (0, node_util.styleText)("red", formatted);
|
|
304
|
+
}
|
|
305
|
+
//#endregion
|
|
306
|
+
//#region ../../internals/utils/src/formatters.ts
|
|
307
|
+
/**
|
|
308
|
+
* CLI command descriptors for each supported code formatter.
|
|
309
|
+
*
|
|
310
|
+
* Each entry contains the executable `command`, an `args` factory that maps an
|
|
311
|
+
* output path to the correct argument list, and an `errorMessage` shown when
|
|
312
|
+
* the formatter is not found.
|
|
313
|
+
*/
|
|
314
|
+
const formatters = {
|
|
315
|
+
prettier: {
|
|
316
|
+
command: "prettier",
|
|
317
|
+
args: (outputPath) => [
|
|
318
|
+
"--ignore-unknown",
|
|
319
|
+
"--write",
|
|
320
|
+
outputPath
|
|
321
|
+
],
|
|
322
|
+
errorMessage: "Prettier not found"
|
|
323
|
+
},
|
|
324
|
+
biome: {
|
|
325
|
+
command: "biome",
|
|
326
|
+
args: (outputPath) => [
|
|
327
|
+
"format",
|
|
328
|
+
"--write",
|
|
329
|
+
outputPath
|
|
330
|
+
],
|
|
331
|
+
errorMessage: "Biome not found"
|
|
332
|
+
},
|
|
333
|
+
oxfmt: {
|
|
334
|
+
command: "oxfmt",
|
|
335
|
+
args: (outputPath) => [outputPath],
|
|
336
|
+
errorMessage: "Oxfmt not found"
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
async function isFormatterAvailable(formatter) {
|
|
340
|
+
return new Promise((resolve) => {
|
|
341
|
+
const child = (0, node_child_process.spawn)(formatter, ["--version"], { stdio: "ignore" });
|
|
342
|
+
child.on("close", (code) => resolve(code === 0));
|
|
343
|
+
child.on("error", () => resolve(false));
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Detects the first available code formatter on the current system.
|
|
348
|
+
*
|
|
349
|
+
* - Checks in preference order: `oxfmt`, `biome`, `prettier`.
|
|
350
|
+
* - Returns `null` when none are found.
|
|
351
|
+
*
|
|
352
|
+
* @example
|
|
353
|
+
* ```ts
|
|
354
|
+
* const formatter = await detectFormatter()
|
|
355
|
+
* if (formatter) {
|
|
356
|
+
* console.log(`Using ${formatter} for formatting`)
|
|
357
|
+
* }
|
|
358
|
+
* ```
|
|
359
|
+
*/
|
|
360
|
+
async function detectFormatter() {
|
|
361
|
+
const formatterNames = new Set([
|
|
362
|
+
"oxfmt",
|
|
363
|
+
"biome",
|
|
364
|
+
"prettier"
|
|
365
|
+
]);
|
|
366
|
+
for (const formatter of formatterNames) if (await isFormatterAvailable(formatter)) return formatter;
|
|
367
|
+
return null;
|
|
368
|
+
}
|
|
369
|
+
//#endregion
|
|
370
|
+
//#region ../../internals/utils/src/linters.ts
|
|
371
|
+
/**
|
|
372
|
+
* CLI command descriptors for each supported linter.
|
|
373
|
+
*
|
|
374
|
+
* Each entry contains the executable `command`, an `args` factory that maps an
|
|
375
|
+
* output path to the correct argument list, and an `errorMessage` shown when
|
|
376
|
+
* the linter is not found.
|
|
377
|
+
*/
|
|
378
|
+
const linters = {
|
|
379
|
+
eslint: {
|
|
380
|
+
command: "eslint",
|
|
381
|
+
args: (outputPath) => [outputPath, "--fix"],
|
|
382
|
+
errorMessage: "Eslint not found"
|
|
383
|
+
},
|
|
384
|
+
biome: {
|
|
385
|
+
command: "biome",
|
|
386
|
+
args: (outputPath) => [
|
|
387
|
+
"lint",
|
|
388
|
+
"--fix",
|
|
389
|
+
outputPath
|
|
390
|
+
],
|
|
391
|
+
errorMessage: "Biome not found"
|
|
392
|
+
},
|
|
393
|
+
oxlint: {
|
|
394
|
+
command: "oxlint",
|
|
395
|
+
args: (outputPath) => [
|
|
396
|
+
"--fix",
|
|
397
|
+
"--no-ignore",
|
|
398
|
+
outputPath
|
|
399
|
+
],
|
|
400
|
+
errorMessage: "Oxlint not found"
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
async function isLinterAvailable(linter) {
|
|
404
|
+
return new Promise((resolve) => {
|
|
405
|
+
const child = (0, node_child_process.spawn)(linter, ["--version"], { stdio: "ignore" });
|
|
406
|
+
child.on("close", (code) => resolve(code === 0));
|
|
407
|
+
child.on("error", () => resolve(false));
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Detects the first available linter on the current system.
|
|
412
|
+
*
|
|
413
|
+
* - Checks in preference order: `oxlint`, `biome`, `eslint`.
|
|
414
|
+
* - Returns `null` when none are found.
|
|
415
|
+
*
|
|
416
|
+
* @example
|
|
417
|
+
* ```ts
|
|
418
|
+
* const linter = await detectLinter()
|
|
419
|
+
* if (linter) {
|
|
420
|
+
* console.log(`Using ${linter} for linting`)
|
|
421
|
+
* }
|
|
422
|
+
* ```
|
|
423
|
+
*/
|
|
424
|
+
async function detectLinter() {
|
|
425
|
+
const linterNames = new Set([
|
|
426
|
+
"oxlint",
|
|
427
|
+
"biome",
|
|
428
|
+
"eslint"
|
|
429
|
+
]);
|
|
430
|
+
for (const linter of linterNames) if (await isLinterAvailable(linter)) return linter;
|
|
431
|
+
return null;
|
|
432
|
+
}
|
|
433
|
+
//#endregion
|
|
434
|
+
//#region src/loggers/defineLogger.ts
|
|
435
|
+
/**
|
|
436
|
+
* Defines a typed logger. The `install` method subscribes to lifecycle events
|
|
437
|
+
* on the shared emitter and forwards them to the logger's destination.
|
|
438
|
+
*
|
|
439
|
+
* @example
|
|
440
|
+
* ```ts
|
|
441
|
+
* import { defineLogger } from '@kubb/cli'
|
|
442
|
+
*
|
|
443
|
+
* export const myLogger = defineLogger({
|
|
444
|
+
* name: 'my-logger',
|
|
445
|
+
* install(context) {
|
|
446
|
+
* context.on('kubb:info', ({ message }) => console.log('ℹ', message))
|
|
447
|
+
* context.on('kubb:error', ({ error }) => console.error('✗', error.message))
|
|
448
|
+
* },
|
|
449
|
+
* })
|
|
450
|
+
* ```
|
|
451
|
+
*/
|
|
452
|
+
function defineLogger(logger) {
|
|
453
|
+
return logger;
|
|
454
|
+
}
|
|
455
|
+
//#endregion
|
|
456
|
+
//#region src/loggers/clackLogger.ts
|
|
457
|
+
/**
|
|
458
|
+
* TTY logger with beautiful UI and progress indicators for local development.
|
|
459
|
+
*/
|
|
460
|
+
const clackLogger = defineLogger({
|
|
461
|
+
name: "clack",
|
|
462
|
+
install(context, options) {
|
|
463
|
+
const logLevel = options?.logLevel ?? _kubb_core.logLevel.info;
|
|
464
|
+
const state = {
|
|
465
|
+
...createProgressCounters(),
|
|
466
|
+
spinner: _clack_prompts.spinner(),
|
|
467
|
+
isSpinning: false,
|
|
468
|
+
runningPlugins: /* @__PURE__ */ new Set(),
|
|
469
|
+
activeProgress: /* @__PURE__ */ new Map(),
|
|
470
|
+
activeHookLogs: /* @__PURE__ */ new Map()
|
|
471
|
+
};
|
|
472
|
+
function stopActiveProgress() {
|
|
473
|
+
for (const [, active] of state.activeProgress) {
|
|
474
|
+
if (active.interval) clearInterval(active.interval);
|
|
475
|
+
active.progressBar?.stop();
|
|
476
|
+
}
|
|
477
|
+
state.activeProgress.clear();
|
|
478
|
+
}
|
|
479
|
+
function reset() {
|
|
480
|
+
stopActiveProgress();
|
|
481
|
+
resetProgressCounters(state);
|
|
482
|
+
state.spinner = _clack_prompts.spinner();
|
|
483
|
+
state.isSpinning = false;
|
|
484
|
+
state.runningPlugins.clear();
|
|
485
|
+
state.activeHookLogs.clear();
|
|
486
|
+
}
|
|
487
|
+
function pluginProgressText() {
|
|
488
|
+
const running = [...state.runningPlugins].map((name) => (0, node_util.styleText)("bold", name));
|
|
489
|
+
return getMessage(running.length > 0 ? `Generating ${running.join(", ")}` : "Generating plugins");
|
|
490
|
+
}
|
|
491
|
+
function showProgressStep() {
|
|
492
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
493
|
+
const line = buildProgressLine(state);
|
|
494
|
+
if (line) _clack_prompts.log.step(getMessage(line));
|
|
495
|
+
}
|
|
496
|
+
function getMessage(message) {
|
|
497
|
+
return formatMessage(message, logLevel);
|
|
498
|
+
}
|
|
499
|
+
function onStep(event, message) {
|
|
500
|
+
context.on(event, () => {
|
|
501
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
502
|
+
_clack_prompts.log.step(getMessage(message));
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
function stopSpinner(text) {
|
|
506
|
+
if (!state.isSpinning) return;
|
|
507
|
+
state.spinner.stop(text);
|
|
508
|
+
state.isSpinning = false;
|
|
509
|
+
}
|
|
510
|
+
context.on("kubb:info", ({ message, info = "" }) => {
|
|
511
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
512
|
+
const text = getMessage([
|
|
513
|
+
(0, node_util.styleText)("blue", "ℹ"),
|
|
514
|
+
message,
|
|
515
|
+
info ? (0, node_util.styleText)("dim", info) : void 0
|
|
516
|
+
].filter(Boolean).join(" "));
|
|
517
|
+
if (state.isSpinning) {
|
|
518
|
+
state.spinner.message(text);
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
_clack_prompts.log.info(text);
|
|
522
|
+
});
|
|
523
|
+
context.on("kubb:success", ({ message, info = "" }) => {
|
|
524
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
525
|
+
const text = getMessage([
|
|
526
|
+
(0, node_util.styleText)("blue", "✓"),
|
|
527
|
+
message,
|
|
528
|
+
logLevel >= _kubb_core.logLevel.info ? (0, node_util.styleText)("dim", info) : void 0
|
|
529
|
+
].filter(Boolean).join(" "));
|
|
530
|
+
if (state.isSpinning) {
|
|
531
|
+
stopSpinner(text);
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
_clack_prompts.log.success(text);
|
|
535
|
+
});
|
|
536
|
+
context.on("kubb:warn", ({ message, info }) => {
|
|
537
|
+
if (logLevel < _kubb_core.logLevel.warn) return;
|
|
538
|
+
const text = getMessage([
|
|
539
|
+
(0, node_util.styleText)("yellow", "⚠"),
|
|
540
|
+
message,
|
|
541
|
+
logLevel >= _kubb_core.logLevel.info && info ? (0, node_util.styleText)("dim", info) : void 0
|
|
542
|
+
].filter(Boolean).join(" "));
|
|
543
|
+
_clack_prompts.log.warn(text);
|
|
544
|
+
});
|
|
545
|
+
context.on("kubb:error", ({ error }) => {
|
|
546
|
+
const caused = require_errors.toCause(error);
|
|
547
|
+
const text = [(0, node_util.styleText)("red", "✗"), error.message].join(" ");
|
|
548
|
+
if (state.isSpinning) {
|
|
549
|
+
stopSpinner(getMessage(text));
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
_clack_prompts.log.error(getMessage(text));
|
|
553
|
+
if (logLevel >= _kubb_core.logLevel.verbose && error.stack) {
|
|
554
|
+
const frames = error.stack.split("\n").slice(1, 4);
|
|
555
|
+
for (const frame of frames) _clack_prompts.log.message(getMessage((0, node_util.styleText)("dim", frame.trim())));
|
|
556
|
+
if (caused?.stack) {
|
|
557
|
+
_clack_prompts.log.message((0, node_util.styleText)("dim", `└─ caused by ${caused.message}`));
|
|
558
|
+
const frames = caused.stack.split("\n").slice(1, 4);
|
|
559
|
+
for (const frame of frames) _clack_prompts.log.message(getMessage(` ${(0, node_util.styleText)("dim", frame.trim())}`));
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
});
|
|
563
|
+
context.on("kubb:diagnostic", ({ diagnostic }) => {
|
|
564
|
+
if (logLevel <= _kubb_core.logLevel.silent && diagnostic.severity !== "error") return;
|
|
565
|
+
stopSpinner();
|
|
566
|
+
stopActiveProgress();
|
|
567
|
+
if (_kubb_core.Diagnostics.isUpdate(diagnostic)) {
|
|
568
|
+
_clack_prompts.box(`\`v${diagnostic.currentVersion}\` → \`v${diagnostic.latestVersion}\`
|
|
569
|
+
Run \`npm install -g @kubb/cli\` to update`, "Update available for `Kubb`", {
|
|
570
|
+
width: "auto",
|
|
571
|
+
formatBorder: (s) => (0, node_util.styleText)("yellow", s),
|
|
572
|
+
rounded: true,
|
|
573
|
+
withGuide: false,
|
|
574
|
+
contentAlign: "center",
|
|
575
|
+
titleAlign: "center"
|
|
576
|
+
});
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
const { symbol, headline, details } = _kubb_core.Diagnostics.format(diagnostic);
|
|
580
|
+
_clack_prompts.log.message([headline, ...details], { symbol });
|
|
581
|
+
});
|
|
582
|
+
context.on("kubb:lifecycle:start", async ({ version }) => {
|
|
583
|
+
console.log(`\n${getIntro({
|
|
584
|
+
title: "The meta framework for code generation",
|
|
585
|
+
description: "Ready to start",
|
|
586
|
+
version,
|
|
587
|
+
areEyesOpen: true
|
|
588
|
+
})}\n`);
|
|
589
|
+
reset();
|
|
590
|
+
});
|
|
591
|
+
context.on("kubb:generation:start", ({ config }) => {
|
|
592
|
+
reset();
|
|
593
|
+
state.totalPlugins = config.plugins?.length ?? 0;
|
|
594
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
595
|
+
const text = getMessage(["Generation started", config.name ? `for ${(0, node_util.styleText)("dim", config.name)}` : void 0].filter(Boolean).join(" "));
|
|
596
|
+
_clack_prompts.intro(text);
|
|
597
|
+
});
|
|
598
|
+
context.on("kubb:plugin:start", ({ plugin }) => {
|
|
599
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
600
|
+
stopSpinner();
|
|
601
|
+
state.runningPlugins.add(plugin.name);
|
|
602
|
+
const active = state.activeProgress.get("plugins");
|
|
603
|
+
if (active) {
|
|
604
|
+
active.progressBar.advance(0, pluginProgressText());
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
const progressBar = _clack_prompts.progress({
|
|
608
|
+
style: "block",
|
|
609
|
+
max: Math.max(state.totalPlugins, 1),
|
|
610
|
+
size: 30
|
|
611
|
+
});
|
|
612
|
+
progressBar.start(pluginProgressText());
|
|
613
|
+
progressBar.advance(state.completedPlugins + state.failedPlugins, pluginProgressText());
|
|
614
|
+
state.activeProgress.set("plugins", { progressBar });
|
|
615
|
+
});
|
|
616
|
+
context.on("kubb:plugin:end", ({ plugin, success }) => {
|
|
617
|
+
stopSpinner();
|
|
618
|
+
const active = state.activeProgress.get("plugins");
|
|
619
|
+
if (!active || logLevel === _kubb_core.logLevel.silent) return;
|
|
620
|
+
state.runningPlugins.delete(plugin.name);
|
|
621
|
+
recordPluginResult(state, success);
|
|
622
|
+
active.progressBar.advance(1, pluginProgressText());
|
|
623
|
+
if (state.runningPlugins.size === 0) {
|
|
624
|
+
active.progressBar.stop(getMessage("Plugins generated"));
|
|
625
|
+
state.activeProgress.delete("plugins");
|
|
626
|
+
showProgressStep();
|
|
627
|
+
}
|
|
628
|
+
});
|
|
629
|
+
context.on("kubb:files:processing:start", ({ files }) => {
|
|
630
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
631
|
+
stopSpinner();
|
|
632
|
+
state.totalFiles = files.length;
|
|
633
|
+
state.processedFiles = 0;
|
|
634
|
+
const text = `Writing ${files.length} files`;
|
|
635
|
+
const progressBar = _clack_prompts.progress({
|
|
636
|
+
style: "block",
|
|
637
|
+
max: files.length,
|
|
638
|
+
size: 30
|
|
639
|
+
});
|
|
640
|
+
context.emit("kubb:info", { message: text });
|
|
641
|
+
progressBar.start(getMessage(text));
|
|
642
|
+
state.activeProgress.set("files", { progressBar });
|
|
643
|
+
});
|
|
644
|
+
context.on("kubb:files:processing:update", ({ files }) => {
|
|
645
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
646
|
+
stopSpinner();
|
|
647
|
+
const active = state.activeProgress.get("files");
|
|
648
|
+
for (const { file, config } of files) {
|
|
649
|
+
state.processedFiles++;
|
|
650
|
+
if (active) active.progressBar.advance(void 0, `Writing ${(0, node_path.relative)(config.root, file.path)}`);
|
|
651
|
+
}
|
|
652
|
+
});
|
|
653
|
+
context.on("kubb:files:processing:end", () => {
|
|
654
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
655
|
+
stopSpinner();
|
|
656
|
+
const text = getMessage("Files written successfully");
|
|
657
|
+
const active = state.activeProgress.get("files");
|
|
658
|
+
if (!active) return;
|
|
659
|
+
active.progressBar.stop(text);
|
|
660
|
+
state.activeProgress.delete("files");
|
|
661
|
+
showProgressStep();
|
|
662
|
+
});
|
|
663
|
+
context.on("kubb:generation:end", ({ config }) => {
|
|
664
|
+
stopSpinner();
|
|
665
|
+
const text = getMessage(config.name ? `Generation completed for ${(0, node_util.styleText)("dim", config.name)}` : "Generation completed");
|
|
666
|
+
_clack_prompts.outro(text);
|
|
667
|
+
});
|
|
668
|
+
onStep("kubb:format:start", "Formatting");
|
|
669
|
+
onStep("kubb:lint:start", "Linting");
|
|
670
|
+
onStep("kubb:hooks:start", "Running hooks");
|
|
671
|
+
context.on("kubb:hook:start", ({ id, command, args }) => {
|
|
672
|
+
if (logLevel <= _kubb_core.logLevel.silent || !id) return;
|
|
673
|
+
stopSpinner();
|
|
674
|
+
const title = getMessage(`Running ${(0, node_util.styleText)("dim", formatCommandWithArgs(command, args))}`);
|
|
675
|
+
const taskLog = _clack_prompts.taskLog({ title });
|
|
676
|
+
state.activeHookLogs.set(id, {
|
|
677
|
+
taskLog,
|
|
678
|
+
hrStart: node_process.default.hrtime()
|
|
679
|
+
});
|
|
680
|
+
});
|
|
681
|
+
if (logLevel > _kubb_core.logLevel.silent) context.on("kubb:hook:line", ({ id, line }) => {
|
|
682
|
+
state.activeHookLogs.get(id)?.taskLog.message((0, node_util.styleText)("dim", line));
|
|
683
|
+
});
|
|
684
|
+
context.on("kubb:hook:end", ({ id, command, args, success, error, stdout, stderr }) => {
|
|
685
|
+
if (!id) return;
|
|
686
|
+
if (logLevel <= _kubb_core.logLevel.silent) {
|
|
687
|
+
if (!success) {
|
|
688
|
+
if (stdout) console.log(stdout);
|
|
689
|
+
if (stderr) console.error(stderr);
|
|
690
|
+
}
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
const active = state.activeHookLogs.get(id);
|
|
694
|
+
if (!active) return;
|
|
695
|
+
state.activeHookLogs.delete(id);
|
|
696
|
+
const commandWithArgs = formatCommandWithArgs(command, args);
|
|
697
|
+
const duration = formatMsWithColor(getElapsedMs(active.hrStart));
|
|
698
|
+
if (success) active.taskLog.success(getMessage(`${(0, node_util.styleText)("dim", commandWithArgs)} completed in ${duration}`));
|
|
699
|
+
else {
|
|
700
|
+
const reason = error?.message ? ` (${error.message})` : "";
|
|
701
|
+
active.taskLog.error(getMessage(`${(0, node_util.styleText)("dim", commandWithArgs)} failed${reason}`), { showLog: true });
|
|
702
|
+
}
|
|
703
|
+
});
|
|
704
|
+
context.on("kubb:lifecycle:end", () => {
|
|
705
|
+
reset();
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
});
|
|
709
|
+
//#endregion
|
|
710
|
+
//#region src/loggers/plainLogger.ts
|
|
711
|
+
/**
|
|
712
|
+
* Plain console adapter for non-TTY environments with simple `console.log` output.
|
|
713
|
+
*/
|
|
714
|
+
const plainLogger = defineLogger({
|
|
715
|
+
name: "plain",
|
|
716
|
+
install(context, options) {
|
|
717
|
+
const logLevel = options?.logLevel ?? _kubb_core.logLevel.info;
|
|
718
|
+
const hookTimer = createHookTimer();
|
|
719
|
+
function getMessage(message) {
|
|
720
|
+
return formatMessage(message, logLevel);
|
|
721
|
+
}
|
|
722
|
+
function onStep(event, message) {
|
|
723
|
+
context.on(event, () => {
|
|
724
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
725
|
+
console.log(getMessage(message));
|
|
726
|
+
});
|
|
727
|
+
}
|
|
728
|
+
context.on("kubb:info", ({ message, info }) => {
|
|
729
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
730
|
+
const text = getMessage([
|
|
731
|
+
"ℹ",
|
|
732
|
+
message,
|
|
733
|
+
info
|
|
734
|
+
].join(" "));
|
|
735
|
+
console.log(text);
|
|
736
|
+
});
|
|
737
|
+
context.on("kubb:success", ({ message, info = "" }) => {
|
|
738
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
739
|
+
const text = getMessage([
|
|
740
|
+
"✓",
|
|
741
|
+
message,
|
|
742
|
+
logLevel >= _kubb_core.logLevel.info ? info : void 0
|
|
743
|
+
].filter(Boolean).join(" "));
|
|
744
|
+
console.log(text);
|
|
745
|
+
});
|
|
746
|
+
context.on("kubb:warn", ({ message, info }) => {
|
|
747
|
+
if (logLevel < _kubb_core.logLevel.warn) return;
|
|
748
|
+
const text = getMessage([
|
|
749
|
+
"⚠",
|
|
750
|
+
message,
|
|
751
|
+
logLevel >= _kubb_core.logLevel.info ? info : void 0
|
|
752
|
+
].filter(Boolean).join(" "));
|
|
753
|
+
console.log(text);
|
|
754
|
+
});
|
|
755
|
+
context.on("kubb:error", ({ error }) => {
|
|
756
|
+
const caused = require_errors.toCause(error);
|
|
757
|
+
const text = getMessage(["✗", error.message].join(" "));
|
|
758
|
+
console.log(text);
|
|
759
|
+
if (logLevel >= _kubb_core.logLevel.verbose && error.stack) {
|
|
760
|
+
const frames = error.stack.split("\n").slice(1, 4);
|
|
761
|
+
for (const frame of frames) console.log(getMessage(frame.trim()));
|
|
762
|
+
if (caused?.stack) {
|
|
763
|
+
console.log(`└─ caused by ${caused.message}`);
|
|
764
|
+
const frames = caused.stack.split("\n").slice(1, 4);
|
|
765
|
+
for (const frame of frames) console.log(getMessage(` ${frame.trim()}`));
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
});
|
|
769
|
+
context.on("kubb:diagnostic", ({ diagnostic }) => {
|
|
770
|
+
if (logLevel <= _kubb_core.logLevel.silent && diagnostic.severity !== "error") return;
|
|
771
|
+
console.log(getMessage(_kubb_core.Diagnostics.formatLines(diagnostic).join("\n")));
|
|
772
|
+
});
|
|
773
|
+
context.on("kubb:lifecycle:start", ({ version }) => {
|
|
774
|
+
console.log(`Kubb CLI v${version}`);
|
|
775
|
+
});
|
|
776
|
+
context.on("kubb:generation:start", () => {
|
|
777
|
+
const text = getMessage("Generation started");
|
|
778
|
+
console.log(text);
|
|
779
|
+
});
|
|
780
|
+
context.on("kubb:plugin:start", ({ plugin }) => {
|
|
781
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
782
|
+
const text = getMessage(`Generating ${plugin.name}`);
|
|
783
|
+
console.log(text);
|
|
784
|
+
});
|
|
785
|
+
context.on("kubb:plugin:end", ({ plugin, duration, success }) => {
|
|
786
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
787
|
+
const durationStr = formatMs(duration);
|
|
788
|
+
const text = getMessage(success ? `${plugin.name} completed in ${durationStr}` : `${plugin.name} failed in ${durationStr}`);
|
|
789
|
+
console.log(text);
|
|
790
|
+
});
|
|
791
|
+
context.on("kubb:files:processing:start", ({ files }) => {
|
|
792
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
793
|
+
const text = getMessage(`Writing ${files.length} files`);
|
|
794
|
+
console.log(text);
|
|
795
|
+
});
|
|
796
|
+
context.on("kubb:files:processing:update", ({ files }) => {
|
|
797
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
798
|
+
for (const { file, config } of files) console.log(getMessage(`Writing ${(0, node_path.relative)(config.root, file.path)}`));
|
|
799
|
+
});
|
|
800
|
+
context.on("kubb:files:processing:end", () => {
|
|
801
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
802
|
+
const text = getMessage("Files written successfully");
|
|
803
|
+
console.log(text);
|
|
804
|
+
});
|
|
805
|
+
context.on("kubb:generation:end", ({ config }) => {
|
|
806
|
+
const text = getMessage(config.name ? `Generation completed for ${config.name}` : "Generation completed");
|
|
807
|
+
console.log(text);
|
|
808
|
+
});
|
|
809
|
+
onStep("kubb:format:start", "Format started");
|
|
810
|
+
onStep("kubb:format:end", "Format completed");
|
|
811
|
+
onStep("kubb:lint:start", "Lint started");
|
|
812
|
+
onStep("kubb:lint:end", "Lint completed");
|
|
813
|
+
onStep("kubb:hooks:start", "Hooks started");
|
|
814
|
+
onStep("kubb:hooks:end", "Hooks completed");
|
|
815
|
+
context.on("kubb:hook:start", ({ id, command, args }) => {
|
|
816
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
817
|
+
if (id) hookTimer.start(id);
|
|
818
|
+
const commandWithArgs = formatCommandWithArgs(command, args);
|
|
819
|
+
console.log(getMessage(`Hook ${commandWithArgs} started`));
|
|
820
|
+
});
|
|
821
|
+
context.on("kubb:hook:end", ({ id, command, args, success, error, stdout, stderr }) => {
|
|
822
|
+
if (logLevel <= _kubb_core.logLevel.silent) return;
|
|
823
|
+
const ms = id ? hookTimer.end(id) : void 0;
|
|
824
|
+
const durationStr = ms !== void 0 ? ` in ${formatMs(ms)}` : "";
|
|
825
|
+
const commandWithArgs = formatCommandWithArgs(command, args);
|
|
826
|
+
if (success) console.log(getMessage(`✓ Hook ${commandWithArgs} completed${durationStr}`));
|
|
827
|
+
else {
|
|
828
|
+
if (stdout) console.log(stdout);
|
|
829
|
+
if (stderr) console.error(stderr);
|
|
830
|
+
const reason = error?.message ? ` (${error.message})` : "";
|
|
831
|
+
console.log(getMessage(`✗ Hook ${commandWithArgs} failed${durationStr}${reason}`));
|
|
832
|
+
}
|
|
833
|
+
});
|
|
834
|
+
}
|
|
835
|
+
});
|
|
836
|
+
//#endregion
|
|
837
|
+
//#region src/loggers/utils.ts
|
|
838
|
+
/**
|
|
839
|
+
* Optionally prefix a message with a [HH:MM:SS] timestamp when logLevel >= verbose.
|
|
840
|
+
* Shared across all logger adapters to avoid duplication.
|
|
841
|
+
*/
|
|
842
|
+
function formatMessage(message, logLevel) {
|
|
843
|
+
if (logLevel >= _kubb_core.logLevel.verbose) return `${(0, node_util.styleText)("dim", `[${(/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", {
|
|
844
|
+
hour12: false,
|
|
845
|
+
hour: "2-digit",
|
|
846
|
+
minute: "2-digit",
|
|
847
|
+
second: "2-digit"
|
|
848
|
+
})}]`)} ${message}`;
|
|
849
|
+
return message;
|
|
850
|
+
}
|
|
851
|
+
/**
|
|
852
|
+
* Build the progress summary line shown by the clack logger.
|
|
853
|
+
* Returns null when there is nothing to display.
|
|
854
|
+
*/
|
|
855
|
+
function buildProgressLine(state) {
|
|
856
|
+
const parts = [];
|
|
857
|
+
const duration = formatHrtime(state.hrStart);
|
|
858
|
+
if (state.totalPlugins > 0) {
|
|
859
|
+
const pluginStr = state.failedPlugins > 0 ? `Plugins ${(0, node_util.styleText)("green", state.completedPlugins.toString())}/${state.totalPlugins} ${(0, node_util.styleText)("red", `(${state.failedPlugins} failed)`)}` : `Plugins ${(0, node_util.styleText)("green", state.completedPlugins.toString())}/${state.totalPlugins}`;
|
|
860
|
+
parts.push(pluginStr);
|
|
861
|
+
}
|
|
862
|
+
if (state.totalFiles > 0) parts.push(`Files ${(0, node_util.styleText)("green", state.processedFiles.toString())}/${state.totalFiles}`);
|
|
863
|
+
if (parts.length === 0) return null;
|
|
864
|
+
parts.push(`${(0, node_util.styleText)("green", duration)} elapsed`);
|
|
865
|
+
return parts.join((0, node_util.styleText)("dim", " | "));
|
|
866
|
+
}
|
|
867
|
+
/**
|
|
868
|
+
* Creates the per-run progress counters used by the clack logger.
|
|
869
|
+
*/
|
|
870
|
+
function createProgressCounters() {
|
|
871
|
+
return {
|
|
872
|
+
totalPlugins: 0,
|
|
873
|
+
completedPlugins: 0,
|
|
874
|
+
failedPlugins: 0,
|
|
875
|
+
totalFiles: 0,
|
|
876
|
+
processedFiles: 0,
|
|
877
|
+
hrStart: node_process.default.hrtime()
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
/**
|
|
881
|
+
* Resets the progress counters in place at the start/end of a generation run.
|
|
882
|
+
*/
|
|
883
|
+
function resetProgressCounters(state) {
|
|
884
|
+
state.totalPlugins = 0;
|
|
885
|
+
state.completedPlugins = 0;
|
|
886
|
+
state.failedPlugins = 0;
|
|
887
|
+
state.totalFiles = 0;
|
|
888
|
+
state.processedFiles = 0;
|
|
889
|
+
state.hrStart = node_process.default.hrtime();
|
|
890
|
+
}
|
|
891
|
+
/**
|
|
892
|
+
* Records a finished plugin against the progress counters.
|
|
893
|
+
*/
|
|
894
|
+
function recordPluginResult(state, success) {
|
|
895
|
+
if (success) state.completedPlugins++;
|
|
896
|
+
else state.failedPlugins++;
|
|
897
|
+
}
|
|
898
|
+
/**
|
|
899
|
+
* Creates a {@link HookTimer} backed by a private `id → hrtime` map.
|
|
900
|
+
*/
|
|
901
|
+
function createHookTimer() {
|
|
902
|
+
const starts = /* @__PURE__ */ new Map();
|
|
903
|
+
return {
|
|
904
|
+
start(id) {
|
|
905
|
+
starts.set(id, node_process.default.hrtime());
|
|
906
|
+
},
|
|
907
|
+
end(id) {
|
|
908
|
+
const hrStart = starts.get(id);
|
|
909
|
+
if (!hrStart) return;
|
|
910
|
+
starts.delete(id);
|
|
911
|
+
return getElapsedMs(hrStart);
|
|
912
|
+
},
|
|
913
|
+
clear() {
|
|
914
|
+
starts.clear();
|
|
915
|
+
}
|
|
916
|
+
};
|
|
917
|
+
}
|
|
918
|
+
/**
|
|
919
|
+
* Join a command and its optional args into a single display string.
|
|
920
|
+
* e.g. ("prettier", ["--write", "."]) → "prettier --write ."
|
|
921
|
+
*/
|
|
922
|
+
function formatCommandWithArgs(command, args) {
|
|
923
|
+
return args?.length ? `${command} ${args.join(" ")}` : command;
|
|
924
|
+
}
|
|
925
|
+
function detectLogger() {
|
|
926
|
+
if (require_Telemetry.canUseTTY()) return "clack";
|
|
927
|
+
return "plain";
|
|
928
|
+
}
|
|
929
|
+
const logMapper = {
|
|
930
|
+
clack: clackLogger,
|
|
931
|
+
plain: plainLogger
|
|
932
|
+
};
|
|
933
|
+
/**
|
|
934
|
+
* Bridges a {@link Reporter} onto the run's event emitter: calls `report` with each config's
|
|
935
|
+
* {@link GenerationResult} on `kubb:generation:end`. The reporter never touches the emitter.
|
|
936
|
+
*/
|
|
937
|
+
function installReporter(context, reporter, ctx) {
|
|
938
|
+
context.on("kubb:generation:end", async ({ config, diagnostics = [], filesCreated = 0, status = "success", hrStart = node_process.default.hrtime() }) => {
|
|
939
|
+
await reporter.report({
|
|
940
|
+
config,
|
|
941
|
+
diagnostics,
|
|
942
|
+
filesCreated,
|
|
943
|
+
status,
|
|
944
|
+
hrStart
|
|
945
|
+
}, ctx);
|
|
946
|
+
});
|
|
947
|
+
if (reporter.drain) context.on("kubb:lifecycle:end", () => reporter.drain?.(ctx));
|
|
948
|
+
}
|
|
949
|
+
/**
|
|
950
|
+
* Installs the live logger (the TUI view) and the given reporters (the output). The reporters are
|
|
951
|
+
* already selected by the caller (the CLI maps `--reporter` to names via `selectReporters`); this
|
|
952
|
+
* only wires them. Loggers receive hook subprocess output through `kubb:hook:line` and the
|
|
953
|
+
* `stdout`/`stderr` on `kubb:hook:end`, so nothing is returned here.
|
|
954
|
+
*
|
|
955
|
+
* Loggers and reporters are independent: the `cli` reporter also activates the env logger summary.
|
|
956
|
+
* The `json` reporter owns stdout, so the live logger and the `cli` summary are suppressed whenever
|
|
957
|
+
* `json` is among the reporters, even if `cli` is also listed.
|
|
958
|
+
*/
|
|
959
|
+
async function setupReporters(context, { logLevel, reporters }) {
|
|
960
|
+
const hasJson = reporters.some((reporter) => reporter.name === "json");
|
|
961
|
+
const ctx = { logLevel };
|
|
962
|
+
for (const reporter of reporters) {
|
|
963
|
+
if (reporter.name === "cli") {
|
|
964
|
+
if (hasJson) continue;
|
|
965
|
+
const type = detectLogger();
|
|
966
|
+
const logger = logMapper[type];
|
|
967
|
+
if (!logger) throw new Error(`Unknown adapter type: ${type}`);
|
|
968
|
+
await logger.install(context, { logLevel });
|
|
969
|
+
}
|
|
970
|
+
installReporter(context, reporter, ctx);
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
/**
|
|
974
|
+
* Picks the reporters whose `name` matches one of `names`, in the order the names are given.
|
|
975
|
+
* The config carries every available reporter, and the host selects which to activate by name
|
|
976
|
+
* (the CLI maps `--reporter` to this). Duplicate names and names without a matching reporter are
|
|
977
|
+
* skipped.
|
|
978
|
+
*/
|
|
979
|
+
function selectReporters(reporters, names) {
|
|
980
|
+
const seen = /* @__PURE__ */ new Set();
|
|
981
|
+
const selected = [];
|
|
982
|
+
for (const name of names) {
|
|
983
|
+
if (seen.has(name)) continue;
|
|
984
|
+
seen.add(name);
|
|
985
|
+
const reporter = reporters.find((candidate) => candidate.name === name);
|
|
986
|
+
if (reporter) selected.push(reporter);
|
|
987
|
+
}
|
|
988
|
+
return selected;
|
|
989
|
+
}
|
|
990
|
+
//#endregion
|
|
991
|
+
//#region src/runners/generate/utils.ts
|
|
992
|
+
const jiti$1 = (0, jiti.createJiti)(require("url").pathToFileURL(__filename).href, {
|
|
993
|
+
jsx: {
|
|
994
|
+
runtime: "automatic",
|
|
995
|
+
importSource: "@kubb/renderer-jsx"
|
|
996
|
+
},
|
|
997
|
+
moduleCache: false
|
|
998
|
+
});
|
|
999
|
+
const tsLoader = (configFile) => jiti$1.import(configFile, { default: true });
|
|
1000
|
+
const MODULE_NAME = "kubb";
|
|
1001
|
+
const BASE_SEARCH_PLACES = [
|
|
1002
|
+
"package.json",
|
|
1003
|
+
`.${MODULE_NAME}rc`,
|
|
1004
|
+
`.${MODULE_NAME}rc.json`,
|
|
1005
|
+
`.${MODULE_NAME}rc.yaml`,
|
|
1006
|
+
`.${MODULE_NAME}rc.yml`,
|
|
1007
|
+
`.${MODULE_NAME}rc.ts`,
|
|
1008
|
+
`.${MODULE_NAME}rc.mts`,
|
|
1009
|
+
`.${MODULE_NAME}rc.cts`,
|
|
1010
|
+
`.${MODULE_NAME}rc.js`,
|
|
1011
|
+
`.${MODULE_NAME}rc.mjs`,
|
|
1012
|
+
`.${MODULE_NAME}rc.cjs`,
|
|
1013
|
+
`${MODULE_NAME}.config.ts`,
|
|
1014
|
+
`${MODULE_NAME}.config.mts`,
|
|
1015
|
+
`${MODULE_NAME}.config.cts`,
|
|
1016
|
+
`${MODULE_NAME}.config.js`,
|
|
1017
|
+
`${MODULE_NAME}.config.mjs`,
|
|
1018
|
+
`${MODULE_NAME}.config.cjs`
|
|
1019
|
+
];
|
|
1020
|
+
const SEARCH_PLACES = [
|
|
1021
|
+
"",
|
|
1022
|
+
".config/",
|
|
1023
|
+
"configs/"
|
|
1024
|
+
].flatMap((prefix) => BASE_SEARCH_PLACES.map((p) => `${prefix}${p}`));
|
|
1025
|
+
async function getCosmiConfig(configFile) {
|
|
1026
|
+
const explorer = (0, cosmiconfig.cosmiconfig)(MODULE_NAME, {
|
|
1027
|
+
cache: false,
|
|
1028
|
+
searchPlaces: SEARCH_PLACES,
|
|
1029
|
+
loaders: {
|
|
1030
|
+
".ts": tsLoader,
|
|
1031
|
+
".mts": tsLoader,
|
|
1032
|
+
".cts": tsLoader
|
|
1033
|
+
}
|
|
1034
|
+
});
|
|
1035
|
+
let result;
|
|
1036
|
+
try {
|
|
1037
|
+
result = configFile ? await explorer.load(configFile) : await explorer.search();
|
|
1038
|
+
} catch (error) {
|
|
1039
|
+
throw new Error("Config failed loading", { cause: error });
|
|
1040
|
+
}
|
|
1041
|
+
if (!result?.config || result.isEmpty) throw new Error("Config not defined, create a kubb.config.js or pass through your config with the option --config");
|
|
1042
|
+
return result;
|
|
1043
|
+
}
|
|
1044
|
+
/**
|
|
1045
|
+
* Discovers the Kubb config via cosmiconfig and resolves it into a normalized array of configs.
|
|
1046
|
+
* Every config in the result is guaranteed to have a `plugins` array.
|
|
1047
|
+
*/
|
|
1048
|
+
async function getConfigs({ configPath, input, watch, logLevel, noCache }) {
|
|
1049
|
+
const result = await getCosmiConfig(configPath);
|
|
1050
|
+
const cli = {
|
|
1051
|
+
config: configPath,
|
|
1052
|
+
input,
|
|
1053
|
+
watch,
|
|
1054
|
+
logLevel,
|
|
1055
|
+
noCache
|
|
1056
|
+
};
|
|
1057
|
+
const resolved = await (typeof result.config === "function" ? result.config(cli) : result.config);
|
|
1058
|
+
const userConfigs = Array.isArray(resolved) ? resolved : [resolved];
|
|
1059
|
+
return {
|
|
1060
|
+
configPath: result.filepath,
|
|
1061
|
+
configs: userConfigs.map((item) => {
|
|
1062
|
+
const config = {
|
|
1063
|
+
...item,
|
|
1064
|
+
plugins: item.plugins ?? []
|
|
1065
|
+
};
|
|
1066
|
+
return noCache ? {
|
|
1067
|
+
...config,
|
|
1068
|
+
cache: void 0
|
|
1069
|
+
} : config;
|
|
1070
|
+
})
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1073
|
+
/**
|
|
1074
|
+
* Runs the `done` hooks defined in a Kubb config in sequence.
|
|
1075
|
+
*/
|
|
1076
|
+
async function executeHooks({ configHooks, hooks }) {
|
|
1077
|
+
const commands = Array.isArray(configHooks.done) ? configHooks.done : [configHooks.done].filter(Boolean);
|
|
1078
|
+
for (const command of commands) {
|
|
1079
|
+
const [cmd, ...args] = require_shell.tokenize(command);
|
|
1080
|
+
if (!cmd) continue;
|
|
1081
|
+
const hookId = (0, node_crypto.hash)("sha256", command, "hex");
|
|
1082
|
+
const commandWithArgs = [cmd, ...args].join(" ");
|
|
1083
|
+
await hooks.emit("kubb:hook:start", {
|
|
1084
|
+
id: hookId,
|
|
1085
|
+
command: cmd,
|
|
1086
|
+
args
|
|
1087
|
+
});
|
|
1088
|
+
await runHook({
|
|
1089
|
+
id: hookId,
|
|
1090
|
+
command: cmd,
|
|
1091
|
+
args,
|
|
1092
|
+
commandWithArgs,
|
|
1093
|
+
hooks
|
|
1094
|
+
});
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
async function runHook({ id, command, args, commandWithArgs, hooks }) {
|
|
1098
|
+
const emitEnd = (success, error, output) => hooks.emit("kubb:hook:end", {
|
|
1099
|
+
command,
|
|
1100
|
+
args,
|
|
1101
|
+
id,
|
|
1102
|
+
success,
|
|
1103
|
+
error,
|
|
1104
|
+
...output
|
|
1105
|
+
});
|
|
1106
|
+
const stream = hooks.listenerCount("kubb:hook:line") > 0;
|
|
1107
|
+
try {
|
|
1108
|
+
const proc = (0, tinyexec.x)(command, [...args ?? []], {
|
|
1109
|
+
nodeOptions: { detached: process.platform !== "win32" },
|
|
1110
|
+
throwOnError: true
|
|
1111
|
+
});
|
|
1112
|
+
if (stream) for await (const line of proc) await hooks.emit("kubb:hook:line", {
|
|
1113
|
+
id,
|
|
1114
|
+
line
|
|
1115
|
+
});
|
|
1116
|
+
await proc;
|
|
1117
|
+
await hooks.emit("kubb:success", { message: `${(0, node_util.styleText)("dim", commandWithArgs)} successfully executed` });
|
|
1118
|
+
await emitEnd(true, null);
|
|
1119
|
+
} catch (err) {
|
|
1120
|
+
if (!(err instanceof tinyexec.NonZeroExitError)) {
|
|
1121
|
+
await emitEnd(false, require_errors.toError(err));
|
|
1122
|
+
return;
|
|
1123
|
+
}
|
|
1124
|
+
const stderr = err.output?.stderr ?? "";
|
|
1125
|
+
const stdout = err.output?.stdout ?? "";
|
|
1126
|
+
await emitEnd(false, /* @__PURE__ */ new Error(`Hook execute failed: ${commandWithArgs}`), {
|
|
1127
|
+
stdout,
|
|
1128
|
+
stderr
|
|
1129
|
+
});
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
/**
|
|
1133
|
+
* Starts a file watcher on the given paths and calls `cb` on any change.
|
|
1134
|
+
* Ignores `.git` and `node_modules` directories.
|
|
1135
|
+
*/
|
|
1136
|
+
async function startWatcher(path, cb, log = {
|
|
1137
|
+
info: console.log,
|
|
1138
|
+
error: console.log
|
|
1139
|
+
}) {
|
|
1140
|
+
const { watch } = await import("chokidar");
|
|
1141
|
+
const watcher = watch(path, {
|
|
1142
|
+
ignorePermissionErrors: true,
|
|
1143
|
+
ignored: require_Telemetry.WATCHER_IGNORED_PATHS
|
|
1144
|
+
});
|
|
1145
|
+
process.once("SIGINT", () => {
|
|
1146
|
+
watcher.close();
|
|
1147
|
+
});
|
|
1148
|
+
process.once("SIGTERM", () => {
|
|
1149
|
+
watcher.close();
|
|
1150
|
+
});
|
|
1151
|
+
watcher.on("all", async (type, file) => {
|
|
1152
|
+
log.info((0, node_util.styleText)("yellow", (0, node_util.styleText)("bold", `Change detected: ${type} ${file}`)));
|
|
1153
|
+
try {
|
|
1154
|
+
await cb(path);
|
|
1155
|
+
} catch (_e) {
|
|
1156
|
+
log.error((0, node_util.styleText)("red", "Watcher failed"));
|
|
1157
|
+
}
|
|
1158
|
+
});
|
|
1159
|
+
}
|
|
1160
|
+
//#endregion
|
|
1161
|
+
//#region src/runners/generate/run.ts
|
|
1162
|
+
/**
|
|
1163
|
+
* Registers a one-shot `kubb:hook:end` listener for `hookId` BEFORE the caller emits `kubb:hook:start`,
|
|
1164
|
+
* avoiding the race where a synchronous emitter fires end before the listener is attached.
|
|
1165
|
+
*/
|
|
1166
|
+
function waitForHookEnd(hooks, hookId, onSuccess, fallbackErrorMessage) {
|
|
1167
|
+
return new Promise((resolve, reject) => {
|
|
1168
|
+
const handler = (ctx) => {
|
|
1169
|
+
if (ctx.id !== hookId) return;
|
|
1170
|
+
hooks.off("kubb:hook:end", handler);
|
|
1171
|
+
if (!ctx.success) {
|
|
1172
|
+
reject(ctx.error ?? new Error(fallbackErrorMessage));
|
|
1173
|
+
return;
|
|
1174
|
+
}
|
|
1175
|
+
Promise.resolve(onSuccess()).then(resolve).catch(reject);
|
|
1176
|
+
};
|
|
1177
|
+
hooks.on("kubb:hook:end", handler);
|
|
1178
|
+
});
|
|
1179
|
+
}
|
|
1180
|
+
async function runToolPass({ toolValue, detect, toolMap, toolLabel, successPrefix, noToolMessage, configName, outputPath, logLevel, hooks, onStart, onEnd }) {
|
|
1181
|
+
await onStart();
|
|
1182
|
+
let resolvedTool = toolValue;
|
|
1183
|
+
if (resolvedTool === "auto") {
|
|
1184
|
+
const detected = await detect();
|
|
1185
|
+
if (!detected) await hooks.emit("kubb:warn", { message: noToolMessage });
|
|
1186
|
+
else {
|
|
1187
|
+
resolvedTool = detected;
|
|
1188
|
+
await hooks.emit("kubb:info", { message: `Auto-detected ${toolLabel}: ${(0, node_util.styleText)("dim", resolvedTool)}` });
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
let toolError;
|
|
1192
|
+
if (resolvedTool && resolvedTool !== "auto" && resolvedTool in toolMap && (0, node_fs.existsSync)(outputPath)) {
|
|
1193
|
+
const toolConfig = toolMap[resolvedTool];
|
|
1194
|
+
const hookId = (0, node_crypto.hash)("sha256", [configName, resolvedTool].filter(Boolean).join("-"), "hex");
|
|
1195
|
+
const successMessage = [
|
|
1196
|
+
`${successPrefix} with ${(0, node_util.styleText)("dim", resolvedTool)}`,
|
|
1197
|
+
logLevel >= _kubb_core.logLevel.info ? `on ${(0, node_util.styleText)("dim", outputPath)}` : void 0,
|
|
1198
|
+
"successfully"
|
|
1199
|
+
].filter(Boolean).join(" ");
|
|
1200
|
+
try {
|
|
1201
|
+
const hookArgs = toolConfig.args(outputPath);
|
|
1202
|
+
const commandWithArgs = [toolConfig.command, ...hookArgs].join(" ");
|
|
1203
|
+
const hookEndPromise = waitForHookEnd(hooks, hookId, () => hooks.emit("kubb:success", { message: successMessage }), toolConfig.errorMessage);
|
|
1204
|
+
await hooks.emit("kubb:hook:start", {
|
|
1205
|
+
id: hookId,
|
|
1206
|
+
command: toolConfig.command,
|
|
1207
|
+
args: hookArgs
|
|
1208
|
+
});
|
|
1209
|
+
runHook({
|
|
1210
|
+
id: hookId,
|
|
1211
|
+
command: toolConfig.command,
|
|
1212
|
+
args: hookArgs,
|
|
1213
|
+
commandWithArgs,
|
|
1214
|
+
hooks
|
|
1215
|
+
}).catch(() => {});
|
|
1216
|
+
await hookEndPromise;
|
|
1217
|
+
} catch (caughtError) {
|
|
1218
|
+
toolError = require_errors.toError(caughtError);
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
await onEnd();
|
|
1222
|
+
if (toolError) throw toolError;
|
|
1223
|
+
}
|
|
1224
|
+
async function generate(options) {
|
|
1225
|
+
const { input, hooks, logLevel } = options;
|
|
1226
|
+
const hrStart = node_process.default.hrtime();
|
|
1227
|
+
const inputPath = input ?? (options.config.input && "path" in options.config.input ? options.config.input.path : void 0);
|
|
1228
|
+
const config = {
|
|
1229
|
+
...options.config,
|
|
1230
|
+
input: inputPath ? {
|
|
1231
|
+
...options.config.input,
|
|
1232
|
+
path: inputPath
|
|
1233
|
+
} : options.config.input,
|
|
1234
|
+
...options.config.output
|
|
1235
|
+
};
|
|
1236
|
+
const kubb = (0, _kubb_core.createKubb)(config, { hooks });
|
|
1237
|
+
await hooks.emit("kubb:generation:start", { config });
|
|
1238
|
+
await hooks.emit("kubb:info", {
|
|
1239
|
+
message: config.name ? `Setup generation ${(0, node_util.styleText)("bold", config.name)}` : "Setup generation",
|
|
1240
|
+
info: inputPath
|
|
1241
|
+
});
|
|
1242
|
+
await kubb.setup();
|
|
1243
|
+
await hooks.emit("kubb:info", {
|
|
1244
|
+
message: config.name ? `Build generation ${(0, node_util.styleText)("bold", config.name)}` : "Build generation",
|
|
1245
|
+
info: inputPath
|
|
1246
|
+
});
|
|
1247
|
+
const { files, diagnostics, driver } = await kubb.safeBuild();
|
|
1248
|
+
await hooks.emit("kubb:info", { message: "Load summary" });
|
|
1249
|
+
const telemetryPlugins = Array.from(driver.plugins.values(), (p) => ({
|
|
1250
|
+
name: p.name,
|
|
1251
|
+
options: p.options
|
|
1252
|
+
}));
|
|
1253
|
+
const reportTelemetry = (status) => require_Telemetry.Telemetry.send(require_Telemetry.Telemetry.build({
|
|
1254
|
+
command: "generate",
|
|
1255
|
+
kubbVersion: require_package.version,
|
|
1256
|
+
plugins: telemetryPlugins,
|
|
1257
|
+
hrStart,
|
|
1258
|
+
filesCreated: files.length,
|
|
1259
|
+
status
|
|
1260
|
+
}));
|
|
1261
|
+
for (const diagnostic of diagnostics) {
|
|
1262
|
+
if (!_kubb_core.Diagnostics.isProblem(diagnostic)) continue;
|
|
1263
|
+
const unknown = _kubb_core.Diagnostics.narrow(diagnostic, _kubb_core.Diagnostics.code.unknown);
|
|
1264
|
+
if (unknown) await hooks.emit("kubb:error", { error: unknown.cause ?? new Error(unknown.message) });
|
|
1265
|
+
else await _kubb_core.Diagnostics.emit(hooks, diagnostic);
|
|
1266
|
+
}
|
|
1267
|
+
if (_kubb_core.Diagnostics.hasError(diagnostics)) {
|
|
1268
|
+
await hooks.emit("kubb:generation:end", {
|
|
1269
|
+
config,
|
|
1270
|
+
storage: kubb.storage,
|
|
1271
|
+
diagnostics,
|
|
1272
|
+
filesCreated: files.length,
|
|
1273
|
+
status: "failed",
|
|
1274
|
+
hrStart
|
|
1275
|
+
});
|
|
1276
|
+
await reportTelemetry("failed");
|
|
1277
|
+
return false;
|
|
1278
|
+
}
|
|
1279
|
+
const outputPath = node_path.default.resolve(config.root, config.output.path);
|
|
1280
|
+
const outputDiagnostics = [];
|
|
1281
|
+
const toolPasses = [config.output.format && {
|
|
1282
|
+
code: _kubb_core.Diagnostics.code.formatFailed,
|
|
1283
|
+
toolValue: config.output.format,
|
|
1284
|
+
detect: detectFormatter,
|
|
1285
|
+
toolMap: formatters,
|
|
1286
|
+
toolLabel: "formatter",
|
|
1287
|
+
successPrefix: "Formatting",
|
|
1288
|
+
noToolMessage: "No formatter found (oxfmt, biome, or prettier). Skipping formatting.",
|
|
1289
|
+
onStart: () => hooks.emit("kubb:format:start"),
|
|
1290
|
+
onEnd: () => hooks.emit("kubb:format:end")
|
|
1291
|
+
}, config.output.lint && {
|
|
1292
|
+
code: _kubb_core.Diagnostics.code.lintFailed,
|
|
1293
|
+
toolValue: config.output.lint,
|
|
1294
|
+
detect: detectLinter,
|
|
1295
|
+
toolMap: linters,
|
|
1296
|
+
toolLabel: "linter",
|
|
1297
|
+
successPrefix: "Linting",
|
|
1298
|
+
noToolMessage: "No linter found (oxlint, biome, or eslint). Skipping linting.",
|
|
1299
|
+
onStart: () => hooks.emit("kubb:lint:start"),
|
|
1300
|
+
onEnd: () => hooks.emit("kubb:lint:end")
|
|
1301
|
+
}].filter(Boolean);
|
|
1302
|
+
for (const { code, ...pass } of toolPasses) try {
|
|
1303
|
+
await runToolPass({
|
|
1304
|
+
...pass,
|
|
1305
|
+
configName: config.name,
|
|
1306
|
+
outputPath,
|
|
1307
|
+
logLevel,
|
|
1308
|
+
hooks
|
|
1309
|
+
});
|
|
1310
|
+
} catch (caughtError) {
|
|
1311
|
+
const diagnostic = outputDiagnostic(code, pass.toolLabel, caughtError);
|
|
1312
|
+
outputDiagnostics.push(diagnostic);
|
|
1313
|
+
await _kubb_core.Diagnostics.emit(hooks, diagnostic);
|
|
1314
|
+
}
|
|
1315
|
+
if (config.hooks) {
|
|
1316
|
+
await hooks.emit("kubb:hooks:start");
|
|
1317
|
+
const hookFailures = [];
|
|
1318
|
+
const onHookEnd = (ctx) => {
|
|
1319
|
+
if (!ctx.success) hookFailures.push(ctx.error ?? /* @__PURE__ */ new Error("Post-generate hook failed"));
|
|
1320
|
+
};
|
|
1321
|
+
hooks.on("kubb:hook:end", onHookEnd);
|
|
1322
|
+
try {
|
|
1323
|
+
await executeHooks({
|
|
1324
|
+
configHooks: config.hooks,
|
|
1325
|
+
hooks
|
|
1326
|
+
});
|
|
1327
|
+
} finally {
|
|
1328
|
+
hooks.off("kubb:hook:end", onHookEnd);
|
|
1329
|
+
}
|
|
1330
|
+
for (const error of hookFailures) {
|
|
1331
|
+
const diagnostic = outputDiagnostic(_kubb_core.Diagnostics.code.hookFailed, "Post-generate hook", error);
|
|
1332
|
+
outputDiagnostics.push(diagnostic);
|
|
1333
|
+
await _kubb_core.Diagnostics.emit(hooks, diagnostic);
|
|
1334
|
+
}
|
|
1335
|
+
await hooks.emit("kubb:hooks:end");
|
|
1336
|
+
}
|
|
1337
|
+
const finalDiagnostics = [...diagnostics, ...outputDiagnostics];
|
|
1338
|
+
const failed = _kubb_core.Diagnostics.hasError(outputDiagnostics);
|
|
1339
|
+
if (!failed) await hooks.emit("kubb:success", {
|
|
1340
|
+
message: "Generation succeeded",
|
|
1341
|
+
info: inputPath
|
|
1342
|
+
});
|
|
1343
|
+
await hooks.emit("kubb:generation:end", {
|
|
1344
|
+
config,
|
|
1345
|
+
storage: kubb.storage,
|
|
1346
|
+
diagnostics: finalDiagnostics,
|
|
1347
|
+
filesCreated: files.length,
|
|
1348
|
+
status: failed ? "failed" : "success",
|
|
1349
|
+
hrStart
|
|
1350
|
+
});
|
|
1351
|
+
await reportTelemetry(failed ? "failed" : "success");
|
|
1352
|
+
return !failed;
|
|
1353
|
+
}
|
|
1354
|
+
/**
|
|
1355
|
+
* Builds a coded diagnostic for an output-phase failure (formatter, linter, or `done` hook).
|
|
1356
|
+
*/
|
|
1357
|
+
function outputDiagnostic(code, label, caughtError) {
|
|
1358
|
+
const error = require_errors.toError(caughtError);
|
|
1359
|
+
return {
|
|
1360
|
+
code,
|
|
1361
|
+
severity: "error",
|
|
1362
|
+
message: `${label} failed: ${error.message}`,
|
|
1363
|
+
help: "Check that the tool is installed and that the command and its config are correct.",
|
|
1364
|
+
location: { kind: "config" },
|
|
1365
|
+
cause: error
|
|
1366
|
+
};
|
|
1367
|
+
}
|
|
1368
|
+
async function checkForUpdate(hooks) {
|
|
1369
|
+
await require_Telemetry.executeIfOnline(async () => {
|
|
1370
|
+
try {
|
|
1371
|
+
const data = await (await fetch(require_Telemetry.KUBB_NPM_PACKAGE_URL)).json();
|
|
1372
|
+
if (data.version && require_package.version < data.version) await _kubb_core.Diagnostics.emit(hooks, _kubb_core.Diagnostics.update({
|
|
1373
|
+
currentVersion: require_package.version,
|
|
1374
|
+
latestVersion: data.version
|
|
1375
|
+
}));
|
|
1376
|
+
} catch {}
|
|
1377
|
+
});
|
|
1378
|
+
}
|
|
1379
|
+
/**
|
|
1380
|
+
* Runs the full Kubb generation lifecycle for the given CLI options.
|
|
1381
|
+
* Loads configs, sets up the selected reporters (CLI `--reporter` overrides `config.reporters`),
|
|
1382
|
+
* checks for a newer version, and calls `generate` for each config entry.
|
|
1383
|
+
*/
|
|
1384
|
+
async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters, noCache }) {
|
|
1385
|
+
const logLevel = _kubb_core.logLevel[logLevelKey] ?? _kubb_core.logLevel.info;
|
|
1386
|
+
const hooks = new AsyncEventEmitter();
|
|
1387
|
+
let configs;
|
|
1388
|
+
let resolvedConfigPath;
|
|
1389
|
+
try {
|
|
1390
|
+
const loaded = await getConfigs({
|
|
1391
|
+
configPath,
|
|
1392
|
+
input,
|
|
1393
|
+
watch,
|
|
1394
|
+
logLevel: logLevelKey,
|
|
1395
|
+
noCache
|
|
1396
|
+
});
|
|
1397
|
+
configs = loaded.configs;
|
|
1398
|
+
resolvedConfigPath = loaded.configPath;
|
|
1399
|
+
} catch (error) {
|
|
1400
|
+
await setupReporters(hooks, {
|
|
1401
|
+
logLevel,
|
|
1402
|
+
reporters: [_kubb_core.cliReporter]
|
|
1403
|
+
});
|
|
1404
|
+
await hooks.emit("kubb:error", { error: require_errors.toError(error) });
|
|
1405
|
+
node_process.default.exit(1);
|
|
1406
|
+
}
|
|
1407
|
+
const requestedNames = cliReporters?.length ? cliReporters : ["cli"];
|
|
1408
|
+
await setupReporters(hooks, {
|
|
1409
|
+
logLevel,
|
|
1410
|
+
reporters: selectReporters(configs[0]?.reporters ?? [], requestedNames)
|
|
1411
|
+
});
|
|
1412
|
+
await hooks.emit("kubb:lifecycle:start", { version: require_package.version });
|
|
1413
|
+
await checkForUpdate(hooks);
|
|
1414
|
+
try {
|
|
1415
|
+
const relativeConfigPath = node_path.default.relative(node_process.default.cwd(), resolvedConfigPath);
|
|
1416
|
+
await hooks.emit("kubb:info", {
|
|
1417
|
+
message: "Config loaded",
|
|
1418
|
+
info: relativeConfigPath
|
|
1419
|
+
});
|
|
1420
|
+
await hooks.emit("kubb:success", {
|
|
1421
|
+
message: "Config loaded successfully",
|
|
1422
|
+
info: relativeConfigPath
|
|
1423
|
+
});
|
|
1424
|
+
let anyFailed = false;
|
|
1425
|
+
for (const config of configs) if (config.input && "path" in config.input && watch) await startWatcher([input || config.input.path], async (paths) => {
|
|
1426
|
+
await generate({
|
|
1427
|
+
input,
|
|
1428
|
+
config,
|
|
1429
|
+
logLevel,
|
|
1430
|
+
hooks
|
|
1431
|
+
});
|
|
1432
|
+
_clack_prompts.log.step((0, node_util.styleText)("yellow", `Watching for changes in ${paths.join(" and ")}`));
|
|
1433
|
+
}, {
|
|
1434
|
+
info: (msg) => _clack_prompts.log.info(msg),
|
|
1435
|
+
error: (msg) => _clack_prompts.log.error(msg)
|
|
1436
|
+
});
|
|
1437
|
+
else try {
|
|
1438
|
+
if (!await generate({
|
|
1439
|
+
input,
|
|
1440
|
+
config,
|
|
1441
|
+
logLevel,
|
|
1442
|
+
hooks
|
|
1443
|
+
})) anyFailed = true;
|
|
1444
|
+
} catch (configError) {
|
|
1445
|
+
await hooks.emit("kubb:error", { error: require_errors.toError(configError) });
|
|
1446
|
+
anyFailed = true;
|
|
1447
|
+
}
|
|
1448
|
+
await hooks.emit("kubb:lifecycle:end");
|
|
1449
|
+
if (anyFailed) node_process.default.exit(1);
|
|
1450
|
+
} catch (error) {
|
|
1451
|
+
await hooks.emit("kubb:error", { error: require_errors.toError(error) });
|
|
1452
|
+
node_process.default.exit(1);
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1455
|
+
//#endregion
|
|
1456
|
+
exports.run = run;
|
|
1457
|
+
|
|
1458
|
+
//# sourceMappingURL=run-CDs_ebOt.cjs.map
|