@kubb/cli 5.0.0-beta.9 → 5.0.0-beta.93

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