@kubb/cli 5.2.7 → 5.3.0

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 (76) hide show
  1. package/dist/{Telemetry-DIDDCARm.js → Telemetry-CJcQkQOT.js} +2 -2
  2. package/dist/Telemetry-CJcQkQOT.js.map +1 -0
  3. package/dist/{Telemetry-C-y1OMHs.cjs → Telemetry-CvHQevSK.cjs} +4 -4
  4. package/dist/Telemetry-CvHQevSK.cjs.map +1 -0
  5. package/dist/agent-3JmkMghp.js +24 -0
  6. package/dist/agent-3JmkMghp.js.map +1 -0
  7. package/dist/agent-BPqs9VRj.cjs +36 -0
  8. package/dist/agent-BPqs9VRj.cjs.map +1 -0
  9. package/dist/{generate-Rb7ZSrZM.cjs → generate-CCjNi8-B.cjs} +6 -5
  10. package/dist/generate-CCjNi8-B.cjs.map +1 -0
  11. package/dist/{generate-DAszcRsb.js → generate-DnOsvKdA.js} +6 -5
  12. package/dist/generate-DnOsvKdA.js.map +1 -0
  13. package/dist/index.cjs +20 -10
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.js +20 -10
  16. package/dist/index.js.map +1 -1
  17. package/dist/{init-B2x0IqYy.cjs → init-BEZE-TU-.cjs} +3 -3
  18. package/dist/{init-B2x0IqYy.cjs.map → init-BEZE-TU-.cjs.map} +1 -1
  19. package/dist/{init-D4ZkBmLw.js → init-DFBbp97w.js} +3 -3
  20. package/dist/{init-D4ZkBmLw.js.map → init-DFBbp97w.js.map} +1 -1
  21. package/dist/{output-LZvrgF3z.js → output-DH2Uoy4x.js} +32 -3
  22. package/dist/output-DH2Uoy4x.js.map +1 -0
  23. package/dist/{output-B2V2MN_C.cjs → output-kmklyYIv.cjs} +42 -7
  24. package/dist/output-kmklyYIv.cjs.map +1 -0
  25. package/dist/package-DYdGw7-C.js +6 -0
  26. package/dist/package-DYdGw7-C.js.map +1 -0
  27. package/dist/{package-ALlJ_R7l.cjs → package-DgNWnCoo.cjs} +2 -2
  28. package/dist/package-DgNWnCoo.cjs.map +1 -0
  29. package/dist/{run-BWdOuixw.js → run-B1-xSKKe.js} +3 -3
  30. package/dist/{run-BWdOuixw.js.map → run-B1-xSKKe.js.map} +1 -1
  31. package/dist/{run-Dp_cu_Sq.cjs → run-BWahaRPU.cjs} +3 -3
  32. package/dist/{run-Dp_cu_Sq.cjs.map → run-BWahaRPU.cjs.map} +1 -1
  33. package/dist/{run-DH7L-NJ7.cjs → run-Bh9GxeT8.cjs} +6 -7
  34. package/dist/{run-DH7L-NJ7.cjs.map → run-Bh9GxeT8.cjs.map} +1 -1
  35. package/dist/{run-BCsAD0fU.cjs → run-BwMRCeWt.cjs} +3 -3
  36. package/dist/{run-BCsAD0fU.cjs.map → run-BwMRCeWt.cjs.map} +1 -1
  37. package/dist/{run-BxTAsxxj.cjs → run-CDLUop5s.cjs} +290 -32
  38. package/dist/run-CDLUop5s.cjs.map +1 -0
  39. package/dist/{run-oAiRfQ1w.js → run-CIkCVMy_.js} +3 -3
  40. package/dist/{run-oAiRfQ1w.js.map → run-CIkCVMy_.js.map} +1 -1
  41. package/dist/{run-DiZjX981.js → run-CZaUf7i2.js} +290 -32
  42. package/dist/run-CZaUf7i2.js.map +1 -0
  43. package/dist/{run-YTMp0zre.js → run-DiL672xB.js} +6 -7
  44. package/dist/{run-YTMp0zre.js.map → run-DiL672xB.js.map} +1 -1
  45. package/dist/{run-DRBqVXX0.cjs → run-VK50TiB7.cjs} +2 -2
  46. package/dist/{run-DRBqVXX0.cjs.map → run-VK50TiB7.cjs.map} +1 -1
  47. package/dist/{run-BzvsJ0Ek.js → run-kdxqOL8u.js} +2 -2
  48. package/dist/{run-BzvsJ0Ek.js.map → run-kdxqOL8u.js.map} +1 -1
  49. package/dist/{studio-PDMxqFN0.cjs → studio-BQV9CeZK.cjs} +32 -4
  50. package/dist/studio-BQV9CeZK.cjs.map +1 -0
  51. package/dist/{studio-DKv2YLJZ.js → studio-DUNPmQ5V.js} +32 -4
  52. package/dist/studio-DUNPmQ5V.js.map +1 -0
  53. package/dist/{utils-BgEQilnN.cjs → utils-CMU1rLfY.cjs} +22 -6
  54. package/dist/utils-CMU1rLfY.cjs.map +1 -0
  55. package/dist/{utils-VadUNZOm.js → utils-s6yetN6W.js} +21 -5
  56. package/dist/utils-s6yetN6W.js.map +1 -0
  57. package/package.json +7 -7
  58. package/dist/Telemetry-C-y1OMHs.cjs.map +0 -1
  59. package/dist/Telemetry-DIDDCARm.js.map +0 -1
  60. package/dist/env-DHaFBZTX.cjs +0 -82
  61. package/dist/env-DHaFBZTX.cjs.map +0 -1
  62. package/dist/env-DqPKEL59.js +0 -59
  63. package/dist/env-DqPKEL59.js.map +0 -1
  64. package/dist/generate-DAszcRsb.js.map +0 -1
  65. package/dist/generate-Rb7ZSrZM.cjs.map +0 -1
  66. package/dist/output-B2V2MN_C.cjs.map +0 -1
  67. package/dist/output-LZvrgF3z.js.map +0 -1
  68. package/dist/package-ALlJ_R7l.cjs.map +0 -1
  69. package/dist/package-CqrP-sja.js +0 -6
  70. package/dist/package-CqrP-sja.js.map +0 -1
  71. package/dist/run-BxTAsxxj.cjs.map +0 -1
  72. package/dist/run-DiZjX981.js.map +0 -1
  73. package/dist/studio-DKv2YLJZ.js.map +0 -1
  74. package/dist/studio-PDMxqFN0.cjs.map +0 -1
  75. package/dist/utils-BgEQilnN.cjs.map +0 -1
  76. package/dist/utils-VadUNZOm.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"run-YTMp0zre.js","names":["logLevel","logLevelMap"],"sources":["../src/runners/generate/run.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport {\n Hookable,\n type CLIOptions,\n cliReporter,\n type Config,\n createKubb,\n type Diagnostic,\n Diagnostics,\n getInputKind,\n type KubbHooks,\n logLevel as logLevelMap,\n memoryStorage,\n type ProblemDiagnostic,\n type ReporterName,\n} from '@kubb/core'\nimport { version } from '../../../package.json'\nimport { KUBB_NPM_PACKAGE_URL, UPDATE_CHECK_TIMEOUT_MS } from '../../constants.ts'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport setupReporters, { selectReporters } from '../../loggers/utils.ts'\nimport { logError, logInfo, logStep } from '../../loggers/output.ts'\nimport { fetchUrlBody, getConfigs, isNewerVersion, runHook, runPostGenerate, startUrlWatcher, startWatcher } from './utils.ts'\nimport { FORMATTER_PREFERENCE, LINTER_PREFERENCE } from '@internals/utils'\nimport { detectTool, formatters, linters } from '../../tools.ts'\n\ntype GenerateProps = {\n input?: string\n config: Config\n hooks: Hookable<KubbHooks>\n logLevel: number\n /**\n * When `true`, generates in memory instead of writing to disk, and skips formatting, linting,\n * and post-generate commands.\n */\n dryRun?: boolean\n}\n\ntype ToolMap = typeof formatters | typeof linters\n\n/**\n * Static description of one output tool: its command table, the label and messages the pass logs,\n * and how to auto-detect it. Format and lint differ only in these values.\n */\ntype Tool = {\n label: string\n map: ToolMap\n detect: () => Promise<string | null>\n successPrefix: string\n noToolMessage: string\n}\n\ntype RunToolPassOptions = {\n toolValue: string\n tool: Tool\n outputPath: string\n logLevel: number\n hooks: Hookable<KubbHooks>\n onStart: () => Promise<void> | void\n onEnd: () => Promise<void> | void\n}\n\n/**\n * Runs one formatter or linter pass over the output directory. Returns the failure instead of\n * throwing, so the caller can turn it into a coded diagnostic. Failures never render here:\n * the caller emits them through `Diagnostics.emit`, like every other diagnostic.\n */\nasync function runToolPass({ toolValue, tool, outputPath, logLevel, hooks, onStart, onEnd }: RunToolPassOptions): Promise<Error | null> {\n await onStart()\n\n let resolvedTool = toolValue\n if (resolvedTool === 'auto') {\n const detected = await tool.detect()\n if (!detected) {\n await hooks.callHook('kubb:warn', { message: tool.noToolMessage })\n } else {\n resolvedTool = detected\n await hooks.callHook('kubb:info', { message: `Auto-detected ${tool.label}: ${styleText('dim', resolvedTool)}` })\n }\n }\n\n let toolError: Error | null = null\n\n // Nothing to lint or format when the output dir was never written. Skip so the tool\n // (e.g. oxlint with --no-ignore) doesn't fail with \"No files found to lint\".\n if (resolvedTool && resolvedTool !== 'auto' && resolvedTool in tool.map && existsSync(outputPath)) {\n const toolConfig = tool.map[resolvedTool as keyof ToolMap]\n\n const successMessage = [\n `${tool.successPrefix} with ${styleText('dim', resolvedTool)}`,\n logLevel >= logLevelMap.info ? `on ${styleText('dim', outputPath)}` : undefined,\n 'successfully',\n ]\n .filter(Boolean)\n .join(' ')\n\n try {\n const hookId = randomUUID()\n const hookArgs = toolConfig.args(outputPath)\n const commandWithArgs = [toolConfig.command, ...hookArgs].join(' ')\n\n await hooks.callHook('kubb:hook:start', { id: hookId, command: toolConfig.command, args: hookArgs })\n\n const result = await runHook({ id: hookId, command: toolConfig.command, args: hookArgs, commandWithArgs, hooks })\n\n if (result.success) {\n await hooks.callHook('kubb:success', { message: successMessage })\n } else {\n toolError = result.error ?? new Error(toolConfig.errorMessage)\n }\n } catch (caughtError) {\n toolError = toError(caughtError)\n }\n }\n\n await onEnd()\n\n return toolError\n}\n\nasync function generate(options: GenerateProps): Promise<boolean> {\n const { input, hooks, logLevel, dryRun = false } = options\n\n const hrStart = process.hrtime()\n const inputPath = input ?? (typeof options.config.input === 'string' ? options.config.input : undefined)\n\n const config: Config = {\n ...options.config,\n input: input ?? options.config.input,\n // Dry-run never touches disk, regardless of the config's own storage driver.\n storage: dryRun ? memoryStorage() : options.config.storage,\n // Also keeps core's `hasOutputPasses` false, so dry-run skips the output manifest write too.\n output: dryRun ? { ...options.config.output, format: false, lint: false, postGenerate: [] } : options.config.output,\n }\n\n // The formatter, linter, and post-generate commands run after a successful build. Collect their\n // failures as coded diagnostics so they reach the summary, the json report, and the exit code.\n const processOutput = async ({ config: resolvedConfig, outputPath }: { config: Config; outputPath: string }): Promise<Array<Diagnostic>> => {\n if (dryRun) return []\n\n const outputDiagnostics: Array<Diagnostic> = []\n const reportOutputFailure = async (code: ProblemDiagnostic['code'], label: string, error: Error) => {\n const diagnostic = outputDiagnostic(code, label, error)\n outputDiagnostics.push(diagnostic)\n await Diagnostics.emit(hooks, diagnostic)\n }\n\n // Format and lint are the same pass over the output directory, differing only in the tool\n // table and the hooks they announce themselves with, so run them from one descriptor list.\n const toolPasses = [\n {\n value: resolvedConfig.output.format,\n code: Diagnostics.code.formatFailed,\n tool: {\n label: 'formatter',\n map: formatters,\n detect: () => detectTool(FORMATTER_PREFERENCE),\n successPrefix: 'Formatting',\n noToolMessage: `No formatter found (${FORMATTER_PREFERENCE.join(', ')}). Skipping formatting.`,\n },\n onStart: () => hooks.callHook('kubb:format:start'),\n onEnd: () => hooks.callHook('kubb:format:end'),\n },\n {\n value: resolvedConfig.output.lint,\n code: Diagnostics.code.lintFailed,\n tool: {\n label: 'linter',\n map: linters,\n detect: () => detectTool(LINTER_PREFERENCE),\n successPrefix: 'Linting',\n noToolMessage: `No linter found (${LINTER_PREFERENCE.join(', ')}). Skipping linting.`,\n },\n onStart: () => hooks.callHook('kubb:lint:start'),\n onEnd: () => hooks.callHook('kubb:lint:end'),\n },\n ]\n\n for (const pass of toolPasses) {\n if (!pass.value) continue\n const error = await runToolPass({\n toolValue: pass.value,\n tool: pass.tool,\n onStart: pass.onStart,\n onEnd: pass.onEnd,\n outputPath,\n logLevel,\n hooks,\n })\n if (error) await reportOutputFailure(pass.code, pass.tool.label, error)\n }\n\n if (resolvedConfig.output.postGenerate?.length) {\n await hooks.callHook('kubb:hooks:start')\n const hookResults = await runPostGenerate({ commands: resolvedConfig.output.postGenerate, hooks })\n for (const hookResult of hookResults) {\n if (hookResult.success) continue\n await reportOutputFailure(Diagnostics.code.postGenerateFailed, 'Post-generate command', hookResult.error ?? new Error('Post-generate command failed'))\n }\n await hooks.callHook('kubb:hooks:end')\n }\n\n return outputDiagnostics\n }\n\n hooks.hook('kubb:generation:end', ({ status }) => {\n if (status === 'success') return hooks.callHook('kubb:success', { message: 'Generation succeeded', info: inputPath })\n })\n\n const kubb = createKubb(config, { hooks })\n const result = await kubb.generate({ processOutput })\n\n if (dryRun) {\n await hooks.callHook('kubb:info', { message: 'Dry run: no files were written', info: `${result.files.length} file(s) would be generated` })\n }\n\n const telemetryPlugins = Array.from(kubb.driver.plugins.values(), (p) => ({ name: p.name, options: p.options as Record<string, unknown> }))\n await sendTelemetry(\n buildTelemetryEvent({\n command: 'generate',\n kubbVersion: version,\n plugins: telemetryPlugins,\n hrStart,\n filesCreated: result.files.length,\n status: result.success ? 'success' : 'failed',\n }),\n )\n\n return result.success\n}\n\n/**\n * Builds a coded diagnostic for an output-phase failure (formatter, linter, or `done` hook).\n */\nfunction outputDiagnostic(code: ProblemDiagnostic['code'], label: string, caughtError: unknown): ProblemDiagnostic {\n const error = toError(caughtError)\n return {\n code,\n severity: 'error',\n message: `${label} failed: ${error.message}`,\n help: 'Check that the tool is installed and that the command and its config are correct.',\n location: { kind: 'config' },\n cause: error,\n }\n}\n\ntype GenerateCommandOptions = {\n input?: string\n configPath?: string\n logLevel: string\n watch: boolean\n reporters?: Array<ReporterName>\n dryRun?: boolean\n}\n\nasync function checkForUpdate(hooks: Hookable<KubbHooks>): Promise<void> {\n try {\n const res = await fetch(KUBB_NPM_PACKAGE_URL, { signal: AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS) })\n const data = (await res.json()) as { version: string }\n if (data.version && isNewerVersion(version, data.version)) {\n await Diagnostics.emit(hooks, Diagnostics.update({ currentVersion: version, latestVersion: data.version }))\n }\n } catch {\n // Ignore network errors\n }\n}\n\n/**\n * Runs the full Kubb generation lifecycle for the given CLI options.\n * Loads configs, sets up the reporters (CLI `--reporter` picks which of `config.reporters` to trigger),\n * checks for a newer version, and calls `generate` for each config entry.\n */\nexport async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters, dryRun }: GenerateCommandOptions): Promise<void> {\n const logLevel = logLevelMap[logLevelKey as keyof typeof logLevelMap] ?? logLevelMap.info\n const hooks = new Hookable<KubbHooks>()\n\n // Load the config first so `config.reporters` can pick the reporters. A failure here has no\n // reporter installed yet, so fall back to the default `cli` reporter to surface it.\n let configs: Array<Config>\n let resolvedConfigPath: string\n try {\n const loaded = await getConfigs({\n configPath,\n input,\n watch,\n logLevel: logLevelKey as CLIOptions['logLevel'],\n })\n configs = loaded.configs\n resolvedConfigPath = loaded.configPath\n } catch (error) {\n await setupReporters(hooks, { logLevel, reporters: [cliReporter] })\n await hooks.callHook('kubb:error', { error: toError(error) })\n process.exit(1)\n }\n\n // CLI `--reporter` selects which reporters to trigger by name, defaulting to `cli`. The config\n // always carries the available reporters (defineConfig registers the built-ins).\n const requestedNames: Array<ReporterName> = cliReporters?.length ? cliReporters : ['cli']\n const available = configs[0]?.reporters ?? []\n const reporters = selectReporters(available, requestedNames)\n await setupReporters(hooks, { logLevel, reporters })\n\n await hooks.callHook('kubb:lifecycle:start', { version })\n\n await checkForUpdate(hooks)\n\n try {\n const relativeConfigPath = path.relative(process.cwd(), resolvedConfigPath)\n\n await hooks.callHook('kubb:info', { message: 'Config loaded', info: relativeConfigPath })\n await hooks.callHook('kubb:success', { message: 'Config loaded successfully', info: relativeConfigPath })\n\n let anyFailed = false\n for (const config of configs) {\n const effectiveInput = input ?? config.input\n const inputKind = typeof effectiveInput === 'string' ? getInputKind(effectiveInput) : undefined\n const watchPath = inputKind === 'file' || inputKind === 'url' ? (effectiveInput as string) : undefined\n if (watchPath && watch) {\n const watchedPaths = [watchPath]\n // Don't removeAll() between builds, that would also drop logger and lifecycle\n // listeners. Plugin listeners are already disposed by safeBuild's dispose()\n // in its finally block, so re-running generate() on the same hooks emitter is safe.\n const build = async (paths: Array<string>) => {\n await generate({ input, config, logLevel, hooks, dryRun })\n logStep(styleText('yellow', `Watching for changes in ${paths.join(' and ')}`))\n }\n\n // For a URL input, capture the document before the build: it becomes the watcher's\n // change-detection baseline, so an edit landing before the first poll still rebuilds.\n // When the server is down the baseline stays undefined and the watcher rebuilds on its\n // first successful poll, so recovery with an unchanged document still generates output.\n const initialBody = inputKind === 'url' ? await fetchUrlBody(watchPath) : undefined\n\n // The watchers ignore their startup state (chokidar's initial events, the baseline\n // above), so run the first build here. A failing first build keeps watching, since\n // the user can fix the input and save.\n try {\n await build(watchedPaths)\n } catch (buildError) {\n await hooks.callHook('kubb:error', { error: toError(buildError) })\n }\n\n if (inputKind === 'url') {\n startUrlWatcher(watchPath, build, { log: { info: logInfo, error: logError }, initialBody })\n } else {\n await startWatcher(watchedPaths, build, { info: logInfo, error: logError })\n }\n } else {\n try {\n const succeeded = await generate({ input, config, logLevel, hooks, dryRun })\n if (!succeeded) anyFailed = true\n } catch (configError) {\n await hooks.callHook('kubb:error', { error: toError(configError) })\n anyFailed = true\n }\n }\n }\n\n await hooks.callHook('kubb:lifecycle:end')\n\n if (anyFailed) {\n process.exit(1)\n }\n } catch (error) {\n await hooks.callHook('kubb:error', { error: toError(error) })\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuEA,eAAe,YAAY,EAAE,WAAW,MAAM,YAAY,UAAA,YAAU,OAAO,SAAS,SAAoD;CACtI,MAAM,QAAQ;CAEd,IAAI,eAAe;CACnB,IAAI,iBAAiB,QAAQ;EAC3B,MAAM,WAAW,MAAM,KAAK,OAAO;EACnC,IAAI,CAAC,UACH,MAAM,MAAM,SAAS,aAAa,EAAE,SAAS,KAAK,cAAc,CAAC;OAC5D;GACL,eAAe;GACf,MAAM,MAAM,SAAS,aAAa,EAAE,SAAS,iBAAiB,KAAK,MAAM,IAAI,UAAU,OAAO,YAAY,IAAI,CAAC;EACjH;CACF;CAEA,IAAI,YAA0B;CAI9B,IAAI,gBAAgB,iBAAiB,UAAU,gBAAgB,KAAK,OAAO,WAAW,UAAU,GAAG;EACjG,MAAM,aAAa,KAAK,IAAI;EAE5B,MAAM,iBAAiB;GACrB,GAAG,KAAK,cAAc,QAAQ,UAAU,OAAO,YAAY;GAC3DA,cAAYC,SAAY,OAAO,MAAM,UAAU,OAAO,UAA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AO;KAAO,CAAC;KACzD,QAAQ,UAAU,UAAU,2BAA2B,MAAM,KAAK,OAAO,GAAG,CAAC;IAC/E;IAMA,MAAM,cAAc,cAAc,QAAQ,MAAM,aAAa,SAAS,IAAI,KAAA;IAK1E,IAAI;KACF,MAAM,MAAM,YAAY;IAC1B,SAAS,YAAY;KACnB,MAAM,MAAM,SAAS,cAAc,EAAE,OAAO,QAAQ,UAAU,EAAE,CAAC;IACnE;IAEA,IAAI,cAAc,OAChB,gBAAgB,WAAW,OAAO;KAAE,KAAK;MAAE,MAAM;MAAS,OAAO;KAAS;KAAG;IAAY,CAAC;SAE1F,MAAM,aAAa,cAAc,OAAO;KAAE,MAAM;KAAS,OAAO;IAAS,CAAC;GAE9E,OACE,IAAI;IAEF,IAAI,CAAC,MADmB,SAAS;KAAE;KAAO;KAAQ,UAAA;KAAU;KAAO;IAAO,CAAC,GAC3D,YAAY;GAC9B,SAAS,aAAa;IACpB,MAAM,MAAM,SAAS,cAAc,EAAE,OAAO,QAAQ,WAAW,EAAE,CAAC;IAClE,YAAY;GACd;EAEJ;EAEA,MAAM,MAAM,SAAS,oBAAoB;EAEzC,IAAI,WACF,QAAQ,KAAK,CAAC;CAElB,SAAS,OAAO;EACd,MAAM,MAAM,SAAS,cAAc,EAAE,OAAO,QAAQ,KAAK,EAAE,CAAC;EAC5D,QAAQ,KAAK,CAAC;CAChB;AACF"}
