@kubb/cli 5.0.0-beta.63 → 5.0.0-beta.64

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 (87) hide show
  1. package/bin/kubb.js +9 -3
  2. package/dist/{Telemetry-C6rbhJMo.cjs → Telemetry-CfPP7MYq.cjs} +4 -4
  3. package/dist/{Telemetry-C6rbhJMo.cjs.map → Telemetry-CfPP7MYq.cjs.map} +1 -1
  4. package/dist/{Telemetry-DTKcvgbx.js → Telemetry-uAr3lK_-.js} +2 -2
  5. package/dist/{Telemetry-DTKcvgbx.js.map → Telemetry-uAr3lK_-.js.map} +1 -1
  6. package/dist/{define-C4AB3POr.cjs → define-Cq9hOxpK.cjs} +2 -2
  7. package/dist/{define-C4AB3POr.cjs.map → define-Cq9hOxpK.cjs.map} +1 -1
  8. package/dist/{define-C63T4jp6.js → define-GYXr00ky.js} +2 -2
  9. package/dist/{define-C63T4jp6.js.map → define-GYXr00ky.js.map} +1 -1
  10. package/dist/{errors-BsemQCMn.js → errors-Dc_d7BfX.js} +2 -2
  11. package/dist/{errors-BsemQCMn.js.map → errors-Dc_d7BfX.js.map} +1 -1
  12. package/dist/{errors-DykI11xo.cjs → errors-gxFK0vrp.cjs} +2 -2
  13. package/dist/{errors-DykI11xo.cjs.map → errors-gxFK0vrp.cjs.map} +1 -1
  14. package/dist/{generate-DC4--Iha.js → generate-DHQnl_F1.js} +4 -4
  15. package/dist/{generate-DC4--Iha.js.map → generate-DHQnl_F1.js.map} +1 -1
  16. package/dist/{generate-Dw7aWzeb.cjs → generate-svfhwhEK.cjs} +4 -4
  17. package/dist/{generate-Dw7aWzeb.cjs.map → generate-svfhwhEK.cjs.map} +1 -1
  18. package/dist/index.cjs +8 -8
  19. package/dist/index.d.ts +1 -1
  20. package/dist/index.js +8 -8
  21. package/dist/{init-D2VvDsET.js → init-B02NN_88.js} +5 -5
  22. package/dist/{init-D2VvDsET.js.map → init-B02NN_88.js.map} +1 -1
  23. package/dist/{init-C7GC2NA8.cjs → init-Bg_68Ok6.cjs} +5 -5
  24. package/dist/{init-C7GC2NA8.cjs.map → init-Bg_68Ok6.cjs.map} +1 -1
  25. package/dist/{mcp-uTUssJam.cjs → mcp-DUzIXdRV.cjs} +7 -25
  26. package/dist/mcp-DUzIXdRV.cjs.map +1 -0
  27. package/dist/mcp-ZJQksVUU.js +21 -0
  28. package/dist/mcp-ZJQksVUU.js.map +1 -0
  29. package/dist/package-BoXPsuNH.js +6 -0
  30. package/dist/package-BoXPsuNH.js.map +1 -0
  31. package/dist/{package-IO7JFU8g.cjs → package-Cdu8eJMb.cjs} +2 -2
  32. package/dist/package-Cdu8eJMb.cjs.map +1 -0
  33. package/dist/{run-DpKny2hT.cjs → run-B4rIAnch.cjs} +7 -7
  34. package/dist/{run-DpKny2hT.cjs.map → run-B4rIAnch.cjs.map} +1 -1
  35. package/dist/{run-D_sbcTfX.cjs → run-BM1t8CSM.cjs} +8 -13
  36. package/dist/run-BM1t8CSM.cjs.map +1 -0
  37. package/dist/{run-Ctz9-vGE.js → run-BlFVmIJl.js} +7 -12
  38. package/dist/run-BlFVmIJl.js.map +1 -0
  39. package/dist/{run-BoXg14l_.cjs → run-CBc896in.cjs} +5 -5
  40. package/dist/{run-BoXg14l_.cjs.map → run-CBc896in.cjs.map} +1 -1
  41. package/dist/{run-FiqbWZEH.cjs → run-CD3BE8yP.cjs} +55 -62
  42. package/dist/run-CD3BE8yP.cjs.map +1 -0
  43. package/dist/{run-Bp8sI6h0.js → run-D_dWNFhX.js} +4 -4
  44. package/dist/{run-Bp8sI6h0.js.map → run-D_dWNFhX.js.map} +1 -1
  45. package/dist/{run-DybX4Hpr.js → run-DkW2VQBq.js} +53 -60
  46. package/dist/run-DkW2VQBq.js.map +1 -0
  47. package/dist/{run-BG7Giryi.js → run-DzYeru-0.js} +3 -3
  48. package/dist/{run-BG7Giryi.js.map → run-DzYeru-0.js.map} +1 -1
  49. package/dist/{tools-_Xp8-_zy.cjs → tools-CZT9wSA6.cjs} +2 -2
  50. package/dist/{tools-_Xp8-_zy.cjs.map → tools-CZT9wSA6.cjs.map} +1 -1
  51. package/dist/{tools-BU99bhi8.js → tools-D0UogMU3.js} +2 -2
  52. package/dist/{tools-BU99bhi8.js.map → tools-D0UogMU3.js.map} +1 -1
  53. package/dist/{validate-DVYs1uzP.cjs → validate-B3EwltHu.cjs} +5 -5
  54. package/dist/{validate-DVYs1uzP.cjs.map → validate-B3EwltHu.cjs.map} +1 -1
  55. package/dist/{validate-C6tYZ5Bd.js → validate-DXYcZCm_.js} +5 -5
  56. package/dist/{validate-C6tYZ5Bd.js.map → validate-DXYcZCm_.js.map} +1 -1
  57. package/package.json +7 -8
  58. package/dist/mcp-DKPUyzpK.js +0 -39
  59. package/dist/mcp-DKPUyzpK.js.map +0 -1
  60. package/dist/mcp-uTUssJam.cjs.map +0 -1
  61. package/dist/package-DCrqV1yP.js +0 -6
  62. package/dist/package-DCrqV1yP.js.map +0 -1
  63. package/dist/package-IO7JFU8g.cjs.map +0 -1
  64. package/dist/run-Ctz9-vGE.js.map +0 -1
  65. package/dist/run-D_sbcTfX.cjs.map +0 -1
  66. package/dist/run-DybX4Hpr.js.map +0 -1
  67. package/dist/run-FiqbWZEH.cjs.map +0 -1
  68. package/src/Telemetry.ts +0 -304
  69. package/src/commands/generate.ts +0 -65
  70. package/src/commands/init.ts +0 -51
  71. package/src/commands/mcp.ts +0 -36
  72. package/src/commands/validate.ts +0 -22
  73. package/src/constants.ts +0 -19
  74. package/src/index.ts +0 -32
  75. package/src/loggers/clackLogger.ts +0 -392
  76. package/src/loggers/defineLogger.ts +0 -59
  77. package/src/loggers/plainLogger.ts +0 -199
  78. package/src/loggers/types.ts +0 -6
  79. package/src/loggers/utils.ts +0 -250
  80. package/src/runners/generate/run.ts +0 -399
  81. package/src/runners/generate/utils.ts +0 -235
  82. package/src/runners/init/run.ts +0 -210
  83. package/src/runners/init/utils.ts +0 -39
  84. package/src/runners/mcp/run.ts +0 -42
  85. package/src/runners/validate/run.ts +0 -63
  86. /package/dist/{chunk-Bx3C2hgW.cjs → rolldown-runtime-Bx3C2hgW.cjs} +0 -0
  87. /package/dist/{chunk-C0LytTxp.js → rolldown-runtime-C0LytTxp.js} +0 -0
