@kubb/cli 5.0.0-beta.8 → 5.0.0-beta.80

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