@kubb/cli 5.0.0-beta.4 → 5.0.0-beta.41

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 (157) hide show
  1. package/README.md +209 -51
  2. package/dist/agent-D3K_-kiv.js +68 -0
  3. package/dist/agent-D3K_-kiv.js.map +1 -0
  4. package/dist/agent-DTqKBULa.cjs +70 -0
  5. package/dist/agent-DTqKBULa.cjs.map +1 -0
  6. package/dist/{chunk--u3MIqq1.js → chunk-CRm0XQPb.js} +1 -0
  7. package/dist/constants-84a47qA-.js +35 -0
  8. package/dist/constants-84a47qA-.js.map +1 -0
  9. package/dist/constants-AHhyFH15.cjs +139 -0
  10. package/dist/constants-AHhyFH15.cjs.map +1 -0
  11. package/dist/constants-BtmponZ3.cjs +58 -0
  12. package/dist/constants-BtmponZ3.cjs.map +1 -0
  13. package/dist/constants-C94RKp3A.js +116 -0
  14. package/dist/constants-C94RKp3A.js.map +1 -0
  15. package/dist/{define-Bdn8j5VM.cjs → define-C4AB3POr.cjs} +2 -2
  16. package/dist/{define-Bdn8j5VM.cjs.map → define-C4AB3POr.cjs.map} +1 -1
  17. package/dist/{define-Ctii4bel.js → define-DNG1U8ha.js} +2 -2
  18. package/dist/{define-Ctii4bel.js.map → define-DNG1U8ha.js.map} +1 -1
  19. package/dist/{errors-CjPmyZHy.js → errors-CoxrNXaA.js} +2 -2
  20. package/dist/{errors-CjPmyZHy.js.map → errors-CoxrNXaA.js.map} +1 -1
  21. package/dist/{errors-CLCjoSg0.cjs → errors-DykI11xo.cjs} +2 -2
  22. package/dist/{errors-CLCjoSg0.cjs.map → errors-DykI11xo.cjs.map} +1 -1
  23. package/dist/generate-CZYIOngX.cjs +76 -0
  24. package/dist/generate-CZYIOngX.cjs.map +1 -0
  25. package/dist/generate-HcvbU80u.js +77 -0
  26. package/dist/generate-HcvbU80u.js.map +1 -0
  27. package/dist/index.cjs +23 -14
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.js +23 -14
  31. package/dist/index.js.map +1 -1
  32. package/dist/init-BMtuczv8.js +53 -0
  33. package/dist/init-BMtuczv8.js.map +1 -0
  34. package/dist/init-DybfkgNy.cjs +53 -0
  35. package/dist/init-DybfkgNy.cjs.map +1 -0
  36. package/dist/mcp-BF9dnH_F.js +39 -0
  37. package/dist/mcp-BF9dnH_F.js.map +1 -0
  38. package/dist/mcp-YzKoU6_l.cjs +39 -0
  39. package/dist/mcp-YzKoU6_l.cjs.map +1 -0
  40. package/dist/package-BCwMApnr.js +6 -0
  41. package/dist/package-BCwMApnr.js.map +1 -0
  42. package/dist/{package-BapVyQ-w.cjs → package-DPe5CA4S.cjs} +2 -2
  43. package/dist/package-DPe5CA4S.cjs.map +1 -0
  44. package/dist/{agent-sdYBBgrd.js → run-BQ3Qj0xB.js} +46 -43
  45. package/dist/run-BQ3Qj0xB.js.map +1 -0
  46. package/dist/run-BQzoaxjR.js +32 -0
  47. package/dist/run-BQzoaxjR.js.map +1 -0
  48. package/dist/run-CGf0KEts.js +51 -0
  49. package/dist/run-CGf0KEts.js.map +1 -0
  50. package/dist/{init-CZ5Xq2Hd.cjs → run-C_NMctua.cjs} +107 -149
  51. package/dist/run-C_NMctua.cjs.map +1 -0
  52. package/dist/run-CkTpemme.cjs +52 -0
  53. package/dist/run-CkTpemme.cjs.map +1 -0
  54. package/dist/run-Cl4SrSob.cjs +33 -0
  55. package/dist/run-Cl4SrSob.cjs.map +1 -0
  56. package/dist/{agent-B4cAAab2.cjs → run-D-s2LdlW.cjs} +46 -43
  57. package/dist/run-D-s2LdlW.cjs.map +1 -0
  58. package/dist/{init-eNRlotJK.js → run-D8dCWepS.js} +107 -149
  59. package/dist/run-D8dCWepS.js.map +1 -0
  60. package/dist/run-DaV_NiKR.js +1509 -0
  61. package/dist/run-DaV_NiKR.js.map +1 -0
  62. package/dist/run-UWQ9wImP.cjs +1512 -0
  63. package/dist/run-UWQ9wImP.cjs.map +1 -0
  64. package/dist/{shell-DLzN4fRo.js → shell-BrqyJdB7.js} +2 -2
  65. package/dist/{shell-DLzN4fRo.js.map → shell-BrqyJdB7.js.map} +1 -1
  66. package/dist/{shell-475fQKaX.cjs → shell-Lh-vLWwH.cjs} +2 -2
  67. package/dist/{shell-475fQKaX.cjs.map → shell-Lh-vLWwH.cjs.map} +1 -1
  68. package/dist/validate-BHc3lUKB.js +26 -0
  69. package/dist/validate-BHc3lUKB.js.map +1 -0
  70. package/dist/validate-CqRqJxmQ.cjs +26 -0
  71. package/dist/validate-CqRqJxmQ.cjs.map +1 -0
  72. package/package.json +16 -15
  73. package/src/commands/agent/start.ts +10 -7
  74. package/src/commands/agent.ts +3 -1
  75. package/src/commands/generate.ts +21 -13
  76. package/src/commands/init.ts +34 -3
  77. package/src/commands/mcp.ts +28 -4
  78. package/src/commands/validate.ts +6 -4
  79. package/src/constants.ts +3 -74
  80. package/src/index.ts +6 -4
  81. package/src/loggers/clackLogger.ts +137 -178
  82. package/src/loggers/plainLogger.ts +49 -102
  83. package/src/loggers/types.ts +6 -1
  84. package/src/loggers/utils.ts +141 -26
  85. package/src/runners/agent/run.ts +113 -0
  86. package/src/runners/agent/utils.ts +98 -0
  87. package/src/runners/generate/run.ts +404 -0
  88. package/src/runners/generate/utils.ts +219 -0
  89. package/src/runners/init/run.ts +212 -0
  90. package/src/{utils/packageManager.ts → runners/init/utils.ts} +12 -2
  91. package/src/runners/mcp/run.ts +37 -0
  92. package/src/runners/validate/run.ts +63 -0
  93. package/dist/agent-B4cAAab2.cjs.map +0 -1
  94. package/dist/agent-CR6Z96og.js +0 -56
  95. package/dist/agent-CR6Z96og.js.map +0 -1
  96. package/dist/agent-Dmxzqg4d.cjs +0 -58
  97. package/dist/agent-Dmxzqg4d.cjs.map +0 -1
  98. package/dist/agent-sdYBBgrd.js.map +0 -1
  99. package/dist/constants-CnDXa1R6.cjs +0 -148
  100. package/dist/constants-CnDXa1R6.cjs.map +0 -1
  101. package/dist/constants-aL3CP_Wq.js +0 -95
  102. package/dist/constants-aL3CP_Wq.js.map +0 -1
  103. package/dist/generate-B1Pa2ho-.cjs +0 -1756
  104. package/dist/generate-B1Pa2ho-.cjs.map +0 -1
  105. package/dist/generate-BDGOOsBM.cjs +0 -65
  106. package/dist/generate-BDGOOsBM.cjs.map +0 -1
  107. package/dist/generate-CNrRLY4n.js +0 -1753
  108. package/dist/generate-CNrRLY4n.js.map +0 -1
  109. package/dist/generate-DuhxPLGr.js +0 -66
  110. package/dist/generate-DuhxPLGr.js.map +0 -1
  111. package/dist/init-CZ5Xq2Hd.cjs.map +0 -1
  112. package/dist/init-CnZXHrbq.js +0 -25
  113. package/dist/init-CnZXHrbq.js.map +0 -1
  114. package/dist/init-NYJSZJSb.cjs +0 -25
  115. package/dist/init-NYJSZJSb.cjs.map +0 -1
  116. package/dist/init-eNRlotJK.js.map +0 -1
  117. package/dist/mcp-CYOgxB82.cjs +0 -47
  118. package/dist/mcp-CYOgxB82.cjs.map +0 -1
  119. package/dist/mcp-CdFWyrwi.cjs +0 -16
  120. package/dist/mcp-CdFWyrwi.cjs.map +0 -1
  121. package/dist/mcp-DhSxuDMD.js +0 -16
  122. package/dist/mcp-DhSxuDMD.js.map +0 -1
  123. package/dist/mcp-DmJm3TrU.js +0 -46
  124. package/dist/mcp-DmJm3TrU.js.map +0 -1
  125. package/dist/package-BapVyQ-w.cjs.map +0 -1
  126. package/dist/package-DyJE-qNq.js +0 -6
  127. package/dist/package-DyJE-qNq.js.map +0 -1
  128. package/dist/telemetry-DN95_2pF.cjs +0 -282
  129. package/dist/telemetry-DN95_2pF.cjs.map +0 -1
  130. package/dist/telemetry-LgT_sdPe.js +0 -245
  131. package/dist/telemetry-LgT_sdPe.js.map +0 -1
  132. package/dist/validate-C6npXzel.cjs +0 -25
  133. package/dist/validate-C6npXzel.cjs.map +0 -1
  134. package/dist/validate-kLJoT_hi.js +0 -33
  135. package/dist/validate-kLJoT_hi.js.map +0 -1
  136. package/dist/validate-n38Rh-Y7.js +0 -25
  137. package/dist/validate-n38Rh-Y7.js.map +0 -1
  138. package/dist/validate-yKKzqEZ5.cjs +0 -34
  139. package/dist/validate-yKKzqEZ5.cjs.map +0 -1
  140. package/src/loggers/fileSystemLogger.ts +0 -138
  141. package/src/loggers/githubActionsLogger.ts +0 -379
  142. package/src/runners/agent.ts +0 -155
  143. package/src/runners/generate.ts +0 -333
  144. package/src/runners/init.ts +0 -296
  145. package/src/runners/mcp.ts +0 -51
  146. package/src/runners/validate.ts +0 -39
  147. package/src/types.ts +0 -11
  148. package/src/utils/Writables.ts +0 -17
  149. package/src/utils/executeHooks.ts +0 -45
  150. package/src/utils/flags.ts +0 -9
  151. package/src/utils/getConfig.ts +0 -10
  152. package/src/utils/getCosmiConfig.ts +0 -80
  153. package/src/utils/getSummary.ts +0 -68
  154. package/src/utils/runHook.ts +0 -91
  155. package/src/utils/telemetry.ts +0 -273
  156. package/src/utils/watcher.ts +0 -19
  157. /package/dist/{chunk-ByKO4r7w.cjs → chunk-Bx3C2hgW.cjs} +0 -0