@@ -1,235 +0,0 @@
1
- import { hash } from 'node:crypto'
2
- import { styleText } from 'node:util'
3
- import { createModuleLoader } from '@internals/shared'
4
- import type { AsyncEventEmitter } from '@internals/utils'
5
- import { toError } from '@internals/utils'
6
- import type { CLIOptions, Config, KubbHooks, PossibleConfig } from '@kubb/core'
7
- import { cosmiconfig } from 'cosmiconfig'
8
- import { NonZeroExitError, x } from 'tinyexec'
9
- import { WATCHER_IGNORED_PATHS } from '../../constants.ts'
10
-
11
- type CosmiconfigResult = {
12
- filepath: string
13
- isEmpty?: boolean
14
- config: PossibleConfig<CLIOptions>
15
- }
16
-
17
- const loader = createModuleLoader()
18
-
19
- const tsLoader = (configFile: string) => loader.load(configFile, { default: true })
20
-
21
- const MODULE_NAME = 'kubb'
22
-
23
- const BASE_SEARCH_PLACES = [
24
- 'package.json',
25
- `.${MODULE_NAME}rc`,
26
- `.${MODULE_NAME}rc.json`,
27
- `.${MODULE_NAME}rc.yaml`,
28
- `.${MODULE_NAME}rc.yml`,
29
- `.${MODULE_NAME}rc.ts`,
30
- `.${MODULE_NAME}rc.mts`,
31
- `.${MODULE_NAME}rc.cts`,
32
- `.${MODULE_NAME}rc.js`,
33
- `.${MODULE_NAME}rc.mjs`,
34
- `.${MODULE_NAME}rc.cjs`,
35
- `${MODULE_NAME}.config.ts`,
36
- `${MODULE_NAME}.config.mts`,
37
- `${MODULE_NAME}.config.cts`,
38
- `${MODULE_NAME}.config.js`,
39
- `${MODULE_NAME}.config.mjs`,
40
- `${MODULE_NAME}.config.cjs`,
41
- ]
42
-
43
- const SEARCH_PLACES = ['', '.config/', 'configs/'].flatMap((prefix) => BASE_SEARCH_PLACES.map((p) => `${prefix}${p}`))
44
-
45
- async function getCosmiConfig(configFile?: string): Promise<CosmiconfigResult> {
46
- const explorer = cosmiconfig(MODULE_NAME, {
47
- cache: false,
48
- searchPlaces: SEARCH_PLACES,
49
- loaders: { '.ts': tsLoader, '.mts': tsLoader, '.cts': tsLoader },
50
- })
51
-
52
- let result: CosmiconfigResult
53
- try {
54
- result = (configFile ? await explorer.load(configFile) : await explorer.search()) as CosmiconfigResult
55
- } catch (error) {
56
- throw new Error('Config failed loading', { cause: error })
57
- }
58
-
59
- if (!result?.config || result.isEmpty) {
60
- throw new Error('Config not defined, create a kubb.config.js or pass through your config with the option --config')
61
- }
62
-
63
- return result
64
- }
65
-
66
- type GetConfigsOptions = {
67
- /**
68
- * Explicit path to the Kubb config file. When omitted, cosmiconfig searches from the current directory.
69
- */
70
- configPath?: string
71
- /**
72
- * Optional OpenAPI input path that overrides `config.input.path` for this run.
73
- */
74
- input?: string
75
- /**
76
- * Watch flag forwarded to the user's `defineConfig` function.
77
- */
78
- watch?: boolean
79
- /**
80
- * Log level forwarded to the user's `defineConfig` function.
81
- */
82
- logLevel?: CLIOptions['logLevel']
83
- }
84
-
85
- type GetConfigsResult = {
86
- /**
87
- * Absolute path to the resolved config file.
88
- */
89
- configPath: string
90
- /**
91
- * Resolved and normalized array of Kubb configs, each guaranteed to have a `plugins` array.
92
- */
93
- configs: Array<Config>
94
- }
95
-
96
- /**
97
- * Discovers the Kubb config via cosmiconfig and resolves it into a normalized array of configs.
98
- * Every config in the result is guaranteed to have a `plugins` array.
99
- */
100
- export async function getConfigs({ configPath, input, watch, logLevel }: GetConfigsOptions): Promise<GetConfigsResult> {
101
- const result = await getCosmiConfig(configPath)
102
- const cli: CLIOptions = { config: configPath, input, watch, logLevel }
103
- const resolved = await (typeof result.config === 'function' ? result.config(cli) : result.config)
104
- const userConfigs = Array.isArray(resolved) ? resolved : [resolved]
105
-
106
- return {
107
- configPath: result.filepath,
108
- configs: userConfigs.map((item) => ({ ...item, plugins: item.plugins ?? [] }) as Config),
109
- }
110
- }
111
-
112
- type ExecuteHooksOptions = {
113
- configHooks: NonNullable<Config['hooks']>
114
- hooks: AsyncEventEmitter<KubbHooks>
115
- }
116
-
117
- /**
118
- * Tokenizes a shell command string, respecting single and double quotes.
119
- *
120
- * @example
121
- * ```ts
122
- * tokenize('git commit -m "initial commit"')
123
- * // → ['git', 'commit', '-m', 'initial commit']
124
- * ```
125
- */
126
- function tokenize(command: string): Array<string> {
127
- return (command.match(/[^\s"']+|"([^"]*)"|'([^']*)'/g) ?? []).map((token) => token.replace(/^["']|["']$/g, ''))
128
- }
129
-
130
- /**
131
- * Runs the `done` hooks defined in a Kubb config in sequence.
132
- */
133
- export async function executeHooks({ configHooks, hooks }: ExecuteHooksOptions): Promise<void> {
134
- const commands = Array.isArray(configHooks.done) ? configHooks.done : [configHooks.done].filter(Boolean)
135
-
136
- for (const command of commands) {
137
- const [cmd, ...args] = tokenize(command)
138
- if (!cmd) continue
139
-
140
- const hookId = hash('sha256', command, 'hex')
141
- const commandWithArgs = [cmd, ...args].join(' ')
142
-
143
- await hooks.emit('kubb:hook:start', { id: hookId, command: cmd, args })
144
- await runHook({ id: hookId, command: cmd, args, commandWithArgs, hooks })
145
- }
146
- }
147
-
148
- type RunHookOptions = {
149
- id: string
150
- command: string
151
- args?: ReadonlyArray<string>
152
- commandWithArgs: string
153
- hooks: AsyncEventEmitter<KubbHooks>
154
- }
155
-
156
- /**
157
- * Spawns a hook command and reports its outcome through `kubb:hook:end`.
158
- * A non-zero exit signals failure via `kubb:hook:end` rather than throwing, so the caller can turn
159
- * it into a diagnostic. Other spawn errors do the same. Output is streamed through `kubb:hook:line`
160
- * only while a listener is attached.
161
- */
162
- export async function runHook({ id, command, args, commandWithArgs, hooks }: RunHookOptions): Promise<void> {
163
- const emitEnd = (success: boolean, error: Error | null, output?: { stdout?: string; stderr?: string }) =>
164
- hooks.emit('kubb:hook:end', { command, args, id, success, error, ...output })
165
-
166
- // Only stream line-by-line when a logger is listening, so the non-streaming plain
167
- // logger doesn't pay to iterate the subprocess output.
168
- const stream = hooks.listenerCount('kubb:hook:line') > 0
169
-
170
- try {
171
- const proc = x(command, [...(args ?? [])], {
172
- nodeOptions: { detached: process.platform !== 'win32' },
173
- throwOnError: true,
174
- })
175
-
176
- if (stream) {
177
- for await (const line of proc) {
178
- await hooks.emit('kubb:hook:line', { id, line })
179
- }
180
- }
181
-
182
- await proc
183
- await hooks.emit('kubb:success', { message: `${styleText('dim', commandWithArgs)} successfully executed` })
184
- await emitEnd(true, null)
185
- } catch (err) {
186
- if (!(err instanceof NonZeroExitError)) {
187
- const error = toError(err)
188
- await emitEnd(false, error)
189
- return
190
- }
191
-
192
- const stderr = err.output?.stderr ?? ''
193
- const stdout = err.output?.stdout ?? ''
194
-
195
- const error = new Error(`Hook execute failed: ${commandWithArgs}`)
196
- // Signal the failure via `kubb:hook:end` only, carrying the captured output so the logger can
197
- // render it. The caller turns this into a coded diagnostic and emits that through
198
- // `Diagnostics.emit`, so emitting `kubb:error` here would render it twice.
199
- await emitEnd(false, error, { stdout, stderr })
200
- }
201
- }
202
-
203
- type WatcherLog = {
204
- info: (message: string) => void
205
- error: (message: string) => void
206
- }
207
-
208
- /**
209
- * Starts a file watcher on the given paths and calls `cb` on any change.
210
- * Ignores `.git` and `node_modules` directories.
211
- */
212
- export async function startWatcher(
213
- path: Array<string>,
214
- cb: (path: Array<string>) => Promise<void>,
215
- log: WatcherLog = { info: console.log, error: console.log },
216
- ): Promise<void> {
217
- const { watch } = await import('chokidar')
218
- const watcher = watch(path, { ignorePermissionErrors: true, ignored: WATCHER_IGNORED_PATHS })
219
-
220
- process.once('SIGINT', () => {
221
- watcher.close()
222
- })
223
- process.once('SIGTERM', () => {
224
- watcher.close()
225
- })
226
-
227
- watcher.on('all', async (type, file) => {
228
- log.info(styleText('yellow', styleText('bold', `Change detected: ${type} ${file}`)))
229
- try {
230
- await cb(path)
231
- } catch (_e) {
232
- log.error(styleText('red', 'Watcher failed'))
233
- }
234
- })
235
- }
@@ -1,210 +0,0 @@
1
- import fs from 'node:fs'
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 { detectPackageManager } from '@internals/utils'
7
- import { availablePlugins, generateConfigFile, initDefaults, KUBB_CONFIG_FILENAME, type PluginOption } from '@internals/shared'
8
- import { hasPackageJson, initPackageJson, installPackages } from './utils.ts'
9
-
10
- function cancelAndExit(message = 'Operation canceled.'): never {
11
- clack.cancel(message)
12
- process.exit(0)
13
- }
14
-
15
- type InitOptions = {
16
- /**
17
- * When `true`, skips all interactive prompts and uses default values.
18
- */
19
- yes: boolean
20
- /**
21
- * Current `@kubb/cli` version string, shown in the closing outro.
22
- */
23
- version: string
24
- /**
25
- * Input path flag value from `--input`. When provided, skips the input prompt.
26
- */
27
- input?: string
28
- /**
29
- * Output directory flag value from `--output`. When provided, skips the output prompt.
30
- */
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
- */
35
- plugins?: string
36
- }
37
-
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> {
44
- const cwd = process.cwd()
45
-
46
- clack.intro(styleText('bgCyan', styleText('black', ' Kubb Init ')))
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
-
66
- try {
67
- // Check/create package.json, detect package manager once after the block
68
- if (!hasPackageJson(cwd)) {
69
- if (!yes) {
70
- const shouldInit = await clack.confirm({
71
- message: 'No package.json found. Would you like to create one?',
72
- initialValue: true,
73
- })
74
-
75
- if (clack.isCancel(shouldInit) || !shouldInit) {
76
- cancelAndExit()
77
- }
78
- }
79
-
80
- const packageManager = detectPackageManager(cwd)
81
- const spinner = clack.spinner()
82
- spinner.start(`Initializing package.json with ${packageManager.name}`)
83
- await initPackageJson(cwd, packageManager)
84
- spinner.stop(`Created package.json with ${packageManager.name}`)
85
- }
86
-
87
- const packageManager = detectPackageManager(cwd)
88
- if (hasPackageJson(cwd)) {
89
- clack.log.info(`Detected package manager: ${styleText('cyan', packageManager.name)}`)
90
- }
91
-
92
- // Prompt for OpenAPI spec path
93
- const inputPath = await resolveOrPrompt(inputFlag, initDefaults.inputPath, 'Using input path', () =>
94
- clack.text({
95
- message: 'Where is your OpenAPI specification located?',
96
- placeholder: initDefaults.inputPath,
97
- defaultValue: initDefaults.inputPath,
98
- validate: (value) => {
99
- if (!value) return 'Input path is required'
100
- },
101
- }),
102
- )
103
-
104
- // Prompt for output directory
105
- const outputPath = await resolveOrPrompt(outputFlag, initDefaults.outputPath, 'Using output path', () =>
106
- clack.text({
107
- message: 'Where should the generated files be output?',
108
- placeholder: initDefaults.outputPath,
109
- defaultValue: initDefaults.outputPath,
110
- validate: (value) => {
111
- if (!value) return 'Output path is required'
112
- },
113
- }),
114
- )
115
-
116
- // Plugin selection
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
133
- }
134
- if (yes) {
135
- clack.log.info(`Using plugins: ${pluginLabel(defaultPlugins)}`)
136
- return defaultPlugins
137
- }
138
- const values = await clack.multiselect({
139
- message: 'Select plugins to use:',
140
- options: availablePlugins.map(({ value, label, hint }) => ({ value, label, hint })),
141
- initialValues: [...initDefaults.plugins],
142
- required: true,
143
- })
144
- if (clack.isCancel(values)) cancelAndExit()
145
- return availablePlugins.filter((p) => (values as Array<string>).includes(p.value))
146
- })()
147
-
148
- // Install packages
149
- const packagesToInstall = ['kubb', ...selectedPlugins.map((p) => p.packageName)]
150
-
151
- const spinner = clack.spinner()
152
- spinner.start(`Installing ${packagesToInstall.length} packages with ${packageManager.name}`)
153
-
154
- try {
155
- await installPackages(packagesToInstall, packageManager, cwd)
156
- spinner.stop(`Installed ${packagesToInstall.length} packages`)
157
- } catch (error) {
158
- spinner.stop('Installation failed')
159
- throw error
160
- }
161
-
162
- // Generate config file
163
- const configSpinner = clack.spinner()
164
- configSpinner.start(`Creating ${KUBB_CONFIG_FILENAME}`)
165
-
166
- const configContent = generateConfigFile({ selectedPlugins, inputPath, outputPath })
167
- const configPath = path.join(cwd, KUBB_CONFIG_FILENAME)
168
-
169
- if (fs.existsSync(configPath)) {
170
- configSpinner.stop(`${KUBB_CONFIG_FILENAME} already exists`)
171
-
172
- if (!yes) {
173
- const shouldOverwrite = await clack.confirm({
174
- message: `${KUBB_CONFIG_FILENAME} already exists. Overwrite?`,
175
- initialValue: false,
176
- })
177
-
178
- if (clack.isCancel(shouldOverwrite) || !shouldOverwrite) {
179
- cancelAndExit('Keeping existing configuration. Packages have been installed.')
180
- }
181
- }
182
-
183
- configSpinner.start(`Overwriting ${KUBB_CONFIG_FILENAME}`)
184
- }
185
-
186
- await fs.promises.writeFile(configPath, configContent, 'utf-8')
187
-
188
- configSpinner.stop(`Created ${KUBB_CONFIG_FILENAME}`)
189
-
190
- clack.outro(
191
- styleText('green', '✓ All set!') +
192
- '\n\n' +
193
- styleText('dim', 'Next steps:') +
194
- '\n' +
195
- styleText('cyan', ` 1. Make sure your OpenAPI spec is at: ${inputPath}`) +
196
- '\n' +
197
- styleText('cyan', ' 2. Generate code with: npx kubb generate') +
198
- '\n' +
199
- styleText('cyan', ` 3. Find generated files in: ${outputPath}`) +
200
- '\n\n' +
201
- styleText('dim', `Using ${packageManager.name} • Kubb v${version}`),
202
- )
203
- } catch (error) {
204
- clack.log.error(styleText('red', 'An error occurred during initialization'))
205
- if (error instanceof Error) {
206
- clack.log.error(error.message)
207
- }
208
- process.exit(1)
209
- }
210
- }
@@ -1,39 +0,0 @@
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
- }
@@ -1,42 +0,0 @@
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
- /**
25
- * Starts the `@kubb/mcp` server and reports the outcome to telemetry.
26
- *
27
- * Runs over HTTP when `port` is set, otherwise over stdio.
28
- */
29
- export async function run({ version, port, host }: McpOptions): Promise<void> {
30
- const { run: startMcpServer } = (await import('@kubb/mcp')) as typeof McpModule
31
- const hrStart = process.hrtime()
32
- const report = (status: 'success' | 'failed') => Telemetry.send(Telemetry.build({ command: 'mcp', kubbVersion: version, hrStart, status }))
33
- try {
34
- console.log(styleText('cyan', '⏳ Starting MCP server...'))
35
- console.warn(styleText('yellow', 'This feature is still under development, use with caution'))
36
- await startMcpServer(undefined, { port: port !== undefined ? Number(port) : undefined, host })
37
- await report('success')
38
- } catch (error) {
39
- await report('failed')
40
- console.error(getErrorMessage(error))
41
- }
42
- }
@@ -1,63 +0,0 @@
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
-
6
- type ValidateOptions = {
7
- /**
8
- * Path or URL to the OpenAPI/Swagger file to validate.
9
- */
10
- input: string
11
- /**
12
- * Current `@kubb/cli` version string, used for the telemetry payload.
13
- */
14
- version: string
15
- }
16
-
17
- type ValidateModule = typeof import('@kubb/adapter-oas')
18
- type ValidateDependencies = {
19
- /**
20
- * Loads `@kubb/adapter-oas`. Injected so tests can substitute a mock.
21
- */
22
- loadValidateModule: () => Promise<ValidateModule>
23
- }
24
-
25
- /**
26
- * Dynamically loads `@kubb/adapter-oas` for OpenAPI validation.
27
- */
28
- export function loadValidateModule(): Promise<ValidateModule> {
29
- return import('@kubb/adapter-oas') as Promise<ValidateModule>
30
- }
31
-
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> {
37
- const hrStart = process.hrtime()
38
- const report = (status: 'success' | 'failed') => Telemetry.send(Telemetry.build({ command: 'validate', kubbVersion: version, hrStart, status }))
39
- try {
40
- const { adapterOas } = await dependencies.loadValidateModule()
41
- const adapter = adapterOas()
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')
47
- console.log('✅ Validation success')
48
- } catch (error) {
49
- await report('failed')
50
- if (error instanceof Error && /@kubb\/adapter-oas/.test(error.message)) {
51
- console.error(styleText('red', 'The @kubb/adapter-oas package is not installed.'))
52
- console.error('')
53
- console.error('Install it with:')
54
- console.error(styleText('cyan', ' npm install @kubb/adapter-oas'))
55
- console.error(styleText('cyan', ' # or'))
56
- console.error(styleText('cyan', ' pnpm install @kubb/adapter-oas'))
57
- console.error('')
58
- }
59
- console.error('❌ Validation failed')
60
- console.error(getErrorMessage(error))
61
- process.exit(1)
62
- }
63
- }