@kubb/cli 5.0.0-beta.7 → 5.0.0-beta.70

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 (133) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +45 -77
  3. package/bin/kubb.js +9 -3
  4. package/dist/Telemetry-CfPP7MYq.cjs +321 -0
  5. package/dist/Telemetry-CfPP7MYq.cjs.map +1 -0
  6. package/dist/Telemetry-uAr3lK_-.js +284 -0
  7. package/dist/Telemetry-uAr3lK_-.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-BY-juRdH.js → generate-BdxIouwm.js} +21 -16
  17. package/dist/generate-BdxIouwm.js.map +1 -0
  18. package/dist/{generate-Bod9YCbF.cjs → generate-tRupKbnI.cjs} +21 -16
  19. package/dist/generate-tRupKbnI.cjs.map +1 -0
  20. package/dist/index.cjs +34 -81
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.ts +6 -1
  23. package/dist/index.js +34 -81
  24. package/dist/index.js.map +1 -1
  25. package/dist/{init-Cs3Fp6nN.js → init-D_9I495E.js} +5 -5
  26. package/dist/{init-Cs3Fp6nN.js.map → init-D_9I495E.js.map} +1 -1
  27. package/dist/{init-BIkZU6mB.cjs → init-XlS3aia7.cjs} +6 -6
  28. package/dist/{init-BIkZU6mB.cjs.map → init-XlS3aia7.cjs.map} +1 -1
  29. package/dist/mcp-BlKi3z04.js +21 -0
  30. package/dist/mcp-BlKi3z04.js.map +1 -0
  31. package/dist/mcp-DSo5Ccwz.cjs +21 -0
  32. package/dist/mcp-DSo5Ccwz.cjs.map +1 -0
  33. package/dist/package-CsDaFmfZ.js +6 -0
  34. package/dist/package-CsDaFmfZ.js.map +1 -0
  35. package/dist/{package-DrUndPET.cjs → package-HWZRLSO4.cjs} +2 -2
  36. package/dist/package-HWZRLSO4.cjs.map +1 -0
  37. package/dist/{chunk-BvFE5Tac.js → rolldown-runtime-C0LytTxp.js} +0 -1
  38. package/dist/{run-YsoCk5we.cjs → run-AYlRjIX5.cjs} +136 -98
  39. package/dist/run-AYlRjIX5.cjs.map +1 -0
  40. package/dist/run-BM1t8CSM.cjs +33 -0
  41. package/dist/run-BM1t8CSM.cjs.map +1 -0
  42. package/dist/run-BlFVmIJl.js +32 -0
  43. package/dist/run-BlFVmIJl.js.map +1 -0
  44. package/dist/{run-CQbj3ley.cjs → run-CBc896in.cjs} +6 -6
  45. package/dist/run-CBc896in.cjs.map +1 -0
  46. package/dist/{run-CF97BWVa.js → run-D9mQoQHA.js} +123 -85
  47. package/dist/run-D9mQoQHA.js.map +1 -0
  48. package/dist/{run-CCZ24VKk.js → run-D_dWNFhX.js} +5 -5
  49. package/dist/run-D_dWNFhX.js.map +1 -0
  50. package/dist/run-DwylXpzM.cjs +1380 -0
  51. package/dist/run-DwylXpzM.cjs.map +1 -0
  52. package/dist/run-KlHwxNTr.js +1377 -0
  53. package/dist/run-KlHwxNTr.js.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-Bfpf_UIh.cjs → validate-3gu3yglv.cjs} +6 -6
  59. package/dist/{validate-Bfpf_UIh.cjs.map → validate-3gu3yglv.cjs.map} +1 -1
  60. package/dist/{validate-lbUkWQ5o.js → validate-DBqdV14W.js} +5 -5
  61. package/dist/{validate-lbUkWQ5o.js.map → validate-DBqdV14W.js.map} +1 -1
  62. package/package.json +13 -25
  63. package/dist/agent-DN7o8nlE.js +0 -68
  64. package/dist/agent-DN7o8nlE.js.map +0 -1
  65. package/dist/agent-Fm9_8BBH.cjs +0 -70
  66. package/dist/agent-Fm9_8BBH.cjs.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-BY-juRdH.js.map +0 -1
  78. package/dist/generate-Bod9YCbF.cjs.map +0 -1
  79. package/dist/mcp-BSNulBcC.js +0 -39
  80. package/dist/mcp-BSNulBcC.js.map +0 -1
  81. package/dist/mcp-DcSrFhhP.cjs +0 -39
  82. package/dist/mcp-DcSrFhhP.cjs.map +0 -1
  83. package/dist/package-D5wmvFl4.js +0 -6
  84. package/dist/package-D5wmvFl4.js.map +0 -1
  85. package/dist/package-DrUndPET.cjs.map +0 -1
  86. package/dist/run-BAJubgdA.js +0 -1735
  87. package/dist/run-BAJubgdA.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-CqKd6JNc.cjs +0 -1738
  94. package/dist/run-CqKd6JNc.cjs.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-YsoCk5we.cjs.map +0 -1
  102. package/dist/shell-475fQKaX.cjs +0 -62
  103. package/dist/shell-475fQKaX.cjs.map +0 -1
  104. package/dist/shell-CN6DNqeC.js +0 -51
  105. package/dist/shell-CN6DNqeC.js.map +0 -1
  106. package/dist/telemetry-B2iWkY5e.cjs +0 -280
  107. package/dist/telemetry-B2iWkY5e.cjs.map +0 -1
  108. package/dist/telemetry-BkektVz6.js +0 -243
  109. package/dist/telemetry-BkektVz6.js.map +0 -1
  110. package/src/commands/agent/start.ts +0 -50
  111. package/src/commands/agent.ts +0 -10
  112. package/src/commands/generate.ts +0 -59
  113. package/src/commands/init.ts +0 -51
  114. package/src/commands/mcp.ts +0 -36
  115. package/src/commands/validate.ts +0 -22
  116. package/src/constants.ts +0 -48
  117. package/src/index.ts +0 -45
  118. package/src/loggers/clackLogger.ts +0 -460
  119. package/src/loggers/fileSystemLogger.ts +0 -148
  120. package/src/loggers/githubActionsLogger.ts +0 -367
  121. package/src/loggers/plainLogger.ts +0 -243
  122. package/src/loggers/types.ts +0 -7
  123. package/src/loggers/utils.ts +0 -252
  124. package/src/runners/agent/run.ts +0 -113
  125. package/src/runners/agent/utils.ts +0 -98
  126. package/src/runners/generate/run.ts +0 -276
  127. package/src/runners/generate/utils.ts +0 -209
  128. package/src/runners/init/run.ts +0 -211
  129. package/src/runners/init/utils.ts +0 -33
  130. package/src/runners/mcp/run.ts +0 -55
  131. package/src/runners/validate/run.ts +0 -63
  132. package/src/telemetry.ts +0 -280
  133. /package/dist/{chunk-ByKO4r7w.cjs → rolldown-runtime-Bx3C2hgW.cjs} +0 -0