@@ -1,10 +1,7 @@
1
1
  import { relative } from 'node:path'
2
2
  import { formatMs, toCause } from '@internals/utils'
3
- import { defineLogger, logLevel as logLevelMap } from '@kubb/core'
4
- import { SUMMARY_SEPARATOR } from '../constants.ts'
5
- import { getSummary } from '../utils/getSummary.ts'
6
- import { runHook } from '../utils/runHook.ts'
7
- import { formatCommandWithArgs, formatMessage } from './utils.ts'
3
+ import { defineLogger, Diagnostics, type KubbHooks, logLevel as logLevelMap } from '@kubb/core'
4
+ import { createHookTimer, formatCommandWithArgs, formatMessage } from './utils.ts'
8
5
 
9
6
  /**
10
7
  * Plain console adapter for non-TTY environments with simple `console.log` output.
@@ -13,11 +10,22 @@ export const plainLogger = defineLogger({
13
10
  name: 'plain',
14
11
  install(context, options) {
15
12
  const logLevel = options?.logLevel ?? logLevelMap.info
13
+ const hookTimer = createHookTimer()
16
14
 
17
15
  function getMessage(message: string): string {
18
16
  return formatMessage(message, logLevel)
19
17
  }
20
18
 
19
+ // Registers a handler that logs a fixed message, skipped at silent level.
20
+ function onStep<E extends keyof KubbHooks>(event: E, message: string): void {
21
+ context.on(event, () => {
22
+ if (logLevel <= logLevelMap.silent) {
23
+ return
24
+ }
25
+ console.log(getMessage(message))
26
+ })
27
+ }
28
+
21
29
  context.on('kubb:info', ({ message, info }) => {
22
30
  if (logLevel <= logLevelMap.silent) {
23
31
  return
@@ -55,8 +63,8 @@ export const plainLogger = defineLogger({
55
63
 
56
64
  console.log(text)
57
65
 
58
- // Show stack trace in debug mode (first 3 frames)
59
- if (logLevel >= logLevelMap.debug && error.stack) {
66
+ // Show stack trace in verbose mode (first 3 frames)
67
+ if (logLevel >= logLevelMap.verbose && error.stack) {
60
68
  const frames = error.stack.split('\n').slice(1, 4)
61
69
  for (const frame of frames) {
62
70
  console.log(getMessage(frame.trim()))
@@ -73,30 +81,21 @@ export const plainLogger = defineLogger({
73
81
  }
74
82
  })
75
83
 
76
- context.on('kubb:lifecycle:start', () => {
77
- console.log('Kubb CLI 🧩')
78
- })
79
-
80
- context.on('kubb:config:start', () => {
81
- if (logLevel <= logLevelMap.silent) {
84
+ context.on('kubb:diagnostic', ({ diagnostic }) => {
85
+ // Silent still surfaces errors so failures stay visible. It drops warnings and info.
86
+ if (logLevel <= logLevelMap.silent && diagnostic.severity !== 'error') {
82
87
  return
83
88
  }
84
-
85
- const text = getMessage('Configuration started')
86
-
87
- console.log(text)
89
+ console.log(getMessage(Diagnostics.formatLines(diagnostic).join('\n')))
88
90
  })
89
91
 
90
- context.on('kubb:config:end', () => {
91
- if (logLevel <= logLevelMap.silent) {
92
- return
93
- }
94
-
95
- const text = getMessage('Configuration completed')
96
-
97
- console.log(text)
92
+ context.on('kubb:lifecycle:start', ({ version }) => {
93
+ console.log(`Kubb CLI v${version}`)
98
94
  })
99
95
 
96
+ onStep('kubb:config:start', 'Configuration started')
97
+ onStep('kubb:config:end', 'Configuration completed')
98
+
100
99
  context.on('kubb:generation:start', () => {
101
100
  const text = getMessage('Generation started')
102
101
 
@@ -133,14 +132,14 @@ export const plainLogger = defineLogger({
133
132
  console.log(text)
134
133
  })
135
134
 
136
- context.on('kubb:file:processing:update', ({ file, config }) => {
135
+ context.on('kubb:files:processing:update', ({ files }) => {
137
136
  if (logLevel <= logLevelMap.silent) {
138
137
  return
139
138
  }
140
139
 
141
- const text = getMessage(`Writing ${relative(config.root, file.path)}`)
142
-
143
- console.log(text)
140
+ for (const { file, config } of files) {
141
+ console.log(getMessage(`Writing ${relative(config.root, file.path)}`))
142
+ }
144
143
  })
145
144
 
146
145
  context.on('kubb:files:processing:end', () => {
@@ -159,96 +158,44 @@ export const plainLogger = defineLogger({
159
158
  console.log(text)
160
159
  })
161
160
 
162
- context.on('kubb:format:start', () => {
163
- if (logLevel <= logLevelMap.silent) {
164
- return
165
- }
166
-
167
- const text = getMessage('Format started')
161
+ onStep('kubb:format:start', 'Format started')
162
+ onStep('kubb:format:end', 'Format completed')
163
+ onStep('kubb:lint:start', 'Lint started')
164
+ onStep('kubb:lint:end', 'Lint completed')
165
+ onStep('kubb:hooks:start', 'Hooks started')
166
+ onStep('kubb:hooks:end', 'Hooks completed')
168
167
 
169
- console.log(text)
170
- })
171
-
172
- context.on('kubb:format:end', () => {
168
+ context.on('kubb:hook:start', ({ id, command, args }) => {
173
169
  if (logLevel <= logLevelMap.silent) {
174
170
  return
175
171
  }
176
172
 
177
- const text = getMessage('Format completed')
178
-
179
- console.log(text)
180
- })
181
-
182
- context.on('kubb:lint:start', () => {
183
- if (logLevel <= logLevelMap.silent) {
184
- return
173
+ if (id) {
174
+ hookTimer.start(id)
185
175
  }
186
176
 
187
- const text = getMessage('Lint started')
188
-
189
- console.log(text)
177
+ const commandWithArgs = formatCommandWithArgs(command, args)
178
+ console.log(getMessage(`Hook ${commandWithArgs} started`))
190
179
  })
191
180
 
192
- context.on('kubb:lint:end', () => {
181
+ context.on('kubb:hook:end', ({ id, command, args, success, error, stdout, stderr }) => {
193
182
  if (logLevel <= logLevelMap.silent) {
194
183
  return
195
184
  }
196
185
 
197
- const text = getMessage('Lint completed')
186
+ const ms = id ? hookTimer.end(id) : undefined
187
+ const durationStr = ms !== undefined ? ` in ${formatMs(ms)}` : ''
198
188
 
199
- console.log(text)
200
- })
201
-
202
- context.on('kubb:hook:start', async ({ id, command, args }) => {
203
189
  const commandWithArgs = formatCommandWithArgs(command, args)
204
- const text = getMessage(`Hook ${commandWithArgs} started`)
205
-
206
- if (logLevel > logLevelMap.silent) {
207
- console.log(text)
208
- }
209
-
210
- // Skip hook execution if no id is provided (e.g., during benchmarks or tests)
211
- if (!id) {
212
- return
213
- }
214
-
215
- await runHook({
216
- id,
217
- command,
218
- args,
219
- commandWithArgs,
220
- context,
221
- sink: {
222
- onStdout: logLevel > logLevelMap.silent ? (s) => console.log(s) : undefined,
223
- onStderr: logLevel > logLevelMap.silent ? (s) => console.error(s) : undefined,
224
- },
225
- })
226
- })
227
190
 
228
- context.on('kubb:hook:end', ({ command, args }) => {
229
- if (logLevel <= logLevelMap.silent) {
230
- return
191
+ if (success) {
192
+ console.log(getMessage(`✓ Hook ${commandWithArgs} completed${durationStr}`))
193
+ } else {
194
+ if (stdout) console.log(stdout)
195
+ if (stderr) console.error(stderr)
196
+ const reason = error?.message ? ` (${error.message})` : ''
197
+ console.log(getMessage(`✗ Hook ${commandWithArgs} failed${durationStr}${reason}`))
231
198
  }
232
-
233
- const commandWithArgs = formatCommandWithArgs(command, args)
234
- const text = getMessage(`Hook ${commandWithArgs} completed`)
235
-
236
- console.log(text)
237
- })
238
-
239
- context.on('kubb:generation:summary', ({ config, pluginTimings, status, hrStart, failedPlugins, filesCreated }) => {
240
- const summary = getSummary({
241
- failedPlugins,
242
- filesCreated,
243
- config,
244
- status,
245
- hrStart,
246
- pluginTimings: logLevel >= logLevelMap.verbose ? pluginTimings : undefined,
247
- })
248
-
249
- console.log(SUMMARY_SEPARATOR)
250
- console.log(summary.join('\n'))
251
- console.log(SUMMARY_SEPARATOR)
252
199
  })
253
200
  },
254
201
  })
@@ -1 +1,6 @@
1
- export type LoggerType = 'clack' | 'github-actions' | 'plain'
1
+ /**
2
+ * Logger adapter selected by `setupReporters` based on the runtime environment.
3
+ * - `'clack'`: TTY-aware output with spinners and progress bars.
4
+ * - `'plain'`: Plain `console.log` output for non-TTY environments.
5
+ */
6
+ export type LoggerType = 'clack' | 'plain'
@@ -1,10 +1,9 @@
1
+ import process from 'node:process'
1
2
  import { styleText } from 'node:util'
