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

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