@@ -0,0 +1,1377 @@
1
+ import "./rolldown-runtime-C0LytTxp.js";
2
+ import { n as toCause, r as toError } from "./errors-Dc_d7BfX.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-uAr3lK_-.js";
4
+ import { i as linters, n as detectTool, r as formatters } from "./tools-D0UogMU3.js";
5
+ import { t as version } from "./package-CsDaFmfZ.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, { basename, dirname, relative, resolve } 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 { NonZeroExitError, x } from "tinyexec";
17
+ import { loadConfig } from "unconfig";
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 { headline, details } = Diagnostics.format(diagnostic);
449
+ clack.log.message([headline, ...details], {
450
+ symbol: "",
451
+ secondarySymbol: ""
452
+ });
453
+ });
454
+ context.on("kubb:lifecycle:start", async ({ version }) => {
455
+ console.log(`\n${getIntro({
456
+ title: "The meta framework for code generation",
457
+ description: "Ready to start",
458
+ version,
459
+ areEyesOpen: true
460
+ })}\n`);
461
+ reset();
462
+ });
463
+ context.on("kubb:generation:start", ({ config }) => {
464
+ reset();
465
+ state.totalPlugins = config.plugins?.length ?? 0;
466
+ if (logLevel$5 <= logLevel.silent) return;
467
+ const text = getMessage(["Generation started", config.name ? `for ${styleText("dim", config.name)}` : void 0].filter(Boolean).join(" "));
468
+ clack.intro(text);
469
+ });
470
+ context.on("kubb:plugin:start", ({ plugin }) => {
471
+ if (logLevel$5 <= logLevel.silent) return;
472
+ stopSpinner();
473
+ state.runningPlugins.add(plugin.name);
474
+ const active = state.activeProgress.get("plugins");
475
+ if (active) {
476
+ active.progressBar.advance(0, pluginProgressText());
477
+ return;
478
+ }
479
+ const progressBar = clack.progress({
480
+ style: "block",
481
+ max: Math.max(state.totalPlugins, 1),
482
+ size: 30
483
+ });
484
+ progressBar.start(pluginProgressText());
485
+ progressBar.advance(state.completedPlugins + state.failedPlugins, pluginProgressText());
486
+ state.activeProgress.set("plugins", { progressBar });
487
+ });
488
+ context.on("kubb:plugin:end", ({ plugin, success }) => {
489
+ stopSpinner();
490
+ const active = state.activeProgress.get("plugins");
491
+ if (!active || logLevel$5 === logLevel.silent) return;
492
+ state.runningPlugins.delete(plugin.name);
493
+ recordPluginResult(state, success);
494
+ active.progressBar.advance(1, pluginProgressText());
495
+ if (state.runningPlugins.size === 0) {
496
+ active.progressBar.stop(getMessage("Plugins generated"));
497
+ state.activeProgress.delete("plugins");
498
+ showProgressStep();
499
+ }
500
+ });
501
+ context.on("kubb:files:processing:start", ({ files }) => {
502
+ if (logLevel$5 <= logLevel.silent) return;
503
+ stopSpinner();
504
+ state.totalFiles = files.length;
505
+ state.processedFiles = 0;
506
+ const text = `Writing ${files.length} files`;
507
+ const progressBar = clack.progress({
508
+ style: "block",
509
+ max: files.length,
510
+ size: 30
511
+ });
512
+ context.emit("kubb:info", { message: text });
513
+ progressBar.start(getMessage(text));
514
+ state.activeProgress.set("files", { progressBar });
515
+ });
516
+ context.on("kubb:files:processing:update", ({ files }) => {
517
+ if (logLevel$5 <= logLevel.silent) return;
518
+ stopSpinner();
519
+ const active = state.activeProgress.get("files");
520
+ for (const { file, config } of files) {
521
+ state.processedFiles++;
522
+ if (active) active.progressBar.advance(void 0, `Writing ${relative(config.root, file.path)}`);
523
+ }
524
+ });
525
+ context.on("kubb:files:processing:end", () => {
526
+ if (logLevel$5 <= logLevel.silent) return;
527
+ stopSpinner();
528
+ const text = getMessage("Files written successfully");
529
+ const active = state.activeProgress.get("files");
530
+ if (!active) return;
531
+ active.progressBar.stop(text);
532
+ state.activeProgress.delete("files");
533
+ showProgressStep();
534
+ });
535
+ context.on("kubb:generation:end", ({ config }) => {
536
+ stopSpinner();
537
+ const text = getMessage(config.name ? `Generation completed for ${styleText("dim", config.name)}` : "Generation completed");
538
+ clack.outro(text);
539
+ });
540
+ onStep("kubb:format:start", "Formatting");
541
+ onStep("kubb:lint:start", "Linting");
542
+ onStep("kubb:hooks:start", "Running hooks");
543
+ context.on("kubb:hook:start", ({ id, command, args }) => {
544
+ if (logLevel$5 <= logLevel.silent || !id) return;
545
+ stopSpinner();
546
+ const title = getMessage(`Running ${styleText("dim", formatCommandWithArgs(command, args))}`);
547
+ const taskLog = clack.taskLog({ title });
548
+ state.activeHookLogs.set(id, {
549
+ taskLog,
550
+ hrStart: process$1.hrtime()
551
+ });
552
+ });
553
+ if (logLevel$5 > logLevel.silent) context.on("kubb:hook:line", ({ id, line }) => {
554
+ state.activeHookLogs.get(id)?.taskLog.message(styleText("dim", line));
555
+ });
556
+ context.on("kubb:hook:end", ({ id, command, args, success, error, stdout, stderr }) => {
557
+ if (!id) return;
558
+ if (logLevel$5 <= logLevel.silent) {
559
+ if (!success) {
560
+ if (stdout) console.log(stdout);
561
+ if (stderr) console.error(stderr);
562
+ }
563
+ return;
564
+ }
565
+ const active = state.activeHookLogs.get(id);
566
+ if (!active) return;
567
+ state.activeHookLogs.delete(id);
568
+ const commandWithArgs = formatCommandWithArgs(command, args);
569
+ const duration = formatMsWithColor(getElapsedMs(active.hrStart));
570
+ if (success) active.taskLog.success(getMessage(`${styleText("dim", commandWithArgs)} completed in ${duration}`));
571
+ else {
572
+ const reason = error?.message ? ` (${error.message})` : "";
573
+ active.taskLog.error(getMessage(`${styleText("dim", commandWithArgs)} failed${reason}`), { showLog: true });
574
+ }
575
+ });
576
+ context.on("kubb:lifecycle:end", () => {
577
+ reset();
578
+ });
579
+ }
580
+ });
581
+ //#endregion
582
+ //#region src/loggers/plainLogger.ts
583
+ /**
584
+ * Plain console adapter for non-TTY environments, built on `console.log`.
585
+ */
586
+ const plainLogger = defineLogger({
587
+ name: "plain",
588
+ install(context, options) {
589
+ const logLevel$4 = options?.logLevel ?? logLevel.info;
590
+ const hookTimer = createHookTimer();
591
+ function getMessage(message) {
592
+ return formatMessage(message, logLevel$4);
593
+ }
594
+ function onStep(event, message) {
595
+ context.on(event, () => {
596
+ if (logLevel$4 <= logLevel.silent) return;
597
+ console.log(getMessage(message));
598
+ });
599
+ }
600
+ context.on("kubb:info", ({ message, info }) => {
601
+ if (logLevel$4 <= logLevel.silent) return;
602
+ const text = getMessage([
603
+ "ℹ",
604
+ message,
605
+ info
606
+ ].join(" "));
607
+ console.log(text);
608
+ });
609
+ context.on("kubb:success", ({ message, info = "" }) => {
610
+ if (logLevel$4 <= logLevel.silent) return;
611
+ const text = getMessage([
612
+ "✓",
613
+ message,
614
+ logLevel$4 >= logLevel.info ? info : void 0
615
+ ].filter(Boolean).join(" "));
616
+ console.log(text);
617
+ });
618
+ context.on("kubb:warn", ({ message, info }) => {
619
+ if (logLevel$4 < logLevel.warn) return;
620
+ const text = getMessage([
621
+ "⚠",
622
+ message,
623
+ logLevel$4 >= logLevel.info ? info : void 0
624
+ ].filter(Boolean).join(" "));
625
+ console.log(text);
626
+ });
627
+ context.on("kubb:error", ({ error }) => {
628
+ const caused = toCause(error);
629
+ const text = getMessage(["✗", error.message].join(" "));
630
+ console.log(text);
631
+ if (logLevel$4 >= logLevel.verbose && error.stack) {
632
+ const frames = error.stack.split("\n").slice(1, 4);
633
+ for (const frame of frames) console.log(getMessage(frame.trim()));
634
+ if (caused?.stack) {
635
+ console.log(`└─ caused by ${caused.message}`);
636
+ const frames = caused.stack.split("\n").slice(1, 4);
637
+ for (const frame of frames) console.log(getMessage(` ${frame.trim()}`));
638
+ }
639
+ }
640
+ });
641
+ context.on("kubb:diagnostic", ({ diagnostic }) => {
642
+ if (logLevel$4 <= logLevel.silent && diagnostic.severity !== "error") return;
643
+ console.log(getMessage(Diagnostics.formatLines(diagnostic).join("\n")));
644
+ });
645
+ context.on("kubb:lifecycle:start", ({ version }) => {
646
+ console.log(`Kubb CLI v${version}`);
647
+ });
648
+ context.on("kubb:generation:start", () => {
649
+ const text = getMessage("Generation started");
650
+ console.log(text);
651
+ });
652
+ context.on("kubb:plugin:start", ({ plugin }) => {
653
+ if (logLevel$4 <= logLevel.silent) return;
654
+ const text = getMessage(`Generating ${plugin.name}`);
655
+ console.log(text);
656
+ });
657
+ context.on("kubb:plugin:end", ({ plugin, duration, success }) => {
658
+ if (logLevel$4 <= logLevel.silent) return;
659
+ const durationStr = formatMs(duration);
660
+ const text = getMessage(success ? `${plugin.name} completed in ${durationStr}` : `${plugin.name} failed in ${durationStr}`);
661
+ console.log(text);
662
+ });
663
+ context.on("kubb:files:processing:start", ({ files }) => {
664
+ if (logLevel$4 <= logLevel.silent) return;
665
+ const text = getMessage(`Writing ${files.length} files`);
666
+ console.log(text);
667
+ });
668
+ context.on("kubb:files:processing:update", ({ files }) => {
669
+ if (logLevel$4 <= logLevel.silent) return;
670
+ for (const { file, config } of files) console.log(getMessage(`Writing ${relative(config.root, file.path)}`));
671
+ });
672
+ context.on("kubb:files:processing:end", () => {
673
+ if (logLevel$4 <= logLevel.silent) return;
674
+ const text = getMessage("Files written successfully");
675
+ console.log(text);
676
+ });
677
+ context.on("kubb:generation:end", ({ config }) => {
678
+ const text = getMessage(config.name ? `Generation completed for ${config.name}` : "Generation completed");
679
+ console.log(text);
680
+ });
681
+ onStep("kubb:format:start", "Format started");
682
+ onStep("kubb:format:end", "Format completed");
683
+ onStep("kubb:lint:start", "Lint started");
684
+ onStep("kubb:lint:end", "Lint completed");
685
+ onStep("kubb:hooks:start", "Hooks started");
686
+ onStep("kubb:hooks:end", "Hooks completed");
687
+ context.on("kubb:hook:start", ({ id, command, args }) => {
688
+ if (logLevel$4 <= logLevel.silent) return;
689
+ if (id) hookTimer.start(id);
690
+ const commandWithArgs = formatCommandWithArgs(command, args);
691
+ console.log(getMessage(`Hook ${commandWithArgs} started`));
692
+ });
693
+ context.on("kubb:hook:end", ({ id, command, args, success, error, stdout, stderr }) => {
694
+ if (logLevel$4 <= logLevel.silent) return;
695
+ const ms = id ? hookTimer.end(id) : void 0;
696
+ const durationStr = ms !== void 0 ? ` in ${formatMs(ms)}` : "";
697
+ const commandWithArgs = formatCommandWithArgs(command, args);
698
+ if (success) console.log(getMessage(`✓ Hook ${commandWithArgs} completed${durationStr}`));
699
+ else {
700
+ if (stdout) console.log(stdout);
701
+ if (stderr) console.error(stderr);
702
+ const reason = error?.message ? ` (${error.message})` : "";
703
+ console.log(getMessage(`✗ Hook ${commandWithArgs} failed${durationStr}${reason}`));
704
+ }
705
+ });
706
+ }
707
+ });
708
+ //#endregion
709
+ //#region src/loggers/utils.ts
710
+ /**
711
+ * Optionally prefix a message with a [HH:MM:SS] timestamp when logLevel >= verbose.
712
+ * Shared across all logger adapters to avoid duplication.
713
+ */
714
+ function formatMessage(message, logLevel$3) {
715
+ if (logLevel$3 >= logLevel.verbose) return `${styleText("dim", `[${(/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", {
716
+ hour12: false,
717
+ hour: "2-digit",
718
+ minute: "2-digit",
719
+ second: "2-digit"
720
+ })}]`)} ${message}`;
721
+ return message;
722
+ }
723
+ /**
724
+ * Build the progress summary line shown by the clack logger.
725
+ * Returns null when there is nothing to display.
726
+ */
727
+ function buildProgressLine(state) {
728
+ const parts = [];
729
+ const duration = formatHrtime(state.hrStart);
730
+ if (state.totalPlugins > 0) {
731
+ 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}`;
732
+ parts.push(pluginStr);
733
+ }
734
+ if (state.totalFiles > 0) parts.push(`Files ${styleText("green", state.processedFiles.toString())}/${state.totalFiles}`);
735
+ if (parts.length === 0) return null;
736
+ parts.push(`${styleText("green", duration)} elapsed`);
737
+ return parts.join(styleText("dim", " | "));
738
+ }
739
+ /**
740
+ * Creates the per-run progress counters used by the clack logger.
741
+ */
742
+ function createProgressCounters() {
743
+ return {
744
+ totalPlugins: 0,
745
+ completedPlugins: 0,
746
+ failedPlugins: 0,
747
+ totalFiles: 0,
748
+ processedFiles: 0,
749
+ hrStart: process$1.hrtime()
750
+ };
751
+ }
752
+ /**
753
+ * Resets the progress counters in place at the start/end of a generation run.
754
+ */
755
+ function resetProgressCounters(state) {
756
+ state.totalPlugins = 0;
757
+ state.completedPlugins = 0;
758
+ state.failedPlugins = 0;
759
+ state.totalFiles = 0;
760
+ state.processedFiles = 0;
761
+ state.hrStart = process$1.hrtime();
762
+ }
763
+ /**
764
+ * Records a finished plugin against the progress counters.
765
+ */
766
+ function recordPluginResult(state, success) {
767
+ if (success) state.completedPlugins++;
768
+ else state.failedPlugins++;
769
+ }
770
+ /**
771
+ * Creates a {@link HookTimer} backed by a private `id → hrtime` map.
772
+ */
773
+ function createHookTimer() {
774
+ const starts = /* @__PURE__ */ new Map();
775
+ return {
776
+ start(id) {
777
+ starts.set(id, process$1.hrtime());
778
+ },
779
+ end(id) {
780
+ const hrStart = starts.get(id);
781
+ if (!hrStart) return;
782
+ starts.delete(id);
783
+ return getElapsedMs(hrStart);
784
+ },
785
+ clear() {
786
+ starts.clear();
787
+ }
788
+ };
789
+ }
790
+ /**
791
+ * Join a command and its optional args into a single display string.
792
+ *
793
+ * @example With args
794
+ * `formatCommandWithArgs('prettier', ['--write', '.'])` returns `'prettier --write .'`
795
+ */
796
+ function formatCommandWithArgs(command, args) {
797
+ return args?.length ? `${command} ${args.join(" ")}` : command;
798
+ }
799
+ function detectLogger() {
800
+ if (canUseTTY()) return "clack";
801
+ return "plain";
802
+ }
803
+ const logMapper = {
804
+ clack: clackLogger,
805
+ plain: plainLogger
806
+ };
807
+ /**
808
+ * Bridges a {@link Reporter} onto the run's event emitter: calls `report` with each config's
809
+ * {@link GenerationResult} on `kubb:generation:end`. The reporter never touches the emitter.
810
+ */
811
+ function installReporter(context, reporter, ctx) {
812
+ context.on("kubb:generation:end", async ({ config, diagnostics = [], filesCreated = 0, status = "success", hrStart = process$1.hrtime() }) => {
813
+ await reporter.report({
814
+ config,
815
+ diagnostics,
816
+ filesCreated,
817
+ status,
818
+ hrStart
819
+ }, ctx);
820
+ });
821
+ if (reporter.drain) context.on("kubb:lifecycle:end", () => reporter.drain?.(ctx));
822
+ }
823
+ /**
824
+ * Installs the live logger (the TUI view) and the given reporters (the output). The reporters are
825
+ * already selected by the caller (the CLI maps `--reporter` to names via `selectReporters`). This
826
+ * only wires them. Loggers receive hook subprocess output through `kubb:hook:line` and the
827
+ * `stdout`/`stderr` on `kubb:hook:end`, so nothing is returned here.
828
+ *
829
+ * Loggers and reporters are independent, except for `cli`: it both installs the live logger view
830
+ * here and registers as a reporter that prints the per-config summary. The `json` reporter owns
831
+ * stdout, so the whole `cli` reporter (live logger and summary) is skipped whenever `json` is
832
+ * among the reporters, even if `cli` is also listed.
833
+ */
834
+ async function setupReporters(context, { logLevel, reporters }) {
835
+ const hasJson = reporters.some((reporter) => reporter.name === "json");
836
+ const ctx = { logLevel };
837
+ for (const reporter of reporters) {
838
+ if (reporter.name === "cli") {
839
+ if (hasJson) continue;
840
+ const type = detectLogger();
841
+ const logger = logMapper[type];
842
+ if (!logger) throw new Error(`Unknown adapter type: ${type}`);
843
+ await logger.install(context, { logLevel });
844
+ }
845
+ installReporter(context, reporter, ctx);
846
+ }
847
+ }
848
+ /**
849
+ * Picks the reporters whose `name` matches one of `names`, in the order the names are given.
850
+ * The config carries every available reporter, and the host selects which to activate by name
851
+ * (the CLI maps `--reporter` to this). Duplicate names and names without a matching reporter are
852
+ * skipped.
853
+ */
854
+ function selectReporters(reporters, names) {
855
+ const seen = /* @__PURE__ */ new Set();
856
+ const selected = [];
857
+ for (const name of names) {
858
+ if (seen.has(name)) continue;
859
+ seen.add(name);
860
+ const reporter = reporters.find((candidate) => candidate.name === name);
861
+ if (reporter) selected.push(reporter);
862
+ }
863
+ return selected;
864
+ }
865
+ //#endregion
866
+ //#region ../../internals/shared/src/loader.ts
867
+ /**
868
+ * jiti options for loading Kubb config modules: the automatic JSX runtime pointed at
869
+ * `@kubb/renderer-jsx`, and `moduleCache` off so a re-load re-evaluates the file.
870
+ */
871
+ const JITI_OPTIONS = {
872
+ jsx: {
873
+ runtime: "automatic",
874
+ importSource: "@kubb/renderer-jsx"
875
+ },
876
+ moduleCache: false
877
+ };
878
+ /**
879
+ * Creates a runtime-aware loader for Kubb's TypeScript and JavaScript config modules.
880
+ *
881
+ * On Bun and Deno it imports the file natively, skipping jiti's transform step, and falls back to
882
+ * jiti only when the native import throws. On Node it always uses jiti, which transpiles TypeScript
883
+ * and the `@kubb/renderer-jsx` JSX runtime on the fly. The jiti instance is created lazily, so the
884
+ * Bun/Deno happy path never pays for it.
885
+ *
886
+ * @example
887
+ * ```ts
888
+ * const config = await createModuleLoader().load('/abs/kubb.config.ts', { default: true })
889
+ * ```
890
+ */
891
+ function createModuleLoader() {
892
+ let jiti;
893
+ const getJiti = () => jiti ??= createJiti(import.meta.url, JITI_OPTIONS);
894
+ const viaJiti = (filePath, options) => options?.default ? getJiti().import(filePath, { default: true }) : getJiti().import(filePath);
895
+ const viaNative = async (filePath, options) => {
896
+ const href = pathToFileURL(filePath).href;
897
+ const mod = await (options?.bust != null ? import(`${href}?t=${options.bust}`) : import(href));
898
+ return options?.default ? mod.default ?? mod : mod;
899
+ };
900
+ return { async load(filePath, options) {
901
+ if (runtime.isBun || runtime.isDeno) try {
902
+ return await viaNative(filePath, options);
903
+ } catch {
904
+ return viaJiti(filePath, options);
905
+ }
906
+ return viaJiti(filePath, options);
907
+ } };
908
+ }
909
+ //#endregion
910
+ //#region src/runners/generate/utils.ts
911
+ const loader = createModuleLoader();
912
+ const tsLoader = (configFile) => loader.load(configFile, { default: true });
913
+ const MODULE_NAME = "kubb";
914
+ const SEARCH_FILES = [
915
+ "",
916
+ ".config/",
917
+ "configs/"
918
+ ].flatMap((prefix) => [`${prefix}.${MODULE_NAME}rc`, `${prefix}${MODULE_NAME}.config`]);
919
+ const SEARCH_EXTENSIONS = [
920
+ "ts",
921
+ "mts",
922
+ "cts",
923
+ "js",
924
+ "mjs",
925
+ "cjs"
926
+ ];
927
+ /**
928
+ * Discovers the Kubb config and resolves it into a normalized array of configs.
929
+ * Every config in the result is guaranteed to have a `plugins` array.
930
+ */
931
+ async function getConfigs({ configPath, input, watch, logLevel }) {
932
+ const abs = configPath ? resolve(configPath) : void 0;
933
+ const sources = abs ? [{
934
+ files: [basename(abs)],
935
+ extensions: [],
936
+ parser: tsLoader
937
+ }] : [{
938
+ files: SEARCH_FILES,
939
+ extensions: SEARCH_EXTENSIONS,
940
+ parser: tsLoader
941
+ }];
942
+ let result;
943
+ try {
944
+ result = await loadConfig({
945
+ cwd: abs ? dirname(abs) : process$1.cwd(),
946
+ sources,
947
+ merge: false
948
+ });
949
+ } catch (error) {
950
+ throw new Error("Config failed loading", { cause: error });
951
+ }
952
+ const [filepath] = result.sources;
953
+ if (!result.config || !filepath) throw new Error("Config not defined, create a kubb.config.js or pass through your config with the option --config");
954
+ const config = result.config;
955
+ const resolved = await (typeof config === "function" ? config({
956
+ config: configPath,
957
+ input,
958
+ watch,
959
+ logLevel
960
+ }) : config);
961
+ return {
962
+ configPath: filepath,
963
+ configs: (Array.isArray(resolved) ? resolved : [resolved]).map((item) => ({
964
+ ...item,
965
+ plugins: item.plugins ?? []
966
+ }))
967
+ };
968
+ }
969
+ /**
970
+ * Tokenizes a shell command string, respecting single and double quotes.
971
+ *
972
+ * @example
973
+ * ```ts
974
+ * tokenize('git commit -m "initial commit"')
975
+ * // → ['git', 'commit', '-m', 'initial commit']
976
+ * ```
977
+ */
978
+ function tokenize(command) {
979
+ return (command.match(/[^\s"']+|"([^"]*)"|'([^']*)'/g) ?? []).map((token) => token.replace(/^["']|["']$/g, ""));
980
+ }
981
+ /**
982
+ * Runs the `done` hooks defined in a Kubb config in sequence.
983
+ */
984
+ async function executeHooks({ configHooks, hooks }) {
985
+ const commands = Array.isArray(configHooks.done) ? configHooks.done : [configHooks.done].filter(Boolean);
986
+ for (const command of commands) {
987
+ const [cmd, ...args] = tokenize(command);
988
+ if (!cmd) continue;
989
+ const hookId = hash("sha256", command, "hex");
990
+ const commandWithArgs = [cmd, ...args].join(" ");
991
+ await hooks.emit("kubb:hook:start", {
992
+ id: hookId,
993
+ command: cmd,
994
+ args
995
+ });
996
+ await runHook({
997
+ id: hookId,
998
+ command: cmd,
999
+ args,
1000
+ commandWithArgs,
1001
+ hooks
1002
+ });
1003
+ }
1004
+ }
1005
+ /**
1006
+ * Spawns a hook command and reports its outcome through `kubb:hook:end`.
1007
+ * A non-zero exit signals failure via `kubb:hook:end` rather than throwing, so the caller can turn
1008
+ * it into a diagnostic. Other spawn errors do the same. Output is streamed through `kubb:hook:line`
1009
+ * only while a listener is attached.
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$1.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$1.once("SIGINT", () => {
1060
+ watcher.close();
1061
+ });
1062
+ process$1.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 cannot 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 reporters (CLI `--reporter` picks which of `config.reporters` to trigger),
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-KlHwxNTr.js.map