@kubb/cli 5.0.0-beta.5 → 5.0.0-beta.50

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 (146) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +171 -51
  3. package/dist/constants-BQ8LZB1P.js +23 -0
  4. package/dist/constants-BQ8LZB1P.js.map +1 -0
  5. package/dist/constants-MzEjK668.cjs +40 -0
  6. package/dist/constants-MzEjK668.cjs.map +1 -0
  7. package/dist/{define-Bdn8j5VM.cjs → define-C4AB3POr.cjs} +2 -2
  8. package/dist/{define-Bdn8j5VM.cjs.map → define-C4AB3POr.cjs.map} +1 -1
  9. package/dist/{define-Ctii4bel.js → define-C63T4jp6.js} +2 -2
  10. package/dist/{define-Ctii4bel.js.map → define-C63T4jp6.js.map} +1 -1
  11. package/dist/{errors-CjPmyZHy.js → errors-BsemQCMn.js} +2 -2
  12. package/dist/{errors-CjPmyZHy.js.map → errors-BsemQCMn.js.map} +1 -1
  13. package/dist/{errors-CLCjoSg0.cjs → errors-DykI11xo.cjs} +2 -2
  14. package/dist/{errors-CLCjoSg0.cjs.map → errors-DykI11xo.cjs.map} +1 -1
  15. package/dist/generate-CKnn3tQa.js +83 -0
  16. package/dist/generate-CKnn3tQa.js.map +1 -0
  17. package/dist/generate-Q6GMu4L8.cjs +82 -0
  18. package/dist/generate-Q6GMu4L8.cjs.map +1 -0
  19. package/dist/index.cjs +22 -15
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.js +22 -15
  23. package/dist/index.js.map +1 -1
  24. package/dist/init-C5iCqBwA.cjs +53 -0
  25. package/dist/init-C5iCqBwA.cjs.map +1 -0
  26. package/dist/init-DyOF6CiQ.js +53 -0
  27. package/dist/init-DyOF6CiQ.js.map +1 -0
  28. package/dist/mcp-09FvxYWS.js +39 -0
  29. package/dist/mcp-09FvxYWS.js.map +1 -0
  30. package/dist/mcp-BN5HQYdK.cjs +39 -0
  31. package/dist/mcp-BN5HQYdK.cjs.map +1 -0
  32. package/dist/package-Bm6VUbtL.js +6 -0
  33. package/dist/package-Bm6VUbtL.js.map +1 -0
  34. package/dist/{package-BmYRU2hz.cjs → package-DOVOGEEY.cjs} +2 -2
  35. package/dist/package-DOVOGEEY.cjs.map +1 -0
  36. package/dist/run-BO7phoNN.js +51 -0
  37. package/dist/run-BO7phoNN.js.map +1 -0
  38. package/dist/{init-C5sZulT6.cjs → run-BtjzfTz3.cjs} +155 -85
  39. package/dist/run-BtjzfTz3.cjs.map +1 -0
  40. package/dist/run-BzaKz_nl.js +32 -0
  41. package/dist/run-BzaKz_nl.js.map +1 -0
  42. package/dist/{init-Cag3082g.js → run-C-omuksC.js} +147 -77
  43. package/dist/run-C-omuksC.js.map +1 -0
  44. package/dist/run-CkTpemme.cjs +52 -0
  45. package/dist/run-CkTpemme.cjs.map +1 -0
  46. package/dist/run-Cl4SrSob.cjs +33 -0
  47. package/dist/run-Cl4SrSob.cjs.map +1 -0
  48. package/dist/run-CrvmI4G2.cjs +1520 -0
  49. package/dist/run-CrvmI4G2.cjs.map +1 -0
  50. package/dist/run-DvZ5i2lT.js +1517 -0
  51. package/dist/run-DvZ5i2lT.js.map +1 -0
  52. package/dist/{shell-DLzN4fRo.js → shell-DsgkfUSW.js} +2 -2
  53. package/dist/{shell-DLzN4fRo.js.map → shell-DsgkfUSW.js.map} +1 -1
  54. package/dist/{shell-475fQKaX.cjs → shell-Lh-vLWwH.cjs} +2 -2
  55. package/dist/{shell-475fQKaX.cjs.map → shell-Lh-vLWwH.cjs.map} +1 -1
  56. package/dist/validate-5atkOC73.js +26 -0
  57. package/dist/validate-5atkOC73.js.map +1 -0
  58. package/dist/validate-C6KPFEex.cjs +26 -0
  59. package/dist/validate-C6KPFEex.cjs.map +1 -0
  60. package/package.json +14 -24
  61. package/src/commands/generate.ts +27 -13
  62. package/src/commands/init.ts +34 -3
  63. package/src/commands/mcp.ts +28 -4
  64. package/src/commands/validate.ts +6 -4
  65. package/src/constants.ts +1 -86
  66. package/src/index.ts +7 -6
  67. package/src/loggers/clackLogger.ts +137 -178
  68. package/src/loggers/plainLogger.ts +49 -102
  69. package/src/loggers/types.ts +6 -1
  70. package/src/loggers/utils.ts +141 -26
  71. package/src/runners/generate/run.ts +406 -0
  72. package/src/runners/generate/utils.ts +228 -0
  73. package/src/runners/init/run.ts +210 -0
  74. package/src/{utils/packageManager.ts → runners/init/utils.ts} +12 -2
  75. package/src/runners/mcp/run.ts +37 -0
  76. package/src/runners/validate/run.ts +63 -0
  77. package/dist/agent-BcUEl9yB.js +0 -56
  78. package/dist/agent-BcUEl9yB.js.map +0 -1
  79. package/dist/agent-CS45W0kL.cjs +0 -122
  80. package/dist/agent-CS45W0kL.cjs.map +0 -1
  81. package/dist/agent-CsMvXeqI.cjs +0 -58
  82. package/dist/agent-CsMvXeqI.cjs.map +0 -1
  83. package/dist/agent-IP0eLV3C.js +0 -118
  84. package/dist/agent-IP0eLV3C.js.map +0 -1
  85. package/dist/constants-B4iBDvCe.cjs +0 -148
  86. package/dist/constants-B4iBDvCe.cjs.map +0 -1
  87. package/dist/constants-DmPrkaz8.js +0 -95
  88. package/dist/constants-DmPrkaz8.js.map +0 -1
  89. package/dist/generate-7td_hs73.cjs +0 -65
  90. package/dist/generate-7td_hs73.cjs.map +0 -1
  91. package/dist/generate-BqeFFQGD.js +0 -66
  92. package/dist/generate-BqeFFQGD.js.map +0 -1
  93. package/dist/generate-CUd1dUY5.cjs +0 -1755
  94. package/dist/generate-CUd1dUY5.cjs.map +0 -1
  95. package/dist/generate-DVmGtwWe.js +0 -1752
  96. package/dist/generate-DVmGtwWe.js.map +0 -1
  97. package/dist/init-C5sZulT6.cjs.map +0 -1
  98. package/dist/init-Cag3082g.js.map +0 -1
  99. package/dist/init-CfAn19gC.js +0 -25
  100. package/dist/init-CfAn19gC.js.map +0 -1
  101. package/dist/init-CfsYoyGe.cjs +0 -25
  102. package/dist/init-CfsYoyGe.cjs.map +0 -1
  103. package/dist/mcp-BfORW-mY.cjs +0 -47
  104. package/dist/mcp-BfORW-mY.cjs.map +0 -1
  105. package/dist/mcp-BtOV6acy.js +0 -16
  106. package/dist/mcp-BtOV6acy.js.map +0 -1
  107. package/dist/mcp-CIbuLGMx.cjs +0 -16
  108. package/dist/mcp-CIbuLGMx.cjs.map +0 -1
  109. package/dist/mcp-DtQ5o0On.js +0 -46
  110. package/dist/mcp-DtQ5o0On.js.map +0 -1
  111. package/dist/package-BmYRU2hz.cjs.map +0 -1
  112. package/dist/package-DBU5ii-k.js +0 -6
  113. package/dist/package-DBU5ii-k.js.map +0 -1
  114. package/dist/telemetry-BU25EoI-.cjs +0 -282
  115. package/dist/telemetry-BU25EoI-.cjs.map +0 -1
  116. package/dist/telemetry-CaNU4-Bf.js +0 -245
  117. package/dist/telemetry-CaNU4-Bf.js.map +0 -1
  118. package/dist/validate-CQqM9siF.js +0 -25
  119. package/dist/validate-CQqM9siF.js.map +0 -1
  120. package/dist/validate-DBXLaLIn.cjs +0 -34
  121. package/dist/validate-DBXLaLIn.cjs.map +0 -1
  122. package/dist/validate-DI23zgmL.js +0 -33
  123. package/dist/validate-DI23zgmL.js.map +0 -1
  124. package/dist/validate-DwX4LzYq.cjs +0 -25
  125. package/dist/validate-DwX4LzYq.cjs.map +0 -1
  126. package/src/commands/agent/start.ts +0 -47
  127. package/src/commands/agent.ts +0 -8
  128. package/src/loggers/fileSystemLogger.ts +0 -138
  129. package/src/loggers/githubActionsLogger.ts +0 -379
  130. package/src/runners/agent.ts +0 -155
  131. package/src/runners/generate.ts +0 -333
  132. package/src/runners/init.ts +0 -296
  133. package/src/runners/mcp.ts +0 -51
  134. package/src/runners/validate.ts +0 -39
  135. package/src/types.ts +0 -11
  136. package/src/utils/Writables.ts +0 -17
  137. package/src/utils/executeHooks.ts +0 -45
  138. package/src/utils/flags.ts +0 -9
  139. package/src/utils/getConfig.ts +0 -10
  140. package/src/utils/getCosmiConfig.ts +0 -75
  141. package/src/utils/getSummary.ts +0 -68
  142. package/src/utils/runHook.ts +0 -91
  143. package/src/utils/telemetry.ts +0 -273
  144. package/src/utils/watcher.ts +0 -19
  145. /package/dist/{chunk-ByKO4r7w.cjs → chunk-Bx3C2hgW.cjs} +0 -0
  146. /package/dist/{chunk--u3MIqq1.js → chunk-C0LytTxp.js} +0 -0
