@kubb/cli 5.0.0-beta.6 → 5.0.0-beta.61

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 (142) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +170 -51
  3. package/dist/Telemetry-CVdyJarO.js +283 -0
  4. package/dist/Telemetry-CVdyJarO.js.map +1 -0
  5. package/dist/Telemetry-DrppRqqW.cjs +320 -0
  6. package/dist/Telemetry-DrppRqqW.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-BB2Q7I9s.cjs → generate-CJuBlTeJ.cjs} +22 -17
  16. package/dist/generate-CJuBlTeJ.cjs.map +1 -0
  17. package/dist/{generate-BmulGxIM.js → generate-DAePC4G2.js} +22 -17
  18. package/dist/generate-DAePC4G2.js.map +1 -0
  19. package/dist/index.cjs +10 -27
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.js +10 -27
  23. package/dist/index.js.map +1 -1
  24. package/dist/{init-BTp9if7K.js → init-C8m7Z_W8.js} +6 -6
  25. package/dist/{init-BTp9if7K.js.map → init-C8m7Z_W8.js.map} +1 -1
  26. package/dist/{init-Dpg8e1HN.cjs → init-T1DC44PT.cjs} +6 -6
  27. package/dist/{init-Dpg8e1HN.cjs.map → init-T1DC44PT.cjs.map} +1 -1
  28. package/dist/{mcp-wpl6sYYR.cjs → mcp-B60MeTmD.cjs} +6 -6
  29. package/dist/{mcp-wpl6sYYR.cjs.map → mcp-B60MeTmD.cjs.map} +1 -1
  30. package/dist/{mcp-C9RoU-Dg.js → mcp-lEYflz1a.js} +6 -6
  31. package/dist/{mcp-C9RoU-Dg.js.map → mcp-lEYflz1a.js.map} +1 -1
  32. package/dist/package-BynuV_3t.js +6 -0
  33. package/dist/package-BynuV_3t.js.map +1 -0
  34. package/dist/{package-iheSdfas.cjs → package-QUV6JOtx.cjs} +2 -2
  35. package/dist/package-QUV6JOtx.cjs.map +1 -0
  36. package/dist/run-9ZhHuNZQ.cjs +33 -0
  37. package/dist/run-9ZhHuNZQ.cjs.map +1 -0
  38. package/dist/run-BG7Giryi.js +296 -0
  39. package/dist/run-BG7Giryi.js.map +1 -0
  40. package/dist/{validate-BU4fPTMc.cjs → run-BQO_tPlc.cjs} +25 -20
  41. package/dist/run-BQO_tPlc.cjs.map +1 -0
  42. package/dist/run-C-5oRB_f.cjs +1380 -0
  43. package/dist/run-C-5oRB_f.cjs.map +1 -0
  44. package/dist/run-CYnDu3ch.js +51 -0
  45. package/dist/run-CYnDu3ch.js.map +1 -0
  46. package/dist/run-Da0AZlgo.js +1377 -0
  47. package/dist/run-Da0AZlgo.js.map +1 -0
  48. package/dist/run-DpKny2hT.cjs +300 -0
  49. package/dist/run-DpKny2hT.cjs.map +1 -0
  50. package/dist/run-h8NTawHO.js +32 -0
  51. package/dist/run-h8NTawHO.js.map +1 -0
  52. package/dist/tools-BU99bhi8.js +152 -0
  53. package/dist/tools-BU99bhi8.js.map +1 -0
  54. package/dist/tools-_Xp8-_zy.cjs +175 -0
  55. package/dist/tools-_Xp8-_zy.cjs.map +1 -0
  56. package/dist/{validate-BfJoCxrC.js → validate-BhDi3x5e.js} +6 -6
  57. package/dist/{validate-BfJoCxrC.js.map → validate-BhDi3x5e.js.map} +1 -1
  58. package/dist/{validate-DIDBROB2.cjs → validate-CUEvWAyG.cjs} +6 -6
  59. package/dist/{validate-DIDBROB2.cjs.map → validate-CUEvWAyG.cjs.map} +1 -1
  60. package/package.json +12 -27
  61. package/src/Telemetry.ts +297 -0
  62. package/src/commands/generate.ts +18 -12
  63. package/src/commands/init.ts +2 -2
  64. package/src/commands/mcp.ts +2 -2
  65. package/src/commands/validate.ts +2 -2
  66. package/src/constants.ts +2 -35
  67. package/src/index.ts +5 -21
  68. package/src/loggers/clackLogger.ts +136 -202
  69. package/src/loggers/defineLogger.ts +59 -0
  70. package/src/loggers/plainLogger.ts +48 -103
  71. package/src/loggers/types.ts +6 -1
  72. package/src/loggers/utils.ts +167 -24
  73. package/src/runners/generate/run.ts +399 -0
  74. package/src/runners/generate/utils.ts +229 -0
  75. package/src/runners/{init.ts → init/run.ts} +81 -78
  76. package/src/runners/init/utils.ts +39 -0
  77. package/src/runners/mcp/run.ts +37 -0
  78. package/src/runners/{validate.ts → validate/run.ts} +25 -20
  79. package/dist/agent-BJEvbSiP.js +0 -68
  80. package/dist/agent-BJEvbSiP.js.map +0 -1
  81. package/dist/agent-CXNO6dgj.cjs +0 -70
  82. package/dist/agent-CXNO6dgj.cjs.map +0 -1
  83. package/dist/agent-D9CKYh4K.cjs +0 -122
  84. package/dist/agent-D9CKYh4K.cjs.map +0 -1
  85. package/dist/agent-VXKxLCho.js +0 -118
  86. package/dist/agent-VXKxLCho.js.map +0 -1
  87. package/dist/constants-BPJBMT_6.js +0 -45
  88. package/dist/constants-BPJBMT_6.js.map +0 -1
  89. package/dist/constants-BYGmiFs0.cjs +0 -139
  90. package/dist/constants-BYGmiFs0.cjs.map +0 -1
  91. package/dist/constants-DSJ-Xrbv.js +0 -116
  92. package/dist/constants-DSJ-Xrbv.js.map +0 -1
  93. package/dist/constants-Rcaqzyd-.cjs +0 -80
  94. package/dist/constants-Rcaqzyd-.cjs.map +0 -1
  95. package/dist/generate-BB2Q7I9s.cjs.map +0 -1
  96. package/dist/generate-B_p5dl68.cjs +0 -1755
  97. package/dist/generate-B_p5dl68.cjs.map +0 -1
  98. package/dist/generate-BmulGxIM.js.map +0 -1
  99. package/dist/generate-DAsdUw3z.js +0 -1752
  100. package/dist/generate-DAsdUw3z.js.map +0 -1
  101. package/dist/init-CJ80lKSP.cjs +0 -239
  102. package/dist/init-CJ80lKSP.cjs.map +0 -1
  103. package/dist/init-DCqcEq86.js +0 -235
  104. package/dist/init-DCqcEq86.js.map +0 -1
  105. package/dist/mcp-D1llTaRM.cjs +0 -50
  106. package/dist/mcp-D1llTaRM.cjs.map +0 -1
  107. package/dist/mcp-DNUw8nqb.js +0 -49
  108. package/dist/mcp-DNUw8nqb.js.map +0 -1
  109. package/dist/package-iheSdfas.cjs.map +0 -1
  110. package/dist/package-vLafMWCe.js +0 -6
  111. package/dist/package-vLafMWCe.js.map +0 -1
  112. package/dist/shell-475fQKaX.cjs +0 -62
  113. package/dist/shell-475fQKaX.cjs.map +0 -1
  114. package/dist/shell-DLzN4fRo.js +0 -51
  115. package/dist/shell-DLzN4fRo.js.map +0 -1
  116. package/dist/telemetry-BLX0NzRk.cjs +0 -282
  117. package/dist/telemetry-BLX0NzRk.cjs.map +0 -1
  118. package/dist/telemetry-juq4QBf7.js +0 -245
  119. package/dist/telemetry-juq4QBf7.js.map +0 -1
  120. package/dist/validate-BU4fPTMc.cjs.map +0 -1
  121. package/dist/validate-k9s_hFah.js +0 -46
  122. package/dist/validate-k9s_hFah.js.map +0 -1
  123. package/src/commands/agent/start.ts +0 -50
  124. package/src/commands/agent.ts +0 -10
  125. package/src/loggers/fileSystemLogger.ts +0 -138
  126. package/src/loggers/githubActionsLogger.ts +0 -379
  127. package/src/runners/agent.ts +0 -155
  128. package/src/runners/generate.ts +0 -333
  129. package/src/runners/mcp.ts +0 -56
  130. package/src/types.ts +0 -11
  131. package/src/utils/Writables.ts +0 -17
  132. package/src/utils/executeHooks.ts +0 -45
  133. package/src/utils/flags.ts +0 -9
  134. package/src/utils/getConfig.ts +0 -10
  135. package/src/utils/getCosmiConfig.ts +0 -75
  136. package/src/utils/getSummary.ts +0 -68
  137. package/src/utils/packageManager.ts +0 -23
  138. package/src/utils/runHook.ts +0 -91
  139. package/src/utils/telemetry.ts +0 -273
  140. package/src/utils/watcher.ts +0 -19
  141. /package/dist/{chunk-ByKO4r7w.cjs → chunk-Bx3C2hgW.cjs} +0 -0
  142. /package/dist/{chunk--u3MIqq1.js → chunk-C0LytTxp.js} +0 -0