1
+ {"version":3,"file":"run-DiL672xB.js","names":["logLevel","logLevelMap"],"sources":["../src/runners/generate/run.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { toError } from '@internals/utils'\nimport {\n Hookable,\n type CLIOptions,\n cliReporter,\n type Config,\n createKubb,\n type Diagnostic,\n Diagnostics,\n getInputKind,\n type KubbHooks,\n logLevel as logLevelMap,\n memoryStorage,\n type ProblemDiagnostic,\n type ReporterName,\n} from '@kubb/core'\nimport { version } from '../../../package.json'\nimport { KUBB_NPM_PACKAGE_URL, UPDATE_CHECK_TIMEOUT_MS } from '../../constants.ts'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport setupReporters, { selectReporters } from '../../loggers/utils.ts'\nimport { logError, logInfo, logStep } from '../../loggers/output.ts'\nimport { fetchUrlBody, getConfigs, isNewerVersion, runHook, runPostGenerate, startUrlWatcher, startWatcher } from './utils.ts'\nimport { FORMATTER_PREFERENCE, LINTER_PREFERENCE } from '@internals/utils'\nimport { detectTool, formatters, linters } from '../../tools.ts'\n\ntype GenerateProps = {\n input?: string\n config: Config\n hooks: Hookable<KubbHooks>\n logLevel: number\n /**\n * When `true`, generates in memory instead of writing to disk, and skips formatting, linting,\n * and post-generate commands.\n */\n dryRun?: boolean\n}\n\ntype ToolMap = typeof formatters | typeof linters\n\n/**\n * Static description of one output tool: its command table, the label and messages the pass logs,\n * and how to auto-detect it. Format and lint differ only in these values.\n */\ntype Tool = {\n label: string\n map: ToolMap\n detect: () => Promise<string | null>\n successPrefix: string\n noToolMessage: string\n}\n\ntype RunToolPassOptions = {\n toolValue: string\n tool: Tool\n outputPath: string\n logLevel: number\n hooks: Hookable<KubbHooks>\n onStart: () => Promise<void> | void\n onEnd: () => Promise<void> | void\n}\n\n/**\n * Runs one formatter or linter pass over the output directory. Returns the failure instead of\n * throwing, so the caller can turn it into a coded diagnostic. Failures never render here:\n * the caller emits them through `Diagnostics.emit`, like every other diagnostic.\n */\nasync function runToolPass({ toolValue, tool, outputPath, logLevel, hooks, onStart, onEnd }: RunToolPassOptions): Promise<Error | null> {\n await onStart()\n\n let resolvedTool = toolValue\n if (resolvedTool === 'auto') {\n const detected = await tool.detect()\n if (!detected) {\n await hooks.callHook('kubb:warn', { message: tool.noToolMessage })\n } else {\n resolvedTool = detected\n await hooks.callHook('kubb:info', { message: `Auto-detected ${tool.label}: ${styleText('dim', resolvedTool)}` })\n }\n }\n\n let toolError: Error | null = null\n\n // Nothing to lint or format when the output dir was never written. Skip so the tool\n // (e.g. oxlint with --no-ignore) doesn't fail with \"No files found to lint\".\n if (resolvedTool && resolvedTool !== 'auto' && resolvedTool in tool.map && existsSync(outputPath)) {\n const toolConfig = tool.map[resolvedTool as keyof ToolMap]\n\n const successMessage = [\n `${tool.successPrefix} with ${styleText('dim', resolvedTool)}`,\n logLevel >= logLevelMap.info ? `on ${styleText('dim', outputPath)}` : undefined,\n 'successfully',\n ]\n .filter(Boolean)\n .join(' ')\n\n try {\n const hookId = randomUUID()\n const hookArgs = toolConfig.args(outputPath)\n const commandWithArgs = [toolConfig.command, ...hookArgs].join(' ')\n\n await hooks.callHook('kubb:hook:start', { id: hookId, command: toolConfig.command, args: hookArgs })\n\n const result = await runHook({ id: hookId, command: toolConfig.command, args: hookArgs, commandWithArgs, hooks })\n\n if (result.success) {\n await hooks.callHook('kubb:success', { message: successMessage })\n } else {\n toolError = result.error ?? new Error(toolConfig.errorMessage)\n }\n } catch (caughtError) {\n toolError = toError(caughtError)\n }\n }\n\n await onEnd()\n\n return toolError\n}\n\nasync function generate(options: GenerateProps): Promise<boolean> {\n const { input, hooks, logLevel, dryRun = false } = options\n\n const hrStart = process.hrtime()\n const inputPath = input ?? (typeof options.config.input === 'string' ? options.config.input : undefined)\n\n const config: Config = {\n ...options.config,\n input: input ?? options.config.input,\n // Dry-run never touches disk, regardless of the config's own storage driver.\n storage: dryRun ? memoryStorage() : options.config.storage,\n // Also keeps core's `hasOutputPasses` false, so dry-run skips the output manifest write too.\n output: dryRun ? { ...options.config.output, format: false, lint: false, postGenerate: [] } : options.config.output,\n }\n\n // The formatter, linter, and post-generate commands run after a successful build. Collect their\n // failures as coded diagnostics so they reach the summary, the json report, and the exit code.\n const processOutput = async ({ config: resolvedConfig, outputPath }: { config: Config; outputPath: string }): Promise<Array<Diagnostic>> => {\n if (dryRun) return []\n\n const outputDiagnostics: Array<Diagnostic> = []\n const reportOutputFailure = async (code: ProblemDiagnostic['code'], label: string, error: Error) => {\n const diagnostic = outputDiagnostic(code, label, error)\n outputDiagnostics.push(diagnostic)\n await Diagnostics.emit(hooks, diagnostic)\n }\n\n // Format and lint are the same pass over the output directory, differing only in the tool\n // table and the hooks they announce themselves with, so run them from one descriptor list.\n const toolPasses = [\n {\n value: resolvedConfig.output.format,\n code: Diagnostics.code.formatFailed,\n tool: {\n label: 'formatter',\n map: formatters,\n detect: () => detectTool(FORMATTER_PREFERENCE),\n successPrefix: 'Formatting',\n noToolMessage: `No formatter found (${FORMATTER_PREFERENCE.join(', ')}). Skipping formatting.`,\n },\n onStart: () => hooks.callHook('kubb:format:start'),\n onEnd: () => hooks.callHook('kubb:format:end'),\n },\n {\n value: resolvedConfig.output.lint,\n code: Diagnostics.code.lintFailed,\n tool: {\n label: 'linter',\n map: linters,\n detect: () => detectTool(LINTER_PREFERENCE),\n successPrefix: 'Linting',\n noToolMessage: `No linter found (${LINTER_PREFERENCE.join(', ')}). Skipping linting.`,\n },\n onStart: () => hooks.callHook('kubb:lint:start'),\n onEnd: () => hooks.callHook('kubb:lint:end'),\n },\n ]\n\n for (const pass of toolPasses) {\n if (!pass.value) continue\n const error = await runToolPass({\n toolValue: pass.value,\n tool: pass.tool,\n onStart: pass.onStart,\n onEnd: pass.onEnd,\n outputPath,\n logLevel,\n hooks,\n })\n if (error) await reportOutputFailure(pass.code, pass.tool.label, error)\n }\n\n if (resolvedConfig.output.postGenerate?.length) {\n await hooks.callHook('kubb:hooks:start')\n const hookResults = await runPostGenerate({ commands: resolvedConfig.output.postGenerate, hooks })\n for (const hookResult of hookResults) {\n if (hookResult.success) continue\n await reportOutputFailure(Diagnostics.code.postGenerateFailed, 'Post-generate command', hookResult.error ?? new Error('Post-generate command failed'))\n }\n await hooks.callHook('kubb:hooks:end')\n }\n\n return outputDiagnostics\n }\n\n hooks.hook('kubb:generation:end', ({ status }) => {\n if (status === 'success') return hooks.callHook('kubb:success', { message: 'Generation succeeded', info: inputPath })\n })\n\n const kubb = createKubb(config, { hooks })\n const result = await kubb.generate({ processOutput })\n\n if (dryRun) {\n await hooks.callHook('kubb:info', { message: 'Dry run: no files were written', info: `${result.files.length} file(s) would be generated` })\n }\n\n const telemetryPlugins = Array.from(kubb.driver.plugins.values(), (p) => ({ name: p.name, options: p.options as Record<string, unknown> }))\n await sendTelemetry(\n buildTelemetryEvent({\n command: 'generate',\n kubbVersion: version,\n plugins: telemetryPlugins,\n hrStart,\n filesCreated: result.files.length,\n status: result.success ? 'success' : 'failed',\n }),\n )\n\n return result.success\n}\n\n/**\n * Builds a coded diagnostic for an output-phase failure (formatter, linter, or `done` hook).\n */\nfunction outputDiagnostic(code: ProblemDiagnostic['code'], label: string, caughtError: unknown): ProblemDiagnostic {\n const error = toError(caughtError)\n return {\n code,\n severity: 'error',\n message: `${label} failed: ${error.message}`,\n help: 'Check that the tool is installed and that the command and its config are correct.',\n location: { kind: 'config' },\n cause: error,\n }\n}\n\ntype GenerateCommandOptions = {\n input?: string\n configPath?: string\n logLevel: string\n watch: boolean\n reporters?: Array<ReporterName>\n dryRun?: boolean\n}\n\nasync function checkForUpdate(hooks: Hookable<KubbHooks>): Promise<void> {\n try {\n const res = await fetch(KUBB_NPM_PACKAGE_URL, { signal: AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS) })\n const data = (await res.json()) as { version: string }\n if (data.version && isNewerVersion(version, data.version)) {\n await Diagnostics.emit(hooks, Diagnostics.update({ currentVersion: version, latestVersion: data.version }))\n }\n } catch {\n // Ignore network errors\n }\n}\n\n/**\n * Runs the full Kubb generation lifecycle for the given CLI options.\n * Loads configs, sets up the reporters (CLI `--reporter` picks which of `config.reporters` to trigger),\n * checks for a newer version, and calls `generate` for each config entry.\n */\nexport async function run({ input, configPath, logLevel: logLevelKey, watch, reporters: cliReporters, dryRun }: GenerateCommandOptions): Promise<void> {\n const logLevel = logLevelMap[logLevelKey as keyof typeof logLevelMap] ?? logLevelMap.info\n const hooks = new Hookable<KubbHooks>()\n\n // Load the config first so `config.reporters` can pick the reporters. A failure here has no\n // reporter installed yet, so fall back to the default `cli` reporter to surface it.\n let configs: Array<Config>\n let resolvedConfigPath: string\n try {\n const loaded = await getConfigs({\n configPath,\n input,\n watch,\n logLevel: logLevelKey as CLIOptions['logLevel'],\n })\n configs = loaded.configs\n resolvedConfigPath = loaded.configPath\n } catch (error) {\n await setupReporters(hooks, { logLevel, reporters: [cliReporter] })\n await hooks.callHook('kubb:error', { error: toError(error) })\n process.exit(1)\n }\n\n // CLI `--reporter` selects which reporters to trigger by name, defaulting to `cli`. The config\n // always carries the available reporters (defineConfig registers the built-ins).\n const requestedNames: Array<ReporterName> = cliReporters?.length ? cliReporters : ['cli']\n const reporters = selectReporters(configs[0]?.reporters ?? [], requestedNames)\n await setupReporters(hooks, { logLevel, reporters })\n\n await hooks.callHook('kubb:lifecycle:start', { version })\n\n await checkForUpdate(hooks)\n\n try {\n const relativeConfigPath = path.relative(process.cwd(), resolvedConfigPath)\n\n await hooks.callHook('kubb:info', { message: 'Config loaded', info: relativeConfigPath })\n await hooks.callHook('kubb:success', { message: 'Config loaded successfully', info: relativeConfigPath })\n\n let anyFailed = false\n for (const config of configs) {\n const effectiveInput = input ?? config.input\n const inputKind = typeof effectiveInput === 'string' ? getInputKind(effectiveInput) : undefined\n const watchPath = inputKind === 'file' || inputKind === 'url' ? (effectiveInput as string) : undefined\n if (watchPath && watch) {\n const watchedPaths = [watchPath]\n // Don't removeAll() between builds, that would also drop logger and lifecycle\n // listeners. Plugin listeners are already disposed by safeBuild's dispose()\n // in its finally block, so re-running generate() on the same hooks emitter is safe.\n const build = async (paths: Array<string>) => {\n await generate({ input, config, logLevel, hooks, dryRun })\n logStep(styleText('yellow', `Watching for changes in ${paths.join(' and ')}`))\n }\n\n // For a URL input, capture the document before the build: it becomes the watcher's\n // change-detection baseline, so an edit landing before the first poll still rebuilds.\n // When the server is down the baseline stays undefined and the watcher rebuilds on its\n // first successful poll, so recovery with an unchanged document still generates output.\n const initialBody = inputKind === 'url' ? await fetchUrlBody(watchPath) : undefined\n\n // The watchers ignore their startup state (chokidar's initial events, the baseline\n // above), so run the first build here. A failing first build keeps watching, since\n // the user can fix the input and save.\n try {\n await build(watchedPaths)\n } catch (buildError) {\n await hooks.callHook('kubb:error', { error: toError(buildError) })\n }\n\n if (inputKind === 'url') {\n startUrlWatcher(watchPath, build, { log: { info: logInfo, error: logError }, initialBody })\n } else {\n await startWatcher(watchedPaths, build, { info: logInfo, error: logError })\n }\n } else {\n try {\n const succeeded = await generate({ input, config, logLevel, hooks, dryRun })\n if (!succeeded) anyFailed = true\n } catch (configError) {\n await hooks.callHook('kubb:error', { error: toError(configError) })\n anyFailed = true\n }\n }\n }\n\n await hooks.callHook('kubb:lifecycle:end')\n\n if (anyFailed) {\n process.exit(1)\n }\n } catch (error) {\n await hooks.callHook('kubb:error', { error: toError(error) })\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuEA,eAAe,YAAY,EAAE,WAAW,MAAM,YAAY,UAAA,YAAU,OAAO,SAAS,SAAoD;CACtI,MAAM,QAAQ;CAEd,IAAI,eAAe;CACnB,IAAI,iBAAiB,QAAQ;EAC3B,MAAM,WAAW,MAAM,KAAK,OAAO;EACnC,IAAI,CAAC,UACH,MAAM,MAAM,SAAS,aAAa,EAAE,SAAS,KAAK,cAAc,CAAC;OAC5D;GACL,eAAe;GACf,MAAM,MAAM,SAAS,aAAa,EAAE,SAAS,iBAAiB,KAAK,MAAM,IAAI,UAAU,OAAO,YAAY,IAAI,CAAC;EACjH;CACF;CAEA,IAAI,YAA0B;CAI9B,IAAI,gBAAgB,iBAAiB,UAAU,gBAAgB,KAAK,OAAO,WAAW,UAAU,GAAG;EACjG,MAAM,aAAa,KAAK,IAAI;EAE5B,MAAM,iBAAiB;GACrB,GAAG,KAAK,cAAc,QAAQ,UAAU,OAAO,YAAY;GAC3DA,cAAYC,SAAY,OAAO,MAAM,UAAU,OAAO,UAAU,MAAM,KAAA;GACtE;EACF,CAAC,CACE,OAAO,OAAO,C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AAG,CAAC;IAC/E;IAMA,MAAM,cAAc,cAAc,QAAQ,MAAM,aAAa,SAAS,IAAI,KAAA;IAK1E,IAAI;KACF,MAAM,MAAM,YAAY;IAC1B,SAAS,YAAY;KACnB,MAAM,MAAM,SAAS,cAAc,EAAE,OAAO,QAAQ,UAAU,EAAE,CAAC;IACnE;IAEA,IAAI,cAAc,OAChB,gBAAgB,WAAW,OAAO;KAAE,KAAK;MAAE,MAAM;MAAS,OAAO;KAAS;KAAG;IAAY,CAAC;SAE1F,MAAM,aAAa,cAAc,OAAO;KAAE,MAAM;KAAS,OAAO;IAAS,CAAC;GAE9E,OACE,IAAI;IAEF,IAAI,CAAC,MADmB,SAAS;KAAE;KAAO;KAAQ,UAAA;KAAU;KAAO;IAAO,CAAC,GAC3D,YAAY;GAC9B,SAAS,aAAa;IACpB,MAAM,MAAM,SAAS,cAAc,EAAE,OAAO,QAAQ,WAAW,EAAE,CAAC;IAClE,YAAY;GACd;EAEJ;EAEA,MAAM,MAAM,SAAS,oBAAoB;EAEzC,IAAI,WACF,QAAQ,KAAK,CAAC;CAElB,SAAS,OAAO;EACd,MAAM,MAAM,SAAS,cAAc,EAAE,OAAO,QAAQ,KAAK,EAAE,CAAC;EAC5D,QAAQ,KAAK,CAAC;CAChB;AACF"}
@@ -1,5 +1,5 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-qbf5tadS.cjs");
2
- const require_output = require("./output-B2V2MN_C.cjs");
2
+ const require_output = require("./output-kmklyYIv.cjs");
3
3
  const require_constants = require("./constants-CdxpgX3_.cjs");
4
4
  let node_util = require("node:util");
5
5
  let node_process = require("node:process");
@@ -280,4 +280,4 @@ async function run({ yes, version, input: inputFlag, output: outputFlag, plugins
280
280
  //#endregion
281
281
  exports.run = run;
282
282
 
283
- //# sourceMappingURL=run-DRBqVXX0.cjs.map
283
+ //# sourceMappingURL=run-VK50TiB7.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-DRBqVXX0.cjs","names":["availablePlugins","join","existsSync","readFileSync","process","fs","path","x","process","styleText","clack","createSpinner","initDefaults","availablePlugins","KUBB_PACKAGE_NAME","KUBB_CONFIG_FILENAME","path","fs"],"sources":["../../../internals/shared/src/init.ts","../src/tools.ts","../src/runners/init/utils.ts","../src/runners/init/run.ts"],"sourcesContent":["import { availablePlugins, KUBB_PACKAGE_NAME } from './constants.ts'\nimport type { PluginOption } from './types.ts'\n\n/**\n * Resolves a comma-separated plugin flag (e.g. `--plugins plugin-ts,plugin-zod`) into the\n * matching known plugin options. Unrecognized names are dropped, and a missing flag yields\n * an empty list.\n */\nexport function resolvePlugins(pluginsFlag: string | undefined): Array<PluginOption> {\n if (!pluginsFlag) {\n return []\n }\n const requested = pluginsFlag\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n return availablePlugins.filter((plugin) => requested.includes(plugin.value))\n}\n\nexport function generateConfigFile({\n selectedPlugins,\n inputPath,\n outputPath,\n}: {\n selectedPlugins: Array<PluginOption>\n inputPath: string\n outputPath: string\n}): string {\n const imports = selectedPlugins.map((plugin) => `import { ${plugin.importName} } from '${plugin.packageName}'`).join('\\n')\n\n const pluginConfigs = selectedPlugins.map((plugin) => ` ${plugin.importName}(),`).join('\\n')\n\n return `import { defineConfig } from 'kubb/config'\n${imports}\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [\n${pluginConfigs}\n ],\n})\n`\n}\n\n/**\n * Turns package names into install specifiers for the wizard.\n *\n * `kubb` is pinned to the exact version of the running CLI, since both ship from the same release\n * and resolving `kubb@beta` separately can land on a different version than the CLI doing the\n * scaffolding. Plugins release from their own repo on their own cadence, so they follow the\n * release channel of the CLI through its dist-tag.\n */\nexport function resolveInstallVersions({ packages, version }: { packages: Array<string>; version: string }): Array<string> {\n const prerelease = version.match(/-([a-z]+)/)?.[1]\n const tag = prerelease ?? 'latest'\n\n return packages.map((name) => (name === KUBB_PACKAGE_NAME ? `${name}@${version}` : `${name}@${tag}`))\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { formatters, linters } from '@internals/utils'\nimport type { Config } from '@kubb/core'\n\n/**\n * The configurable formatter names, mirrored from `Config['output'].format`. Excludes `'auto'`\n * (detection, not a tool) and `false` (skip). The `formatters`/`linters` tables below are pinned to\n * these so adding a tool to the config union without a descriptor fails to compile.\n */\ntype FormatterName = Exclude<NonNullable<Config['output']['format']>, 'auto' | false>\ntype LinterName = Exclude<NonNullable<Config['output']['lint']>, 'auto' | false>\n\n// Pinned to core's union here rather than in `@internals/utils`, which must not import `@kubb/core`:\n// adding a tool to the config union without a descriptor stays a compile error.\nformatters satisfies Record<FormatterName, unknown>\nlinters satisfies Record<LinterName, unknown>\n\nexport { detectTool, formatters, linters } from '@internals/utils'\n\nexport type PackageManagerName = 'npm' | 'pnpm' | 'yarn' | 'bun'\n\n/**\n * Metadata describing a package manager's lock file and install command.\n */\nexport interface PackageManagerInfo {\n /**\n * Identifier used in CLI commands, e.g. `pnpm`, `yarn`.\n */\n name: PackageManagerName\n /**\n * Lock file name that uniquely identifies this package manager in a project root.\n */\n lockFile: string\n /**\n * Subcommands passed to the package manager binary to install a dev dependency.\n */\n installCommand: ReadonlyArray<string>\n}\n\n/**\n * Metadata for each supported package manager, keyed by its short name.\n *\n * @example\n * ```ts\n * packageManagers.pnpm.installCommand // ['add', '-D']\n * packageManagers.npm.lockFile // 'package-lock.json'\n * ```\n */\nconst packageManagers: Record<PackageManagerName, PackageManagerInfo> = {\n pnpm: {\n name: 'pnpm',\n lockFile: 'pnpm-lock.yaml',\n installCommand: ['add', '-D'],\n },\n yarn: {\n name: 'yarn',\n lockFile: 'yarn.lock',\n installCommand: ['add', '-D'],\n },\n bun: {\n name: 'bun',\n lockFile: 'bun.lockb',\n installCommand: ['add', '-d'],\n },\n npm: {\n name: 'npm',\n lockFile: 'package-lock.json',\n installCommand: ['install', '--save-dev'],\n },\n}\n\n/**\n * Minimal shape of `package.json` fields read during detection.\n */\ntype PackageJson = {\n /**\n * The `packageManager` field from `package.json` (e.g. `\"pnpm@9.0.0\"`).\n */\n packageManager?: string\n}\n\n/**\n * Detects the active package manager for the given directory.\n * Resolution order: `packageManager` field in `package.json`, then presence of a lock file.\n * Falls back to `npm` when no signal is found.\n *\n * @example\n * ```ts\n * detectPackageManager('/my/project') // { name: 'pnpm', lockFile: 'pnpm-lock.yaml', ... }\n * detectPackageManager() // falls back to npm when no lock file is found\n * ```\n */\nexport function detectPackageManager(cwd: string = process.cwd()): PackageManagerInfo {\n const packageJsonPath = join(cwd, 'package.json')\n if (existsSync(packageJsonPath)) {\n try {\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as PackageJson\n const pmField = packageJson.packageManager\n if (typeof pmField === 'string') {\n const name = pmField.split('@')[0]\n if (name && name in packageManagers) {\n return packageManagers[name as PackageManagerName]\n }\n }\n } catch {\n // Continue to lock file detection\n }\n }\n\n for (const pm of Object.values(packageManagers)) {\n if (existsSync(join(cwd, pm.lockFile))) {\n return pm\n }\n }\n\n return packageManagers.npm\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { x } from 'tinyexec'\nimport type { PackageManagerInfo, PackageManagerName } from '../../tools.ts'\n\n/**\n * Returns `true` when a `package.json` exists at `cwd`.\n */\nexport function hasPackageJson(cwd: string = process.cwd()): boolean {\n return fs.existsSync(path.join(cwd, 'package.json'))\n}\n\n/**\n * Initializes a new `package.json` at `cwd` using the detected package manager.\n */\nexport async function initPackageJson(cwd: string, packageManager: PackageManagerInfo): Promise<void> {\n const commands: Record<PackageManagerName, Array<string>> = {\n npm: ['init', '-y'],\n pnpm: ['init'],\n yarn: ['init', '-y'],\n bun: ['init', '-y'],\n }\n\n await x(packageManager.name, commands[packageManager.name], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n\n/**\n * Installs the given packages at `cwd` using the detected package manager.\n */\nexport async function installPackages(packages: Array<string>, packageManager: PackageManagerInfo, cwd: string = process.cwd()): Promise<void> {\n await x(packageManager.name, [...packageManager.installCommand, ...packages], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport type { DryRunExtension } from '@gunshi/plugin-dryrun'\nimport {\n availablePlugins,\n generateConfigFile,\n initDefaults,\n KUBB_CONFIG_FILENAME,\n KUBB_PACKAGE_NAME,\n type PluginOption,\n resolveInstallVersions,\n resolvePlugins,\n} from '@internals/shared'\nimport { createSpinner, logError, logInfo, logIntro, logOutro, logWarn } from '../../loggers/output.ts'\nimport { hasPackageJson, initPackageJson, installPackages } from './utils.ts'\nimport { detectPackageManager } from '../../tools.ts'\n\nfunction cancelAndExit(message = 'Operation canceled.'): never {\n clack.cancel(message)\n process.exit(0)\n}\n\ntype InitOptions = {\n /**\n * When `true`, skips all interactive prompts and uses default values.\n */\n yes: boolean\n /**\n * Current `@kubb/cli` version string, shown in the closing outro.\n */\n version: string\n /**\n * Input path flag value from `--input`. When provided, skips the input prompt.\n */\n input?: string\n /**\n * Output directory flag value from `--output`. When provided, skips the output prompt.\n */\n output?: string\n /**\n * Comma-separated plugin list from `--plugins`, e.g. `'plugin-ts,plugin-zod'`. When provided, skips the plugin selection prompt.\n */\n plugins?: string\n /**\n * Dry-run extension from `@gunshi/plugin-dryrun`. When enabled, package installation and the\n * config file write are skipped.\n */\n dryRun: DryRunExtension\n}\n\n/**\n * Runs the interactive Kubb scaffolding wizard.\n * Detects the package manager, prompts for input/output paths and plugins, installs packages, and writes `kubb.config.ts`.\n * Pass `yes: true` to skip all prompts and use defaults.\n */\nexport async function run({ yes, version, input: inputFlag, output: outputFlag, plugins: pluginsFlag, dryRun }: InitOptions): Promise<void> {\n const cwd = process.cwd()\n\n logIntro({ title: styleText('bgCyan', styleText('black', ' Kubb Init ')) })\n\n /**\n * Returns `flag` when provided, the `defaultValue` when `yes` is set,\n * or calls `prompt()` for interactive input. Exits on cancellation.\n */\n async function resolveOrPrompt<T>(flag: T | undefined, defaultValue: T, logLabel: string, prompt: () => Promise<T | symbol>): Promise<T> {\n if (flag !== undefined) {\n logInfo(`${logLabel}: ${styleText('cyan', String(flag))}`)\n return flag\n }\n if (yes) {\n logInfo(`${logLabel}: ${styleText('cyan', String(defaultValue))}`)\n return defaultValue\n }\n const result = await prompt()\n if (clack.isCancel(result)) cancelAndExit()\n return result as T\n }\n\n try {\n // Check/create package.json, detect package manager once after the block\n if (!hasPackageJson(cwd)) {\n if (!yes) {\n const shouldInit = await clack.confirm({\n message: 'No package.json found. Would you like to create one?',\n initialValue: true,\n })\n\n if (clack.isCancel(shouldInit) || !shouldInit) {\n cancelAndExit()\n }\n }\n\n const packageManager = detectPackageManager(cwd)\n const spinner = createSpinner()\n spinner.start(`Initializing package.json with ${packageManager.name}`)\n await initPackageJson(cwd, packageManager)\n spinner.stop(`Created package.json with ${packageManager.name}`)\n }\n\n const packageManager = detectPackageManager(cwd)\n if (hasPackageJson(cwd)) {\n logInfo(`Detected package manager: ${styleText('cyan', packageManager.name)}`)\n }\n\n // Prompt for OpenAPI spec path\n const inputPath = await resolveOrPrompt(inputFlag, initDefaults.inputPath, 'Using input path', () =>\n clack.text({\n message: 'Where is your OpenAPI specification located?',\n placeholder: initDefaults.inputPath,\n defaultValue: initDefaults.inputPath,\n validate: (value) => {\n if (!value) return 'Input path is required'\n },\n }),\n )\n\n // Prompt for output directory\n const outputPath = await resolveOrPrompt(outputFlag, initDefaults.outputPath, 'Using output path', () =>\n clack.text({\n message: 'Where should the generated files be output?',\n placeholder: initDefaults.outputPath,\n defaultValue: initDefaults.outputPath,\n validate: (value) => {\n if (!value) return 'Output path is required'\n },\n }),\n )\n\n // Plugin selection\n const defaultPlugins = availablePlugins.filter((p) => (initDefaults.plugins as ReadonlyArray<string>).includes(p.value))\n const pluginLabel = (plugins: Array<PluginOption>) => styleText('cyan', plugins.map((p) => p.label).join(', '))\n\n const selectedPlugins: Array<PluginOption> = await (async () => {\n if (pluginsFlag) {\n const plugins = resolvePlugins(pluginsFlag)\n if (plugins.length === 0) {\n logWarn(`No valid plugins found in --plugins value; falling back to default: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n logInfo(`Using plugins: ${pluginLabel(plugins)}`)\n return plugins\n }\n if (yes) {\n logInfo(`Using plugins: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n const values = await clack.multiselect({\n message: 'Select plugins to use:',\n options: availablePlugins.map(({ value, label, hint }) => ({ value, label, hint })),\n initialValues: [...initDefaults.plugins],\n required: true,\n })\n if (clack.isCancel(values)) cancelAndExit()\n return availablePlugins.filter((p) => (values as Array<string>).includes(p.value))\n })()\n\n // Install packages, matching the release of the running CLI\n const packagesToInstall = resolveInstallVersions({ packages: [KUBB_PACKAGE_NAME, ...selectedPlugins.map((p) => p.packageName)], version })\n\n const spinner = createSpinner()\n spinner.start(`Installing ${packagesToInstall.length} packages with ${packageManager.name}`)\n\n try {\n await dryRun.run(() => installPackages(packagesToInstall, packageManager, cwd), {\n message: `install ${packagesToInstall.length} packages with ${packageManager.name}`,\n })\n spinner.stop(`Installed ${packagesToInstall.length} packages`)\n } catch (error) {\n spinner.stop('Installation failed')\n throw error\n }\n\n // Generate config file\n const configSpinner = createSpinner()\n configSpinner.start(`Creating ${KUBB_CONFIG_FILENAME}`)\n\n const configContent = generateConfigFile({ selectedPlugins, inputPath, outputPath })\n const configPath = path.join(cwd, KUBB_CONFIG_FILENAME)\n\n if (fs.existsSync(configPath)) {\n configSpinner.stop(`${KUBB_CONFIG_FILENAME} already exists`)\n\n if (!yes) {\n const shouldOverwrite = await clack.confirm({\n message: `${KUBB_CONFIG_FILENAME} already exists. Overwrite?`,\n initialValue: false,\n })\n\n if (clack.isCancel(shouldOverwrite) || !shouldOverwrite) {\n cancelAndExit('Keeping existing configuration. Packages have been installed.')\n }\n }\n\n configSpinner.start(`Overwriting ${KUBB_CONFIG_FILENAME}`)\n }\n\n await dryRun.run(() => fs.promises.writeFile(configPath, configContent, 'utf-8'), { message: `write ${KUBB_CONFIG_FILENAME}` })\n\n configSpinner.stop(`Created ${KUBB_CONFIG_FILENAME}`)\n\n logOutro(\n styleText('green', '✓ All set!') +\n '\\n\\n' +\n styleText('dim', 'Next steps:') +\n '\\n' +\n styleText('cyan', ` 1. Make sure your OpenAPI spec is at: ${inputPath}`) +\n '\\n' +\n styleText('cyan', ' 2. Generate code with: npx kubb generate') +\n '\\n' +\n styleText('cyan', ` 3. Find generated files in: ${outputPath}`) +\n '\\n\\n' +\n styleText('dim', `Using ${packageManager.name} • Kubb v${version}`),\n )\n } catch (error) {\n logError(styleText('red', 'An error occurred during initialization'))\n if (error instanceof Error) {\n logError(error.message)\n }\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAQA,SAAgB,eAAe,aAAsD;CACnF,IAAI,CAAC,aACH,OAAO,CAAC;CAEV,MAAM,YAAY,YACf,MAAM,GAAG,CAAC,CACV,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,CAC5B,OAAO,OAAO;CACjB,OAAOA,kBAAAA,iBAAiB,QAAQ,WAAW,UAAU,SAAS,OAAO,KAAK,CAAC;AAC7E;AAEA,SAAgB,mBAAmB,EACjC,iBACA,WACA,cAKS;CAKT,OAAO;EAJS,gBAAgB,KAAK,WAAW,YAAY,OAAO,WAAW,WAAW,OAAO,YAAY,EAAE,CAAC,CAAC,KAAK,IAK/G,EAAE;;;YAGE,UAAU;;aAET,WAAW;;;;EARA,gBAAgB,KAAK,WAAW,OAAO,OAAO,WAAW,IAAI,CAAC,CAAC,KAAK,IAY9E,EAAE;;;;AAIhB;;;;;;;;;AAUA,SAAgB,uBAAuB,EAAE,UAAU,WAAwE;CAEzH,MAAM,MADa,QAAQ,MAAM,WAAW,CAAC,GAAG,MACtB;CAE1B,OAAO,SAAS,KAAK,SAAU,SAAA,SAA6B,GAAG,KAAK,GAA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EAEtD,IAAIE,QAAAA,QAAG,WAAW,UAAU,GAAG;GAC7B,cAAc,KAAK,GAAGF,kBAAAA,qBAAqB,gBAAgB;GAE3D,IAAI,CAAC,KAAK;IACR,MAAM,kBAAkB,MAAML,eAAM,QAAQ;KAC1C,SAAS,GAAGK,kBAAAA,qBAAqB;KACjC,cAAc;IAChB,CAAC;IAED,IAAIL,eAAM,SAAS,eAAe,KAAK,CAAC,iBACtC,cAAc,+DAA+D;GAEjF;GAEA,cAAc,MAAM,eAAeK,kBAAAA,sBAAsB;EAC3D;EAEA,MAAM,OAAO,UAAUE,QAAAA,QAAG,SAAS,UAAU,YAAY,eAAe,OAAO,GAAG,EAAE,SAAS,SAASF,kBAAAA,uBAAuB,CAAC;EAE9H,cAAc,KAAK,WAAWA,kBAAAA,sBAAsB;EAEpD,eAAA,UAAA,GACEN,UAAAA,UAAAA,CAAU,SAAS,YAAY,IAC7B,UAAA,GACAA,UAAAA,UAAAA,CAAU,OAAO,aAAa,IAC9B,QAAA,GACAA,UAAAA,UAAAA,CAAU,QAAQ,2CAA2C,WAAW,IACxE,QAAA,GACAA,UAAAA,UAAAA,CAAU,QAAQ,4CAA4C,IAC9D,QAAA,GACAA,UAAAA,UAAAA,CAAU,QAAQ,iCAAiC,YAAY,IAC/D,UAAA,GACAA,UAAAA,UAAAA,CAAU,OAAO,SAAS,eAAe,KAAK,WAAW,SAAS,CACtE;CACF,SAAS,OAAO;EACd,eAAA,UAAA,GAASA,UAAAA,UAAAA,CAAU,OAAO,yCAAyC,CAAC;EACpE,IAAI,iBAAiB,OACnB,eAAA,SAAS,MAAM,OAAO;EAExB,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF"}
1
+ {"version":3,"file":"run-VK50TiB7.cjs","names":["availablePlugins","join","existsSync","readFileSync","process","fs","path","x","process","styleText","clack","createSpinner","initDefaults","availablePlugins","KUBB_PACKAGE_NAME","KUBB_CONFIG_FILENAME","path","fs"],"sources":["../../../internals/shared/src/init.ts","../src/tools.ts","../src/runners/init/utils.ts","../src/runners/init/run.ts"],"sourcesContent":["import { availablePlugins, KUBB_PACKAGE_NAME } from './constants.ts'\nimport type { PluginOption } from './types.ts'\n\n/**\n * Resolves a comma-separated plugin flag (e.g. `--plugins plugin-ts,plugin-zod`) into the\n * matching known plugin options. Unrecognized names are dropped, and a missing flag yields\n * an empty list.\n */\nexport function resolvePlugins(pluginsFlag: string | undefined): Array<PluginOption> {\n if (!pluginsFlag) {\n return []\n }\n const requested = pluginsFlag\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n return availablePlugins.filter((plugin) => requested.includes(plugin.value))\n}\n\nexport function generateConfigFile({\n selectedPlugins,\n inputPath,\n outputPath,\n}: {\n selectedPlugins: Array<PluginOption>\n inputPath: string\n outputPath: string\n}): string {\n const imports = selectedPlugins.map((plugin) => `import { ${plugin.importName} } from '${plugin.packageName}'`).join('\\n')\n\n const pluginConfigs = selectedPlugins.map((plugin) => ` ${plugin.importName}(),`).join('\\n')\n\n return `import { defineConfig } from 'kubb/config'\n${imports}\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [\n${pluginConfigs}\n ],\n})\n`\n}\n\n/**\n * Turns package names into install specifiers for the wizard.\n *\n * `kubb` is pinned to the exact version of the running CLI, since both ship from the same release\n * and resolving `kubb@beta` separately can land on a different version than the CLI doing the\n * scaffolding. Plugins release from their own repo on their own cadence, so they follow the\n * release channel of the CLI through its dist-tag.\n */\nexport function resolveInstallVersions({ packages, version }: { packages: Array<string>; version: string }): Array<string> {\n const prerelease = version.match(/-([a-z]+)/)?.[1]\n const tag = prerelease ?? 'latest'\n\n return packages.map((name) => (name === KUBB_PACKAGE_NAME ? `${name}@${version}` : `${name}@${tag}`))\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { formatters, linters } from '@internals/utils'\nimport type { Config } from '@kubb/core'\n\n/**\n * The configurable formatter names, mirrored from `Config['output'].format`. Excludes `'auto'`\n * (detection, not a tool) and `false` (skip). The `formatters`/`linters` tables below are pinned to\n * these so adding a tool to the config union without a descriptor fails to compile.\n */\ntype FormatterName = Exclude<NonNullable<Config['output']['format']>, 'auto' | false>\ntype LinterName = Exclude<NonNullable<Config['output']['lint']>, 'auto' | false>\n\n// Pinned to core's union here rather than in `@internals/utils`, which must not import `@kubb/core`:\n// adding a tool to the config union without a descriptor stays a compile error.\nformatters satisfies Record<FormatterName, unknown>\nlinters satisfies Record<LinterName, unknown>\n\nexport { detectTool, formatters, linters } from '@internals/utils'\n\nexport type PackageManagerName = 'npm' | 'pnpm' | 'yarn' | 'bun'\n\n/**\n * Metadata describing a package manager's lock file and install command.\n */\nexport interface PackageManagerInfo {\n /**\n * Identifier used in CLI commands, e.g. `pnpm`, `yarn`.\n */\n name: PackageManagerName\n /**\n * Lock file name that uniquely identifies this package manager in a project root.\n */\n lockFile: string\n /**\n * Subcommands passed to the package manager binary to install a dev dependency.\n */\n installCommand: ReadonlyArray<string>\n}\n\n/**\n * Metadata for each supported package manager, keyed by its short name.\n *\n * @example\n * ```ts\n * packageManagers.pnpm.installCommand // ['add', '-D']\n * packageManagers.npm.lockFile // 'package-lock.json'\n * ```\n */\nconst packageManagers: Record<PackageManagerName, PackageManagerInfo> = {\n pnpm: {\n name: 'pnpm',\n lockFile: 'pnpm-lock.yaml',\n installCommand: ['add', '-D'],\n },\n yarn: {\n name: 'yarn',\n lockFile: 'yarn.lock',\n installCommand: ['add', '-D'],\n },\n bun: {\n name: 'bun',\n lockFile: 'bun.lockb',\n installCommand: ['add', '-d'],\n },\n npm: {\n name: 'npm',\n lockFile: 'package-lock.json',\n installCommand: ['install', '--save-dev'],\n },\n}\n\n/**\n * Minimal shape of `package.json` fields read during detection.\n */\ntype PackageJson = {\n /**\n * The `packageManager` field from `package.json` (e.g. `\"pnpm@9.0.0\"`).\n */\n packageManager?: string\n}\n\n/**\n * Detects the active package manager for the given directory.\n * Resolution order: `packageManager` field in `package.json`, then presence of a lock file.\n * Falls back to `npm` when no signal is found.\n *\n * @example\n * ```ts\n * detectPackageManager('/my/project') // { name: 'pnpm', lockFile: 'pnpm-lock.yaml', ... }\n * detectPackageManager() // falls back to npm when no lock file is found\n * ```\n */\nexport function detectPackageManager(cwd: string = process.cwd()): PackageManagerInfo {\n const packageJsonPath = join(cwd, 'package.json')\n if (existsSync(packageJsonPath)) {\n try {\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as PackageJson\n const pmField = packageJson.packageManager\n if (typeof pmField === 'string') {\n const name = pmField.split('@')[0]\n if (name && name in packageManagers) {\n return packageManagers[name as PackageManagerName]\n }\n }\n } catch {\n // Continue to lock file detection\n }\n }\n\n for (const pm of Object.values(packageManagers)) {\n if (existsSync(join(cwd, pm.lockFile))) {\n return pm\n }\n }\n\n return packageManagers.npm\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { x } from 'tinyexec'\nimport type { PackageManagerInfo, PackageManagerName } from '../../tools.ts'\n\n/**\n * Returns `true` when a `package.json` exists at `cwd`.\n */\nexport function hasPackageJson(cwd: string = process.cwd()): boolean {\n return fs.existsSync(path.join(cwd, 'package.json'))\n}\n\n/**\n * Initializes a new `package.json` at `cwd` using the detected package manager.\n */\nexport async function initPackageJson(cwd: string, packageManager: PackageManagerInfo): Promise<void> {\n const commands: Record<PackageManagerName, Array<string>> = {\n npm: ['init', '-y'],\n pnpm: ['init'],\n yarn: ['init', '-y'],\n bun: ['init', '-y'],\n }\n\n await x(packageManager.name, commands[packageManager.name], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n\n/**\n * Installs the given packages at `cwd` using the detected package manager.\n */\nexport async function installPackages(packages: Array<string>, packageManager: PackageManagerInfo, cwd: string = process.cwd()): Promise<void> {\n await x(packageManager.name, [...packageManager.installCommand, ...packages], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport type { DryRunExtension } from '@gunshi/plugin-dryrun'\nimport {\n availablePlugins,\n generateConfigFile,\n initDefaults,\n KUBB_CONFIG_FILENAME,\n KUBB_PACKAGE_NAME,\n type PluginOption,\n resolveInstallVersions,\n resolvePlugins,\n} from '@internals/shared'\nimport { createSpinner, logError, logInfo, logIntro, logOutro, logWarn } from '../../loggers/output.ts'\nimport { hasPackageJson, initPackageJson, installPackages } from './utils.ts'\nimport { detectPackageManager } from '../../tools.ts'\n\nfunction cancelAndExit(message = 'Operation canceled.'): never {\n clack.cancel(message)\n process.exit(0)\n}\n\ntype InitOptions = {\n /**\n * When `true`, skips all interactive prompts and uses default values.\n */\n yes: boolean\n /**\n * Current `@kubb/cli` version string, shown in the closing outro.\n */\n version: string\n /**\n * Input path flag value from `--input`. When provided, skips the input prompt.\n */\n input?: string\n /**\n * Output directory flag value from `--output`. When provided, skips the output prompt.\n */\n output?: string\n /**\n * Comma-separated plugin list from `--plugins`, e.g. `'plugin-ts,plugin-zod'`. When provided, skips the plugin selection prompt.\n */\n plugins?: string\n /**\n * Dry-run extension from `@gunshi/plugin-dryrun`. When enabled, package installation and the\n * config file write are skipped.\n */\n dryRun: DryRunExtension\n}\n\n/**\n * Runs the interactive Kubb scaffolding wizard.\n * Detects the package manager, prompts for input/output paths and plugins, installs packages, and writes `kubb.config.ts`.\n * Pass `yes: true` to skip all prompts and use defaults.\n */\nexport async function run({ yes, version, input: inputFlag, output: outputFlag, plugins: pluginsFlag, dryRun }: InitOptions): Promise<void> {\n const cwd = process.cwd()\n\n logIntro({ title: styleText('bgCyan', styleText('black', ' Kubb Init ')) })\n\n /**\n * Returns `flag` when provided, the `defaultValue` when `yes` is set,\n * or calls `prompt()` for interactive input. Exits on cancellation.\n */\n async function resolveOrPrompt<T>(flag: T | undefined, defaultValue: T, logLabel: string, prompt: () => Promise<T | symbol>): Promise<T> {\n if (flag !== undefined) {\n logInfo(`${logLabel}: ${styleText('cyan', String(flag))}`)\n return flag\n }\n if (yes) {\n logInfo(`${logLabel}: ${styleText('cyan', String(defaultValue))}`)\n return defaultValue\n }\n const result = await prompt()\n if (clack.isCancel(result)) cancelAndExit()\n return result as T\n }\n\n try {\n // Check/create package.json, detect package manager once after the block\n if (!hasPackageJson(cwd)) {\n if (!yes) {\n const shouldInit = await clack.confirm({\n message: 'No package.json found. Would you like to create one?',\n initialValue: true,\n })\n\n if (clack.isCancel(shouldInit) || !shouldInit) {\n cancelAndExit()\n }\n }\n\n const packageManager = detectPackageManager(cwd)\n const spinner = createSpinner()\n spinner.start(`Initializing package.json with ${packageManager.name}`)\n await initPackageJson(cwd, packageManager)\n spinner.stop(`Created package.json with ${packageManager.name}`)\n }\n\n const packageManager = detectPackageManager(cwd)\n if (hasPackageJson(cwd)) {\n logInfo(`Detected package manager: ${styleText('cyan', packageManager.name)}`)\n }\n\n // Prompt for OpenAPI spec path\n const inputPath = await resolveOrPrompt(inputFlag, initDefaults.inputPath, 'Using input path', () =>\n clack.text({\n message: 'Where is your OpenAPI specification located?',\n placeholder: initDefaults.inputPath,\n defaultValue: initDefaults.inputPath,\n validate: (value) => {\n if (!value) return 'Input path is required'\n },\n }),\n )\n\n // Prompt for output directory\n const outputPath = await resolveOrPrompt(outputFlag, initDefaults.outputPath, 'Using output path', () =>\n clack.text({\n message: 'Where should the generated files be output?',\n placeholder: initDefaults.outputPath,\n defaultValue: initDefaults.outputPath,\n validate: (value) => {\n if (!value) return 'Output path is required'\n },\n }),\n )\n\n // Plugin selection\n const defaultPlugins = availablePlugins.filter((p) => (initDefaults.plugins as ReadonlyArray<string>).includes(p.value))\n const pluginLabel = (plugins: Array<PluginOption>) => styleText('cyan', plugins.map((p) => p.label).join(', '))\n\n const selectedPlugins: Array<PluginOption> = await (async () => {\n if (pluginsFlag) {\n const plugins = resolvePlugins(pluginsFlag)\n if (plugins.length === 0) {\n logWarn(`No valid plugins found in --plugins value; falling back to default: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n logInfo(`Using plugins: ${pluginLabel(plugins)}`)\n return plugins\n }\n if (yes) {\n logInfo(`Using plugins: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n const values = await clack.multiselect({\n message: 'Select plugins to use:',\n options: availablePlugins.map(({ value, label, hint }) => ({ value, label, hint })),\n initialValues: [...initDefaults.plugins],\n required: true,\n })\n if (clack.isCancel(values)) cancelAndExit()\n return availablePlugins.filter((p) => (values as Array<string>).includes(p.value))\n })()\n\n // Install packages, matching the release of the running CLI\n const packagesToInstall = resolveInstallVersions({ packages: [KUBB_PACKAGE_NAME, ...selectedPlugins.map((p) => p.packageName)], version })\n\n const spinner = createSpinner()\n spinner.start(`Installing ${packagesToInstall.length} packages with ${packageManager.name}`)\n\n try {\n await dryRun.run(() => installPackages(packagesToInstall, packageManager, cwd), {\n message: `install ${packagesToInstall.length} packages with ${packageManager.name}`,\n })\n spinner.stop(`Installed ${packagesToInstall.length} packages`)\n } catch (error) {\n spinner.stop('Installation failed')\n throw error\n }\n\n // Generate config file\n const configSpinner = createSpinner()\n configSpinner.start(`Creating ${KUBB_CONFIG_FILENAME}`)\n\n const configContent = generateConfigFile({ selectedPlugins, inputPath, outputPath })\n const configPath = path.join(cwd, KUBB_CONFIG_FILENAME)\n\n if (fs.existsSync(configPath)) {\n configSpinner.stop(`${KUBB_CONFIG_FILENAME} already exists`)\n\n if (!yes) {\n const shouldOverwrite = await clack.confirm({\n message: `${KUBB_CONFIG_FILENAME} already exists. Overwrite?`,\n initialValue: false,\n })\n\n if (clack.isCancel(shouldOverwrite) || !shouldOverwrite) {\n cancelAndExit('Keeping existing configuration. Packages have been installed.')\n }\n }\n\n configSpinner.start(`Overwriting ${KUBB_CONFIG_FILENAME}`)\n }\n\n await dryRun.run(() => fs.promises.writeFile(configPath, configContent, 'utf-8'), { message: `write ${KUBB_CONFIG_FILENAME}` })\n\n configSpinner.stop(`Created ${KUBB_CONFIG_FILENAME}`)\n\n logOutro(\n styleText('green', '✓ All set!') +\n '\\n\\n' +\n styleText('dim', 'Next steps:') +\n '\\n' +\n styleText('cyan', ` 1. Make sure your OpenAPI spec is at: ${inputPath}`) +\n '\\n' +\n styleText('cyan', ' 2. Generate code with: npx kubb generate') +\n '\\n' +\n styleText('cyan', ` 3. Find generated files in: ${outputPath}`) +\n '\\n\\n' +\n styleText('dim', `Using ${packageManager.name} • Kubb v${version}`),\n )\n } catch (error) {\n logError(styleText('red', 'An error occurred during initialization'))\n if (error instanceof Error) {\n logError(error.message)\n }\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAQA,SAAgB,eAAe,aAAsD;CACnF,IAAI,CAAC,aACH,OAAO,CAAC;CAEV,MAAM,YAAY,YACf,MAAM,GAAG,CAAC,CACV,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,CAC5B,OAAO,OAAO;CACjB,OAAOA,kBAAAA,iBAAiB,QAAQ,WAAW,UAAU,SAAS,OAAO,KAAK,CAAC;AAC7E;AAEA,SAAgB,mBAAmB,EACjC,iBACA,WACA,cAKS;CAKT,OAAO;EAJS,gBAAgB,KAAK,WAAW,YAAY,OAAO,WAAW,WAAW,OAAO,YAAY,EAAE,CAAC,CAAC,KAAK,IAK/G,EAAE;;;YAGE,UAAU;;aAET,WAAW;;;;EARA,gBAAgB,KAAK,WAAW,OAAO,OAAO,WAAW,IAAI,CAAC,CAAC,KAAK,IAY9E,EAAE;;;;AAIhB;;;;;;;;;AAUA,SAAgB,uBAAuB,EAAE,UAAU,WAAwE;CAEzH,MAAM,MADa,QAAQ,MAAM,WAAW,CAAC,GAAG,MACtB;CAE1B,OAAO,SAAS,KAAK,SAAU,SAAA,SAA6B,GAAG,KAAK,GAAG,YAAY,GAAG,KAAK,GAAG,KAAM;AACtG;;;;;;;;;;;;ACZA,MAAM,kBAAkE;CACtE,MAAM;EACJ,MAAM;EACN,UAAU;EACV,gBAAgB,CAAC,OAAO,IAAI;CAC9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AAML,eAAM,QAAQ;KAC1C,SAAS,GAAGK,kBAAAA,qBAAqB;KACjC,cAAc;IAChB,CAAC;IAED,IAAIL,eAAM,SAAS,eAAe,KAAK,CAAC,iBACtC,cAAc,+DAA+D;GAEjF;GAEA,cAAc,MAAM,eAAeK,kBAAAA,sBAAsB;EAC3D;EAEA,MAAM,OAAO,UAAUE,QAAAA,QAAG,SAAS,UAAU,YAAY,eAAe,OAAO,GAAG,EAAE,SAAS,SAASF,kBAAAA,uBAAuB,CAAC;EAE9H,cAAc,KAAK,WAAWA,kBAAAA,sBAAsB;EAEpD,eAAA,UAAA,GACEN,UAAAA,UAAAA,CAAU,SAAS,YAAY,IAC7B,UAAA,GACAA,UAAAA,UAAAA,CAAU,OAAO,aAAa,IAC9B,QAAA,GACAA,UAAAA,UAAAA,CAAU,QAAQ,2CAA2C,WAAW,IACxE,QAAA,GACAA,UAAAA,UAAAA,CAAU,QAAQ,4CAA4C,IAC9D,QAAA,GACAA,UAAAA,UAAAA,CAAU,QAAQ,iCAAiC,YAAY,IAC/D,UAAA,GACAA,UAAAA,UAAAA,CAAU,OAAO,SAAS,eAAe,KAAK,WAAW,SAAS,CACtE;CACF,SAAS,OAAO;EACd,eAAA,UAAA,GAASA,UAAAA,UAAAA,CAAU,OAAO,yCAAyC,CAAC;EACpE,IAAI,iBAAiB,OACnB,eAAA,SAAS,MAAM,OAAO;EAExB,aAAA,QAAQ,KAAK,CAAC;CAChB;AACF"}
@@ -1,5 +1,5 @@
1
1
  import "./rolldown-runtime-C0LytTxp.js";
2
- import { a as logIntro, c as logWarn, i as logInfo, o as logOutro, r as logError, t as createSpinner } from "./output-LZvrgF3z.js";
2
+ import { a as logIntro, c as logWarn, i as logInfo, o as logOutro, r as logError, t as createSpinner } from "./output-DH2Uoy4x.js";
3
3
  import { i as initDefaults, n as KUBB_PACKAGE_NAME, r as availablePlugins, t as KUBB_CONFIG_FILENAME } from "./constants-DHRspBTo.js";
4
4
  import { styleText } from "node:util";
5
5
  import process$1 from "node:process";
@@ -276,4 +276,4 @@ async function run({ yes, version, input: inputFlag, output: outputFlag, plugins
276
276
  //#endregion
277
277
  export { run };
278
278
 
279
- //# sourceMappingURL=run-BzvsJ0Ek.js.map
279
+ //# sourceMappingURL=run-kdxqOL8u.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-BzvsJ0Ek.js","names":["process","process"],"sources":["../../../internals/shared/src/init.ts","../src/tools.ts","../src/runners/init/utils.ts","../src/runners/init/run.ts"],"sourcesContent":["import { availablePlugins, KUBB_PACKAGE_NAME } from './constants.ts'\nimport type { PluginOption } from './types.ts'\n\n/**\n * Resolves a comma-separated plugin flag (e.g. `--plugins plugin-ts,plugin-zod`) into the\n * matching known plugin options. Unrecognized names are dropped, and a missing flag yields\n * an empty list.\n */\nexport function resolvePlugins(pluginsFlag: string | undefined): Array<PluginOption> {\n if (!pluginsFlag) {\n return []\n }\n const requested = pluginsFlag\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n return availablePlugins.filter((plugin) => requested.includes(plugin.value))\n}\n\nexport function generateConfigFile({\n selectedPlugins,\n inputPath,\n outputPath,\n}: {\n selectedPlugins: Array<PluginOption>\n inputPath: string\n outputPath: string\n}): string {\n const imports = selectedPlugins.map((plugin) => `import { ${plugin.importName} } from '${plugin.packageName}'`).join('\\n')\n\n const pluginConfigs = selectedPlugins.map((plugin) => ` ${plugin.importName}(),`).join('\\n')\n\n return `import { defineConfig } from 'kubb/config'\n${imports}\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [\n${pluginConfigs}\n ],\n})\n`\n}\n\n/**\n * Turns package names into install specifiers for the wizard.\n *\n * `kubb` is pinned to the exact version of the running CLI, since both ship from the same release\n * and resolving `kubb@beta` separately can land on a different version than the CLI doing the\n * scaffolding. Plugins release from their own repo on their own cadence, so they follow the\n * release channel of the CLI through its dist-tag.\n */\nexport function resolveInstallVersions({ packages, version }: { packages: Array<string>; version: string }): Array<string> {\n const prerelease = version.match(/-([a-z]+)/)?.[1]\n const tag = prerelease ?? 'latest'\n\n return packages.map((name) => (name === KUBB_PACKAGE_NAME ? `${name}@${version}` : `${name}@${tag}`))\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { formatters, linters } from '@internals/utils'\nimport type { Config } from '@kubb/core'\n\n/**\n * The configurable formatter names, mirrored from `Config['output'].format`. Excludes `'auto'`\n * (detection, not a tool) and `false` (skip). The `formatters`/`linters` tables below are pinned to\n * these so adding a tool to the config union without a descriptor fails to compile.\n */\ntype FormatterName = Exclude<NonNullable<Config['output']['format']>, 'auto' | false>\ntype LinterName = Exclude<NonNullable<Config['output']['lint']>, 'auto' | false>\n\n// Pinned to core's union here rather than in `@internals/utils`, which must not import `@kubb/core`:\n// adding a tool to the config union without a descriptor stays a compile error.\nformatters satisfies Record<FormatterName, unknown>\nlinters satisfies Record<LinterName, unknown>\n\nexport { detectTool, formatters, linters } from '@internals/utils'\n\nexport type PackageManagerName = 'npm' | 'pnpm' | 'yarn' | 'bun'\n\n/**\n * Metadata describing a package manager's lock file and install command.\n */\nexport interface PackageManagerInfo {\n /**\n * Identifier used in CLI commands, e.g. `pnpm`, `yarn`.\n */\n name: PackageManagerName\n /**\n * Lock file name that uniquely identifies this package manager in a project root.\n */\n lockFile: string\n /**\n * Subcommands passed to the package manager binary to install a dev dependency.\n */\n installCommand: ReadonlyArray<string>\n}\n\n/**\n * Metadata for each supported package manager, keyed by its short name.\n *\n * @example\n * ```ts\n * packageManagers.pnpm.installCommand // ['add', '-D']\n * packageManagers.npm.lockFile // 'package-lock.json'\n * ```\n */\nconst packageManagers: Record<PackageManagerName, PackageManagerInfo> = {\n pnpm: {\n name: 'pnpm',\n lockFile: 'pnpm-lock.yaml',\n installCommand: ['add', '-D'],\n },\n yarn: {\n name: 'yarn',\n lockFile: 'yarn.lock',\n installCommand: ['add', '-D'],\n },\n bun: {\n name: 'bun',\n lockFile: 'bun.lockb',\n installCommand: ['add', '-d'],\n },\n npm: {\n name: 'npm',\n lockFile: 'package-lock.json',\n installCommand: ['install', '--save-dev'],\n },\n}\n\n/**\n * Minimal shape of `package.json` fields read during detection.\n */\ntype PackageJson = {\n /**\n * The `packageManager` field from `package.json` (e.g. `\"pnpm@9.0.0\"`).\n */\n packageManager?: string\n}\n\n/**\n * Detects the active package manager for the given directory.\n * Resolution order: `packageManager` field in `package.json`, then presence of a lock file.\n * Falls back to `npm` when no signal is found.\n *\n * @example\n * ```ts\n * detectPackageManager('/my/project') // { name: 'pnpm', lockFile: 'pnpm-lock.yaml', ... }\n * detectPackageManager() // falls back to npm when no lock file is found\n * ```\n */\nexport function detectPackageManager(cwd: string = process.cwd()): PackageManagerInfo {\n const packageJsonPath = join(cwd, 'package.json')\n if (existsSync(packageJsonPath)) {\n try {\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as PackageJson\n const pmField = packageJson.packageManager\n if (typeof pmField === 'string') {\n const name = pmField.split('@')[0]\n if (name && name in packageManagers) {\n return packageManagers[name as PackageManagerName]\n }\n }\n } catch {\n // Continue to lock file detection\n }\n }\n\n for (const pm of Object.values(packageManagers)) {\n if (existsSync(join(cwd, pm.lockFile))) {\n return pm\n }\n }\n\n return packageManagers.npm\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { x } from 'tinyexec'\nimport type { PackageManagerInfo, PackageManagerName } from '../../tools.ts'\n\n/**\n * Returns `true` when a `package.json` exists at `cwd`.\n */\nexport function hasPackageJson(cwd: string = process.cwd()): boolean {\n return fs.existsSync(path.join(cwd, 'package.json'))\n}\n\n/**\n * Initializes a new `package.json` at `cwd` using the detected package manager.\n */\nexport async function initPackageJson(cwd: string, packageManager: PackageManagerInfo): Promise<void> {\n const commands: Record<PackageManagerName, Array<string>> = {\n npm: ['init', '-y'],\n pnpm: ['init'],\n yarn: ['init', '-y'],\n bun: ['init', '-y'],\n }\n\n await x(packageManager.name, commands[packageManager.name], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n\n/**\n * Installs the given packages at `cwd` using the detected package manager.\n */\nexport async function installPackages(packages: Array<string>, packageManager: PackageManagerInfo, cwd: string = process.cwd()): Promise<void> {\n await x(packageManager.name, [...packageManager.installCommand, ...packages], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport type { DryRunExtension } from '@gunshi/plugin-dryrun'\nimport {\n availablePlugins,\n generateConfigFile,\n initDefaults,\n KUBB_CONFIG_FILENAME,\n KUBB_PACKAGE_NAME,\n type PluginOption,\n resolveInstallVersions,\n resolvePlugins,\n} from '@internals/shared'\nimport { createSpinner, logError, logInfo, logIntro, logOutro, logWarn } from '../../loggers/output.ts'\nimport { hasPackageJson, initPackageJson, installPackages } from './utils.ts'\nimport { detectPackageManager } from '../../tools.ts'\n\nfunction cancelAndExit(message = 'Operation canceled.'): never {\n clack.cancel(message)\n process.exit(0)\n}\n\ntype InitOptions = {\n /**\n * When `true`, skips all interactive prompts and uses default values.\n */\n yes: boolean\n /**\n * Current `@kubb/cli` version string, shown in the closing outro.\n */\n version: string\n /**\n * Input path flag value from `--input`. When provided, skips the input prompt.\n */\n input?: string\n /**\n * Output directory flag value from `--output`. When provided, skips the output prompt.\n */\n output?: string\n /**\n * Comma-separated plugin list from `--plugins`, e.g. `'plugin-ts,plugin-zod'`. When provided, skips the plugin selection prompt.\n */\n plugins?: string\n /**\n * Dry-run extension from `@gunshi/plugin-dryrun`. When enabled, package installation and the\n * config file write are skipped.\n */\n dryRun: DryRunExtension\n}\n\n/**\n * Runs the interactive Kubb scaffolding wizard.\n * Detects the package manager, prompts for input/output paths and plugins, installs packages, and writes `kubb.config.ts`.\n * Pass `yes: true` to skip all prompts and use defaults.\n */\nexport async function run({ yes, version, input: inputFlag, output: outputFlag, plugins: pluginsFlag, dryRun }: InitOptions): Promise<void> {\n const cwd = process.cwd()\n\n logIntro({ title: styleText('bgCyan', styleText('black', ' Kubb Init ')) })\n\n /**\n * Returns `flag` when provided, the `defaultValue` when `yes` is set,\n * or calls `prompt()` for interactive input. Exits on cancellation.\n */\n async function resolveOrPrompt<T>(flag: T | undefined, defaultValue: T, logLabel: string, prompt: () => Promise<T | symbol>): Promise<T> {\n if (flag !== undefined) {\n logInfo(`${logLabel}: ${styleText('cyan', String(flag))}`)\n return flag\n }\n if (yes) {\n logInfo(`${logLabel}: ${styleText('cyan', String(defaultValue))}`)\n return defaultValue\n }\n const result = await prompt()\n if (clack.isCancel(result)) cancelAndExit()\n return result as T\n }\n\n try {\n // Check/create package.json, detect package manager once after the block\n if (!hasPackageJson(cwd)) {\n if (!yes) {\n const shouldInit = await clack.confirm({\n message: 'No package.json found. Would you like to create one?',\n initialValue: true,\n })\n\n if (clack.isCancel(shouldInit) || !shouldInit) {\n cancelAndExit()\n }\n }\n\n const packageManager = detectPackageManager(cwd)\n const spinner = createSpinner()\n spinner.start(`Initializing package.json with ${packageManager.name}`)\n await initPackageJson(cwd, packageManager)\n spinner.stop(`Created package.json with ${packageManager.name}`)\n }\n\n const packageManager = detectPackageManager(cwd)\n if (hasPackageJson(cwd)) {\n logInfo(`Detected package manager: ${styleText('cyan', packageManager.name)}`)\n }\n\n // Prompt for OpenAPI spec path\n const inputPath = await resolveOrPrompt(inputFlag, initDefaults.inputPath, 'Using input path', () =>\n clack.text({\n message: 'Where is your OpenAPI specification located?',\n placeholder: initDefaults.inputPath,\n defaultValue: initDefaults.inputPath,\n validate: (value) => {\n if (!value) return 'Input path is required'\n },\n }),\n )\n\n // Prompt for output directory\n const outputPath = await resolveOrPrompt(outputFlag, initDefaults.outputPath, 'Using output path', () =>\n clack.text({\n message: 'Where should the generated files be output?',\n placeholder: initDefaults.outputPath,\n defaultValue: initDefaults.outputPath,\n validate: (value) => {\n if (!value) return 'Output path is required'\n },\n }),\n )\n\n // Plugin selection\n const defaultPlugins = availablePlugins.filter((p) => (initDefaults.plugins as ReadonlyArray<string>).includes(p.value))\n const pluginLabel = (plugins: Array<PluginOption>) => styleText('cyan', plugins.map((p) => p.label).join(', '))\n\n const selectedPlugins: Array<PluginOption> = await (async () => {\n if (pluginsFlag) {\n const plugins = resolvePlugins(pluginsFlag)\n if (plugins.length === 0) {\n logWarn(`No valid plugins found in --plugins value; falling back to default: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n logInfo(`Using plugins: ${pluginLabel(plugins)}`)\n return plugins\n }\n if (yes) {\n logInfo(`Using plugins: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n const values = await clack.multiselect({\n message: 'Select plugins to use:',\n options: availablePlugins.map(({ value, label, hint }) => ({ value, label, hint })),\n initialValues: [...initDefaults.plugins],\n required: true,\n })\n if (clack.isCancel(values)) cancelAndExit()\n return availablePlugins.filter((p) => (values as Array<string>).includes(p.value))\n })()\n\n // Install packages, matching the release of the running CLI\n const packagesToInstall = resolveInstallVersions({ packages: [KUBB_PACKAGE_NAME, ...selectedPlugins.map((p) => p.packageName)], version })\n\n const spinner = createSpinner()\n spinner.start(`Installing ${packagesToInstall.length} packages with ${packageManager.name}`)\n\n try {\n await dryRun.run(() => installPackages(packagesToInstall, packageManager, cwd), {\n message: `install ${packagesToInstall.length} packages with ${packageManager.name}`,\n })\n spinner.stop(`Installed ${packagesToInstall.length} packages`)\n } catch (error) {\n spinner.stop('Installation failed')\n throw error\n }\n\n // Generate config file\n const configSpinner = createSpinner()\n configSpinner.start(`Creating ${KUBB_CONFIG_FILENAME}`)\n\n const configContent = generateConfigFile({ selectedPlugins, inputPath, outputPath })\n const configPath = path.join(cwd, KUBB_CONFIG_FILENAME)\n\n if (fs.existsSync(configPath)) {\n configSpinner.stop(`${KUBB_CONFIG_FILENAME} already exists`)\n\n if (!yes) {\n const shouldOverwrite = await clack.confirm({\n message: `${KUBB_CONFIG_FILENAME} already exists. Overwrite?`,\n initialValue: false,\n })\n\n if (clack.isCancel(shouldOverwrite) || !shouldOverwrite) {\n cancelAndExit('Keeping existing configuration. Packages have been installed.')\n }\n }\n\n configSpinner.start(`Overwriting ${KUBB_CONFIG_FILENAME}`)\n }\n\n await dryRun.run(() => fs.promises.writeFile(configPath, configContent, 'utf-8'), { message: `write ${KUBB_CONFIG_FILENAME}` })\n\n configSpinner.stop(`Created ${KUBB_CONFIG_FILENAME}`)\n\n logOutro(\n styleText('green', '✓ All set!') +\n '\\n\\n' +\n styleText('dim', 'Next steps:') +\n '\\n' +\n styleText('cyan', ` 1. Make sure your OpenAPI spec is at: ${inputPath}`) +\n '\\n' +\n styleText('cyan', ' 2. Generate code with: npx kubb generate') +\n '\\n' +\n styleText('cyan', ` 3. Find generated files in: ${outputPath}`) +\n '\\n\\n' +\n styleText('dim', `Using ${packageManager.name} • Kubb v${version}`),\n )\n } catch (error) {\n logError(styleText('red', 'An error occurred during initialization'))\n if (error instanceof Error) {\n logError(error.message)\n }\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAQA,SAAgB,eAAe,aAAsD;CACnF,IAAI,CAAC,aACH,OAAO,CAAC;CAEV,MAAM,YAAY,YACf,MAAM,GAAG,CAAC,CACV,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,CAC5B,OAAO,OAAO;CACjB,OAAO,iBAAiB,QAAQ,WAAW,UAAU,SAAS,OAAO,KAAK,CAAC;AAC7E;AAEA,SAAgB,mBAAmB,EACjC,iBACA,WACA,cAKS;CAKT,OAAO;EAJS,gBAAgB,KAAK,WAAW,YAAY,OAAO,WAAW,WAAW,OAAO,YAAY,EAAE,CAAC,CAAC,KAAK,IAK/G,EAAE;;;YAGE,UAAU;;aAET,WAAW;;;;EARA,gBAAgB,KAAK,WAAW,OAAO,OAAO,WAAW,IAAI,CAAC,CAAC,KAAK,IAY9E,EAAE;;;;AAIhB;;;;;;;;;AAUA,SAAgB,uBAAuB,EAAE,UAAU,WAAwE;CAEzH,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B;EAEpD,SACE,UAAU,SAAS,YAAY,IAC7B,SACA,UAAU,OAAO,aAAa,IAC9B,OACA,UAAU,QAAQ,2CAA2C,WAAW,IACxE,OACA,UAAU,QAAQ,4CAA4C,IAC9D,OACA,UAAU,QAAQ,iCAAiC,YAAY,IAC/D,SACA,UAAU,OAAO,SAAS,eAAe,KAAK,WAAW,SAAS,CACtE;CACF,SAAS,OAAO;EACd,SAAS,UAAU,OAAO,yCAAyC,CAAC;EACpE,IAAI,iBAAiB,OACnB,SAAS,MAAM,OAAO;EAExB,UAAQ,KAAK,CAAC;CAChB;AACF"}
1
+ {"version":3,"file":"run-kdxqOL8u.js","names":["process","process"],"sources":["../../../internals/shared/src/init.ts","../src/tools.ts","../src/runners/init/utils.ts","../src/runners/init/run.ts"],"sourcesContent":["import { availablePlugins, KUBB_PACKAGE_NAME } from './constants.ts'\nimport type { PluginOption } from './types.ts'\n\n/**\n * Resolves a comma-separated plugin flag (e.g. `--plugins plugin-ts,plugin-zod`) into the\n * matching known plugin options. Unrecognized names are dropped, and a missing flag yields\n * an empty list.\n */\nexport function resolvePlugins(pluginsFlag: string | undefined): Array<PluginOption> {\n if (!pluginsFlag) {\n return []\n }\n const requested = pluginsFlag\n .split(',')\n .map((value) => value.trim())\n .filter(Boolean)\n return availablePlugins.filter((plugin) => requested.includes(plugin.value))\n}\n\nexport function generateConfigFile({\n selectedPlugins,\n inputPath,\n outputPath,\n}: {\n selectedPlugins: Array<PluginOption>\n inputPath: string\n outputPath: string\n}): string {\n const imports = selectedPlugins.map((plugin) => `import { ${plugin.importName} } from '${plugin.packageName}'`).join('\\n')\n\n const pluginConfigs = selectedPlugins.map((plugin) => ` ${plugin.importName}(),`).join('\\n')\n\n return `import { defineConfig } from 'kubb/config'\n${imports}\n\nexport default defineConfig({\n input: '${inputPath}',\n output: {\n path: '${outputPath}',\n clean: true,\n },\n plugins: [\n${pluginConfigs}\n ],\n})\n`\n}\n\n/**\n * Turns package names into install specifiers for the wizard.\n *\n * `kubb` is pinned to the exact version of the running CLI, since both ship from the same release\n * and resolving `kubb@beta` separately can land on a different version than the CLI doing the\n * scaffolding. Plugins release from their own repo on their own cadence, so they follow the\n * release channel of the CLI through its dist-tag.\n */\nexport function resolveInstallVersions({ packages, version }: { packages: Array<string>; version: string }): Array<string> {\n const prerelease = version.match(/-([a-z]+)/)?.[1]\n const tag = prerelease ?? 'latest'\n\n return packages.map((name) => (name === KUBB_PACKAGE_NAME ? `${name}@${version}` : `${name}@${tag}`))\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { formatters, linters } from '@internals/utils'\nimport type { Config } from '@kubb/core'\n\n/**\n * The configurable formatter names, mirrored from `Config['output'].format`. Excludes `'auto'`\n * (detection, not a tool) and `false` (skip). The `formatters`/`linters` tables below are pinned to\n * these so adding a tool to the config union without a descriptor fails to compile.\n */\ntype FormatterName = Exclude<NonNullable<Config['output']['format']>, 'auto' | false>\ntype LinterName = Exclude<NonNullable<Config['output']['lint']>, 'auto' | false>\n\n// Pinned to core's union here rather than in `@internals/utils`, which must not import `@kubb/core`:\n// adding a tool to the config union without a descriptor stays a compile error.\nformatters satisfies Record<FormatterName, unknown>\nlinters satisfies Record<LinterName, unknown>\n\nexport { detectTool, formatters, linters } from '@internals/utils'\n\nexport type PackageManagerName = 'npm' | 'pnpm' | 'yarn' | 'bun'\n\n/**\n * Metadata describing a package manager's lock file and install command.\n */\nexport interface PackageManagerInfo {\n /**\n * Identifier used in CLI commands, e.g. `pnpm`, `yarn`.\n */\n name: PackageManagerName\n /**\n * Lock file name that uniquely identifies this package manager in a project root.\n */\n lockFile: string\n /**\n * Subcommands passed to the package manager binary to install a dev dependency.\n */\n installCommand: ReadonlyArray<string>\n}\n\n/**\n * Metadata for each supported package manager, keyed by its short name.\n *\n * @example\n * ```ts\n * packageManagers.pnpm.installCommand // ['add', '-D']\n * packageManagers.npm.lockFile // 'package-lock.json'\n * ```\n */\nconst packageManagers: Record<PackageManagerName, PackageManagerInfo> = {\n pnpm: {\n name: 'pnpm',\n lockFile: 'pnpm-lock.yaml',\n installCommand: ['add', '-D'],\n },\n yarn: {\n name: 'yarn',\n lockFile: 'yarn.lock',\n installCommand: ['add', '-D'],\n },\n bun: {\n name: 'bun',\n lockFile: 'bun.lockb',\n installCommand: ['add', '-d'],\n },\n npm: {\n name: 'npm',\n lockFile: 'package-lock.json',\n installCommand: ['install', '--save-dev'],\n },\n}\n\n/**\n * Minimal shape of `package.json` fields read during detection.\n */\ntype PackageJson = {\n /**\n * The `packageManager` field from `package.json` (e.g. `\"pnpm@9.0.0\"`).\n */\n packageManager?: string\n}\n\n/**\n * Detects the active package manager for the given directory.\n * Resolution order: `packageManager` field in `package.json`, then presence of a lock file.\n * Falls back to `npm` when no signal is found.\n *\n * @example\n * ```ts\n * detectPackageManager('/my/project') // { name: 'pnpm', lockFile: 'pnpm-lock.yaml', ... }\n * detectPackageManager() // falls back to npm when no lock file is found\n * ```\n */\nexport function detectPackageManager(cwd: string = process.cwd()): PackageManagerInfo {\n const packageJsonPath = join(cwd, 'package.json')\n if (existsSync(packageJsonPath)) {\n try {\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as PackageJson\n const pmField = packageJson.packageManager\n if (typeof pmField === 'string') {\n const name = pmField.split('@')[0]\n if (name && name in packageManagers) {\n return packageManagers[name as PackageManagerName]\n }\n }\n } catch {\n // Continue to lock file detection\n }\n }\n\n for (const pm of Object.values(packageManagers)) {\n if (existsSync(join(cwd, pm.lockFile))) {\n return pm\n }\n }\n\n return packageManagers.npm\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { x } from 'tinyexec'\nimport type { PackageManagerInfo, PackageManagerName } from '../../tools.ts'\n\n/**\n * Returns `true` when a `package.json` exists at `cwd`.\n */\nexport function hasPackageJson(cwd: string = process.cwd()): boolean {\n return fs.existsSync(path.join(cwd, 'package.json'))\n}\n\n/**\n * Initializes a new `package.json` at `cwd` using the detected package manager.\n */\nexport async function initPackageJson(cwd: string, packageManager: PackageManagerInfo): Promise<void> {\n const commands: Record<PackageManagerName, Array<string>> = {\n npm: ['init', '-y'],\n pnpm: ['init'],\n yarn: ['init', '-y'],\n bun: ['init', '-y'],\n }\n\n await x(packageManager.name, commands[packageManager.name], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n\n/**\n * Installs the given packages at `cwd` using the detected package manager.\n */\nexport async function installPackages(packages: Array<string>, packageManager: PackageManagerInfo, cwd: string = process.cwd()): Promise<void> {\n await x(packageManager.name, [...packageManager.installCommand, ...packages], {\n nodeOptions: { cwd, stdio: 'inherit' },\n throwOnError: true,\n })\n}\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport type { DryRunExtension } from '@gunshi/plugin-dryrun'\nimport {\n availablePlugins,\n generateConfigFile,\n initDefaults,\n KUBB_CONFIG_FILENAME,\n KUBB_PACKAGE_NAME,\n type PluginOption,\n resolveInstallVersions,\n resolvePlugins,\n} from '@internals/shared'\nimport { createSpinner, logError, logInfo, logIntro, logOutro, logWarn } from '../../loggers/output.ts'\nimport { hasPackageJson, initPackageJson, installPackages } from './utils.ts'\nimport { detectPackageManager } from '../../tools.ts'\n\nfunction cancelAndExit(message = 'Operation canceled.'): never {\n clack.cancel(message)\n process.exit(0)\n}\n\ntype InitOptions = {\n /**\n * When `true`, skips all interactive prompts and uses default values.\n */\n yes: boolean\n /**\n * Current `@kubb/cli` version string, shown in the closing outro.\n */\n version: string\n /**\n * Input path flag value from `--input`. When provided, skips the input prompt.\n */\n input?: string\n /**\n * Output directory flag value from `--output`. When provided, skips the output prompt.\n */\n output?: string\n /**\n * Comma-separated plugin list from `--plugins`, e.g. `'plugin-ts,plugin-zod'`. When provided, skips the plugin selection prompt.\n */\n plugins?: string\n /**\n * Dry-run extension from `@gunshi/plugin-dryrun`. When enabled, package installation and the\n * config file write are skipped.\n */\n dryRun: DryRunExtension\n}\n\n/**\n * Runs the interactive Kubb scaffolding wizard.\n * Detects the package manager, prompts for input/output paths and plugins, installs packages, and writes `kubb.config.ts`.\n * Pass `yes: true` to skip all prompts and use defaults.\n */\nexport async function run({ yes, version, input: inputFlag, output: outputFlag, plugins: pluginsFlag, dryRun }: InitOptions): Promise<void> {\n const cwd = process.cwd()\n\n logIntro({ title: styleText('bgCyan', styleText('black', ' Kubb Init ')) })\n\n /**\n * Returns `flag` when provided, the `defaultValue` when `yes` is set,\n * or calls `prompt()` for interactive input. Exits on cancellation.\n */\n async function resolveOrPrompt<T>(flag: T | undefined, defaultValue: T, logLabel: string, prompt: () => Promise<T | symbol>): Promise<T> {\n if (flag !== undefined) {\n logInfo(`${logLabel}: ${styleText('cyan', String(flag))}`)\n return flag\n }\n if (yes) {\n logInfo(`${logLabel}: ${styleText('cyan', String(defaultValue))}`)\n return defaultValue\n }\n const result = await prompt()\n if (clack.isCancel(result)) cancelAndExit()\n return result as T\n }\n\n try {\n // Check/create package.json, detect package manager once after the block\n if (!hasPackageJson(cwd)) {\n if (!yes) {\n const shouldInit = await clack.confirm({\n message: 'No package.json found. Would you like to create one?',\n initialValue: true,\n })\n\n if (clack.isCancel(shouldInit) || !shouldInit) {\n cancelAndExit()\n }\n }\n\n const packageManager = detectPackageManager(cwd)\n const spinner = createSpinner()\n spinner.start(`Initializing package.json with ${packageManager.name}`)\n await initPackageJson(cwd, packageManager)\n spinner.stop(`Created package.json with ${packageManager.name}`)\n }\n\n const packageManager = detectPackageManager(cwd)\n if (hasPackageJson(cwd)) {\n logInfo(`Detected package manager: ${styleText('cyan', packageManager.name)}`)\n }\n\n // Prompt for OpenAPI spec path\n const inputPath = await resolveOrPrompt(inputFlag, initDefaults.inputPath, 'Using input path', () =>\n clack.text({\n message: 'Where is your OpenAPI specification located?',\n placeholder: initDefaults.inputPath,\n defaultValue: initDefaults.inputPath,\n validate: (value) => {\n if (!value) return 'Input path is required'\n },\n }),\n )\n\n // Prompt for output directory\n const outputPath = await resolveOrPrompt(outputFlag, initDefaults.outputPath, 'Using output path', () =>\n clack.text({\n message: 'Where should the generated files be output?',\n placeholder: initDefaults.outputPath,\n defaultValue: initDefaults.outputPath,\n validate: (value) => {\n if (!value) return 'Output path is required'\n },\n }),\n )\n\n // Plugin selection\n const defaultPlugins = availablePlugins.filter((p) => (initDefaults.plugins as ReadonlyArray<string>).includes(p.value))\n const pluginLabel = (plugins: Array<PluginOption>) => styleText('cyan', plugins.map((p) => p.label).join(', '))\n\n const selectedPlugins: Array<PluginOption> = await (async () => {\n if (pluginsFlag) {\n const plugins = resolvePlugins(pluginsFlag)\n if (plugins.length === 0) {\n logWarn(`No valid plugins found in --plugins value; falling back to default: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n logInfo(`Using plugins: ${pluginLabel(plugins)}`)\n return plugins\n }\n if (yes) {\n logInfo(`Using plugins: ${pluginLabel(defaultPlugins)}`)\n return defaultPlugins\n }\n const values = await clack.multiselect({\n message: 'Select plugins to use:',\n options: availablePlugins.map(({ value, label, hint }) => ({ value, label, hint })),\n initialValues: [...initDefaults.plugins],\n required: true,\n })\n if (clack.isCancel(values)) cancelAndExit()\n return availablePlugins.filter((p) => (values as Array<string>).includes(p.value))\n })()\n\n // Install packages, matching the release of the running CLI\n const packagesToInstall = resolveInstallVersions({ packages: [KUBB_PACKAGE_NAME, ...selectedPlugins.map((p) => p.packageName)], version })\n\n const spinner = createSpinner()\n spinner.start(`Installing ${packagesToInstall.length} packages with ${packageManager.name}`)\n\n try {\n await dryRun.run(() => installPackages(packagesToInstall, packageManager, cwd), {\n message: `install ${packagesToInstall.length} packages with ${packageManager.name}`,\n })\n spinner.stop(`Installed ${packagesToInstall.length} packages`)\n } catch (error) {\n spinner.stop('Installation failed')\n throw error\n }\n\n // Generate config file\n const configSpinner = createSpinner()\n configSpinner.start(`Creating ${KUBB_CONFIG_FILENAME}`)\n\n const configContent = generateConfigFile({ selectedPlugins, inputPath, outputPath })\n const configPath = path.join(cwd, KUBB_CONFIG_FILENAME)\n\n if (fs.existsSync(configPath)) {\n configSpinner.stop(`${KUBB_CONFIG_FILENAME} already exists`)\n\n if (!yes) {\n const shouldOverwrite = await clack.confirm({\n message: `${KUBB_CONFIG_FILENAME} already exists. Overwrite?`,\n initialValue: false,\n })\n\n if (clack.isCancel(shouldOverwrite) || !shouldOverwrite) {\n cancelAndExit('Keeping existing configuration. Packages have been installed.')\n }\n }\n\n configSpinner.start(`Overwriting ${KUBB_CONFIG_FILENAME}`)\n }\n\n await dryRun.run(() => fs.promises.writeFile(configPath, configContent, 'utf-8'), { message: `write ${KUBB_CONFIG_FILENAME}` })\n\n configSpinner.stop(`Created ${KUBB_CONFIG_FILENAME}`)\n\n logOutro(\n styleText('green', '✓ All set!') +\n '\\n\\n' +\n styleText('dim', 'Next steps:') +\n '\\n' +\n styleText('cyan', ` 1. Make sure your OpenAPI spec is at: ${inputPath}`) +\n '\\n' +\n styleText('cyan', ' 2. Generate code with: npx kubb generate') +\n '\\n' +\n styleText('cyan', ` 3. Find generated files in: ${outputPath}`) +\n '\\n\\n' +\n styleText('dim', `Using ${packageManager.name} • Kubb v${version}`),\n )\n } catch (error) {\n logError(styleText('red', 'An error occurred during initialization'))\n if (error instanceof Error) {\n logError(error.message)\n }\n process.exit(1)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAQA,SAAgB,eAAe,aAAsD;CACnF,IAAI,CAAC,aACH,OAAO,CAAC;CAEV,MAAM,YAAY,YACf,MAAM,GAAG,CAAC,CACV,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,CAC5B,OAAO,OAAO;CACjB,OAAO,iBAAiB,QAAQ,WAAW,UAAU,SAAS,OAAO,KAAK,CAAC;AAC7E;AAEA,SAAgB,mBAAmB,EACjC,iBACA,WACA,cAKS;CAKT,OAAO;EAJS,gBAAgB,KAAK,WAAW,YAAY,OAAO,WAAW,WAAW,OAAO,YAAY,EAAE,CAAC,CAAC,KAAK,IAK/G,EAA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A+D;GAEjF;GAEA,cAAc,MAAM,eAAe,sBAAsB;EAC3D;EAEA,MAAM,OAAO,UAAU,GAAG,SAAS,UAAU,YAAY,eAAe,OAAO,GAAG,EAAE,SAAS,SAAS,uBAAuB,CAAC;EAE9H,cAAc,KAAK,WAAW,sBAAsB;EAEpD,SACE,UAAU,SAAS,YAAY,IAC7B,SACA,UAAU,OAAO,aAAa,IAC9B,OACA,UAAU,QAAQ,2CAA2C,WAAW,IACxE,OACA,UAAU,QAAQ,4CAA4C,IAC9D,OACA,UAAU,QAAQ,iCAAiC,YAAY,IAC/D,SACA,UAAU,OAAO,SAAS,eAAe,KAAK,WAAW,SAAS,CACtE;CACF,SAAS,OAAO;EACd,SAAS,UAAU,OAAO,yCAAyC,CAAC;EACpE,IAAI,iBAAiB,OACnB,SAAS,MAAM,OAAO;EAExB,UAAQ,KAAK,CAAC;CAChB;AACF"}
@@ -5,7 +5,7 @@
5
5
  */
6
6
  const definition = (0, require("gunshi").define)({
7
7
  name: "studio",
8
- description: "Connect this project to Kubb Studio and generate from the browser. The first run pairs the machine: the CLI shows a code, you approve it in Studio, and the token is stored in ~/.kubb. The connection is read-only unless you grant more with --allowWrite, --allowConfigEdit, --allowInput or --allowExec.",
8
+ description: "Connect this project to Kubb Studio and generate from the browser, or run `snapshot` from CI to publish one from a script. The first run pairs the machine: the CLI shows a code, you approve it in Studio, and the token is stored in ~/.kubb. The connection is read-only unless you grant more with --allowWrite, --allowConfigEdit, --allowInput or --allowExec.",
9
9
  examples: [
10
10
  "kubb studio # connect this project, asking what Studio may do",
11
11
  "kubb studio --allowWrite # grant writing generated files, no question asked",
@@ -14,13 +14,15 @@ const definition = (0, require("gunshi").define)({
14
14
  "kubb studio login # pair this machine without connecting",
15
15
  "kubb studio status # show what this machine is paired as",
16
16
  "kubb studio logout # forget the stored token",
17
- "kubb studio --url http://localhost:3000 # use a self-hosted Studio"
17
+ "kubb studio --url http://localhost:3000 # use a self-hosted Studio",
18
+ "kubb studio snapshot # generate and publish a snapshot from CI",
19
+ "kubb studio snapshot --json # print the snapshot as one JSON object"
18
20
  ].join("\n"),
19
21
  args: {
20
22
  action: {
21
23
  type: "positional",
22
24
  required: false,
23
- description: "connect (default), login, logout or status"
25
+ description: "connect (default), login, logout, status or snapshot"
24
26
  },
25
27
  config: {
26
28
  type: "string",
@@ -67,10 +69,36 @@ const definition = (0, require("gunshi").define)({
67
69
  description: "Info, silent or verbose",
68
70
  short: "l",
69
71
  default: "info"
72
+ },
73
+ token: {
74
+ type: "string",
75
+ description: "Organization CI API key for `snapshot`. Defaults to KUBB_TOKEN"
76
+ },
77
+ id: {
78
+ type: "string",
79
+ description: "`snapshot` only: stable identity for the CI agent, such as a pull request. Auto-detected on GitHub Actions, GitLab CI, Bitbucket Pipelines and CircleCI"
80
+ },
81
+ name: {
82
+ type: "string",
83
+ description: "`snapshot` only: package name for the generated tarball. Defaults to the name in package.json"
84
+ },
85
+ packageVersion: {
86
+ type: "string",
87
+ description: "`snapshot` only: package version for the generated tarball. Defaults to the version in package.json"
88
+ },
89
+ timeout: {
90
+ type: "number",
91
+ description: "`snapshot` only: seconds to wait for the job to finish",
92
+ default: 600
93
+ },
94
+ json: {
95
+ type: "boolean",
96
+ description: "`snapshot` only: print the result as one JSON object instead of a summary",
97
+ default: false
70
98
  }
71
99
  }
72
100
  });
73
101
  //#endregion
74
102
  exports.definition = definition;
75
103
 
76
- //# sourceMappingURL=studio-PDMxqFN0.cjs.map
104
+ //# sourceMappingURL=studio-BQV9CeZK.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"studio-BQV9CeZK.cjs","names":["define"],"sources":["../src/commands/studio.ts"],"sourcesContent":["import { define } from 'gunshi'\n\n/**\n * Declaration only, so listing `kubb --help` never loads `@kubb/studio`. `index.ts` pairs this\n * with the runner through gunshi's `lazy`.\n */\nexport const definition = define({\n name: 'studio',\n description:\n 'Connect this project to Kubb Studio and generate from the browser, or run `snapshot` from CI to publish one from a script. The first run pairs the machine: the CLI shows a code, you approve it in Studio, and the token is stored in ~/.kubb. The connection is read-only unless you grant more with --allowWrite, --allowConfigEdit, --allowInput or --allowExec.',\n examples: [\n 'kubb studio # connect this project, asking what Studio may do',\n 'kubb studio --allowWrite # grant writing generated files, no question asked',\n 'kubb studio --allowWrite --allowExec # also run the formatter, the linter, and postGenerate',\n 'kubb studio --allowConfigEdit # let Studio change plugin options in kubb.config.ts',\n 'kubb studio login # pair this machine without connecting',\n 'kubb studio status # show what this machine is paired as',\n 'kubb studio logout # forget the stored token',\n 'kubb studio --url http://localhost:3000 # use a self-hosted Studio',\n 'kubb studio snapshot # generate and publish a snapshot from CI',\n 'kubb studio snapshot --json # print the snapshot as one JSON object',\n ].join('\\n'),\n args: {\n action: {\n type: 'positional',\n required: false,\n description: 'connect (default), login, logout, status or snapshot',\n },\n config: {\n type: 'string',\n description: 'Path to the Kubb config',\n short: 'c',\n },\n url: {\n type: 'string',\n description: 'Base URL of the Kubb Studio instance',\n },\n allowWrite: {\n type: 'boolean',\n description: 'Write generated files to disk. Asked for once per project when omitted',\n default: false,\n },\n allowConfigEdit: {\n type: 'boolean',\n description: 'Let Studio change plugin options in kubb.config.ts. Asked for once per project when omitted',\n default: false,\n },\n allowInput: {\n type: 'boolean',\n description: 'Generate from an OpenAPI spec sent by Studio instead of the one on disk. Asked for once per project when omitted',\n default: false,\n },\n allowExec: {\n type: 'boolean',\n description: 'Run the formatter, the linter, and output.postGenerate after a generation',\n default: false,\n },\n open: {\n type: 'boolean',\n description: 'Open the approval page in a browser while pairing',\n default: true,\n negatable: true,\n },\n logLevel: {\n type: 'enum',\n choices: ['silent', 'info', 'verbose'] as const,\n description: 'Info, silent or verbose',\n short: 'l',\n default: 'info',\n },\n token: {\n type: 'string',\n description: 'Organization CI API key for `snapshot`. Defaults to KUBB_TOKEN',\n },\n id: {\n type: 'string',\n description:\n '`snapshot` only: stable identity for the CI agent, such as a pull request. Auto-detected on GitHub Actions, GitLab CI, Bitbucket Pipelines and CircleCI',\n },\n name: {\n type: 'string',\n description: '`snapshot` only: package name for the generated tarball. Defaults to the name in package.json',\n },\n packageVersion: {\n type: 'string',\n description: '`snapshot` only: package version for the generated tarball. Defaults to the version in package.json',\n },\n timeout: {\n type: 'number',\n description: '`snapshot` only: seconds to wait for the job to finish',\n default: 600,\n },\n json: {\n type: 'boolean',\n description: '`snapshot` only: print the result as one JSON object instead of a summary',\n default: false,\n },\n },\n})\n"],"mappings":";;;;;AAMA,MAAa,cAAA,mBAAaA,CAAAA,CAAAA,OAAAA,CAAO;CAC/B,MAAM;CACN,aACE;CACF,UAAU;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;CACX,MAAM;EACJ,QAAQ;GACN,MAAM;GACN,UAAU;GACV,aAAa;EACf;EACA,QAAQ;GACN,MAAM;GACN,aAAa;GACb,OAAO;EACT;EACA,KAAK;GACH,MAAM;GACN,aAAa;EACf;EACA,YAAY;GACV,MAAM;GACN,aAAa;GACb,SAAS;EACX;EACA,iBAAiB;GACf,MAAM;GACN,aAAa;GACb,SAAS;EACX;EACA,YAAY;GACV,MAAM;GACN,aAAa;GACb,SAAS;EACX;EACA,WAAW;GACT,MAAM;GACN,aAAa;GACb,SAAS;EACX;EACA,MAAM;GACJ,MAAM;GACN,aAAa;GACb,SAAS;GACT,WAAW;EACb;EACA,UAAU;GACR,MAAM;GACN,SAAS;IAAC;IAAU;IAAQ;GAAS;GACrC,aAAa;GACb,OAAO;GACP,SAAS;EACX;EACA,OAAO;GACL,MAAM;GACN,aAAa;EACf;EACA,IAAI;GACF,MAAM;GACN,aACE;EACJ;EACA,MAAM;GACJ,MAAM;GACN,aAAa;EACf;EACA,gBAAgB;GACd,MAAM;GACN,aAAa;EACf;EACA,SAAS;GACP,MAAM;GACN,aAAa;GACb,SAAS;EACX;EACA,MAAM;GACJ,MAAM;GACN,aAAa;GACb,SAAS;EACX;CACF;AACF,CAAC"}
@@ -6,7 +6,7 @@ import { define } from "gunshi";
6
6
  */
7
7
  const definition = define({
8
8
  name: "studio",
9
- description: "Connect this project to Kubb Studio and generate from the browser. The first run pairs the machine: the CLI shows a code, you approve it in Studio, and the token is stored in ~/.kubb. The connection is read-only unless you grant more with --allowWrite, --allowConfigEdit, --allowInput or --allowExec.",
9
+ description: "Connect this project to Kubb Studio and generate from the browser, or run `snapshot` from CI to publish one from a script. The first run pairs the machine: the CLI shows a code, you approve it in Studio, and the token is stored in ~/.kubb. The connection is read-only unless you grant more with --allowWrite, --allowConfigEdit, --allowInput or --allowExec.",
10
10
  examples: [
11
11
  "kubb studio # connect this project, asking what Studio may do",
12
12
  "kubb studio --allowWrite # grant writing generated files, no question asked",
@@ -15,13 +15,15 @@ const definition = define({
15
15
  "kubb studio login # pair this machine without connecting",
16
16
  "kubb studio status # show what this machine is paired as",
17
17
  "kubb studio logout # forget the stored token",
18
- "kubb studio --url http://localhost:3000 # use a self-hosted Studio"
18
+ "kubb studio --url http://localhost:3000 # use a self-hosted Studio",
19
+ "kubb studio snapshot # generate and publish a snapshot from CI",
20
+ "kubb studio snapshot --json # print the snapshot as one JSON object"
19
21
  ].join("\n"),
20
22
  args: {
21
23
  action: {
22
24
  type: "positional",
23
25
  required: false,
24
- description: "connect (default), login, logout or status"
26
+ description: "connect (default), login, logout, status or snapshot"
25
27
  },
26
28
  config: {
27
29
  type: "string",
@@ -68,10 +70,36 @@ const definition = define({
68
70
  description: "Info, silent or verbose",
69
71
  short: "l",
70
72
  default: "info"
73
+ },
74
+ token: {
75
+ type: "string",
76
+ description: "Organization CI API key for `snapshot`. Defaults to KUBB_TOKEN"
77
+ },
78
+ id: {
79
+ type: "string",
80
+ description: "`snapshot` only: stable identity for the CI agent, such as a pull request. Auto-detected on GitHub Actions, GitLab CI, Bitbucket Pipelines and CircleCI"
81
+ },
82
+ name: {
83
+ type: "string",
84
+ description: "`snapshot` only: package name for the generated tarball. Defaults to the name in package.json"
85
+ },
86
+ packageVersion: {
87
+ type: "string",
88
+ description: "`snapshot` only: package version for the generated tarball. Defaults to the version in package.json"
89
+ },
90
+ timeout: {
91
+ type: "number",
92
+ description: "`snapshot` only: seconds to wait for the job to finish",
93
+ default: 600
94
+ },
95
+ json: {
96
+ type: "boolean",
97
+ description: "`snapshot` only: print the result as one JSON object instead of a summary",
98
+ default: false
71
99
  }
72
100
  }
73
101
  });
74
102
  //#endregion
75
103
  export { definition };
76
104
 
77
- //# sourceMappingURL=studio-DKv2YLJZ.js.map
105
+ //# sourceMappingURL=studio-DUNPmQ5V.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"studio-DUNPmQ5V.js","names":[],"sources":["../src/commands/studio.ts"],"sourcesContent":["import { define } from 'gunshi'\n\n/**\n * Declaration only, so listing `kubb --help` never loads `@kubb/studio`. `index.ts` pairs this\n * with the runner through gunshi's `lazy`.\n */\nexport const definition = define({\n name: 'studio',\n description:\n 'Connect this project to Kubb Studio and generate from the browser, or run `snapshot` from CI to publish one from a script. The first run pairs the machine: the CLI shows a code, you approve it in Studio, and the token is stored in ~/.kubb. The connection is read-only unless you grant more with --allowWrite, --allowConfigEdit, --allowInput or --allowExec.',\n examples: [\n 'kubb studio # connect this project, asking what Studio may do',\n 'kubb studio --allowWrite # grant writing generated files, no question asked',\n 'kubb studio --allowWrite --allowExec # also run the formatter, the linter, and postGenerate',\n 'kubb studio --allowConfigEdit # let Studio change plugin options in kubb.config.ts',\n 'kubb studio login # pair this machine without connecting',\n 'kubb studio status # show what this machine is paired as',\n 'kubb studio logout # forget the stored token',\n 'kubb studio --url http://localhost:3000 # use a self-hosted Studio',\n 'kubb studio snapshot # generate and publish a snapshot from CI',\n 'kubb studio snapshot --json # print the snapshot as one JSON object',\n ].join('\\n'),\n args: {\n action: {\n type: 'positional',\n required: false,\n description: 'connect (default), login, logout, status or snapshot',\n },\n config: {\n type: 'string',\n description: 'Path to the Kubb config',\n short: 'c',\n },\n url: {\n type: 'string',\n description: 'Base URL of the Kubb Studio instance',\n },\n allowWrite: {\n type: 'boolean',\n description: 'Write generated files to disk. Asked for once per project when omitted',\n default: false,\n },\n allowConfigEdit: {\n type: 'boolean',\n description: 'Let Studio change plugin options in kubb.config.ts. Asked for once per project when omitted',\n default: false,\n },\n allowInput: {\n type: 'boolean',\n description: 'Generate from an OpenAPI spec sent by Studio instead of the one on disk. Asked for once per project when omitted',\n default: false,\n },\n allowExec: {\n type: 'boolean',\n description: 'Run the formatter, the linter, and output.postGenerate after a generation',\n default: false,\n },\n open: {\n type: 'boolean',\n description: 'Open the approval page in a browser while pairing',\n default: true,\n negatable: true,\n },\n logLevel: {\n type: 'enum',\n choices: ['silent', 'info', 'verbose'] as const,\n description: 'Info, silent or verbose',\n short: 'l',\n default: 'info',\n },\n token: {\n type: 'string',\n description: 'Organization CI API key for `snapshot`. Defaults to KUBB_TOKEN',\n },\n id: {\n type: 'string',\n description:\n '`snapshot` only: stable identity for the CI agent, such as a pull request. Auto-detected on GitHub Actions, GitLab CI, Bitbucket Pipelines and CircleCI',\n },\n name: {\n type: 'string',\n description: '`snapshot` only: package name for the generated tarball. Defaults to the name in package.json',\n },\n packageVersion: {\n type: 'string',\n description: '`snapshot` only: package version for the generated tarball. Defaults to the version in package.json',\n },\n timeout: {\n type: 'number',\n description: '`snapshot` only: seconds to wait for the job to finish',\n default: 600,\n },\n json: {\n type: 'boolean',\n description: '`snapshot` only: print the result as one JSON object instead of a summary',\n default: false,\n },\n },\n})\n"],"mappings":";;;;;;AAMA,MAAa,aAAa,OAAO;CAC/B,MAAM;CACN,aACE;CACF,UAAU;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;CACX,MAAM;EACJ,QAAQ;GACN,MAAM;GACN,UAAU;GACV,aAAa;EACf;EACA,QAAQ;GACN,MAAM;GACN,aAAa;GACb,OAAO;EACT;EACA,KAAK;GACH,MAAM;GACN,aAAa;EACf;EACA,YAAY;GACV,MAAM;GACN,aAAa;GACb,SAAS;EACX;EACA,iBAAiB;GACf,MAAM;GACN,aAAa;GACb,SAAS;EACX;EACA,YAAY;GACV,MAAM;GACN,aAAa;GACb,SAAS;EACX;EACA,WAAW;GACT,MAAM;GACN,aAAa;GACb,SAAS;EACX;EACA,MAAM;GACJ,MAAM;GACN,aAAa;GACb,SAAS;GACT,WAAW;EACb;EACA,UAAU;GACR,MAAM;GACN,SAAS;IAAC;IAAU;IAAQ;GAAS;GACrC,aAAa;GACb,OAAO;GACP,SAAS;EACX;EACA,OAAO;GACL,MAAM;GACN,aAAa;EACf;EACA,IAAI;GACF,MAAM;GACN,aACE;EACJ;EACA,MAAM;GACJ,MAAM;GACN,aAAa;EACf;EACA,gBAAgB;GACd,MAAM;GACN,aAAa;EACf;EACA,SAAS;GACP,MAAM;GACN,aAAa;GACb,SAAS;EACX;EACA,MAAM;GACJ,MAAM;GACN,aAAa;GACb,SAAS;EACX;CACF;AACF,CAAC"}
@@ -1,13 +1,14 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-qbf5tadS.cjs");
2
2
  const require_errors = require("./errors-C-wEou02.cjs");
3
- const require_Telemetry = require("./Telemetry-C-y1OMHs.cjs");
4
- const require_env = require("./env-DHaFBZTX.cjs");
3
+ const require_agent = require("./agent-BPqs9VRj.cjs");
4
+ const require_Telemetry = require("./Telemetry-CvHQevSK.cjs");
5
+ const require_output = require("./output-kmklyYIv.cjs");
5
6
  let node_util = require("node:util");
6
7
  let node_crypto = require("node:crypto");
7
8
  let node_process = require("node:process");
8
9
  node_process = require_rolldown_runtime.__toESM(node_process, 1);
9
- let node_path = require("node:path");
10
10
  let node_child_process = require("node:child_process");
11
+ let node_path = require("node:path");
11
12
  let _kubb_core = require("@kubb/core");
12
13
  let _clack_prompts = require("@clack/prompts");
13
14
  _clack_prompts = require_rolldown_runtime.__toESM(_clack_prompts, 1);
@@ -863,14 +864,29 @@ function formatCommandWithArgs(command, args) {
863
864
  * {@link GenerationResult} on `kubb:generation:end`. The reporter never touches the emitter.
864
865
  */
865
866
  function installReporter(context, reporter, ctx) {
867
+ const pluginFiles = reporter.needsPluginFiles ? /* @__PURE__ */ new Map() : void 0;
868
+ if (pluginFiles) context.hook("kubb:plugin:end", ({ config, plugin, files }) => {
869
+ const filesByPlugin = pluginFiles.get(config) ?? /* @__PURE__ */ new Map();
870
+ const seen = new Set([...filesByPlugin.values()].flatMap((paths) => [...paths]));
871
+ const added = files.filter((file) => !seen.has(file.path)).map((file) => file.path);
872
+ if (added.length) filesByPlugin.set(plugin.name, /* @__PURE__ */ new Set([...filesByPlugin.get(plugin.name) ?? [], ...added]));
873
+ pluginFiles.set(config, filesByPlugin);
874
+ });
866
875
  context.hook("kubb:generation:end", async ({ config, diagnostics = [], filesCreated = 0, status = "success", hrStart = node_process.default.hrtime() }) => {
876
+ const files = pluginFiles?.get(config);
877
+ const grouped = files && [...files].map(([plugin, paths]) => ({
878
+ plugin,
879
+ files: [...paths]
880
+ }));
867
881
  await reporter.report({
868
882
  config,
869
883
  diagnostics,
870
884
  filesCreated,
871
885
  status,
872
- hrStart
886
+ hrStart,
887
+ pluginFiles: grouped
873
888
  }, ctx);
889
+ pluginFiles?.delete(config);
874
890
  });
875
891
  if (reporter.drain) context.hook("kubb:lifecycle:end", () => reporter.drain?.(ctx));
876
892
  }
@@ -891,7 +907,7 @@ async function setupReporters(context, { logLevel, reporters }) {
891
907
  for (const reporter of reporters) {
892
908
  if (reporter.name === "cli") {
893
909
  if (hasJson) continue;
894
- await (require_env.canUseTTY() && !require_env.getAgentName() ? clackLogger : plainLogger).install(context, { logLevel });
910
+ await (require_output.canUseTTY() && !require_agent.getAgentName() ? clackLogger : plainLogger).install(context, { logLevel });
895
911
  }
896
912
  installReporter(context, reporter, ctx);
897
913
  }
@@ -1330,4 +1346,4 @@ Object.defineProperty(exports, "startWatcher", {
1330
1346
  }
1331
1347
  });
1332
1348
 
1333
- //# sourceMappingURL=utils-BgEQilnN.cjs.map
1349
+ //# sourceMappingURL=utils-CMU1rLfY.cjs.map