@@ -1,1752 +0,0 @@
1
- import "./chunk--u3MIqq1.js";
2
- import { n as toCause, r as toError } from "./errors-CjPmyZHy.js";
3
- import { a as canUseTTY, i as executeIfOnline, o as isGitHubActions, r as sendTelemetry, t as buildTelemetryEvent } from "./telemetry-CaNU4-Bf.js";
4
- import { n as tokenize } from "./shell-DLzN4fRo.js";
5
- import { t as version } from "./package-DBU5ii-k.js";
6
- import { a as SUMMARY_SEPARATOR, n as KUBB_NPM_PACKAGE_URL, o as WATCHER_IGNORED_PATHS } from "./constants-DmPrkaz8.js";
7
- import { styleText } from "node:util";
8
- import { EventEmitter } from "node:events";
9
- import { createHash } from "node:crypto";
10
- import { spawn } from "node:child_process";
11
- import { readdirSync } from "node:fs";
12
- import { mkdir, readFile, writeFile } from "node:fs/promises";
13
- import path, { dirname, relative, resolve } from "node:path";
14
- import process$1 from "node:process";
15
- import * as clack from "@clack/prompts";
16
- import { createKubb, defineLogger, isInputPath, logLevel } from "@kubb/core";
17
- import { NonZeroExitError, x } from "tinyexec";
18
- import { Writable } from "node:stream";
19
- import { cosmiconfig } from "cosmiconfig";
20
- import { createJiti } from "jiti";
21
- //#region ../../internals/utils/src/asyncEventEmitter.ts
22
- /**
23
- * Typed `EventEmitter` that awaits all async listeners before resolving.
24
- * Wraps Node's `EventEmitter` with full TypeScript event-map inference.
25
- *
26
- * @example
27
- * ```ts
28
- * const emitter = new AsyncEventEmitter<{ build: [name: string] }>()
29
- * emitter.on('build', async (name) => { console.log(name) })
30
- * await emitter.emit('build', 'petstore') // all listeners awaited
31
- * ```
32
- */
33
- var AsyncEventEmitter = class {
34
- /**
35
- * Maximum number of listeners per event before Node emits a memory-leak warning.
36
- * @default 10
37
- */
38
- constructor(maxListener = 10) {
39
- this.#emitter.setMaxListeners(maxListener);
40
- }
41
- #emitter = new EventEmitter();
42
- /**
43
- * Emits `eventName` and awaits all registered listeners sequentially.
44
- * Throws if any listener rejects, wrapping the cause with the event name and serialized arguments.
45
- *
46
- * @example
47
- * ```ts
48
- * await emitter.emit('build', 'petstore')
49
- * ```
50
- */
51
- async emit(eventName, ...eventArgs) {
52
- const listeners = this.#emitter.listeners(eventName);
53
- if (listeners.length === 0) return;
54
- for (const listener of listeners) try {
55
- await listener(...eventArgs);
56
- } catch (err) {
57
- let serializedArgs;
58
- try {
59
- serializedArgs = JSON.stringify(eventArgs);
60
- } catch {
61
- serializedArgs = String(eventArgs);
62
- }
63
- throw new Error(`Error in async listener for "${eventName}" with eventArgs ${serializedArgs}`, { cause: toError(err) });
64
- }
65
- }
66
- /**
67
- * Registers a persistent listener for `eventName`.
68
- *
69
- * @example
70
- * ```ts
71
- * emitter.on('build', async (name) => { console.log(name) })
72
- * ```
73
- */
74
- on(eventName, handler) {
75
- this.#emitter.on(eventName, handler);
76
- }
77
- /**
78
- * Registers a one-shot listener that removes itself after the first invocation.
79
- *
80
- * @example
81
- * ```ts
82
- * emitter.onOnce('build', async (name) => { console.log(name) })
83
- * ```
84
- */
85
- onOnce(eventName, handler) {
86
- const wrapper = (...args) => {
87
- this.off(eventName, wrapper);
88
- return handler(...args);
89
- };
90
- this.on(eventName, wrapper);
91
- }
92
- /**
93
- * Removes a previously registered listener.
94
- *
95
- * @example
96
- * ```ts
97
- * emitter.off('build', handler)
98
- * ```
99
- */
100
- off(eventName, handler) {
101
- this.#emitter.off(eventName, handler);
102
- }
103
- /**
104
- * Returns the number of listeners registered for `eventName`.
105
- *
106
- * @example
107
- * ```ts
108
- * emitter.on('build', handler)
109
- * emitter.listenerCount('build') // 1
110
- * ```
111
- */
112
- listenerCount(eventName) {
113
- return this.#emitter.listenerCount(eventName);
114
- }
115
- /**
116
- * Removes all listeners from every event channel.
117
- *
118
- * @example
119
- * ```ts
120
- * emitter.removeAll()
121
- * ```
122
- */
123
- removeAll() {
124
- this.#emitter.removeAllListeners();
125
- }
126
- };
127
- //#endregion
128
- //#region ../../internals/utils/src/time.ts
129
- /**
130
- * Calculates elapsed time in milliseconds from a high-resolution `process.hrtime` start time.
131
- * Rounds to 2 decimal places for sub-millisecond precision without noise.
132
- *
133
- * @example
134
- * ```ts
135
- * const start = process.hrtime()
136
- * doWork()
137
- * getElapsedMs(start) // 42.35
138
- * ```
139
- */
140
- function getElapsedMs(hrStart) {
141
- const [seconds, nanoseconds] = process.hrtime(hrStart);
142
- const ms = seconds * 1e3 + nanoseconds / 1e6;
143
- return Math.round(ms * 100) / 100;
144
- }
145
- /**
146
- * Converts a millisecond duration into a human-readable string (`ms`, `s`, or `m s`).
147
- *
148
- * @example
149
- * ```ts
150
- * formatMs(250) // '250ms'
151
- * formatMs(1500) // '1.50s'
152
- * formatMs(90000) // '1m 30.0s'
153
- * ```
154
- */
155
- function formatMs(ms) {
156
- if (ms >= 6e4) return `${Math.floor(ms / 6e4)}m ${(ms % 6e4 / 1e3).toFixed(1)}s`;
157
- if (ms >= 1e3) return `${(ms / 1e3).toFixed(2)}s`;
158
- return `${Math.round(ms)}ms`;
159
- }
160
- /**
161
- * Formats the elapsed time since `hrStart` as a human-readable string.
162
- *
163
- * @example
164
- * ```ts
165
- * const start = process.hrtime()
166
- * doWork()
167
- * formatHrtime(start) // '1.50s'
168
- * ```
169
- */
170
- function formatHrtime(hrStart) {
171
- return formatMs(getElapsedMs(hrStart));
172
- }
173
- //#endregion
174
- //#region ../../internals/utils/src/colors.ts
175
- /**
176
- * Parses a CSS hex color string (`#RGB`) into its RGB channels.
177
- * Falls back to `255` for any channel that cannot be parsed.
178
- */
179
- function parseHex(color) {
180
- const int = Number.parseInt(color.replace("#", ""), 16);
181
- return Number.isNaN(int) ? {
182
- r: 255,
183
- g: 255,
184
- b: 255
185
- } : {
186
- r: int >> 16 & 255,
187
- g: int >> 8 & 255,
188
- b: int & 255
189
- };
190
- }
191
- /**
192
- * Returns a function that wraps a string in a 24-bit ANSI true-color escape sequence
193
- * for the given hex color.
194
- */
195
- function hex(color) {
196
- const { r, g, b } = parseHex(color);
197
- return (text) => `\x1b[38;2;${r};${g};${b}m${text}\x1b[0m`;
198
- }
199
- function gradient(colorStops, text) {
200
- const chars = text.split("");
201
- return chars.map((char, i) => {
202
- const t = chars.length <= 1 ? 0 : i / (chars.length - 1);
203
- const seg = Math.min(Math.floor(t * (colorStops.length - 1)), colorStops.length - 2);
204
- const lt = t * (colorStops.length - 1) - seg;
205
- const from = parseHex(colorStops[seg]);
206
- const to = parseHex(colorStops[seg + 1]);
207
- 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`;
208
- }).join("");
209
- }
210
- /**
211
- * ANSI color functions for each part of the Kubb mascot illustration.
212
- */
213
- const palette = {
214
- /**
215
- * Top cap of the skittle.
216
- */
217
- lid: hex("#F55A17"),
218
- /**
219
- * Upper wood body.
220
- */
221
- woodTop: hex("#F5A217"),
222
- /**
223
- * Middle wood body.
224
- */
225
- woodMid: hex("#F58517"),
226
- /**
227
- * Base wood body.
228
- */
229
- woodBase: hex("#B45309"),
230
- /**
231
- * Eye whites.
232
- */
233
- eye: hex("#FFFFFF"),
234
- /**
235
- * Highlight accent.
236
- */
237
- highlight: hex("#adadc6"),
238
- /**
239
- * Cheek blush.
240
- */
241
- blush: hex("#FDA4AF")
242
- };
243
- /**
244
- * Generates the Kubb mascot welcome banner as an ANSI-colored string.
245
- *
246
- * @example
247
- * ```ts
248
- * console.log(getIntro({ title: 'kubb.config.ts', description: 'generating…', version: '5.0.0', areEyesOpen: true }))
249
- * ```
250
- */
251
- function getIntro({ title, description, version, areEyesOpen }) {
252
- const kubbVersion = gradient([
253
- "#F58517",
254
- "#F5A217",
255
- "#F55A17"
256
- ], `KUBB v${version}`);
257
- const eyeTop = areEyesOpen ? palette.eye("█▀█") : palette.eye("───");
258
- const eyeBottom = areEyesOpen ? palette.eye("▀▀▀") : palette.eye("───");
259
- return `
260
- ${palette.lid("▄▄▄▄▄▄▄▄▄▄▄▄▄")}
261
- ${palette.woodTop("█ ")}${palette.highlight("▄▄")}${palette.woodTop(" ")}${palette.highlight("▄▄")}${palette.woodTop(" █")} ${kubbVersion}
262
- ${palette.woodMid("█ ")}${eyeTop}${palette.woodMid(" ")}${eyeTop}${palette.woodMid(" █")} ${styleText("gray", title)}
263
- ${palette.woodMid("█ ")}${eyeBottom}${palette.woodMid(" ")}${palette.blush("◡")}${palette.woodMid(" ")}${eyeBottom}${palette.woodMid(" █")} ${styleText("yellow", "➜")} ${styleText("white", description)}
264
- ${palette.woodBase("▀▀▀▀▀▀▀▀▀▀▀▀▀")}
265
- `;
266
- }
267
- /**
268
- * ANSI color names used by {@link randomCliColor} for deterministic terminal coloring.
269
- */
270
- const randomColors = [
271
- "black",
272
- "red",
273
- "green",
274
- "yellow",
275
- "blue",
276
- "white",
277
- "magenta",
278
- "cyan",
279
- "gray"
280
- ];
281
- /**
282
- * Wraps `text` in a deterministic ANSI color derived from the text's SHA-256 hash.
283
- *
284
- * @example
285
- * ```ts
286
- * randomCliColor('petstore') // '\x1b[33m' + 'petstore' + '\x1b[39m' (always the same color for 'petstore')
287
- * ```
288
- */
289
- function randomCliColor(text) {
290
- if (!text) return "";
291
- return styleText(randomColors[createHash("sha256").update(text).digest().readUInt32BE(0) % randomColors.length] ?? "white", text);
292
- }
293
- /**
294
- * Formats a millisecond duration with a threshold-based ANSI color.
295
- * `≤ 500 ms` → green · `≤ 1 000 ms` → yellow · `> 1 000 ms` → red.
296
- *
297
- * @example
298
- * ```ts
299
- * formatMsWithColor(200) // '\x1b[32m200ms\x1b[39m'
300
- * formatMsWithColor(800) // '\x1b[33m800ms\x1b[39m'
301
- * formatMsWithColor(1500) // '\x1b[31m1.50s\x1b[39m'
302
- * ```
303
- */
304
- function formatMsWithColor(ms) {
305
- const formatted = formatMs(ms);
306
- if (ms <= 500) return styleText("green", formatted);
307
- if (ms <= 1e3) return styleText("yellow", formatted);
308
- return styleText("red", formatted);
309
- }
310
- //#endregion
311
- //#region ../../internals/utils/src/formatters.ts
312
- /**
313
- * CLI command descriptors for each supported code formatter.
314
- *
315
- * Each entry contains the executable `command`, an `args` factory that maps an
316
- * output path to the correct argument list, and an `errorMessage` shown when
317
- * the formatter is not found.
318
- */
319
- const formatters = {
320
- prettier: {
321
- command: "prettier",
322
- args: (outputPath) => [
323
- "--ignore-unknown",
324
- "--write",
325
- outputPath
326
- ],
327
- errorMessage: "Prettier not found"
328
- },
329
- biome: {
330
- command: "biome",
331
- args: (outputPath) => [
332
- "format",
333
- "--write",
334
- outputPath
335
- ],
336
- errorMessage: "Biome not found"
337
- },
338
- oxfmt: {
339
- command: "oxfmt",
340
- args: (outputPath) => [outputPath],
341
- errorMessage: "Oxfmt not found"
342
- }
343
- };
344
- async function isFormatterAvailable(formatter) {
345
- return new Promise((resolve) => {
346
- const child = spawn(formatter, ["--version"], { stdio: "ignore" });
347
- child.on("close", (code) => resolve(code === 0));
348
- child.on("error", () => resolve(false));
349
- });
350
- }
351
- /**
352
- * Detects the first available code formatter on the current system.
353
- *
354
- * - Checks in preference order: `oxfmt`, `biome`, `prettier`.
355
- * - Returns `null` when none are found.
356
- *
357
- * @example
358
- * ```ts
359
- * const formatter = await detectFormatter()
360
- * if (formatter) {
361
- * console.log(`Using ${formatter} for formatting`)
362
- * }
363
- * ```
364
- */
365
- async function detectFormatter() {
366
- const formatterNames = new Set([
367
- "oxfmt",
368
- "biome",
369
- "prettier"
370
- ]);
371
- for (const formatter of formatterNames) if (await isFormatterAvailable(formatter)) return formatter;
372
- return null;
373
- }
374
- //#endregion
375
- //#region ../../internals/utils/src/fs.ts
376
- /**
377
- * Writes `data` to `path`, trimming leading/trailing whitespace before saving.
378
- * Skips the write when the trimmed content is empty or identical to what is already on disk.
379
- * Creates any missing parent directories automatically.
380
- * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.
381
- *
382
- * @example
383
- * ```ts
384
- * await write('./src/Pet.ts', source) // writes and returns trimmed content
385
- * await write('./src/Pet.ts', source) // null — file unchanged
386
- * await write('./src/Pet.ts', ' ') // null — empty content skipped
387
- * ```
388
- */
389
- async function write(path, data, options = {}) {
390
- const trimmed = data.trim();
391
- if (trimmed === "") return null;
392
- const resolved = resolve(path);
393
- if (typeof Bun !== "undefined") {
394
- const file = Bun.file(resolved);
395
- if ((await file.exists() ? await file.text() : null) === trimmed) return null;
396
- await Bun.write(resolved, trimmed);
397
- return trimmed;
398
- }
399
- try {
400
- if (await readFile(resolved, { encoding: "utf-8" }) === trimmed) return null;
401
- } catch {}
402
- await mkdir(dirname(resolved), { recursive: true });
403
- await writeFile(resolved, trimmed, { encoding: "utf-8" });
404
- if (options.sanity) {
405
- const savedData = await readFile(resolved, { encoding: "utf-8" });
406
- if (savedData !== trimmed) throw new Error(`Sanity check failed for ${path}\n\nData[${data.length}]:\n${data}\n\nSaved[${savedData.length}]:\n${savedData}\n`);
407
- return savedData;
408
- }
409
- return trimmed;
410
- }
411
- //#endregion
412
- //#region ../../internals/utils/src/linters.ts
413
- /**
414
- * Collects all files under `dir` recursively using Node's built-in fs APIs.
415
- *
416
- * Passing explicit file paths to oxlint (instead of a directory) bypasses
417
- * oxlint's `.gitignore`-aware directory traversal, which would otherwise skip
418
- * files that are listed in `.gitignore` (e.g. generated output directories).
419
- */
420
- function findLintableFiles(dir) {
421
- try {
422
- return readdirSync(dir, {
423
- withFileTypes: true,
424
- recursive: true
425
- }).filter((d) => d.isFile()).map((d) => `${d.parentPath}/${d.name}`);
426
- } catch {
427
- return [];
428
- }
429
- }
430
- /**
431
- * CLI command descriptors for each supported linter.
432
- *
433
- * Each entry contains the executable `command`, an `args` factory that maps an
434
- * output path to the correct argument list, and an `errorMessage` shown when
435
- * the linter is not found.
436
- */
437
- const linters = {
438
- eslint: {
439
- command: "eslint",
440
- args: (outputPath) => [outputPath, "--fix"],
441
- errorMessage: "Eslint not found"
442
- },
443
- biome: {
444
- command: "biome",
445
- args: (outputPath) => [
446
- "lint",
447
- "--fix",
448
- outputPath
449
- ],
450
- errorMessage: "Biome not found"
451
- },
452
- oxlint: {
453
- command: "oxlint",
454
- args: (outputPath) => ["--fix", ...findLintableFiles(outputPath)],
455
- errorMessage: "Oxlint not found"
456
- }
457
- };
458
- async function isLinterAvailable(linter) {
459
- return new Promise((resolve) => {
460
- const child = spawn(linter, ["--version"], { stdio: "ignore" });
461
- child.on("close", (code) => resolve(code === 0));
462
- child.on("error", () => resolve(false));
463
- });
464
- }
465
- /**
466
- * Detects the first available linter on the current system.
467
- *
468
- * - Checks in preference order: `oxlint`, `biome`, `eslint`.
469
- * - Returns `null` when none are found.
470
- *
471
- * @example
472
- * ```ts
473
- * const linter = await detectLinter()
474
- * if (linter) {
475
- * console.log(`Using ${linter} for linting`)
476
- * }
477
- * ```
478
- */
479
- async function detectLinter() {
480
- const linterNames = new Set([
481
- "oxlint",
482
- "biome",
483
- "eslint"
484
- ]);
485
- for (const linter of linterNames) if (await isLinterAvailable(linter)) return linter;
486
- return null;
487
- }
488
- //#endregion
489
- //#region src/utils/getSummary.ts
490
- function getSummary({ failedPlugins, filesCreated, status, hrStart, config, pluginTimings }) {
491
- const duration = formatHrtime(hrStart);
492
- const pluginsCount = config.plugins?.length ?? 0;
493
- const successCount = pluginsCount - failedPlugins.size;
494
- const meta = {
495
- plugins: status === "success" ? `${styleText("green", `${successCount} successful`)}, ${pluginsCount} total` : `${styleText("green", `${successCount} successful`)}, ${styleText("red", `${failedPlugins.size} failed`)}, ${pluginsCount} total`,
496
- pluginsFailed: status === "failed" ? [...failedPlugins].map(({ plugin }) => randomCliColor(plugin.name)).join(", ") : void 0,
497
- filesCreated,
498
- time: styleText("green", duration),
499
- output: path.resolve(config.root, config.output.path)
500
- };
501
- const labels = {
502
- plugins: "Plugins:",
503
- failed: "Failed:",
504
- generated: "Generated:",
505
- pluginTimings: "Plugin Timings:",
506
- output: "Output:"
507
- };
508
- const maxLength = Math.max(0, ...[...Object.values(labels), ...pluginTimings ? Array.from(pluginTimings.keys()) : []].map((s) => s.length));
509
- const summaryLines = [];
510
- summaryLines.push(`${labels.plugins.padEnd(maxLength + 2)} ${meta.plugins}`);
511
- if (meta.pluginsFailed) summaryLines.push(`${labels.failed.padEnd(maxLength + 2)} ${meta.pluginsFailed}`);
512
- summaryLines.push(`${labels.generated.padEnd(maxLength + 2)} ${meta.filesCreated} files in ${meta.time}`);
513
- if (pluginTimings && pluginTimings.size > 0) {
514
- const sortedTimings = Array.from(pluginTimings.entries()).sort((a, b) => b[1] - a[1]);
515
- summaryLines.push(`${labels.pluginTimings}`);
516
- sortedTimings.forEach(([name, time]) => {
517
- const timeStr = time >= 1e3 ? `${(time / 1e3).toFixed(2)}s` : `${Math.round(time)}ms`;
518
- const barLength = Math.min(Math.ceil(time / 100), 10);
519
- const bar = styleText("dim", "█".repeat(barLength));
520
- summaryLines.push(`${styleText("dim", "•")} ${name.padEnd(maxLength + 1)}${bar} ${timeStr}`);
521
- });
522
- }
523
- summaryLines.push(`${labels.output.padEnd(maxLength + 2)} ${meta.output}`);
524
- return summaryLines;
525
- }
526
- //#endregion
527
- //#region src/utils/runHook.ts
528
- /**
529
- * Executes a hook command, emits debug and completion events, and forwards output to an optional sink.
530
- */
531
- async function runHook({ id, command, args, commandWithArgs, context, stream = false, sink }) {
532
- try {
533
- const proc = x(command, [...args ?? []], {
534
- nodeOptions: { detached: process.platform !== "win32" },
535
- throwOnError: true
536
- });
537
- if (stream && sink?.onLine) for await (const line of proc) sink.onLine(line);
538
- const result = await proc;
539
- await context.emit("kubb:debug", {
540
- date: /* @__PURE__ */ new Date(),
541
- logs: [result.stdout.trimEnd()]
542
- });
543
- await context.emit("kubb:hook:end", {
544
- command,
545
- args,
546
- id,
547
- success: true,
548
- error: null
549
- });
550
- } catch (err) {
551
- if (!(err instanceof NonZeroExitError)) {
552
- await context.emit("kubb:hook:end", {
553
- command,
554
- args,
555
- id,
556
- success: false,
557
- error: toError(err)
558
- });
559
- await context.emit("kubb:error", { error: toError(err) });
560
- return;
561
- }
562
- const stderr = err.output?.stderr ?? "";
563
- const stdout = err.output?.stdout ?? "";
564
- await context.emit("kubb:debug", {
565
- date: /* @__PURE__ */ new Date(),
566
- logs: [stdout, stderr].filter(Boolean)
567
- });
568
- if (stderr) sink?.onStderr?.(stderr);
569
- if (stdout) sink?.onStdout?.(stdout);
570
- const errorMessage = /* @__PURE__ */ new Error(`Hook execute failed: ${commandWithArgs}`);
571
- await context.emit("kubb:hook:end", {
572
- command,
573
- args,
574
- id,
575
- success: false,
576
- error: errorMessage
577
- });
578
- await context.emit("kubb:error", { error: errorMessage });
579
- }
580
- }
581
- //#endregion
582
- //#region src/utils/Writables.ts
583
- var ClackWritable = class extends Writable {
584
- taskLog;
585
- constructor(taskLog, opts) {
586
- super(opts);
587
- this.taskLog = taskLog;
588
- }
589
- _write(chunk, _encoding, callback) {
590
- this.taskLog.message(`${styleText("dim", chunk.toString())}`);
591
- callback();
592
- }
593
- };
594
- //#endregion
595
- //#region src/loggers/clackLogger.ts
596
- /**
597
- * TTY logger with beautiful UI and progress indicators for local development.
598
- */
599
- const clackLogger = defineLogger({
600
- name: "clack",
601
- install(context, options) {
602
- const logLevel$8 = options?.logLevel ?? logLevel.info;
603
- const state = {
604
- totalPlugins: 0,
605
- completedPlugins: 0,
606
- failedPlugins: 0,
607
- totalFiles: 0,
608
- processedFiles: 0,
609
- hrStart: process$1.hrtime(),
610
- spinner: clack.spinner(),
611
- isSpinning: false,
612
- activeProgress: /* @__PURE__ */ new Map()
613
- };
614
- function reset() {
615
- for (const [_key, active] of state.activeProgress) {
616
- if (active.interval) clearInterval(active.interval);
617
- active.progressBar?.stop();
618
- }
619
- state.totalPlugins = 0;
620
- state.completedPlugins = 0;
621
- state.failedPlugins = 0;
622
- state.totalFiles = 0;
623
- state.processedFiles = 0;
624
- state.hrStart = process$1.hrtime();
625
- state.spinner = clack.spinner();
626
- state.isSpinning = false;
627
- state.activeProgress.clear();
628
- }
629
- function showProgressStep() {
630
- if (logLevel$8 <= logLevel.silent) return;
631
- const line = buildProgressLine(state);
632
- if (line) clack.log.step(getMessage(line));
633
- }
634
- function getMessage(message) {
635
- return formatMessage(message, logLevel$8);
636
- }
637
- function startSpinner(text) {
638
- state.spinner.start(text);
639
- state.isSpinning = true;
640
- }
641
- function stopSpinner(text) {
642
- state.spinner.stop(text);
643
- state.isSpinning = false;
644
- }
645
- context.on("kubb:info", ({ message, info = "" }) => {
646
- if (logLevel$8 <= logLevel.silent) return;
647
- const text = getMessage([
648
- styleText("blue", "ℹ"),
649
- message,
650
- styleText("dim", info)
651
- ].join(" "));
652
- if (state.isSpinning) state.spinner.message(text);
653
- else clack.log.info(text);
654
- });
655
- context.on("kubb:success", ({ message, info = "" }) => {
656
- if (logLevel$8 <= logLevel.silent) return;
657
- const text = getMessage([
658
- styleText("blue", "✓"),
659
- message,
660
- logLevel$8 >= logLevel.info ? styleText("dim", info) : void 0
661
- ].filter(Boolean).join(" "));
662
- if (state.isSpinning) stopSpinner(text);
663
- else clack.log.success(text);
664
- });
665
- context.on("kubb:warn", ({ message, info }) => {
666
- if (logLevel$8 < logLevel.warn) return;
667
- const text = getMessage([
668
- styleText("yellow", "⚠"),
669
- message,
670
- logLevel$8 >= logLevel.info && info ? styleText("dim", info) : void 0
671
- ].filter(Boolean).join(" "));
672
- clack.log.warn(text);
673
- });
674
- context.on("kubb:error", ({ error }) => {
675
- const caused = toCause(error);
676
- const text = [styleText("red", "✗"), error.message].join(" ");
677
- if (state.isSpinning) stopSpinner(getMessage(text));
678
- else clack.log.error(getMessage(text));
679
- if (logLevel$8 >= logLevel.debug && error.stack) {
680
- const frames = error.stack.split("\n").slice(1, 4);
681
- for (const frame of frames) clack.log.message(getMessage(styleText("dim", frame.trim())));
682
- if (caused?.stack) {
683
- clack.log.message(styleText("dim", `└─ caused by ${caused.message}`));
684
- const frames = caused.stack.split("\n").slice(1, 4);
685
- for (const frame of frames) clack.log.message(getMessage(` ${styleText("dim", frame.trim())}`));
686
- }
687
- }
688
- });
689
- context.on("kubb:version:new", ({ currentVersion, latestVersion }) => {
690
- if (logLevel$8 <= logLevel.silent) return;
691
- try {
692
- clack.box(`\`v${currentVersion}\` → \`v${latestVersion}\`
693
- Run \`npm install -g @kubb/cli\` to update`, "Update available for `Kubb`", {
694
- width: "auto",
695
- formatBorder: (s) => styleText("yellow", s),
696
- rounded: true,
697
- withGuide: false,
698
- contentAlign: "center",
699
- titleAlign: "center"
700
- });
701
- } catch {
702
- console.log(`Update available for Kubb: v${currentVersion} → v${latestVersion}`);
703
- console.log("Run `npm install -g @kubb/cli` to update");
704
- }
705
- });
706
- context.on("kubb:lifecycle:start", async ({ version }) => {
707
- console.log(`\n${getIntro({
708
- title: "The ultimate toolkit for working with APIs",
709
- description: "Ready to start",
710
- version,
711
- areEyesOpen: true
712
- })}\n`);
713
- reset();
714
- });
715
- context.on("kubb:config:start", () => {
716
- if (logLevel$8 <= logLevel.silent) return;
717
- const text = getMessage("Configuration started");
718
- clack.intro(text);
719
- startSpinner(getMessage("Configuration loading"));
720
- });
721
- context.on("kubb:config:end", () => {
722
- if (logLevel$8 <= logLevel.silent) return;
723
- const text = getMessage("Configuration completed");
724
- clack.outro(text);
725
- });
726
- context.on("kubb:generation:start", ({ config }) => {
727
- reset();
728
- state.totalPlugins = config.plugins?.length ?? 0;
729
- const text = getMessage(["Generation started", config.name ? `for ${styleText("dim", config.name)}` : void 0].filter(Boolean).join(" "));
730
- clack.intro(text);
731
- });
732
- context.on("kubb:plugin:start", ({ plugin }) => {
733
- if (logLevel$8 <= logLevel.silent) return;
734
- stopSpinner();
735
- const progressBar = clack.progress({
736
- style: "block",
737
- max: 100,
738
- size: 30
739
- });
740
- const text = getMessage(`Generating ${styleText("bold", plugin.name)}`);
741
- progressBar.start(text);
742
- const interval = setInterval(() => {
743
- progressBar.advance();
744
- }, 100);
745
- state.activeProgress.set(plugin.name, {
746
- progressBar,
747
- interval
748
- });
749
- });
750
- context.on("kubb:plugin:end", ({ plugin, duration, success }) => {
751
- stopSpinner();
752
- const active = state.activeProgress.get(plugin.name);
753
- if (!active || logLevel$8 === logLevel.silent) return;
754
- clearInterval(active.interval);
755
- if (success) state.completedPlugins++;
756
- else state.failedPlugins++;
757
- const durationStr = formatMsWithColor(duration);
758
- const text = getMessage(success ? `${styleText("bold", plugin.name)} completed in ${durationStr}` : `${styleText("bold", plugin.name)} failed in ${styleText("red", formatMs(duration))}`);
759
- active.progressBar.stop(text);
760
- state.activeProgress.delete(plugin.name);
761
- showProgressStep();
762
- });
763
- context.on("kubb:files:processing:start", ({ files }) => {
764
- if (logLevel$8 <= logLevel.silent) return;
765
- stopSpinner();
766
- state.totalFiles = files.length;
767
- state.processedFiles = 0;
768
- const text = `Writing ${files.length} files`;
769
- const progressBar = clack.progress({
770
- style: "block",
771
- max: files.length,
772
- size: 30
773
- });
774
- context.emit("kubb:info", { message: text });
775
- progressBar.start(getMessage(text));
776
- state.activeProgress.set("files", { progressBar });
777
- });
778
- context.on("kubb:file:processing:update", ({ file, config }) => {
779
- if (logLevel$8 <= logLevel.silent) return;
780
- stopSpinner();
781
- state.processedFiles++;
782
- const text = `Writing ${relative(config.root, file.path)}`;
783
- const active = state.activeProgress.get("files");
784
- if (!active) return;
785
- active.progressBar.advance(void 0, text);
786
- });
787
- context.on("kubb:files:processing:end", () => {
788
- if (logLevel$8 <= logLevel.silent) return;
789
- stopSpinner();
790
- const text = getMessage("Files written successfully");
791
- const active = state.activeProgress.get("files");
792
- if (!active) return;
793
- active.progressBar.stop(text);
794
- state.activeProgress.delete("files");
795
- showProgressStep();
796
- });
797
- context.on("kubb:generation:end", ({ config }) => {
798
- const text = getMessage(config.name ? `Generation completed for ${styleText("dim", config.name)}` : "Generation completed");
799
- clack.outro(text);
800
- });
801
- context.on("kubb:format:start", () => {
802
- if (logLevel$8 <= logLevel.silent) return;
803
- const text = getMessage("Format started");
804
- clack.intro(text);
805
- });
806
- context.on("kubb:format:end", () => {
807
- if (logLevel$8 <= logLevel.silent) return;
808
- const text = getMessage("Format completed");
809
- clack.outro(text);
810
- });
811
- context.on("kubb:lint:start", () => {
812
- if (logLevel$8 <= logLevel.silent) return;
813
- const text = getMessage("Lint started");
814
- clack.intro(text);
815
- });
816
- context.on("kubb:lint:end", () => {
817
- if (logLevel$8 <= logLevel.silent) return;
818
- const text = getMessage("Lint completed");
819
- clack.outro(text);
820
- });
821
- context.on("kubb:hook:start", async ({ id, command, args }) => {
822
- const commandWithArgs = formatCommandWithArgs(command, args);
823
- const text = getMessage(`Hook ${styleText("dim", commandWithArgs)} started`);
824
- if (!id) return;
825
- if (logLevel$8 <= logLevel.silent) {
826
- await runHook({
827
- id,
828
- command,
829
- args,
830
- commandWithArgs,
831
- context,
832
- sink: {
833
- onStderr: (s) => console.error(s),
834
- onStdout: (s) => console.log(s)
835
- }
836
- });
837
- return;
838
- }
839
- clack.intro(text);
840
- const logger = clack.taskLog({ title: getMessage(["Executing hook", logLevel$8 >= logLevel.info ? styleText("dim", commandWithArgs) : void 0].filter(Boolean).join(" ")) });
841
- const writable = new ClackWritable(logger);
842
- await runHook({
843
- id,
844
- command,
845
- args,
846
- commandWithArgs,
847
- context,
848
- stream: true,
849
- sink: {
850
- onLine: (line) => writable.write(line),
851
- onStderr: (s) => logger.error(s),
852
- onStdout: (s) => logger.message(s)
853
- }
854
- });
855
- });
856
- context.on("kubb:hook:end", ({ command, args }) => {
857
- if (logLevel$8 <= logLevel.silent) return;
858
- const text = getMessage(`Hook ${styleText("dim", formatCommandWithArgs(command, args))} successfully executed`);
859
- clack.outro(text);
860
- });
861
- context.on("kubb:generation:summary", ({ config, pluginTimings, failedPlugins, filesCreated, status, hrStart }) => {
862
- const summary = getSummary({
863
- failedPlugins,
864
- filesCreated,
865
- config,
866
- status,
867
- hrStart,
868
- pluginTimings: logLevel$8 >= logLevel.verbose ? pluginTimings : void 0
869
- });
870
- const title = config.name || "";
871
- summary.unshift("\n");
872
- summary.push("\n");
873
- const borderColor = status === "success" ? "green" : "red";
874
- try {
875
- clack.box(summary.join("\n"), getMessage(title), {
876
- width: "auto",
877
- formatBorder: (s) => styleText(borderColor, s),
878
- rounded: true,
879
- withGuide: false,
880
- contentAlign: "left",
881
- titleAlign: "center"
882
- });
883
- } catch {
884
- console.log(summary.join("\n"));
885
- }
886
- });
887
- context.on("kubb:lifecycle:end", () => {
888
- reset();
889
- });
890
- }
891
- });
892
- //#endregion
893
- //#region src/loggers/fileSystemLogger.ts
894
- /**
895
- * FileSystem logger that captures debug events and writes them to `.kubb` directory files.
896
- * Note: Logs write on `lifecycle:end` or process exit. Cached logs may be lost if the process crashes before these events.
897
- */
898
- const fileSystemLogger = defineLogger({
899
- name: "filesystem",
900
- install(context) {
901
- const state = {
902
- cachedLogs: /* @__PURE__ */ new Set(),
903
- startDate: Date.now()
904
- };
905
- function reset() {
906
- state.cachedLogs = /* @__PURE__ */ new Set();
907
- state.startDate = Date.now();
908
- }
909
- async function writeLogs(name) {
910
- if (state.cachedLogs.size === 0) return [];
911
- const files = {};
912
- for (const log of state.cachedLogs) {
913
- const baseName = log.fileName || `${[
914
- "kubb",
915
- name,
916
- state.startDate
917
- ].filter(Boolean).join("-")}.log`;
918
- const pathName = resolve(process$1.cwd(), ".kubb", baseName);
919
- if (!files[pathName]) files[pathName] = [];
920
- if (log.logs.length > 0) {
921
- const timestamp = log.date.toLocaleString();
922
- files[pathName].push(`[${timestamp}]\n${log.logs.join("\n")}`);
923
- }
924
- }
925
- for (const [fileName, logs] of Object.entries(files)) await write(fileName, logs.join("\n\n"));
926
- return Object.keys(files);
927
- }
928
- context.on("kubb:info", ({ message, info }) => {
929
- state.cachedLogs.add({
930
- date: /* @__PURE__ */ new Date(),
931
- logs: [`ℹ ${message} ${info}`]
932
- });
933
- });
934
- context.on("kubb:success", ({ message, info }) => {
935
- state.cachedLogs.add({
936
- date: /* @__PURE__ */ new Date(),
937
- logs: [`✓ ${message} ${info}`]
938
- });
939
- });
940
- context.on("kubb:warn", ({ message, info }) => {
941
- state.cachedLogs.add({
942
- date: /* @__PURE__ */ new Date(),
943
- logs: [`⚠ ${message} ${info}`]
944
- });
945
- });
946
- context.on("kubb:error", ({ error }) => {
947
- state.cachedLogs.add({
948
- date: /* @__PURE__ */ new Date(),
949
- logs: [`✗ ${error.message}`, error.stack || "unknown stack"]
950
- });
951
- });
952
- context.on("kubb:debug", (message) => {
953
- state.cachedLogs.add({
954
- date: /* @__PURE__ */ new Date(),
955
- logs: message.logs
956
- });
957
- });
958
- context.on("kubb:plugin:start", ({ plugin }) => {
959
- state.cachedLogs.add({
960
- date: /* @__PURE__ */ new Date(),
961
- logs: [`Generating ${plugin.name}`]
962
- });
963
- });
964
- context.on("kubb:plugin:end", ({ plugin, duration, success }) => {
965
- const durationStr = formatMs(duration);
966
- state.cachedLogs.add({
967
- date: /* @__PURE__ */ new Date(),
968
- logs: [success ? `${plugin.name} completed in ${durationStr}` : `${plugin.name} failed in ${durationStr}`]
969
- });
970
- });
971
- context.on("kubb:files:processing:start", ({ files }) => {
972
- state.cachedLogs.add({
973
- date: /* @__PURE__ */ new Date(),
974
- logs: [`Start ${files.length} writing:`, ...files.map((file) => file.path)]
975
- });
976
- });
977
- context.on("kubb:generation:end", async ({ config }) => {
978
- const writtenFilePaths = await writeLogs(config.name);
979
- if (writtenFilePaths.length > 0) {
980
- const files = writtenFilePaths.map((f) => relative(process$1.cwd(), f));
981
- await context.emit("kubb:info", {
982
- message: "Debug files written to:",
983
- info: files.join(", ")
984
- });
985
- }
986
- reset();
987
- });
988
- const exitHandler = () => {
989
- if (state.cachedLogs.size > 0) writeLogs().catch(() => {});
990
- };
991
- process$1.once("exit", exitHandler);
992
- process$1.once("SIGINT", exitHandler);
993
- process$1.once("SIGTERM", exitHandler);
994
- }
995
- });
996
- //#endregion
997
- //#region src/loggers/githubActionsLogger.ts
998
- /**
999
- * GitHub Actions logger using group annotations for collapsible sections in CI.
1000
- */
1001
- const githubActionsLogger = defineLogger({
1002
- name: "github-actions",
1003
- install(context, options) {
1004
- const logLevel$7 = options?.logLevel ?? logLevel.info;
1005
- const state = {
1006
- totalPlugins: 0,
1007
- completedPlugins: 0,
1008
- failedPlugins: 0,
1009
- totalFiles: 0,
1010
- processedFiles: 0,
1011
- hrStart: process.hrtime(),
1012
- currentConfigs: []
1013
- };
1014
- function reset() {
1015
- state.totalPlugins = 0;
1016
- state.completedPlugins = 0;
1017
- state.failedPlugins = 0;
1018
- state.totalFiles = 0;
1019
- state.processedFiles = 0;
1020
- state.hrStart = process.hrtime();
1021
- state.currentConfigs = [];
1022
- }
1023
- function showProgressStep() {
1024
- if (logLevel$7 <= logLevel.silent) return;
1025
- const line = buildProgressLine(state);
1026
- if (line) console.log(getMessage(line));
1027
- }
1028
- function getMessage(message) {
1029
- return formatMessage(message, logLevel$7);
1030
- }
1031
- function openGroup(name) {
1032
- console.log(`::group::${name}`);
1033
- }
1034
- function closeGroup(_name) {
1035
- console.log("::endgroup::");
1036
- }
1037
- context.on("kubb:info", ({ message, info = "" }) => {
1038
- if (logLevel$7 <= logLevel.silent) return;
1039
- const text = getMessage([
1040
- styleText("blue", "ℹ"),
1041
- message,
1042
- styleText("dim", info)
1043
- ].join(" "));
1044
- console.log(text);
1045
- });
1046
- context.on("kubb:success", ({ message, info = "" }) => {
1047
- if (logLevel$7 <= logLevel.silent) return;
1048
- const text = getMessage([
1049
- styleText("blue", "✓"),
1050
- message,
1051
- logLevel$7 >= logLevel.info ? styleText("dim", info) : void 0
1052
- ].filter(Boolean).join(" "));
1053
- console.log(text);
1054
- });
1055
- context.on("kubb:warn", ({ message, info = "" }) => {
1056
- if (logLevel$7 <= logLevel.silent) return;
1057
- const text = getMessage([
1058
- styleText("yellow", "⚠"),
1059
- message,
1060
- logLevel$7 >= logLevel.info ? styleText("dim", info) : void 0
1061
- ].filter(Boolean).join(" "));
1062
- console.warn(`::warning::${text}`);
1063
- });
1064
- context.on("kubb:error", ({ error }) => {
1065
- const caused = toCause(error);
1066
- if (logLevel$7 <= logLevel.silent) return;
1067
- const message = error.message || String(error);
1068
- console.error(`::error::${message}`);
1069
- if (logLevel$7 >= logLevel.debug && error.stack) {
1070
- const frames = error.stack.split("\n").slice(1, 4);
1071
- for (const frame of frames) console.log(getMessage(styleText("dim", frame.trim())));
1072
- if (caused?.stack) {
1073
- console.log(styleText("dim", `└─ caused by ${caused.message}`));
1074
- const frames = caused.stack.split("\n").slice(1, 4);
1075
- for (const frame of frames) console.log(getMessage(` ${styleText("dim", frame.trim())}`));
1076
- }
1077
- }
1078
- });
1079
- context.on("kubb:lifecycle:start", ({ version }) => {
1080
- console.log(styleText("yellow", `Kubb ${version} 🧩`));
1081
- reset();
1082
- });
1083
- context.on("kubb:config:start", () => {
1084
- if (logLevel$7 <= logLevel.silent) return;
1085
- const text = getMessage("Configuration started");
1086
- openGroup("Configuration");
1087
- console.log(text);
1088
- });
1089
- context.on("kubb:config:end", ({ configs }) => {
1090
- state.currentConfigs = configs;
1091
- if (logLevel$7 <= logLevel.silent) return;
1092
- const text = getMessage("Configuration completed");
1093
- console.log(text);
1094
- closeGroup("Configuration");
1095
- });
1096
- context.on("kubb:generation:start", ({ config }) => {
1097
- reset();
1098
- state.totalPlugins = config.plugins?.length ?? 0;
1099
- const text = config.name ? `Generation for ${styleText("bold", config.name)}` : "Generation";
1100
- if (state.currentConfigs.length > 1) openGroup(text);
1101
- if (state.currentConfigs.length === 1) console.log(getMessage(text));
1102
- });
1103
- context.on("kubb:plugin:start", ({ plugin }) => {
1104
- if (logLevel$7 <= logLevel.silent) return;
1105
- const text = getMessage(`Generating ${styleText("bold", plugin.name)}`);
1106
- if (state.currentConfigs.length === 1) openGroup(`Plugin: ${plugin.name}`);
1107
- console.log(text);
1108
- });
1109
- context.on("kubb:plugin:end", ({ plugin, duration, success }) => {
1110
- if (logLevel$7 <= logLevel.silent) return;
1111
- if (success) state.completedPlugins++;
1112
- else state.failedPlugins++;
1113
- const durationStr = formatMsWithColor(duration);
1114
- const text = getMessage(success ? `${styleText("bold", plugin.name)} completed in ${durationStr}` : `${styleText("bold", plugin.name)} failed in ${styleText("red", formatMs(duration))}`);
1115
- console.log(text);
1116
- if (state.currentConfigs.length > 1) console.log(" ");
1117
- if (state.currentConfigs.length === 1) closeGroup(`Plugin: ${plugin.name}`);
1118
- showProgressStep();
1119
- });
1120
- context.on("kubb:files:processing:start", ({ files }) => {
1121
- if (logLevel$7 <= logLevel.silent) return;
1122
- state.totalFiles = files.length;
1123
- state.processedFiles = 0;
1124
- if (state.currentConfigs.length === 1) openGroup("File Generation");
1125
- const text = getMessage(`Writing ${files.length} files`);
1126
- console.log(text);
1127
- });
1128
- context.on("kubb:files:processing:end", () => {
1129
- if (logLevel$7 <= logLevel.silent) return;
1130
- const text = getMessage("Files written successfully");
1131
- console.log(text);
1132
- if (state.currentConfigs.length === 1) closeGroup("File Generation");
1133
- showProgressStep();
1134
- });
1135
- context.on("kubb:file:processing:update", () => {
1136
- if (logLevel$7 <= logLevel.silent) return;
1137
- state.processedFiles++;
1138
- });
1139
- context.on("kubb:generation:end", ({ config }) => {
1140
- const text = getMessage(config.name ? `${styleText("blue", "✓")} Generation completed for ${styleText("dim", config.name)}` : `${styleText("blue", "✓")} Generation completed`);
1141
- console.log(text);
1142
- });
1143
- context.on("kubb:format:start", () => {
1144
- if (logLevel$7 <= logLevel.silent) return;
1145
- const text = getMessage("Format started");
1146
- if (state.currentConfigs.length === 1) openGroup("Formatting");
1147
- console.log(text);
1148
- });
1149
- context.on("kubb:format:end", () => {
1150
- if (logLevel$7 <= logLevel.silent) return;
1151
- const text = getMessage("Format completed");
1152
- console.log(text);
1153
- if (state.currentConfigs.length === 1) closeGroup("Formatting");
1154
- });
1155
- context.on("kubb:lint:start", () => {
1156
- if (logLevel$7 <= logLevel.silent) return;
1157
- const text = getMessage("Lint started");
1158
- if (state.currentConfigs.length === 1) openGroup("Linting");
1159
- console.log(text);
1160
- });
1161
- context.on("kubb:lint:end", () => {
1162
- if (logLevel$7 <= logLevel.silent) return;
1163
- const text = getMessage("Lint completed");
1164
- console.log(text);
1165
- if (state.currentConfigs.length === 1) closeGroup("Linting");
1166
- });
1167
- context.on("kubb:hook:start", async ({ id, command, args }) => {
1168
- const commandWithArgs = formatCommandWithArgs(command, args);
1169
- const text = getMessage(`Hook ${styleText("dim", commandWithArgs)} started`);
1170
- if (logLevel$7 > logLevel.silent) {
1171
- if (state.currentConfigs.length === 1) openGroup(`Hook ${commandWithArgs}`);
1172
- console.log(text);
1173
- }
1174
- if (!id) return;
1175
- await runHook({
1176
- id,
1177
- command,
1178
- args,
1179
- commandWithArgs,
1180
- context,
1181
- sink: {
1182
- onStdout: logLevel$7 > logLevel.silent ? (s) => console.log(s) : void 0,
1183
- onStderr: logLevel$7 > logLevel.silent ? (s) => console.error(`::error::${s}`) : void 0
1184
- }
1185
- });
1186
- });
1187
- context.on("kubb:hook:end", ({ command, args }) => {
1188
- if (logLevel$7 <= logLevel.silent) return;
1189
- const commandWithArgs = formatCommandWithArgs(command, args);
1190
- const text = getMessage(`Hook ${styleText("dim", commandWithArgs)} completed`);
1191
- console.log(text);
1192
- if (state.currentConfigs.length === 1) closeGroup(`Hook ${commandWithArgs}`);
1193
- });
1194
- context.on("kubb:generation:summary", ({ config, status, hrStart, failedPlugins }) => {
1195
- const pluginsCount = config.plugins?.length ?? 0;
1196
- const successCount = pluginsCount - failedPlugins.size;
1197
- const duration = formatHrtime(hrStart);
1198
- if (state.currentConfigs.length > 1) console.log(" ");
1199
- console.log(status === "success" ? `Kubb Summary: ${styleText("blue", "✓")} ${`${successCount} successful`}, ${pluginsCount} total, ${styleText("green", duration)}` : `Kubb Summary: ${styleText("blue", "✓")} ${`${successCount} successful`}, ✗ ${`${failedPlugins.size} failed`}, ${pluginsCount} total, ${styleText("green", duration)}`);
1200
- if (state.currentConfigs.length > 1) closeGroup(config.name ? `Generation for ${styleText("bold", config.name)}` : "Generation");
1201
- });
1202
- context.on("kubb:lifecycle:end", () => {
1203
- reset();
1204
- });
1205
- }
1206
- });
1207
- //#endregion
1208
- //#region src/loggers/plainLogger.ts
1209
- /**
1210
- * Plain console adapter for non-TTY environments with simple `console.log` output.
1211
- */
1212
- const plainLogger = defineLogger({
1213
- name: "plain",
1214
- install(context, options) {
1215
- const logLevel$6 = options?.logLevel ?? logLevel.info;
1216
- function getMessage(message) {
1217
- return formatMessage(message, logLevel$6);
1218
- }
1219
- context.on("kubb:info", ({ message, info }) => {
1220
- if (logLevel$6 <= logLevel.silent) return;
1221
- const text = getMessage([
1222
- "ℹ",
1223
- message,
1224
- info
1225
- ].join(" "));
1226
- console.log(text);
1227
- });
1228
- context.on("kubb:success", ({ message, info = "" }) => {
1229
- if (logLevel$6 <= logLevel.silent) return;
1230
- const text = getMessage([
1231
- "✓",
1232
- message,
1233
- logLevel$6 >= logLevel.info ? info : void 0
1234
- ].filter(Boolean).join(" "));
1235
- console.log(text);
1236
- });
1237
- context.on("kubb:warn", ({ message, info }) => {
1238
- if (logLevel$6 < logLevel.warn) return;
1239
- const text = getMessage([
1240
- "⚠",
1241
- message,
1242
- logLevel$6 >= logLevel.info ? info : void 0
1243
- ].filter(Boolean).join(" "));
1244
- console.log(text);
1245
- });
1246
- context.on("kubb:error", ({ error }) => {
1247
- const caused = toCause(error);
1248
- const text = getMessage(["✗", error.message].join(" "));
1249
- console.log(text);
1250
- if (logLevel$6 >= logLevel.debug && error.stack) {
1251
- const frames = error.stack.split("\n").slice(1, 4);
1252
- for (const frame of frames) console.log(getMessage(frame.trim()));
1253
- if (caused?.stack) {
1254
- console.log(`└─ caused by ${caused.message}`);
1255
- const frames = caused.stack.split("\n").slice(1, 4);
1256
- for (const frame of frames) console.log(getMessage(` ${frame.trim()}`));
1257
- }
1258
- }
1259
- });
1260
- context.on("kubb:lifecycle:start", () => {
1261
- console.log("Kubb CLI 🧩");
1262
- });
1263
- context.on("kubb:config:start", () => {
1264
- if (logLevel$6 <= logLevel.silent) return;
1265
- const text = getMessage("Configuration started");
1266
- console.log(text);
1267
- });
1268
- context.on("kubb:config:end", () => {
1269
- if (logLevel$6 <= logLevel.silent) return;
1270
- const text = getMessage("Configuration completed");
1271
- console.log(text);
1272
- });
1273
- context.on("kubb:generation:start", () => {
1274
- const text = getMessage("Generation started");
1275
- console.log(text);
1276
- });
1277
- context.on("kubb:plugin:start", ({ plugin }) => {
1278
- if (logLevel$6 <= logLevel.silent) return;
1279
- const text = getMessage(`Generating ${plugin.name}`);
1280
- console.log(text);
1281
- });
1282
- context.on("kubb:plugin:end", ({ plugin, duration, success }) => {
1283
- if (logLevel$6 <= logLevel.silent) return;
1284
- const durationStr = formatMs(duration);
1285
- const text = getMessage(success ? `${plugin.name} completed in ${durationStr}` : `${plugin.name} failed in ${durationStr}`);
1286
- console.log(text);
1287
- });
1288
- context.on("kubb:files:processing:start", ({ files }) => {
1289
- if (logLevel$6 <= logLevel.silent) return;
1290
- const text = getMessage(`Writing ${files.length} files`);
1291
- console.log(text);
1292
- });
1293
- context.on("kubb:file:processing:update", ({ file, config }) => {
1294
- if (logLevel$6 <= logLevel.silent) return;
1295
- const text = getMessage(`Writing ${relative(config.root, file.path)}`);
1296
- console.log(text);
1297
- });
1298
- context.on("kubb:files:processing:end", () => {
1299
- if (logLevel$6 <= logLevel.silent) return;
1300
- const text = getMessage("Files written successfully");
1301
- console.log(text);
1302
- });
1303
- context.on("kubb:generation:end", ({ config }) => {
1304
- const text = getMessage(config.name ? `Generation completed for ${config.name}` : "Generation completed");
1305
- console.log(text);
1306
- });
1307
- context.on("kubb:format:start", () => {
1308
- if (logLevel$6 <= logLevel.silent) return;
1309
- const text = getMessage("Format started");
1310
- console.log(text);
1311
- });
1312
- context.on("kubb:format:end", () => {
1313
- if (logLevel$6 <= logLevel.silent) return;
1314
- const text = getMessage("Format completed");
1315
- console.log(text);
1316
- });
1317
- context.on("kubb:lint:start", () => {
1318
- if (logLevel$6 <= logLevel.silent) return;
1319
- const text = getMessage("Lint started");
1320
- console.log(text);
1321
- });
1322
- context.on("kubb:lint:end", () => {
1323
- if (logLevel$6 <= logLevel.silent) return;
1324
- const text = getMessage("Lint completed");
1325
- console.log(text);
1326
- });
1327
- context.on("kubb:hook:start", async ({ id, command, args }) => {
1328
- const commandWithArgs = formatCommandWithArgs(command, args);
1329
- const text = getMessage(`Hook ${commandWithArgs} started`);
1330
- if (logLevel$6 > logLevel.silent) console.log(text);
1331
- if (!id) return;
1332
- await runHook({
1333
- id,
1334
- command,
1335
- args,
1336
- commandWithArgs,
1337
- context,
1338
- sink: {
1339
- onStdout: logLevel$6 > logLevel.silent ? (s) => console.log(s) : void 0,
1340
- onStderr: logLevel$6 > logLevel.silent ? (s) => console.error(s) : void 0
1341
- }
1342
- });
1343
- });
1344
- context.on("kubb:hook:end", ({ command, args }) => {
1345
- if (logLevel$6 <= logLevel.silent) return;
1346
- const text = getMessage(`Hook ${formatCommandWithArgs(command, args)} completed`);
1347
- console.log(text);
1348
- });
1349
- context.on("kubb:generation:summary", ({ config, pluginTimings, status, hrStart, failedPlugins, filesCreated }) => {
1350
- const summary = getSummary({
1351
- failedPlugins,
1352
- filesCreated,
1353
- config,
1354
- status,
1355
- hrStart,
1356
- pluginTimings: logLevel$6 >= logLevel.verbose ? pluginTimings : void 0
1357
- });
1358
- console.log(SUMMARY_SEPARATOR);
1359
- console.log(summary.join("\n"));
1360
- console.log(SUMMARY_SEPARATOR);
1361
- });
1362
- }
1363
- });
1364
- //#endregion
1365
- //#region src/loggers/utils.ts
1366
- /**
1367
- * Optionally prefix a message with a [HH:MM:SS] timestamp when logLevel >= verbose.
1368
- * Shared across all logger adapters to avoid duplication.
1369
- */
1370
- function formatMessage(message, logLevel$4) {
1371
- if (logLevel$4 >= logLevel.verbose) return `${styleText("dim", `[${(/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", {
1372
- hour12: false,
1373
- hour: "2-digit",
1374
- minute: "2-digit",
1375
- second: "2-digit"
1376
- })}]`)} ${message}`;
1377
- return message;
1378
- }
1379
- /**
1380
- * Build the progress summary line shared by clack and GitHub Actions loggers.
1381
- * Returns null when there is nothing to display.
1382
- */
1383
- function buildProgressLine(state) {
1384
- const parts = [];
1385
- const duration = formatHrtime(state.hrStart);
1386
- if (state.totalPlugins > 0) {
1387
- 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}`;
1388
- parts.push(pluginStr);
1389
- }
1390
- if (state.totalFiles > 0) parts.push(`Files ${styleText("green", state.processedFiles.toString())}/${state.totalFiles}`);
1391
- if (parts.length === 0) return null;
1392
- parts.push(`${styleText("green", duration)} elapsed`);
1393
- return parts.join(styleText("dim", " | "));
1394
- }
1395
- /**
1396
- * Join a command and its optional args into a single display string.
1397
- * e.g. ("prettier", ["--write", "."]) → "prettier --write ."
1398
- */
1399
- function formatCommandWithArgs(command, args) {
1400
- return args?.length ? `${command} ${args.join(" ")}` : command;
1401
- }
1402
- function detectLogger() {
1403
- if (isGitHubActions()) return "github-actions";
1404
- if (canUseTTY()) return "clack";
1405
- return "plain";
1406
- }
1407
- const logMapper = {
1408
- clack: clackLogger,
1409
- plain: plainLogger,
1410
- "github-actions": githubActionsLogger
1411
- };
1412
- async function setupLogger(context, { logLevel: logLevel$5 }) {
1413
- const type = detectLogger();
1414
- const logger = logMapper[type];
1415
- if (!logger) throw new Error(`Unknown adapter type: ${type}`);
1416
- const cleanup = await logger.install(context, { logLevel: logLevel$5 });
1417
- if (logLevel$5 >= logLevel.debug) await fileSystemLogger.install(context, { logLevel: logLevel$5 });
1418
- return cleanup;
1419
- }
1420
- //#endregion
1421
- //#region src/utils/executeHooks.ts
1422
- async function executeHooks({ configHooks, hooks }) {
1423
- const commands = Array.isArray(configHooks.done) ? configHooks.done : [configHooks.done].filter(Boolean);
1424
- for (const command of commands) {
1425
- const [cmd, ...args] = tokenize(command);
1426
- if (!cmd) continue;
1427
- const hookId = createHash("sha256").update(command).digest("hex");
1428
- const hookEndPromise = new Promise((resolve, reject) => {
1429
- const handler = (ctx) => {
1430
- if (ctx.id !== hookId) return;
1431
- hooks.off("kubb:hook:end", handler);
1432
- if (!ctx.success) {
1433
- reject(ctx.error ?? /* @__PURE__ */ new Error(`Hook failed: ${command}`));
1434
- return;
1435
- }
1436
- hooks.emit("kubb:success", { message: `${styleText("dim", command)} successfully executed` }).then(resolve).catch(reject);
1437
- };
1438
- hooks.on("kubb:hook:end", handler);
1439
- });
1440
- await hooks.emit("kubb:hook:start", {
1441
- id: hookId,
1442
- command: cmd,
1443
- args
1444
- });
1445
- await hookEndPromise;
1446
- }
1447
- }
1448
- //#endregion
1449
- //#region src/utils/getConfig.ts
1450
- async function getConfigs(config, args) {
1451
- const resolved = await (typeof config === "function" ? config(args) : config);
1452
- return (Array.isArray(resolved) ? resolved : [resolved]).map((item) => ({
1453
- ...item,
1454
- plugins: item.plugins ?? []
1455
- }));
1456
- }
1457
- //#endregion
1458
- //#region src/utils/getCosmiConfig.ts
1459
- const jiti = createJiti(import.meta.url, {
1460
- jsx: {
1461
- runtime: "automatic",
1462
- importSource: "@kubb/renderer-jsx"
1463
- },
1464
- moduleCache: false
1465
- });
1466
- const tsLoader = async (configFile) => {
1467
- return jiti.import(configFile, { default: true });
1468
- };
1469
- async function getCosmiConfig(moduleName, config) {
1470
- let result;
1471
- const searchPlaces = [
1472
- "package.json",
1473
- `.${moduleName}rc`,
1474
- `.${moduleName}rc.json`,
1475
- `.${moduleName}rc.yaml`,
1476
- `.${moduleName}rc.yml`,
1477
- `.${moduleName}rc.ts`,
1478
- `.${moduleName}rc.mts`,
1479
- `.${moduleName}rc.cts`,
1480
- `.${moduleName}rc.js`,
1481
- `.${moduleName}rc.mjs`,
1482
- `.${moduleName}rc.cjs`,
1483
- `${moduleName}.config.ts`,
1484
- `${moduleName}.config.mts`,
1485
- `${moduleName}.config.cts`,
1486
- `${moduleName}.config.js`,
1487
- `${moduleName}.config.mjs`,
1488
- `${moduleName}.config.cjs`
1489
- ];
1490
- const explorer = cosmiconfig(moduleName, {
1491
- cache: false,
1492
- searchPlaces: [
1493
- ...searchPlaces.map((searchPlace) => {
1494
- return `.config/${searchPlace}`;
1495
- }),
1496
- ...searchPlaces.map((searchPlace) => {
1497
- return `configs/${searchPlace}`;
1498
- }),
1499
- ...searchPlaces
1500
- ],
1501
- loaders: {
1502
- ".ts": tsLoader,
1503
- ".mts": tsLoader,
1504
- ".cts": tsLoader
1505
- }
1506
- });
1507
- try {
1508
- result = config ? await explorer.load(config) : await explorer.search();
1509
- } catch (error) {
1510
- throw new Error("Config failed loading", { cause: error });
1511
- }
1512
- if (result?.isEmpty || !result || !result.config) throw new Error("Config not defined, create a kubb.config.js or pass through your config with the option --config");
1513
- return result;
1514
- }
1515
- //#endregion
1516
- //#region src/utils/watcher.ts
1517
- async function startWatcher(path, cb) {
1518
- const { watch } = await import("chokidar");
1519
- watch(path, {
1520
- ignorePermissionErrors: true,
1521
- ignored: WATCHER_IGNORED_PATHS
1522
- }).on("all", async (type, file) => {
1523
- console.log(styleText("yellow", styleText("bold", `Change detected: ${type} ${file}`)));
1524
- try {
1525
- await cb(path);
1526
- } catch (_e) {
1527
- console.log(styleText("red", "Watcher failed"));
1528
- }
1529
- });
1530
- }
1531
- //#endregion
1532
- //#region src/runners/generate.ts
1533
- async function runToolPass({ toolValue, detect, toolMap, toolLabel, successPrefix, noToolMessage, configName, outputPath, logLevel: logLevel$1, hooks, onStart, onEnd }) {
1534
- await onStart();
1535
- let resolvedTool = toolValue;
1536
- if (resolvedTool === "auto") {
1537
- const detected = await detect();
1538
- if (!detected) await hooks.emit("kubb:warn", { message: noToolMessage });
1539
- else {
1540
- resolvedTool = detected;
1541
- await hooks.emit("kubb:info", { message: `Auto-detected ${toolLabel}: ${styleText("dim", resolvedTool)}` });
1542
- }
1543
- }
1544
- let toolError;
1545
- if (resolvedTool && resolvedTool !== "auto" && resolvedTool in toolMap) {
1546
- const toolConfig = toolMap[resolvedTool];
1547
- try {
1548
- const hookId = createHash("sha256").update([configName, resolvedTool].filter(Boolean).join("-")).digest("hex");
1549
- const hookEndPromise = new Promise((resolve, reject) => {
1550
- const handler = (ctx) => {
1551
- if (ctx.id !== hookId) return;
1552
- hooks.off("kubb:hook:end", handler);
1553
- if (!ctx.success) {
1554
- reject(ctx.error ?? /* @__PURE__ */ new Error(`${toolConfig.errorMessage}`));
1555
- return;
1556
- }
1557
- hooks.emit("kubb:success", { message: [
1558
- `${successPrefix} with ${styleText("dim", resolvedTool)}`,
1559
- logLevel$1 >= logLevel.info ? `on ${styleText("dim", outputPath)}` : void 0,
1560
- "successfully"
1561
- ].filter(Boolean).join(" ") }).then(resolve).catch(reject);
1562
- };
1563
- hooks.on("kubb:hook:end", handler);
1564
- });
1565
- await hooks.emit("kubb:hook:start", {
1566
- id: hookId,
1567
- command: toolConfig.command,
1568
- args: toolConfig.args(outputPath)
1569
- });
1570
- await hookEndPromise;
1571
- } catch (caughtError) {
1572
- const err = toError(caughtError);
1573
- await hooks.emit("kubb:error", { error: err });
1574
- toolError = err;
1575
- }
1576
- }
1577
- await onEnd();
1578
- if (toolError) throw toolError;
1579
- }
1580
- async function generate(options) {
1581
- const { input, hooks, logLevel: logLevel$2 } = options;
1582
- const hrStart = process$1.hrtime();
1583
- const inputPath = input ?? (options.config.input && "path" in options.config.input ? options.config.input.path : void 0);
1584
- const config = {
1585
- ...options.config,
1586
- input: inputPath ? {
1587
- ...options.config.input,
1588
- path: inputPath
1589
- } : options.config.input,
1590
- ...options.config.output
1591
- };
1592
- const kubb = createKubb(config, { hooks });
1593
- await kubb.setup();
1594
- await hooks.emit("kubb:generation:start", { config });
1595
- await hooks.emit("kubb:info", {
1596
- message: config.name ? `Setup generation ${styleText("bold", config.name)}` : "Setup generation",
1597
- info: inputPath
1598
- });
1599
- await hooks.emit("kubb:info", {
1600
- message: config.name ? `Build generation ${styleText("bold", config.name)}` : "Build generation",
1601
- info: inputPath
1602
- });
1603
- const { files, failedPlugins, pluginTimings, error, driver } = await kubb.safeBuild();
1604
- await hooks.emit("kubb:info", { message: "Load summary" });
1605
- if (failedPlugins.size > 0 || error) {
1606
- const allErrors = [error, ...Array.from(failedPlugins).filter((it) => it.error).map((it) => it.error)].filter(Boolean);
1607
- for (const err of allErrors) await hooks.emit("kubb:error", { error: err });
1608
- await hooks.emit("kubb:generation:end", {
1609
- config,
1610
- files,
1611
- sources: kubb.sources
1612
- });
1613
- await hooks.emit("kubb:generation:summary", {
1614
- config,
1615
- failedPlugins,
1616
- filesCreated: files.length,
1617
- status: "failed",
1618
- hrStart,
1619
- pluginTimings: logLevel$2 >= logLevel.verbose ? pluginTimings : void 0
1620
- });
1621
- await sendTelemetry(buildTelemetryEvent({
1622
- command: "generate",
1623
- kubbVersion: version,
1624
- plugins: Array.from(driver.plugins.values(), (p) => ({
1625
- name: p.name,
1626
- options: p.options
1627
- })),
1628
- hrStart,
1629
- filesCreated: files.length,
1630
- status: "failed"
1631
- }));
1632
- process$1.exit(1);
1633
- }
1634
- await hooks.emit("kubb:success", {
1635
- message: "Generation successfully",
1636
- info: inputPath
1637
- });
1638
- await hooks.emit("kubb:generation:end", {
1639
- config,
1640
- files,
1641
- sources: kubb.sources
1642
- });
1643
- const outputPath = path.resolve(config.root, config.output.path);
1644
- if (config.output.format) await runToolPass({
1645
- toolValue: config.output.format,
1646
- detect: detectFormatter,
1647
- toolMap: formatters,
1648
- toolLabel: "formatter",
1649
- successPrefix: "Formatting",
1650
- noToolMessage: "No formatter found (oxfmt, biome, or prettier). Skipping formatting.",
1651
- configName: config.name,
1652
- outputPath,
1653
- logLevel: logLevel$2,
1654
- hooks,
1655
- onStart: () => hooks.emit("kubb:format:start"),
1656
- onEnd: () => hooks.emit("kubb:format:end")
1657
- });
1658
- if (config.output.lint) await runToolPass({
1659
- toolValue: config.output.lint,
1660
- detect: detectLinter,
1661
- toolMap: linters,
1662
- toolLabel: "linter",
1663
- successPrefix: "Linting",
1664
- noToolMessage: "No linter found (oxlint, biome, or eslint). Skipping linting.",
1665
- configName: config.name,
1666
- outputPath,
1667
- logLevel: logLevel$2,
1668
- hooks,
1669
- onStart: () => hooks.emit("kubb:lint:start"),
1670
- onEnd: () => hooks.emit("kubb:lint:end")
1671
- });
1672
- if (config.hooks) {
1673
- await hooks.emit("kubb:hooks:start");
1674
- await executeHooks({
1675
- configHooks: config.hooks,
1676
- hooks
1677
- });
1678
- await hooks.emit("kubb:hooks:end");
1679
- }
1680
- await hooks.emit("kubb:generation:summary", {
1681
- config,
1682
- failedPlugins,
1683
- filesCreated: files.length,
1684
- status: "success",
1685
- hrStart,
1686
- pluginTimings
1687
- });
1688
- await sendTelemetry(buildTelemetryEvent({
1689
- command: "generate",
1690
- kubbVersion: version,
1691
- plugins: Array.from(driver.plugins.values(), (p) => ({
1692
- name: p.name,
1693
- options: p.options
1694
- })),
1695
- hrStart,
1696
- filesCreated: files.length,
1697
- status: "success"
1698
- }));
1699
- }
1700
- async function runGenerateCommand({ input, configPath, logLevel: logLevelKey, watch }) {
1701
- const logLevel$3 = logLevel[logLevelKey] ?? logLevel.info;
1702
- const hooks = new AsyncEventEmitter();
1703
- await setupLogger(hooks, { logLevel: logLevel$3 });
1704
- await executeIfOnline(async () => {
1705
- try {
1706
- const latestVersion = (await (await fetch(KUBB_NPM_PACKAGE_URL)).json()).version;
1707
- if (latestVersion && version < latestVersion) await hooks.emit("kubb:version:new", {
1708
- currentVersion: version,
1709
- latestVersion
1710
- });
1711
- } catch {}
1712
- });
1713
- try {
1714
- const result = await getCosmiConfig("kubb", configPath);
1715
- const configs = await getConfigs(result.config, { input });
1716
- await hooks.emit("kubb:config:start");
1717
- await hooks.emit("kubb:info", {
1718
- message: "Config loaded",
1719
- info: path.relative(process$1.cwd(), result.filepath)
1720
- });
1721
- await hooks.emit("kubb:success", {
1722
- message: "Config loaded successfully",
1723
- info: path.relative(process$1.cwd(), result.filepath)
1724
- });
1725
- await hooks.emit("kubb:config:end", { configs });
1726
- await hooks.emit("kubb:lifecycle:start", { version });
1727
- for (const config of configs) if (isInputPath(config) && watch) await startWatcher([input || config.input.path], async (paths) => {
1728
- hooks.removeAll();
1729
- await generate({
1730
- input,
1731
- config,
1732
- logLevel: logLevel$3,
1733
- hooks
1734
- });
1735
- clack.log.step(styleText("yellow", `Watching for changes in ${paths.join(" and ")}`));
1736
- });
1737
- else await generate({
1738
- input,
1739
- config,
1740
- logLevel: logLevel$3,
1741
- hooks
1742
- });
1743
- await hooks.emit("kubb:lifecycle:end");
1744
- } catch (error) {
1745
- await hooks.emit("kubb:error", { error: toError(error) });
1746
- process$1.exit(1);
1747
- }
1748
- }
1749
- //#endregion
1750
- export { runGenerateCommand };
1751
-
1752
- //# sourceMappingURL=generate-DVmGtwWe.js.map