2
- import { canUseTTY, formatHrtime, isGitHubActions } from '@internals/utils'
3
- import type { Logger, LoggerContext, LoggerOptions } from '@kubb/core'
3
+ import { canUseTTY, formatHrtime, getElapsedMs } from '@internals/utils'
4
+ import type { Logger, LoggerContext, LoggerOptions, Reporter, ReporterContext } from '@kubb/core'
4
5
  import { logLevel as logLevelMap } from '@kubb/core'
5
6
  import { clackLogger } from './clackLogger.ts'
6
- import { fileSystemLogger } from './fileSystemLogger.ts'
7
- import { githubActionsLogger } from './githubActionsLogger.ts'
8
7
  import { plainLogger } from './plainLogger.ts'
9
8
  import type { LoggerType } from './types.ts'
10
9
 
@@ -26,20 +25,38 @@ export function formatMessage(message: string, logLevel: number): string {
26
25
  }
27
26
 
28
27
  type ProgressState = {
28
+ /**
29
+ * Total number of plugins scheduled for this generation run.
30
+ */
29
31
  totalPlugins: number
32
+ /**
33
+ * Number of plugins that have finished without error.
34
+ */
30
35
  completedPlugins: number
36
+ /**
37
+ * Number of plugins that exited with an error.
38
+ */
31
39
  failedPlugins: number
40
+ /**
41
+ * Total number of files expected to be written.
42
+ */
32
43
  totalFiles: number
44
+ /**
45
+ * Number of files written so far.
46
+ */
33
47
  processedFiles: number
48
+ /**
49
+ * `process.hrtime()` snapshot taken at the start of generation, used to compute elapsed time.
50
+ */
34
51
  hrStart: [number, number]
35
52
  }
