@kubb/cli 5.0.0-beta.6 → 5.0.0-beta.61

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