@@ -3,32 +3,68 @@ import path from 'node:path'
3
3
  import process from 'node:process'
4
4
  import { styleText } from 'node:util'
5
5
  import * as clack from '@clack/prompts'
6
- import type { PackageManagerInfo } from '@internals/utils'
7
6
  import { detectPackageManager } from '@internals/utils'
8
7
  import { availablePlugins, generateConfigFile, initDefaults, KUBB_CONFIG_FILENAME, type PluginOption } from '@internals/shared'
9
- import { hasPackageJson, initPackageJson, installPackages } from '../utils/packageManager.ts'
8
+ import { hasPackageJson, initPackageJson, installPackages } from './utils.ts'
10
9
 
11
- function cancelAndExit(message = 'Operation cancelled.'): never {
10
+ function cancelAndExit(message = 'Operation canceled.'): never {
12
11
  clack.cancel(message)
13
12
  process.exit(0)
14
13
  }
15
14
 
16
15
  type InitOptions = {
16
+ /**
17
+ * When `true`, skips all interactive prompts and uses default values.
18
+ */
17
19
  yes: boolean
20
+ /**
21
+ * Current `@kubb/cli` version string, shown in the outro and used for package installation.
22
+ */
18
23
  version: string
24
+ /**
25
+ * Input path flag value from `--input`. When provided, skips the input prompt.
26
+ */
19
27
  input?: string
28
+ /**
29
+ * Output directory flag value from `--output`. When provided, skips the output prompt.
30
+ */
20
31
  output?: string
32
+ /**
33
+ * Comma-separated plugin list from `--plugins`, e.g. `'plugin-ts,plugin-zod'`. When provided, skips the plugin selection prompt.
34
+ */
21
35
  plugins?: string
22
36
  }
23
37
 
24
- export async function runInit({ yes, version, input: inputFlag, output: outputFlag, plugins: pluginsFlag }: InitOptions): Promise<void> {
38
+ /**
39
+ * Runs the interactive Kubb scaffolding wizard.
40
+ * Detects the package manager, prompts for input/output paths and plugins, installs packages, and writes `kubb.config.ts`.
41
+ * Pass `yes: true` to skip all prompts and use defaults.
42
+ */
43
+ export async function run({ yes, version, input: inputFlag, output: outputFlag, plugins: pluginsFlag }: InitOptions): Promise<void> {
25
44
  const cwd = process.cwd()
26
45
 
27
46
  clack.intro(styleText('bgCyan', styleText('black', ' Kubb Init ')))
28
47
 
48
+ /**
49
+ * Returns `flag` when provided, the `defaultValue` when `yes` is set,
50
+ * or calls `prompt()` for interactive input. Exits on cancellation.
51
+ */
52
+ async function resolveOrPrompt<T>(flag: T | undefined, defaultValue: T, logLabel: string, prompt: () => Promise<T | symbol>): Promise<T> {
53
+ if (flag !== undefined) {
54
+ clack.log.info(`${logLabel}: ${styleText('cyan', String(flag))}`)
55
+ return flag
56
+ }
57
+ if (yes) {
58
+ clack.log.info(`${logLabel}: ${styleText('cyan', String(defaultValue))}`)
59
+ return defaultValue
60
+ }
61
+ const result = await prompt()
62
+ if (clack.isCancel(result)) cancelAndExit()
63
+ return result as T
64
+ }
65
+
29
66
  try {
30
- // Check/create package.json
31
- let packageManager: PackageManagerInfo
67
+ // Check/create package.json, detect package manager once after the block
32
68
  if (!hasPackageJson(cwd)) {
33
69
  if (!yes) {
34
70
  const shouldInit = await clack.confirm({
@@ -41,104 +77,73 @@ export async function runInit({ yes, version, input: inputFlag, output: outputFl
41
77
  }
42
78
  }
43
79
 
44
- packageManager = detectPackageManager(cwd)
45
-
80
+ const packageManager = detectPackageManager(cwd)
46
81
  const spinner = clack.spinner()
47
82
  spinner.start(`Initializing package.json with ${packageManager.name}`)
48
-
49
83
  await initPackageJson(cwd, packageManager)
50
-
51
84
  spinner.stop(`Created package.json with ${packageManager.name}`)
52
- } else {
53
- packageManager = detectPackageManager(cwd)
85
+ }
86
+
87
+ const packageManager = detectPackageManager(cwd)
88
+ if (hasPackageJson(cwd)) {
54
89
  clack.log.info(`Detected package manager: ${styleText('cyan', packageManager.name)}`)
55
90
  }
56
91
 
57
92
  // Prompt for OpenAPI spec path
58
- let inputPath: string
59
- if (inputFlag) {
60
- inputPath = inputFlag
61
- clack.log.info(`Using input path: ${styleText('cyan', inputPath)}`)
62
- } else if (yes) {
63
- inputPath = initDefaults.inputPath
64
- clack.log.info(`Using input path: ${styleText('cyan', inputPath)}`)
65
- } else {
66
- const inputPathResult = await clack.text({
93
+ const inputPath = await resolveOrPrompt(inputFlag, initDefaults.inputPath, 'Using input path', () =>
94
+ clack.text({
67
95
  message: 'Where is your OpenAPI specification located?',
68
96
  placeholder: initDefaults.inputPath,
69
97
  defaultValue: initDefaults.inputPath,
70
98
  validate: (value) => {
71
99
  if (!value) return 'Input path is required'
72
100
  },
73
- })
74
-
75
- if (clack.isCancel(inputPathResult)) {
76
- cancelAndExit()
77
- }
78
- inputPath = inputPathResult as string
79
- }
101
+ }),
102
+ )
80
103
 
81
104
  // Prompt for output directory
82
- let outputPath: string
83
- if (outputFlag) {
84
- outputPath = outputFlag
85
- clack.log.info(`Using output path: ${styleText('cyan', outputPath)}`)
86
- } else if (yes) {
87
- outputPath = initDefaults.outputPath
88
- clack.log.info(`Using output path: ${styleText('cyan', outputPath)}`)
89
- } else {
90
- const outputPathResult = await clack.text({
105
+ const outputPath = await resolveOrPrompt(outputFlag, initDefaults.outputPath, 'Using output path', () =>
106
+ clack.text({
91
107
  message: 'Where should the generated files be output?',
92
108
  placeholder: initDefaults.outputPath,
93
109
  defaultValue: initDefaults.outputPath,
94
110
  validate: (value) => {
95
111
  if (!value) return 'Output path is required'
96
112
  },
97
- })
98
-
99
- if (clack.isCancel(outputPathResult)) {
100
- cancelAndExit()
101
- }
102
- outputPath = outputPathResult as string
103
- }
113
+ }),
114
+ )
104
115
 
105
116
  // Plugin selection
106
- let selectedPlugins: PluginOption[]
107
- if (pluginsFlag) {
108
- const requestedValues = pluginsFlag
109
- .split(',')
110
- .map((v) => v.trim())
111
- .filter(Boolean)
112
- selectedPlugins = availablePlugins.filter((plugin) => requestedValues.includes(plugin.value))
113
- if (selectedPlugins.length === 0) {
114
- selectedPlugins = availablePlugins.filter((plugin) => (initDefaults.plugins as readonly string[]).includes(plugin.value))
115
- clack.log.warn(
116
- `No valid plugins found in --plugins value; falling back to default: ${styleText('cyan', selectedPlugins.map((p) => p.label).join(', '))}`,
117
- )
118
- } else {
119
- clack.log.info(`Using plugins: ${styleText('cyan', selectedPlugins.map((p) => p.label).join(', '))}`)
117
+ const defaultPlugins = availablePlugins.filter((p) => (initDefaults.plugins as ReadonlyArray<string>).includes(p.value))
118
+ const pluginLabel = (plugins: Array<PluginOption>) => styleText('cyan', plugins.map((p) => p.label).join(', '))
119
+
120
+ const selectedPlugins: Array<PluginOption> = await (async () => {
121
+ if (pluginsFlag) {
122
+ const requested = pluginsFlag
123
+ .split(',')
124
+ .map((v) => v.trim())
125
+ .filter(Boolean)
126
+ const plugins = availablePlugins.filter((p) => requested.includes(p.value))
127
+ if (plugins.length === 0) {
128
+ clack.log.warn(`No valid plugins found in --plugins value; falling back to default: ${pluginLabel(defaultPlugins)}`)
129
+ return defaultPlugins
130
+ }
131
+ clack.log.info(`Using plugins: ${pluginLabel(plugins)}`)
132
+ return plugins
120
133
  }
121
- } else if (yes) {
122
- selectedPlugins = availablePlugins.filter((plugin) => (initDefaults.plugins as readonly string[]).includes(plugin.value))
123
- clack.log.info(`Using plugins: ${styleText('cyan', selectedPlugins.map((p) => p.label).join(', '))}`)
124
- } else {
125
- const selectedPluginValues = await clack.multiselect({
134
+ if (yes) {
135
+ clack.log.info(`Using plugins: ${pluginLabel(defaultPlugins)}`)
136
+ return defaultPlugins
137
+ }
138
+ const values = await clack.multiselect({
126
139
  message: 'Select plugins to use:',
127
- options: availablePlugins.map((plugin) => ({
128
- value: plugin.value,
129
- label: plugin.label,
130
- hint: plugin.hint,
131
- })),
140
+ options: availablePlugins.map(({ value, label, hint }) => ({ value, label, hint })),
132
141
  initialValues: [...initDefaults.plugins],
133
142
  required: true,
134
143
  })
135
-
136
- if (clack.isCancel(selectedPluginValues)) {
137
- cancelAndExit()
138
- }
139
-
140
- selectedPlugins = availablePlugins.filter((plugin) => (selectedPluginValues as string[]).includes(plugin.value))
141
- }
144
+ if (clack.isCancel(values)) cancelAndExit()
145
+ return availablePlugins.filter((p) => (values as Array<string>).includes(p.value))
146
+ })()
142
147
 
143
148
  // Install packages
144
149
  const packagesToInstall = ['kubb', ...selectedPlugins.map((p) => p.packageName)]
@@ -178,7 +183,7 @@ export async function runInit({ yes, version, input: inputFlag, output: outputFl
178
183
  configSpinner.start(`Overwriting ${KUBB_CONFIG_FILENAME}`)
179
184
  }
180
185
 
181
- fs.writeFileSync(configPath, configContent, 'utf-8')
186
+ await fs.promises.writeFile(configPath, configContent, 'utf-8')
182
187
 
183
188
  configSpinner.stop(`Created ${KUBB_CONFIG_FILENAME}`)
184
189
 
@@ -191,8 +196,6 @@ export async function runInit({ yes, version, input: inputFlag, output: outputFl
191
196
  '\n' +
192
197
  styleText('cyan', ' 2. Generate code with: npx kubb generate') +
193
198
  '\n' +
194
- styleText('cyan', ' Or start a stream server with: npx kubb start') +
195
- '\n' +
196
199
  styleText('cyan', ` 3. Find generated files in: ${outputPath}`) +
197
200
  '\n\n' +
198
201
  styleText('dim', `Using ${packageManager.name} • Kubb v${version}`),
@@ -0,0 +1,39 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import process from 'node:process'
4
+ import type { PackageManagerInfo, PackageManagerName } from '@internals/utils'
5
+ import { x } from 'tinyexec'
6
+
7
+ /**
8
+ * Returns `true` when a `package.json` exists at `cwd`.
9
+ */
10
+ export function hasPackageJson(cwd: string = process.cwd()): boolean {
11
+ return fs.existsSync(path.join(cwd, 'package.json'))
12
+ }
13
+
14
+ /**
15
+ * Initializes a new `package.json` at `cwd` using the detected package manager.
16
+ */
17
+ export async function initPackageJson(cwd: string, packageManager: PackageManagerInfo): Promise<void> {
18
+ const commands: Record<PackageManagerName, Array<string>> = {
19
+ npm: ['init', '-y'],
20
+ pnpm: ['init'],
21
+ yarn: ['init', '-y'],
22
+ bun: ['init', '-y'],
23
+ }
24
+
25
+ await x(packageManager.name, commands[packageManager.name], {
26
+ nodeOptions: { cwd, stdio: 'inherit' },
27
+ throwOnError: true,
28
+ })
29
+ }
30
+
31
+ /**
32
+ * Installs the given packages at `cwd` using the detected package manager.
33
+ */
34
+ export async function installPackages(packages: Array<string>, packageManager: PackageManagerInfo, cwd: string = process.cwd()): Promise<void> {
35
+ await x(packageManager.name, [...packageManager.installCommand, ...packages], {
36
+ nodeOptions: { cwd, stdio: 'inherit' },
37
+ throwOnError: true,
38
+ })
39
+ }
@@ -0,0 +1,37 @@
1
+ import process from 'node:process'
2
+ import { styleText } from 'node:util'
3
+ import { getErrorMessage } from '@internals/utils'
4
+ import { Telemetry } from '../../Telemetry.ts'
5
+ import type * as McpModule from '@kubb/mcp'
6
+
7
+ type McpOptions = {
8
+ /**
9
+ * Current `@kubb/cli` version string, used for the telemetry payload.
10
+ */
11
+ version: string
12
+ /**
13
+ * TCP port for the HTTP MCP server. When `undefined`, the server uses stdio transport.
14
+ */
15
+ port?: string
16
+ /**
17
+ * Hostname to bind to when running in HTTP mode.
18
+ *
19
+ * @default 'localhost'
20
+ */
21
+ host?: string
22
+ }
23
+
24
+ export async function run({ version, port, host }: McpOptions): Promise<void> {
25
+ const { run: startMcpServer } = (await import('@kubb/mcp')) as typeof McpModule
26
+ const hrStart = process.hrtime()
27
+ const report = (status: 'success' | 'failed') => Telemetry.send(Telemetry.build({ command: 'mcp', kubbVersion: version, hrStart, status }))
28
+ try {
29
+ console.log(styleText('cyan', '⏳ Starting MCP server...'))
30
+ console.warn(styleText('yellow', 'This feature is still under development, use with caution'))
31
+ await startMcpServer(undefined, { port: port !== undefined ? Number(port) : undefined, host })
32
+ await report('success')
33
+ } catch (error) {
34
+ await report('failed')
35
+ console.error(getErrorMessage(error))
36
+ }
37
+ }
@@ -1,47 +1,52 @@
1
1
  import process from 'node:process'
2
2
  import { styleText } from 'node:util'
3
3
  import { getErrorMessage } from '@internals/utils'
4
- import { buildTelemetryEvent, sendTelemetry } from '../utils/telemetry.ts'
4
+ import { Telemetry } from '../../Telemetry.ts'
5
5
 
6
6
  type ValidateOptions = {
7
+ /**
8
+ * Path or URL to the OpenAPI/Swagger file to validate.
9
+ */
7
10
  input: string
11
+ /**
12
+ * Current `@kubb/cli` version string, used for the telemetry payload.
13
+ */
8
14
  version: string
9
15
  }
10
16
 
11
17
  type ValidateModule = typeof import('@kubb/adapter-oas')
12
18
  type ValidateDependencies = {
19
+ /**
20
+ * Loads `@kubb/adapter-oas`. Injected so tests can substitute a mock.
21
+ */
13
22
  loadValidateModule: () => Promise<ValidateModule>
14
23
  }
15
24
 
25
+ /**
26
+ * Dynamically loads `@kubb/adapter-oas` for OpenAPI validation.
27
+ */
16
28
  export function loadValidateModule(): Promise<ValidateModule> {
17
29
  return import('@kubb/adapter-oas') as Promise<ValidateModule>
18
30
  }
19
31
 
20
- export async function runValidate({ input, version }: ValidateOptions, dependencies: ValidateDependencies = { loadValidateModule }): Promise<void> {
32
+ /**
33
+ * Validates an OpenAPI/Swagger file at `input` using `@kubb/adapter-oas`.
34
+ * Exits the process with code 1 on validation failure or missing dependency.
35
+ */
36
+ export async function run({ input, version }: ValidateOptions, dependencies: ValidateDependencies = { loadValidateModule }): Promise<void> {
21
37
  const hrStart = process.hrtime()
38
+ const report = (status: 'success' | 'failed') => Telemetry.send(Telemetry.build({ command: 'validate', kubbVersion: version, hrStart, status }))
22
39
  try {
23
40
  const { adapterOas } = await dependencies.loadValidateModule()
24
41
  const adapter = adapterOas()
25
- await adapter.validate!(input, { throwOnError: true })
26
-
27
- await sendTelemetry(
28
- buildTelemetryEvent({
29
- command: 'validate',
30
- kubbVersion: version,
31
- hrStart,
32
- status: 'success',
33
- }),
34
- )
42
+ if (!adapter.validate) {
43
+ throw new Error('The loaded adapter does not support validation.')
44
+ }
45
+ await adapter.validate(input, { throwOnError: true })
46
+ await report('success')
35
47
  console.log('✅ Validation success')
36
48
  } catch (error) {
37
- await sendTelemetry(
38
- buildTelemetryEvent({
39
- command: 'validate',
40
- kubbVersion: version,
41
- hrStart,
42
- status: 'failed',
43
- }),
44
- )
49
+ await report('failed')
45
50
  if (error instanceof Error && /@kubb\/adapter-oas/.test(error.message)) {
46
51
  console.error(styleText('red', 'The @kubb/adapter-oas package is not installed.'))
47
52
  console.error('')
@@ -1,68 +0,0 @@
1
- import "./chunk--u3MIqq1.js";
2
- import { n as defineCommand } from "./define-Ctii4bel.js";
3
- import { t as version } from "./package-vLafMWCe.js";
4
- import { o as agentDefaults } from "./constants-BPJBMT_6.js";
5
- //#endregion
6
- //#region src/commands/agent.ts
7
- const command = defineCommand({
8
- name: "agent",
9
- description: "Manage the Kubb Agent — an HTTP server that lets AI agents trigger code generation programmatically via a REST API. Useful when an AI workflow needs to generate code without direct CLI access.",
10
- examples: [
11
- "kubb agent start",
12
- "kubb agent start --port 4000 --allow-write",
13
- "kubb agent start --config ./kubb.config.ts --allow-all"
14
- ],
15
- subCommands: [defineCommand({
16
- name: "start",
17
- description: "Start the Kubb Agent HTTP server. Exposes a REST API that accepts a kubb.config.ts patch and returns generated code as a stream. Use --allow-write to also write files to disk.",
18
- examples: [
19
- "kubb agent start",
20
- "kubb agent start --port 4000",
21
- "kubb agent start --allow-write",
22
- "kubb agent start --config ./kubb.config.ts --allow-all"
23
- ],
24
- options: {
25
- config: {
26
- type: "string",
27
- description: "Path to the Kubb config file",
28
- short: "c"
29
- },
30
- port: {
31
- type: "string",
32
- description: "Port the HTTP server listens on",
33
- short: "p",
34
- default: agentDefaults.port
35
- },
36
- host: {
37
- type: "string",
38
- description: "Hostname the HTTP server binds to",
39
- default: agentDefaults.host
40
- },
41
- "allow-write": {
42
- type: "boolean",
43
- description: "Write generated files to the filesystem. When omitted, output is streamed only and no files are written.",
44
- default: false
45
- },
46
- "allow-all": {
47
- type: "boolean",
48
- description: "Grant all permissions (implies --allow-write).",
49
- default: false
50
- }
51
- },
52
- async run({ values }) {
53
- const { runAgentStart } = await import("./agent-VXKxLCho.js");
54
- await runAgentStart({
55
- port: values.port !== void 0 ? values.port : void 0,
56
- host: values.host,
57
- configPath: values.config,
58
- allowWrite: values["allow-write"],
59
- allowAll: values["allow-all"],
60
- version
61
- });
62
- }
63
- })]
64
- });
65
- //#endregion
66
- export { command };
67
-
68
- //# sourceMappingURL=agent-BJEvbSiP.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"agent-BJEvbSiP.js","names":["command","startCommand"],"sources":["../src/commands/agent/start.ts","../src/commands/agent.ts"],"sourcesContent":["import { defineCommand } from '@internals/utils'\nimport { version } from '../../../package.json'\nimport { agentDefaults } from '../../constants.ts'\n\nexport const command = defineCommand({\n name: 'start',\n description:\n 'Start the Kubb Agent HTTP server. Exposes a REST API that accepts a kubb.config.ts patch and returns generated code as a stream. Use --allow-write to also write files to disk.',\n examples: ['kubb agent start', 'kubb agent start --port 4000', 'kubb agent start --allow-write', 'kubb agent start --config ./kubb.config.ts --allow-all'],\n options: {\n config: {\n type: 'string',\n description: 'Path to the Kubb config file',\n short: 'c',\n },\n port: {\n type: 'string',\n description: 'Port the HTTP server listens on',\n short: 'p',\n default: agentDefaults.port,\n },\n host: {\n type: 'string',\n description: 'Hostname the HTTP server binds to',\n default: agentDefaults.host,\n },\n 'allow-write': {\n type: 'boolean',\n description: 'Write generated files to the filesystem. When omitted, output is streamed only and no files are written.',\n default: false,\n },\n 'allow-all': {\n type: 'boolean',\n description: 'Grant all permissions (implies --allow-write).',\n default: false,\n },\n },\n async run({ values }) {\n const { runAgentStart } = await import('../../runners/agent.ts')\n\n await runAgentStart({\n port: values.port !== undefined ? values.port : undefined,\n host: values.host,\n configPath: values.config,\n allowWrite: values['allow-write'],\n allowAll: values['allow-all'],\n version,\n })\n },\n})\n","import { defineCommand } from '@internals/utils'\nimport { command as startCommand } from './agent/start.ts'\n\nexport const command = defineCommand({\n name: 'agent',\n description:\n 'Manage the Kubb Agent — an HTTP server that lets AI agents trigger code generation programmatically via a REST API. Useful when an AI workflow needs to generate code without direct CLI access.',\n examples: ['kubb agent start', 'kubb agent start --port 4000 --allow-write', 'kubb agent start --config ./kubb.config.ts --allow-all'],\n subCommands: [startCommand],\n})\n"],"mappings":";;;;;;ACGA,MAAa,UAAU,cAAc;CACnC,MAAM;CACN,aACE;CACF,UAAU;EAAC;EAAoB;EAA8C;EAAyD;CACtI,aAAa,CDJQ,cAAc;EACnC,MAAM;EACN,aACE;EACF,UAAU;GAAC;GAAoB;GAAgC;GAAkC;GAAyD;EAC1J,SAAS;GACP,QAAQ;IACN,MAAM;IACN,aAAa;IACb,OAAO;IACR;GACD,MAAM;IACJ,MAAM;IACN,aAAa;IACb,OAAO;IACP,SAAS,cAAc;IACxB;GACD,MAAM;IACJ,MAAM;IACN,aAAa;IACb,SAAS,cAAc;IACxB;GACD,eAAe;IACb,MAAM;IACN,aAAa;IACb,SAAS;IACV;GACD,aAAa;IACX,MAAM;IACN,aAAa;IACb,SAAS;IACV;GACF;EACD,MAAM,IAAI,EAAE,UAAU;GACpB,MAAM,EAAE,kBAAkB,MAAM,OAAO;GAEvC,MAAM,cAAc;IAClB,MAAM,OAAO,SAAS,KAAA,IAAY,OAAO,OAAO,KAAA;IAChD,MAAM,OAAO;IACb,YAAY,OAAO;IACnB,YAAY,OAAO;IACnB,UAAU,OAAO;IACjB;IACD,CAAC;;EAEL,CCzCeC,CAAa;CAC5B,CAAC"}
@@ -1,70 +0,0 @@
1
- require("./chunk-ByKO4r7w.cjs");
2
- const require_define = require("./define-Bdn8j5VM.cjs");
3
- const require_package = require("./package-iheSdfas.cjs");
4
- const require_constants = require("./constants-Rcaqzyd-.cjs");
5
- //#region src/commands/agent/start.ts
6
- const command$1 = require_define.defineCommand({
7
- name: "start",
8
- description: "Start the Kubb Agent HTTP server. Exposes a REST API that accepts a kubb.config.ts patch and returns generated code as a stream. Use --allow-write to also write files to disk.",
9
- examples: [
10
- "kubb agent start",
11
- "kubb agent start --port 4000",
12
- "kubb agent start --allow-write",
13
- "kubb agent start --config ./kubb.config.ts --allow-all"
14
- ],
15
- options: {
16
- config: {
17
- type: "string",
18
- description: "Path to the Kubb config file",
19
- short: "c"
20
- },
21
- port: {
22
- type: "string",
23
- description: "Port the HTTP server listens on",
24
- short: "p",
25
- default: require_constants.agentDefaults.port
26
- },
27
- host: {
28
- type: "string",
29
- description: "Hostname the HTTP server binds to",
30
- default: require_constants.agentDefaults.host
31
- },
32
- "allow-write": {
33
- type: "boolean",
34
- description: "Write generated files to the filesystem. When omitted, output is streamed only and no files are written.",
35
- default: false
36
- },
37
- "allow-all": {
38
- type: "boolean",
39
- description: "Grant all permissions (implies --allow-write).",
40
- default: false
41
- }
42
- },
43
- async run({ values }) {
44
- const { runAgentStart } = await Promise.resolve().then(() => require("./agent-D9CKYh4K.cjs"));
45
- await runAgentStart({
46
- port: values.port !== void 0 ? values.port : void 0,
47
- host: values.host,
48
- configPath: values.config,
49
- allowWrite: values["allow-write"],
50
- allowAll: values["allow-all"],
51
- version: require_package.version
52
- });
53
- }
54
- });
55
- //#endregion
56
- //#region src/commands/agent.ts
57
- const command = require_define.defineCommand({
58
- name: "agent",
59
- description: "Manage the Kubb Agent — an HTTP server that lets AI agents trigger code generation programmatically via a REST API. Useful when an AI workflow needs to generate code without direct CLI access.",
60
- examples: [
61
- "kubb agent start",
62
- "kubb agent start --port 4000 --allow-write",
63
- "kubb agent start --config ./kubb.config.ts --allow-all"
64
- ],
65
- subCommands: [command$1]
66
- });
67
- //#endregion
68
- exports.command = command;
69
-
70
- //# sourceMappingURL=agent-CXNO6dgj.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"agent-CXNO6dgj.cjs","names":["command","defineCommand","agentDefaults","defineCommand","startCommand"],"sources":["../src/commands/agent/start.ts","../src/commands/agent.ts"],"sourcesContent":["import { defineCommand } from '@internals/utils'\nimport { version } from '../../../package.json'\nimport { agentDefaults } from '../../constants.ts'\n\nexport const command = defineCommand({\n name: 'start',\n description:\n 'Start the Kubb Agent HTTP server. Exposes a REST API that accepts a kubb.config.ts patch and returns generated code as a stream. Use --allow-write to also write files to disk.',\n examples: ['kubb agent start', 'kubb agent start --port 4000', 'kubb agent start --allow-write', 'kubb agent start --config ./kubb.config.ts --allow-all'],\n options: {\n config: {\n type: 'string',\n description: 'Path to the Kubb config file',\n short: 'c',\n },\n port: {\n type: 'string',\n description: 'Port the HTTP server listens on',\n short: 'p',\n default: agentDefaults.port,\n },\n host: {\n type: 'string',\n description: 'Hostname the HTTP server binds to',\n default: agentDefaults.host,\n },\n 'allow-write': {\n type: 'boolean',\n description: 'Write generated files to the filesystem. When omitted, output is streamed only and no files are written.',\n default: false,\n },\n 'allow-all': {\n type: 'boolean',\n description: 'Grant all permissions (implies --allow-write).',\n default: false,\n },\n },\n async run({ values }) {\n const { runAgentStart } = await import('../../runners/agent.ts')\n\n await runAgentStart({\n port: values.port !== undefined ? values.port : undefined,\n host: values.host,\n configPath: values.config,\n allowWrite: values['allow-write'],\n allowAll: values['allow-all'],\n version,\n })\n },\n})\n","import { defineCommand } from '@internals/utils'\nimport { command as startCommand } from './agent/start.ts'\n\nexport const command = defineCommand({\n name: 'agent',\n description:\n 'Manage the Kubb Agent — an HTTP server that lets AI agents trigger code generation programmatically via a REST API. Useful when an AI workflow needs to generate code without direct CLI access.',\n examples: ['kubb agent start', 'kubb agent start --port 4000 --allow-write', 'kubb agent start --config ./kubb.config.ts --allow-all'],\n subCommands: [startCommand],\n})\n"],"mappings":";;;;;AAIA,MAAaA,YAAUC,eAAAA,cAAc;CACnC,MAAM;CACN,aACE;CACF,UAAU;EAAC;EAAoB;EAAgC;EAAkC;EAAyD;CAC1J,SAAS;EACP,QAAQ;GACN,MAAM;GACN,aAAa;GACb,OAAO;GACR;EACD,MAAM;GACJ,MAAM;GACN,aAAa;GACb,OAAO;GACP,SAASC,kBAAAA,cAAc;GACxB;EACD,MAAM;GACJ,MAAM;GACN,aAAa;GACb,SAASA,kBAAAA,cAAc;GACxB;EACD,eAAe;GACb,MAAM;GACN,aAAa;GACb,SAAS;GACV;EACD,aAAa;GACX,MAAM;GACN,aAAa;GACb,SAAS;GACV;EACF;CACD,MAAM,IAAI,EAAE,UAAU;EACpB,MAAM,EAAE,kBAAkB,MAAA,QAAA,SAAA,CAAA,WAAA,QAAM,uBAAA,CAAA;EAEhC,MAAM,cAAc;GAClB,MAAM,OAAO,SAAS,KAAA,IAAY,OAAO,OAAO,KAAA;GAChD,MAAM,OAAO;GACb,YAAY,OAAO;GACnB,YAAY,OAAO;GACnB,UAAU,OAAO;GACjB,SAAA,gBAAA;GACD,CAAC;;CAEL,CAAC;;;AC9CF,MAAa,UAAUC,eAAAA,cAAc;CACnC,MAAM;CACN,aACE;CACF,UAAU;EAAC;EAAoB;EAA8C;EAAyD;CACtI,aAAa,CAACC,UAAa;CAC5B,CAAC"}
@@ -1,122 +0,0 @@
1
- const require_chunk = require("./chunk-ByKO4r7w.cjs");
2
- const require_telemetry = require("./telemetry-BLX0NzRk.cjs");
3
- const require_shell = require("./shell-475fQKaX.cjs");
4
- const require_constants = require("./constants-Rcaqzyd-.cjs");
5
- let node_util = require("node:util");
6
- let node_path = require("node:path");
7
- node_path = require_chunk.__toESM(node_path, 1);
8
- let node_process = require("node:process");
9
- node_process = require_chunk.__toESM(node_process, 1);
10
- let node_net = require("node:net");
11
- node_net = require_chunk.__toESM(node_net, 1);
12
- let node_url = require("node:url");
13
- let _clack_prompts = require("@clack/prompts");
14
- _clack_prompts = require_chunk.__toESM(_clack_prompts, 1);
15
- //#region src/runners/agent.ts
16
- /**
17
- * Resolves the environment passed to the detached agent process using CLI values first, then environment values, then CLI defaults.
18
- */
19
- function resolveAgentStartEnvironment({ port, host, configPath, allowWrite, allowAll }) {
20
- const resolvedPort = port ?? node_process.env.PORT ?? require_constants.agentDefaults.port;
21
- const resolvedHost = host !== require_constants.agentDefaults.host ? host : node_process.env.HOST ?? require_constants.agentDefaults.host;
22
- const resolvedAllowAll = allowAll || node_process.env.KUBB_AGENT_ALLOW_ALL === "true";
23
- const resolvedAllowWrite = resolvedAllowAll || allowWrite || node_process.env.KUBB_AGENT_ALLOW_WRITE === "true";
24
- const agentRoot = node_process.env.KUBB_AGENT_ROOT ?? node_process.cwd();
25
- const agentConfigPath = node_path.default.resolve(node_process.cwd(), configPath || node_process.env.KUBB_AGENT_CONFIG || require_constants.agentDefaults.configFile);
26
- return {
27
- port: resolvedPort,
28
- host: resolvedHost,
29
- allowWrite: resolvedAllowWrite,
30
- allowAll: resolvedAllowAll,
31
- agentConfigPath,
32
- env: {
33
- ...node_process.env,
34
- PORT: resolvedPort,
35
- HOST: resolvedHost,
36
- KUBB_AGENT_ROOT: agentRoot,
37
- KUBB_AGENT_CONFIG: agentConfigPath,
38
- KUBB_AGENT_ALLOW_WRITE: String(resolvedAllowWrite),
39
- KUBB_AGENT_ALLOW_ALL: String(resolvedAllowAll),
40
- KUBB_AGENT_TOKEN: node_process.env.KUBB_AGENT_TOKEN,
41
- KUBB_AGENT_RETRY_TIMEOUT: node_process.env.KUBB_AGENT_RETRY_TIMEOUT ?? require_constants.agentDefaults.retryTimeout,
42
- KUBB_STUDIO_URL: node_process.env.KUBB_STUDIO_URL ?? require_constants.agentDefaults.studioUrl
43
- }
44
- };
45
- }
46
- function isPortAvailable(port, host) {
47
- return new Promise((resolve) => {
48
- const server = node_net.default.createServer();
49
- server.once("error", () => resolve(false));
50
- server.once("listening", () => {
51
- server.close();
52
- resolve(true);
53
- });
54
- server.listen(port, host);
55
- });
56
- }
57
- async function runAgentStart({ port, host, configPath, allowWrite, allowAll, version }) {
58
- const hrStart = node_process.hrtime();
59
- try {
60
- try {
61
- node_process.loadEnvFile();
62
- } catch {}
63
- let agentPkgUrl;
64
- try {
65
- agentPkgUrl = {}.resolve("@kubb/agent/package.json");
66
- } catch (_e) {
67
- console.error((0, node_util.styleText)("red", "The @kubb/agent package is not installed."));
68
- console.error("");
69
- console.error("Install it with:");
70
- console.error((0, node_util.styleText)("cyan", " npm install @kubb/agent"));
71
- console.error((0, node_util.styleText)("cyan", " # or"));
72
- console.error((0, node_util.styleText)("cyan", " pnpm install @kubb/agent"));
73
- console.error("");
74
- node_process.exit(1);
75
- }
76
- const agentPkgPath = (0, node_url.fileURLToPath)(agentPkgUrl);
77
- const agentDir = node_path.default.dirname(agentPkgPath);
78
- const serverPath = node_path.default.join(agentDir, require_constants.agentDefaults.serverEntryPath);
79
- const resolvedEnv = resolveAgentStartEnvironment({
80
- port,
81
- host,
82
- configPath,
83
- allowWrite,
84
- allowAll
85
- });
86
- const numericPort = Number(resolvedEnv.port);
87
- if (!Number.isInteger(numericPort) || numericPort <= 0) throw new Error(`Invalid port "${resolvedEnv.port}". Provide a positive integer with --port or PORT.`);
88
- _clack_prompts.log.step((0, node_util.styleText)("cyan", "Starting agent server..."));
89
- _clack_prompts.log.info((0, node_util.styleText)("dim", `Config: ${resolvedEnv.agentConfigPath}`));
90
- _clack_prompts.log.info((0, node_util.styleText)("dim", `Host: ${resolvedEnv.host}`));
91
- _clack_prompts.log.info((0, node_util.styleText)("dim", `Port: ${resolvedEnv.port}`));
92
- if (!resolvedEnv.allowWrite && !resolvedEnv.allowAll) _clack_prompts.log.warn((0, node_util.styleText)("yellow", "Filesystem writes disabled. Use --allow-write or --allow-all to enable."));
93
- if (!await isPortAvailable(numericPort, resolvedEnv.host)) {
94
- _clack_prompts.log.error((0, node_util.styleText)("red", `Port ${resolvedEnv.port} is already in use. Stop the existing process or choose a different port with --port.`));
95
- node_process.exit(1);
96
- }
97
- await require_shell.spawnAsync("node", [serverPath], {
98
- env: resolvedEnv.env,
99
- cwd: node_process.cwd()
100
- });
101
- await require_telemetry.sendTelemetry(require_telemetry.buildTelemetryEvent({
102
- command: "agent",
103
- kubbVersion: version,
104
- hrStart,
105
- status: "success"
106
- }));
107
- } catch (error) {
108
- await require_telemetry.sendTelemetry(require_telemetry.buildTelemetryEvent({
109
- command: "agent",
110
- kubbVersion: version,
111
- hrStart,
112
- status: "failed"
113
- }));
114
- _clack_prompts.log.error((0, node_util.styleText)("red", "Failed to start agent server"));
115
- console.error(error);
116
- node_process.exit(1);
117
- }
118
- }
119
- //#endregion
120
- exports.runAgentStart = runAgentStart;
121
-
122
- //# sourceMappingURL=agent-D9CKYh4K.cjs.map