36
53
 
37
54
  /**
38
- * Build the progress summary line shared by clack and GitHub Actions loggers.
55
+ * Build the progress summary line shown by the clack logger.
39
56
  * Returns null when there is nothing to display.
40
57
  */
41
58
  export function buildProgressLine(state: ProgressState): string | null {
42
- const parts: string[] = []
59
+ const parts: Array<string> = []
43
60
  const duration = formatHrtime(state.hrStart)
44
61
 
45
62
  if (state.totalPlugins > 0) {
@@ -62,45 +79,143 @@ export function buildProgressLine(state: ProgressState): string | null {
62
79
  return parts.join(styleText('dim', ' | '))
63
80
  }
64
81
 
82
+ /**
83
+ * Creates the per-run progress counters used by the clack logger.
84
+ */
85
+ export function createProgressCounters(): ProgressState {
86
+ return {
87
+ totalPlugins: 0,
88
+ completedPlugins: 0,
89
+ failedPlugins: 0,
90
+ totalFiles: 0,
91
+ processedFiles: 0,
92
+ hrStart: process.hrtime(),
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Resets the progress counters in place at the start/end of a generation run.
98
+ */
99
+ export function resetProgressCounters(state: ProgressState): void {
100
+ state.totalPlugins = 0
101
+ state.completedPlugins = 0
102
+ state.failedPlugins = 0
103
+ state.totalFiles = 0
104
+ state.processedFiles = 0
105
+ state.hrStart = process.hrtime()
106
+ }
107
+
108
+ /**
109
+ * Records a finished plugin against the progress counters.
110
+ */
111
+ export function recordPluginResult(state: ProgressState, success: boolean): void {
112
+ if (success) {
113
+ state.completedPlugins++
114
+ } else {
115
+ state.failedPlugins++
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Tracks per-hook start times so a logger can report a hook's elapsed duration.
121
+ * Used by the plain logger, which keys timing by hook `id`.
122
+ */
123
+ export type HookTimer = {
124
+ start(id: string): void
125
+ /**
126
+ * Returns the elapsed milliseconds since `start(id)`, or `undefined` when no start was recorded.
127
+ */
128
+ end(id: string): number | undefined
129
+ clear(): void
130
+ }
131
+
132
+ /**
133
+ * Creates a {@link HookTimer} backed by a private `id → hrtime` map.
134
+ */
135
+ export function createHookTimer(): HookTimer {
136
+ const starts = new Map<string, [number, number]>()
137
+
138
+ return {
139
+ start(id: string): void {
140
+ starts.set(id, process.hrtime())
141
+ },
142
+ end(id: string): number | undefined {
143
+ const hrStart = starts.get(id)
144
+ if (!hrStart) {
145
+ return undefined
146
+ }
147
+ starts.delete(id)
148
+ return getElapsedMs(hrStart)
149
+ },
150
+ clear(): void {
151
+ starts.clear()
152
+ },
153
+ }
154
+ }
155
+
65
156
  /**
66
157
  * Join a command and its optional args into a single display string.
67
158
  * e.g. ("prettier", ["--write", "."]) → "prettier --write ."
68
159
  */
69
- export function formatCommandWithArgs(command: string, args?: readonly string[]): string {
160
+ export function formatCommandWithArgs(command: string, args?: ReadonlyArray<string>): string {
70
161
  return args?.length ? `${command} ${args.join(' ')}` : command
71
162
  }
72
163
 
73
164
  function detectLogger(): LoggerType {
74
- if (isGitHubActions()) {
75
- return 'github-actions'
76
- }
77
165
  if (canUseTTY()) {
78
166
  return 'clack'
79
167
  }
80
168
  return 'plain'
81
169
  }
82
170
 
83
- const logMapper = {
171
+ const logMapper: Record<LoggerType, Logger> = {
84
172
  clack: clackLogger,
85
173
  plain: plainLogger,
86
- 'github-actions': githubActionsLogger,
87
- } as const satisfies Record<LoggerType, Logger>
88
-
89
- export async function setupLogger(context: LoggerContext, { logLevel }: LoggerOptions): Promise<void> {
90
- const type = detectLogger()
174
+ }
91
175
 
92
- const logger = logMapper[type] as Logger
176
+ /**
177
+ * Bridges a {@link Reporter} onto the run's event emitter: calls `report` with each config's
178
+ * {@link GenerationResult} on `kubb:generation:end`. The reporter never touches the emitter.
179
+ */
180
+ export function installReporter(context: LoggerContext, reporter: Reporter, ctx: ReporterContext): void {
181
+ context.on('kubb:generation:end', async ({ config, diagnostics = [], filesCreated = 0, status = 'success', hrStart = process.hrtime() }) => {
182
+ await reporter.report({ config, diagnostics, filesCreated, status, hrStart }, ctx)
183
+ })
93
184
 
94
- if (!logger) {
95
- throw new Error(`Unknown adapter type: ${type}`)
185
+ if (reporter.drain) {
186
+ context.on('kubb:lifecycle:end', () => reporter.drain?.(ctx))
96
187
  }
188
+ }
97
189
 
98
- // Install primary logger
99
- const cleanup = await logger.install(context, { logLevel })
100
-
101
- if (logLevel >= logLevelMap.debug) {
102
- await fileSystemLogger.install(context, { logLevel })
190
+ /**
191
+ * Installs the live logger (the TUI view) and the given reporters (the output). The reporters are
192
+ * already selected by the caller (the CLI maps `--reporter` to names via `selectReporters`); this
193
+ * only wires them. Loggers receive hook subprocess output through `kubb:hook:line` and the
194
+ * `stdout`/`stderr` on `kubb:hook:end`, so nothing is returned here.
195
+ *
196
+ * Loggers and reporters are independent: the `cli` reporter also activates the env logger summary.
197
+ * The `json` reporter owns stdout, so the live logger and the `cli` summary are suppressed whenever
198
+ * `json` is among the reporters, even if `cli` is also listed.
199
+ */
200
+ async function setupReporters(context: LoggerContext, { logLevel, reporters }: LoggerOptions & { reporters: ReadonlyArray<Reporter> }): Promise<void> {
201
+ const hasJson = reporters.some((reporter) => reporter.name === 'json')
202
+ const ctx: ReporterContext = { logLevel }
203
+
204
+ for (const reporter of reporters) {
205
+ if (reporter.name === 'cli') {
206
+ if (hasJson) {
207
+ continue
208
+ }
209
+ const type = detectLogger()
210
+ const logger = logMapper[type]
211
+ if (!logger) {
212
+ throw new Error(`Unknown adapter type: ${type}`)
213
+ }
214
+ await logger.install(context, { logLevel })
215
+ }
216
+
217
+ installReporter(context, reporter, ctx)
103
218
  }
104
-
105
- return cleanup
106
219
  }
220
+
221
+ export default setupReporters
@@ -0,0 +1,113 @@
1
+ import { createRequire } from 'node:module'
2
+ import path from 'node:path'
3
+ import process from 'node:process'
4
+ import { styleText } from 'node:util'
5
+ import * as clack from '@clack/prompts'
6
+ import { spawnAsync, getErrorMessage } from '@internals/utils'
7
+ import { Telemetry } from '@kubb/core'
8
+ import { agentDefaults } from '../../constants.ts'
9
+ import { isPortAvailable, resolveAgentStartEnvironment } from './utils.ts'
10
+
11
+ type AgentStartOptions = {
12
+ /**
13
+ * TCP port for the HTTP server. When `undefined`, falls back to `PORT` env var or the default (`3000`).
14
+ */
15
+ port: string | undefined
16
+ /**
17
+ * Hostname the HTTP server binds to.
18
+ *
19
+ * @default 'localhost'
20
+ */
21
+ host: string
22
+ /**
23
+ * Explicit path to the Kubb config file. When `undefined`, falls back to `KUBB_AGENT_CONFIG` or the default filename.
24
+ */
25
+ configPath: string | undefined
26
+ /**
27
+ * Grants the agent permission to write generated files to the filesystem.
28
+ */
29
+ allowWrite: boolean
30
+ /**
31
+ * Grants all agent permissions, including filesystem writes. Implies `allowWrite`.
32
+ */
33
+ allowAll: boolean
34
+ /**
35
+ * Current `@kubb/cli` version string, used for the telemetry payload.
36
+ */
37
+ version: string
38
+ }
39
+
40
+ /**
41
+ * Spawns the Kubb Agent HTTP server as a Node.js subprocess.
42
+ * Resolves config from CLI flags and environment variables, validates the port, and exits with code 1 on failure.
43
+ */
44
+ export async function run({ port, host, configPath, allowWrite, allowAll, version }: AgentStartOptions): Promise<void> {
45
+ const hrStart = process.hrtime()
46
+ const report = (status: 'success' | 'failed') => Telemetry.send(Telemetry.build({ command: 'agent', kubbVersion: version, hrStart, status }))
47
+
48
+ try {
49
+ // Load .env file into process.env using Node.js built-in (v20.12.0+)
50
+ try {
51
+ process.loadEnvFile()
52
+ } catch {
53
+ // .env file may not exist. Ignore
54
+ }
55
+
56
+ // Resolve the @kubb/agent package path, createRequire is CJS/ESM compatible (import.meta.resolve is ESM-only)
57
+ const require = createRequire(import.meta.url)
58
+ let agentPkgPath: string
59
+ try {
60
+ agentPkgPath = require.resolve('@kubb/agent/package.json')
61
+ } catch (_e) {
62
+ console.error(styleText('red', 'The @kubb/agent package is not installed.'))
63
+ console.error('')
64
+ console.error('Install it with:')
65
+ console.error(styleText('cyan', ' npm install @kubb/agent'))
66
+ console.error(styleText('cyan', ' # or'))
67
+ console.error(styleText('cyan', ' pnpm install @kubb/agent'))
68
+ console.error('')
69
+ process.exit(1)
70
+ }
71
+ const agentDir = path.dirname(agentPkgPath)
72
+ const serverPath = path.join(agentDir, agentDefaults.serverEntryPath)
73
+
74
+ const resolvedEnv = resolveAgentStartEnvironment({
75
+ port,
76
+ host,
77
+ configPath,
78
+ allowWrite,
79
+ allowAll,
80
+ })
81
+ const numericPort = Number(resolvedEnv.port)
82
+
83
+ if (!Number.isInteger(numericPort) || numericPort <= 0) {
84
+ throw new Error(`Invalid port "${resolvedEnv.port}". Provide a positive integer with --port or PORT.`)
85
+ }
86
+
87
+ clack.log.step(styleText('cyan', 'Starting agent server...'))
88
+ clack.log.info(styleText('dim', `Config: ${resolvedEnv.agentConfigPath}`))
89
+ clack.log.info(styleText('dim', `Host: ${resolvedEnv.host}`))
90
+ clack.log.info(styleText('dim', `Port: ${resolvedEnv.port}`))
91
+ if (!resolvedEnv.allowWrite && !resolvedEnv.allowAll) {
92
+ clack.log.warn(styleText('yellow', 'Filesystem writes disabled. Use --allow-write or --allow-all to enable.'))
93
+ }
94
+
95
+ if (!(await isPortAvailable(numericPort, resolvedEnv.host))) {
96
+ clack.log.error(styleText('red', `Port ${resolvedEnv.port} is already in use. Stop the existing process or choose a different port with --port.`))
97
+ process.exit(1)
98
+ }
99
+
100
+ // Spawns the server as a detached background process so the CLI can exit independently.
101
+ await spawnAsync('node', [serverPath], {
102
+ env: resolvedEnv.env,
103
+ cwd: process.cwd(),
104
+ })
105
+
106
+ await report('success')
107
+ } catch (error) {
108
+ await report('failed')
109
+ clack.log.error(styleText('red', 'Failed to start agent server'))
110
+ clack.log.error(getErrorMessage(error))
111
+ process.exit(1)
112
+ }
113
+ }
@@ -0,0 +1,98 @@
1
+ import net from 'node:net'
2
+ import path from 'node:path'
3
+ import process from 'node:process'
4
+ import { agentDefaults } from '../../constants.ts'
5
+
6
+ type AgentStartEnvironmentInput = {
7
+ /**
8
+ * TCP port for the HTTP server. When `undefined`, falls back to `PORT` env var or the default (`3000`).
9
+ */
10
+ port: string | undefined
11
+ /**
12
+ * Hostname the HTTP server binds to.
13
+ */
14
+ host: string
15
+ /**
16
+ * Explicit path to the Kubb config file. When `undefined`, falls back to `KUBB_AGENT_CONFIG` or the default filename.
17
+ */
18
+ configPath: string | undefined
19
+ /**
20
+ * Grants the agent permission to write generated files to the filesystem.
21
+ */
22
+ allowWrite: boolean
23
+ /**
24
+ * Grants all agent permissions, including filesystem writes. Implies `allowWrite`.
25
+ */
26
+ allowAll: boolean
27
+ }
28
+
29
+ type ResolvedAgentStartEnvironment = {
30
+ /**
31
+ * Final port string after merging CLI flag, `PORT` env var, and the default.
32
+ */
33
+ port: string
34
+ /**
35
+ * Final hostname after merging CLI flag, `HOST` env var, and the default.
36
+ */
37
+ host: string
38
+ /**
39
+ * Effective write-permission flag, accounting for `allowAll` and `KUBB_AGENT_ALLOW_WRITE`.
40
+ */
41
+ allowWrite: boolean
42
+ /**
43
+ * Effective all-permissions flag, accounting for `KUBB_AGENT_ALLOW_ALL`.
44
+ */
45
+ allowAll: boolean
46
+ /**
47
+ * Absolute path to the Kubb config file passed to the agent subprocess.
48
+ */
49
+ agentConfigPath: string
50
+ /**
51
+ * Merged `process.env` object with all resolved agent environment variables applied.
52
+ */
53
+ env: NodeJS.ProcessEnv
54
+ }
55
+
56
+ /**
57
+ * Resolves the environment passed to the detached agent process using CLI values first, then environment values, then CLI defaults.
58
+ */
59
+ export function resolveAgentStartEnvironment({ port, host, configPath, allowWrite, allowAll }: AgentStartEnvironmentInput): ResolvedAgentStartEnvironment {
60
+ const resolvedPort = port ?? process.env.PORT ?? agentDefaults.port
61
+ const resolvedHost = host !== agentDefaults.host ? host : (process.env.HOST ?? agentDefaults.host)
62
+ const resolvedAllowAll = allowAll || process.env.KUBB_AGENT_ALLOW_ALL === 'true'
63
+ const resolvedAllowWrite = resolvedAllowAll || allowWrite || process.env.KUBB_AGENT_ALLOW_WRITE === 'true'
64
+ const agentRoot = process.env.KUBB_AGENT_ROOT ?? process.cwd()
65
+ const agentConfigPath = path.resolve(process.cwd(), configPath || process.env.KUBB_AGENT_CONFIG || agentDefaults.configFile)
66
+
67
+ return {
68
+ port: resolvedPort,
69
+ host: resolvedHost,
70
+ allowWrite: resolvedAllowWrite,
71
+ allowAll: resolvedAllowAll,
72
+ agentConfigPath,
73
+ env: {
74
+ ...process.env,
75
+ PORT: resolvedPort,
76
+ HOST: resolvedHost,
77
+ KUBB_AGENT_ROOT: agentRoot,
78
+ KUBB_AGENT_CONFIG: agentConfigPath,
79
+ KUBB_AGENT_ALLOW_WRITE: String(resolvedAllowWrite),
80
+ KUBB_AGENT_ALLOW_ALL: String(resolvedAllowAll),
81
+ KUBB_AGENT_TOKEN: process.env.KUBB_AGENT_TOKEN,
82
+ KUBB_AGENT_RETRY_TIMEOUT: process.env.KUBB_AGENT_RETRY_TIMEOUT ?? agentDefaults.retryTimeout,
83
+ KUBB_STUDIO_URL: process.env.KUBB_STUDIO_URL ?? agentDefaults.studioUrl,
84
+ },
85
+ }
86
+ }
87
+
88
+ export function isPortAvailable(port: number, host: string): Promise<boolean> {
89
+ return new Promise((resolve) => {
90
+ const server = net.createServer()
91
+ server.once('error', () => resolve(false))
92
+ server.once('listening', () => {
93
+ server.close()
94
+ resolve(true)
95
+ })
96
+ server.listen(port, host)
97
+ })
98
+ }