@kubb/cli 5.4.1 → 5.4.3

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 (89) hide show
  1. package/dist/background-BR0Ipfrd.js +2 -0
  2. package/dist/{background-CNHhnQ5M.cjs → background-Ce9VMMKw.cjs} +2 -2
  3. package/dist/{background-CNHhnQ5M.cjs.map → background-Ce9VMMKw.cjs.map} +1 -1
  4. package/dist/{background-BDZa6MJS.js → background-Cx8cJj7Y.js} +2 -2
  5. package/dist/{background-BDZa6MJS.js.map → background-Cx8cJj7Y.js.map} +1 -1
  6. package/dist/{connect-CIVmP_6l.js → connect-BIu_PSH-.js} +2 -2
  7. package/dist/{connect-CIVmP_6l.js.map → connect-BIu_PSH-.js.map} +1 -1
  8. package/dist/{connect-DLbFBfoV.cjs → connect-DdHw57kt.cjs} +2 -2
  9. package/dist/{connect-DLbFBfoV.cjs.map → connect-DdHw57kt.cjs.map} +1 -1
  10. package/dist/{generate-BWwjYxN5.cjs → generate-DPHF7HZV.cjs} +2 -2
  11. package/dist/{generate-BWwjYxN5.cjs.map → generate-DPHF7HZV.cjs.map} +1 -1
  12. package/dist/{generate-BY_PbRPu.js → generate-VO87PyfI.js} +2 -2
  13. package/dist/{generate-BY_PbRPu.js.map → generate-VO87PyfI.js.map} +1 -1
  14. package/dist/index.cjs +7 -7
  15. package/dist/index.js +7 -7
  16. package/dist/{init-Dpa1wuah.js → init-BBxc642Q.js} +3 -3
  17. package/dist/{init-Dpa1wuah.js.map → init-BBxc642Q.js.map} +1 -1
  18. package/dist/{init-yb2ZIQwp.cjs → init-DC9FUoxj.cjs} +3 -3
  19. package/dist/{init-yb2ZIQwp.cjs.map → init-DC9FUoxj.cjs.map} +1 -1
  20. package/dist/{login-LVIZdclC.cjs → login-B_izuxO_.cjs} +2 -2
  21. package/dist/{login-LVIZdclC.cjs.map → login-B_izuxO_.cjs.map} +1 -1
  22. package/dist/{login-Di6_DU_V.js → login-CpU9BK7b.js} +2 -2
  23. package/dist/{login-Di6_DU_V.js.map → login-CpU9BK7b.js.map} +1 -1
  24. package/dist/{logout-BOhSROh8.js → logout-CqkHzQH1.js} +3 -3
  25. package/dist/{logout-BOhSROh8.js.map → logout-CqkHzQH1.js.map} +1 -1
  26. package/dist/{logout-B8L-Jb8P.cjs → logout-Di36A0n6.cjs} +3 -3
  27. package/dist/{logout-B8L-Jb8P.cjs.map → logout-Di36A0n6.cjs.map} +1 -1
  28. package/dist/{output-D-9bGS7y.cjs → output-9qUFmWFq.cjs} +2 -2
  29. package/dist/{output-D-9bGS7y.cjs.map → output-9qUFmWFq.cjs.map} +1 -1
  30. package/dist/{output-C5h3LBgQ.js → output-Dkoh9Ig6.js} +32 -32
  31. package/dist/{output-C5h3LBgQ.js.map → output-Dkoh9Ig6.js.map} +1 -1
  32. package/dist/{package-DjS7Xk-S.cjs → package-B4G0q-YP.cjs} +2 -2
  33. package/dist/package-B4G0q-YP.cjs.map +1 -0
  34. package/dist/package-CfCLgvAl.js +6 -0
  35. package/dist/package-CfCLgvAl.js.map +1 -0
  36. package/dist/{run-_hE0GAWu.cjs → run-0D4BZdd3.cjs} +8 -10
  37. package/dist/run-0D4BZdd3.cjs.map +1 -0
  38. package/dist/{run-G2lUygYI.js → run-BH26mNIp.js} +2 -2
  39. package/dist/{run-G2lUygYI.js.map → run-BH26mNIp.js.map} +1 -1
  40. package/dist/{run-BNQt-kUj.cjs → run-BY1obXw_.cjs} +2 -2
  41. package/dist/{run-BNQt-kUj.cjs.map → run-BY1obXw_.cjs.map} +1 -1
  42. package/dist/{run-DQNoMoHW.js → run-BdeIqfMV.js} +4 -4
  43. package/dist/{run-DQNoMoHW.js.map → run-BdeIqfMV.js.map} +1 -1
  44. package/dist/{run-Bidc3n3b.cjs → run-BhRWMu9D.cjs} +2 -2
  45. package/dist/{run-Bidc3n3b.cjs.map → run-BhRWMu9D.cjs.map} +1 -1
  46. package/dist/{run-BsP5syy1.js → run-C1SWZ9eL.js} +8 -10
  47. package/dist/run-C1SWZ9eL.js.map +1 -0
  48. package/dist/{run-GGJ4QLsg.cjs → run-D0wlQfZ8.cjs} +2 -2
  49. package/dist/{run-GGJ4QLsg.cjs.map → run-D0wlQfZ8.cjs.map} +1 -1
  50. package/dist/{run-0k75--OI.cjs → run-DI7XBIsh.cjs} +4 -4
  51. package/dist/{run-0k75--OI.cjs.map → run-DI7XBIsh.cjs.map} +1 -1
  52. package/dist/{run-Drf9rg9j.js → run-D_C7iUvw.js} +2 -2
  53. package/dist/{run-Drf9rg9j.js.map → run-D_C7iUvw.js.map} +1 -1
  54. package/dist/{run-BaqE5cze.js → run-OrUv1xEc.js} +2 -2
  55. package/dist/{run-BaqE5cze.js.map → run-OrUv1xEc.js.map} +1 -1
  56. package/dist/{snapshot-ZY24CtRk.js → snapshot-8XW1pmpz.js} +4 -4
  57. package/dist/{snapshot-ZY24CtRk.js.map → snapshot-8XW1pmpz.js.map} +1 -1
  58. package/dist/{snapshot-DndnZx5y.cjs → snapshot-BX3KCMWD.cjs} +4 -4
  59. package/dist/{snapshot-DndnZx5y.cjs.map → snapshot-BX3KCMWD.cjs.map} +1 -1
  60. package/dist/{start-Bu5xpzix.cjs → start-DI5M1g92.cjs} +3 -3
  61. package/dist/{start-Bu5xpzix.cjs.map → start-DI5M1g92.cjs.map} +1 -1
  62. package/dist/{start-BlwmWZDb.js → start-Dx9F16X8.js} +3 -3
  63. package/dist/{start-BlwmWZDb.js.map → start-Dx9F16X8.js.map} +1 -1
  64. package/dist/{status-5UqQP9WB.js → status-DLbxVdwR.js} +3 -3
  65. package/dist/{status-5UqQP9WB.js.map → status-DLbxVdwR.js.map} +1 -1
  66. package/dist/{status-L4I8buia.cjs → status-hQ-QcLwq.cjs} +3 -3
  67. package/dist/{status-L4I8buia.cjs.map → status-hQ-QcLwq.cjs.map} +1 -1
  68. package/dist/{stop-BQkjAPNH.cjs → stop-KwKHpVjZ.cjs} +2 -2
  69. package/dist/{stop-BQkjAPNH.cjs.map → stop-KwKHpVjZ.cjs.map} +1 -1
  70. package/dist/{stop-mqUTbxMO.js → stop-Sy9iOohk.js} +2 -2
  71. package/dist/{stop-mqUTbxMO.js.map → stop-Sy9iOohk.js.map} +1 -1
  72. package/dist/{studio-BFy085ae.cjs → studio-BWsI-OYx.cjs} +9 -9
  73. package/dist/{studio-BFy085ae.cjs.map → studio-BWsI-OYx.cjs.map} +1 -1
  74. package/dist/{studio-BBnIuXst.js → studio-CfG8y4pJ.js} +9 -9
  75. package/dist/{studio-BBnIuXst.js.map → studio-CfG8y4pJ.js.map} +1 -1
  76. package/dist/studioWorker.js +2 -2
  77. package/dist/{utils-BWksgOYQ.js → utils-BYY3_cyq.js} +266 -266
  78. package/dist/utils-BYY3_cyq.js.map +1 -0
  79. package/dist/{utils-DqUNntyL.cjs → utils-Dcw3l4Wz.cjs} +9 -3
  80. package/dist/utils-Dcw3l4Wz.cjs.map +1 -0
  81. package/package.json +8 -8
  82. package/dist/background-CS7jIBAY.js +0 -2
  83. package/dist/package-DjS7Xk-S.cjs.map +0 -1
  84. package/dist/package-IY922xjh.js +0 -6
  85. package/dist/package-IY922xjh.js.map +0 -1
  86. package/dist/run-BsP5syy1.js.map +0 -1
  87. package/dist/run-_hE0GAWu.cjs.map +0 -1
  88. package/dist/utils-BWksgOYQ.js.map +0 -1
  89. package/dist/utils-DqUNntyL.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils-BYY3_cyq.js","names":["logLevel","logLevelMap","logLevel","logLevelMap"],"sources":["../../../internals/utils/src/tools.ts","../../../internals/shared/src/loader.ts","../src/loggers/clackLogger.ts","../src/loggers/utils.ts","../src/loggers/createLogger.ts","../src/loggers/plainLogger.ts","../src/runners/generate/utils.ts"],"sourcesContent":["import { spawn } from 'node:child_process'\n\n/**\n * How one formatter or linter is invoked: the executable, the argv it takes for an output\n * directory, and what to report when it is not installed.\n */\nexport type ToolCommand = {\n command: string\n args: (outputPath: string) => Array<string>\n errorMessage: string\n}\n\n/**\n * CLI command descriptors for each supported code formatter.\n */\nexport const formatters = {\n prettier: {\n command: 'prettier',\n args: (outputPath: string) => ['--ignore-unknown', '--write', outputPath],\n errorMessage: 'Prettier not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['format', '--write', outputPath],\n errorMessage: 'Biome not found',\n },\n oxfmt: {\n command: 'oxfmt',\n args: (outputPath: string) => [outputPath],\n errorMessage: 'Oxfmt not found',\n },\n} as const satisfies Record<string, ToolCommand>\n\n/**\n * CLI command descriptors for each supported linter.\n */\nexport const linters = {\n eslint: {\n command: 'eslint',\n args: (outputPath: string) => [outputPath, '--fix'],\n errorMessage: 'Eslint not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['lint', '--fix', outputPath],\n errorMessage: 'Biome not found',\n },\n oxlint: {\n command: 'oxlint',\n // --no-ignore so oxlint lints the folder even when it's gitignored (generated output dirs usually are).\n args: (outputPath: string) => ['--fix', '--no-ignore', outputPath],\n errorMessage: 'Oxlint not found',\n },\n} as const satisfies Record<string, ToolCommand>\n\n/**\n * Preference order for `format: 'auto'`, most-preferred first. Spelled out rather than taken from\n * the table's key order, which is arbitrary and would silently change what `auto` picks.\n */\nexport const FORMATTER_PREFERENCE = ['oxfmt', 'biome', 'prettier'] as const\n\n/**\n * Preference order for `lint: 'auto'`, most-preferred first.\n */\nexport const LINTER_PREFERENCE = ['oxlint', 'biome', 'eslint'] as const\n\n/**\n * Whether `name` is on PATH and answers `--version` with a zero exit.\n */\nexport function isToolAvailable(name: string): Promise<boolean> {\n return new Promise((resolve) => {\n const child = spawn(name, ['--version'], { stdio: 'ignore' })\n child.on('close', (code) => resolve(code === 0))\n child.on('error', () => resolve(false))\n })\n}\n\n/**\n * Returns the first installed executable from `candidates`, or `null` when none are found.\n *\n * Not memoized: a long-running host that probes repeatedly should cache the result itself, and a\n * `--watch` build should keep noticing a tool installed mid-session.\n */\nexport async function detectTool<TName extends string>(candidates: ReadonlyArray<TName>): Promise<TName | null> {\n for (const candidate of candidates) {\n if (await isToolAvailable(candidate)) {\n return candidate\n }\n }\n\n return null\n}\n\n/**\n * Tokenizes a shell command string, respecting single and double quotes.\n *\n * @example\n * ```ts\n * tokenize('git commit -m \"initial commit\"')\n * // → ['git', 'commit', '-m', 'initial commit']\n * ```\n */\nexport function tokenize(command: string): Array<string> {\n return (command.match(/[^\\s\"']+|\"([^\"]*)\"|'([^']*)'/g) ?? []).map((token) => token.replace(/^[\"']|[\"']$/g, ''))\n}\n","import { createJiti } from 'jiti'\n\n/**\n * jiti options for loading Kubb config modules: the automatic JSX runtime pointed at\n * `@kubb/renderer-jsx`, and `moduleCache` off so a re-load re-evaluates the file.\n */\nconst JITI_OPTIONS = {\n jsx: { runtime: 'automatic', importSource: '@kubb/renderer-jsx' },\n moduleCache: false,\n} satisfies Parameters<typeof createJiti>[1]\n\n/**\n * Per-call options for {@link ModuleLoader.load}.\n */\ntype LoadModuleOptions = {\n /**\n * Return the module's default export instead of the full namespace.\n */\n default?: boolean\n}\n\n/**\n * Loads `.ts`/`.js` modules via jiti.\n */\ntype ModuleLoader = {\n load<T = unknown>(filePath: string, options?: LoadModuleOptions): Promise<T>\n}\n\n/**\n * Creates a jiti-based loader for Kubb's TypeScript and JavaScript config modules.\n *\n * jiti transpiles TypeScript and the `@kubb/renderer-jsx` JSX runtime on the fly.\n *\n * @example\n * ```ts\n * const config = await createModuleLoader().load('/abs/kubb.config.ts', { default: true })\n * ```\n */\nexport function createModuleLoader(): ModuleLoader {\n const jiti = createJiti(import.meta.url, JITI_OPTIONS)\n\n return {\n load<T>(filePath: string, options?: LoadModuleOptions) {\n return (options?.default ? jiti.import(filePath, { default: true }) : jiti.import(filePath)) as Promise<T>\n },\n }\n}\n","import { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport { createLogger } from './createLogger.ts'\nimport type { Logger, LoggerWriter } from './defineLogger.ts'\n\n/**\n * Draws with clack: a gutter bar per group, animated steps, and a progress bar for the writes.\n */\nconst writer: LoggerWriter = {\n group: (title) => clack.intro(title),\n groupEnd: (text) => clack.outro(text),\n step: (text) => clack.log.step(text, { spacing: 0 }),\n info: (text) => clack.log.info(text),\n success: (text) => clack.log.success(text),\n warn: (text) => clack.log.warn(text),\n error: (text) => clack.log.error(text),\n block: (lines) => clack.log.message(lines, { spacing: 0 }),\n // A subprocess's output is not Kubb's tree, so it goes out past clack and its gutter bar. The\n // step above it is already stopped by the time this runs.\n raw: (lines) => console.log(styleText('dim', lines.join('\\n'))),\n // The diagnostic carries its own code and indented rows, so clear clack's gutter and bar and let\n // the block stand on its own.\n diagnostic: (lines) => clack.log.message(lines, { symbol: '', secondarySymbol: '' }),\n update: (lines, title) =>\n clack.box(lines.join('\\n'), title, {\n width: 'auto',\n formatBorder: (border: string) => styleText('yellow', border),\n rounded: true,\n withGuide: false,\n contentAlign: 'center',\n titleAlign: 'center',\n }),\n spinner() {\n const spinner = clack.spinner()\n\n return {\n start: (text) => spinner.start(text),\n message: (text) => spinner.message(text),\n clear: () => spinner.clear(),\n stop: (text) => spinner.stop(text),\n error: (text) => spinner.error(text),\n }\n },\n progress(max) {\n const bar = clack.progress({ style: 'block', max, size: 30 })\n\n return {\n start: (text) => bar.start(text),\n advance: (text) => bar.advance(1, text),\n stop: (text) => bar.stop(text),\n }\n },\n}\n\n/**\n * TTY logger for local development, with animated steps and progress bars.\n */\nexport const clackLogger = {\n name: 'clack',\n install: createLogger(writer),\n} satisfies Logger\n","import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { formatMs, getElapsedMs } from '@internals/utils'\nimport type { Config, Reporter, ReporterContext, ReporterPluginFiles } from '@kubb/core'\nimport { createCliReporter, logLevel as logLevelMap } from '@kubb/core'\nimport type { StudioConnectedContext } from '@kubb/studio'\nimport { getAgentName } from '../agent.ts'\nimport { canUseTTY } from '../utils/env.ts'\nimport type { Logger, LoggerContext, LoggerHandle, LoggerOptions } from './defineLogger.ts'\nimport { clackLogger } from './clackLogger.ts'\nimport { plainLogger } from './plainLogger.ts'\n\n/**\n * Display path for a config's input: the string form, or its `path` field when the input is an\n * object. Loggers show it alongside `Generation started`.\n */\nexport function getInputPath(config: Config): string | undefined {\n const { input } = config\n if (typeof input === 'string') return input\n return typeof input?.path === 'string' ? input.path : undefined\n}\n\n/**\n * Counts a noun, so a message never reads `1 files`.\n *\n * @example\n * `pluralize(1, 'config')` returns `'1 config'`\n */\nexport function pluralize(count: number, noun: string): string {\n return `${count} ${count === 1 ? noun : `${noun}s`}`\n}\n\n/**\n * Optionally prefix a message with a [HH:MM:SS] timestamp when logLevel >= verbose.\n * Shared across all logger adapters to avoid duplication.\n */\nexport function formatMessage(message: string, logLevel: number): string {\n if (logLevel >= logLevelMap.verbose) {\n const timestamp = new Date().toLocaleTimeString('en-US', {\n hour12: false,\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n })\n return `${styleText('dim', `[${timestamp}]`)} ${message}`\n }\n return message\n}\n\n/**\n * Renders the versions from a `studio:connected` event as one parenthetical. The runtime is listed\n * only when it differs from the host, and Studio's only when it sent one.\n */\nexport function formatVersions({ studio, kubb, agent }: StudioConnectedContext['versions']): string {\n return [`v${agent}`, kubb !== agent ? `runtime v${kubb}` : undefined, studio ? `Studio v${studio}` : undefined].filter(Boolean).join(', ')\n}\n\n/**\n * Extracts the `.cause` of an `Error` as an `Error`, or `undefined` when absent or not an `Error`.\n */\nfunction toCause(error: Error): Error | undefined {\n return error.cause instanceof Error ? error.cause : undefined\n}\n\n/**\n * First stack frames for verbose error output, including an optional `cause` chain.\n */\nexport function formatErrorFrames(error: Error): { frames: Array<string>; cause?: { header: string; frames: Array<string> } } | null {\n if (!error.stack) {\n return null\n }\n\n const frames = error.stack\n .split('\\n')\n .slice(1, 4)\n .map((frame) => frame.trim())\n const caused = toCause(error)\n\n if (!caused?.stack) {\n return { frames }\n }\n\n return {\n frames,\n cause: {\n header: `└─ caused by ${caused.message}`,\n frames: caused.stack\n .split('\\n')\n .slice(1, 4)\n .map((frame) => frame.trim()),\n },\n }\n}\n\ntype ProgressState = {\n /**\n * Total number of plugins scheduled for this generation run.\n */\n totalPlugins: number\n /**\n * Number of plugins that have finished without error.\n */\n completedPlugins: number\n /**\n * Number of plugins that exited with an error.\n */\n failedPlugins: number\n /**\n * Total number of files expected to be written.\n */\n totalFiles: number\n /**\n * Number of files written so far.\n */\n processedFiles: number\n /**\n * `process.hrtime()` snapshot taken at the start of generation, used to compute elapsed time.\n */\n hrStart: [number, number]\n}\n\n/**\n * Build the progress summary line shown by the clack logger.\n * Returns null when there is nothing to display.\n */\nexport function buildProgressLine(state: ProgressState): string | null {\n const parts: Array<string> = []\n const duration = formatMs(getElapsedMs(state.hrStart))\n\n if (state.totalPlugins > 0) {\n const pluginStr =\n state.failedPlugins > 0\n ? `Plugins ${styleText('green', state.completedPlugins.toString())}/${state.totalPlugins} ${styleText('red', `(${state.failedPlugins} failed)`)}`\n : `Plugins ${styleText('green', state.completedPlugins.toString())}/${state.totalPlugins}`\n parts.push(pluginStr)\n }\n\n if (state.totalFiles > 0) {\n parts.push(`Files ${styleText('green', state.processedFiles.toString())}/${state.totalFiles}`)\n }\n\n if (parts.length === 0) {\n return null\n }\n\n parts.push(`${styleText('green', duration)} elapsed`)\n return parts.join(styleText('dim', ' | '))\n}\n\n/**\n * Creates the per-run progress counters used by the clack logger.\n */\nexport function createProgressCounters(): ProgressState {\n return {\n totalPlugins: 0,\n completedPlugins: 0,\n failedPlugins: 0,\n totalFiles: 0,\n processedFiles: 0,\n hrStart: process.hrtime(),\n }\n}\n\n/**\n * Resets the progress counters in place at the start/end of a generation run.\n */\nexport function resetProgressCounters(state: ProgressState): void {\n state.totalPlugins = 0\n state.completedPlugins = 0\n state.failedPlugins = 0\n state.totalFiles = 0\n state.processedFiles = 0\n state.hrStart = process.hrtime()\n}\n\n/**\n * Records a finished plugin against the progress counters.\n */\nexport function recordPluginResult(state: ProgressState, success: boolean): void {\n if (success) {\n state.completedPlugins++\n } else {\n state.failedPlugins++\n }\n}\n\n/**\n * Tracks per-hook start times so a logger can report a hook's elapsed duration.\n * Used by the plain logger, which keys timing by hook `id`.\n */\ntype HookTimer = {\n start(id: string): void\n /**\n * Returns the elapsed milliseconds since `start(id)`, or `undefined` when no start was recorded.\n */\n end(id: string): number | undefined\n}\n\n/**\n * Creates a {@link HookTimer} backed by a private `id → hrtime` map.\n */\nexport function createHookTimer(): HookTimer {\n const starts = new Map<string, [number, number]>()\n\n return {\n start(id: string): void {\n starts.set(id, process.hrtime())\n },\n end(id: string): number | undefined {\n const hrStart = starts.get(id)\n if (!hrStart) {\n return undefined\n }\n starts.delete(id)\n return getElapsedMs(hrStart)\n },\n }\n}\n\n/**\n * Join a command and its optional args into a single display string.\n *\n * @example With args\n * `formatCommandWithArgs('prettier', ['--write', '.'])` returns `'prettier --write .'`\n */\nexport function formatCommandWithArgs(command: string, args?: ReadonlyArray<string>): string {\n return args?.length ? `${command} ${args.join(' ')}` : command\n}\n\n/**\n * Bridges a {@link Reporter} onto the run's hook emitter: calls `report` with each config's\n * {@link GenerationResult} on `kubb:generation:end`. The reporter never touches the emitter.\n */\nexport function installReporter(context: LoggerContext, reporter: Reporter, ctx: ReporterContext): void {\n const pluginFiles = reporter.needsPluginFiles ? new Map<Config, Map<string, Set<string>>>() : undefined\n\n if (pluginFiles) {\n context.hook('kubb:plugin:end', ({ config, plugin, files }) => {\n const filesByPlugin = pluginFiles.get(config) ?? new Map<string, Set<string>>()\n const seen = new Set([...filesByPlugin.values()].flatMap((paths) => [...paths]))\n const added = files.filter((file) => !seen.has(file.path)).map((file) => file.path)\n\n if (added.length) filesByPlugin.set(plugin.name, new Set([...(filesByPlugin.get(plugin.name) ?? []), ...added]))\n\n pluginFiles.set(config, filesByPlugin)\n })\n }\n\n context.hook('kubb:generation:end', async ({ config, diagnostics = [], filesCreated = 0, status = 'success', hrStart = process.hrtime() }) => {\n const files = pluginFiles?.get(config)\n const grouped: ReporterPluginFiles | undefined = files && [...files].map(([plugin, paths]) => ({ plugin, files: [...paths] }))\n\n await reporter.report({ config, diagnostics, filesCreated, status, hrStart, pluginFiles: grouped }, ctx)\n\n pluginFiles?.delete(config)\n })\n\n if (reporter.drain) {\n context.hook('kubb:lifecycle:end', () => reporter.drain?.(ctx))\n }\n}\n\n/**\n * Installs the live logger (the TUI view) and the given reporters (the output). The reporters are\n * already selected by the caller (the CLI maps `--reporter` to names via `selectReporters`). This\n * only wires them. Loggers receive hook subprocess output through `kubb:hook:line` and the\n * `stdout`/`stderr` on `kubb:hook:end`, so nothing is returned here.\n *\n * Loggers and reporters are independent, except for `cli`: it both installs the live logger view\n * here and registers a reporter that renders the per-config summary through that logger, so the\n * summary lands inside the group the logger opened. The `json` reporter owns stdout, so the whole\n * `cli` reporter (live logger and summary) is skipped whenever `json` is among the reporters, even\n * if `cli` is also listed.\n */\nasync function setupReporters(\n context: LoggerContext,\n {\n logLevel,\n reporters,\n logger: forcedLogger,\n }: LoggerOptions & {\n reporters: ReadonlyArray<Reporter>\n /** Overrides the terminal-based pick, e.g. the plain logger for `kubb studio snapshot`. */\n logger?: Logger\n },\n): Promise<LoggerHandle | undefined> {\n let cliHandle: LoggerHandle | undefined\n const hasJson = reporters.some((reporter) => reporter.name === 'json')\n const ctx: ReporterContext = { logLevel }\n\n for (const reporter of reporters) {\n if (reporter.name !== 'cli') {\n installReporter(context, reporter, ctx)\n continue\n }\n\n if (hasJson) {\n continue\n }\n\n // Spinners and cursor-movement escapes are hard for an AI coding agent to parse, even over a pseudo-TTY.\n const logger = forcedLogger ?? (canUseTTY() && !getAgentName() ? clackLogger : plainLogger)\n const handle = (await logger.install(context, { logLevel })) ?? undefined\n cliHandle = handle\n\n // The summary belongs inside the group the logger opened for this config, so hand the writing\n // to the logger rather than letting the reporter print alongside it.\n installReporter(context, createCliReporter({ render: handle?.renderSummary }), ctx)\n }\n\n return cliHandle\n}\n\nexport default setupReporters\n\n/**\n * Picks the reporters whose `name` matches one of `names`, in the order the names are given.\n * The config carries every available reporter, and the host selects which to activate by name\n * (the CLI maps `--reporter` to this). Duplicate names and names without a matching reporter are\n * skipped.\n */\nexport function selectReporters(reporters: ReadonlyArray<Reporter>, names: ReadonlyArray<string>): Array<Reporter> {\n const seen = new Set<string>()\n const selected: Array<Reporter> = []\n\n for (const name of names) {\n if (seen.has(name)) {\n continue\n }\n seen.add(name)\n\n const reporter = reporters.find((candidate) => candidate.name === name)\n if (reporter) {\n selected.push(reporter)\n }\n }\n\n return selected\n}\n","import { relative } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { formatMs, getElapsedMs } from '@internals/utils'\nimport { Diagnostics, logLevel as logLevelMap } from '@kubb/core'\nimport { formatMsWithColor } from './banner.ts'\nimport type { LoggerContext, LoggerHandle, LoggerOptions, LoggerWriter, LogStatus, WriterProgress, WriterSpinner } from './defineLogger.ts'\nimport {\n buildProgressLine,\n createProgressCounters,\n formatCommandWithArgs,\n formatErrorFrames,\n formatMessage,\n formatVersions,\n getInputPath,\n pluralize,\n recordPluginResult,\n resetProgressCounters,\n} from './utils.ts'\n\n/**\n * One output phase while its step owns the line. A phase buffers what it is told, because a spinner\n * redraws over anything written under it, and prints the lot once it knows its own result.\n */\ntype Phase = {\n successLabel: string\n failureLabel: string\n /**\n * Whether each hook's own result is worth a line. Format and lint run one command, so the phase\n * result already says everything; the post-generate phase runs several.\n */\n showHookResults: boolean\n failed: boolean\n hrStart: [number, number]\n lines: Array<string>\n /**\n * Raw lines a hook printed, drawn outside the group.\n */\n output: Array<string>\n}\n\ntype StartPhaseOptions = {\n /**\n * Shown while the phase runs.\n */\n running: string\n success: string\n failure: string\n showHookResults?: boolean\n}\n\n/**\n * The three output phases, in the order the generate runner runs them.\n */\nconst PHASES = {\n format: { running: 'Formatting', success: 'Formatted', failure: 'Formatting failed' },\n lint: { running: 'Linting', success: 'Linted', failure: 'Linting failed' },\n hooks: {\n running: 'Running post-generate hooks',\n success: 'Post-generate hooks completed',\n failure: 'Post-generate hooks failed',\n showHookResults: true,\n },\n} as const satisfies Record<string, StartPhaseOptions>\n\n/**\n * Drops the blank lines a subprocess leaves at either end of its output, so its block does not open\n * or close on an empty row.\n */\nfunction trimBlankEdges(lines: ReadonlyArray<string>): Array<string> {\n const start = lines.findIndex((line) => line.trim())\n if (start === -1) {\n return []\n }\n\n return lines.slice(start, lines.findLastIndex((line) => line.trim()) + 1)\n}\n\n/**\n * Wires a {@link LoggerWriter} onto the run's hooks. This owns what a run says and in what order:\n * one group per config, a step over the plugin work, a progress bar for the writes, one step per\n * output phase, then the summary and the group's closing result. The writer only decides how each\n * line looks, so every logger reports the same run the same way.\n *\n * @example\n * ```ts\n * export const plainLogger = { name: 'plain', install: (context, options) => createLogger(writer)(context, options) }\n * ```\n */\nexport function createLogger(writer: LoggerWriter) {\n return function install(context: LoggerContext, options?: LoggerOptions): LoggerHandle {\n const logLevel = options?.logLevel ?? logLevelMap.info\n const silent = logLevel <= logLevelMap.silent\n const state = {\n ...createProgressCounters(),\n spinner: null as WriterSpinner | null,\n progress: null as WriterProgress | null,\n hooks: new Map<string, { hrStart: [number, number]; lines: Array<string> }>(),\n /**\n * Plugin results held back while the generation step owns the line.\n */\n pluginLines: [] as Array<string>,\n phase: null as Phase | null,\n groupOpen: false,\n }\n\n function text(message: string): string {\n return formatMessage(message, logLevel)\n }\n\n function startSpinner(message: string) {\n if (silent) {\n return\n }\n\n state.spinner = writer.spinner()\n state.spinner.start(text(message))\n }\n\n function stopSpinner(message?: string, status: LogStatus = 'success') {\n const spinner = state.spinner\n if (!spinner) {\n return\n }\n state.spinner = null\n\n if (message === undefined) {\n spinner.clear()\n return\n }\n if (status === 'failed') {\n spinner.error(text(message))\n return\n }\n spinner.stop(text(message))\n }\n\n function stopProgress(message?: string) {\n const progress = state.progress\n if (!progress) {\n return\n }\n state.progress = null\n progress.stop(message === undefined ? '' : text(message))\n }\n\n function startPhase({ running, success, failure, showHookResults = false }: StartPhaseOptions) {\n state.phase = { successLabel: success, failureLabel: failure, showHookResults, failed: false, hrStart: process.hrtime(), lines: [], output: [] }\n startSpinner(running)\n }\n\n function endPhase() {\n const phase = state.phase\n state.phase = null\n\n if (!phase || silent) {\n return\n }\n\n const duration = formatMsWithColor(getElapsedMs(phase.hrStart))\n\n stopSpinner(phase.failed ? `${phase.failureLabel} after ${duration}` : `${phase.successLabel} in ${duration}`, phase.failed ? 'failed' : 'success')\n\n if (phase.lines.length) {\n writer.block(phase.lines)\n }\n writeOutput(phase.output)\n }\n\n function writeOutput(lines: ReadonlyArray<string>) {\n const output = trimBlankEdges(lines)\n if (output.length) {\n writer.raw(output)\n }\n }\n\n // A run that throws before `kubb:generation:end` never reaches the summary, so the lifecycle\n // end calls this too rather than leave a group without its closing line.\n function closeGroup(status: LogStatus) {\n if (!state.groupOpen) {\n return\n }\n state.groupOpen = false\n\n stopSpinner()\n stopProgress()\n writer.groupEnd(status === 'failed' ? styleText('red', '✗ Generation failed') : styleText('green', '✓ Generation succeeded'))\n }\n\n function reset() {\n stopSpinner()\n stopProgress()\n resetProgressCounters(state)\n state.hooks.clear()\n state.pluginLines = []\n state.phase = null\n state.groupOpen = false\n }\n\n context.hook('kubb:info', ({ message, info }) => {\n if (silent) {\n return\n }\n\n const line = text([styleText('blue', 'ℹ'), message, info ? styleText('dim', info) : undefined].filter(Boolean).join(' '))\n\n // Info carries something new (the auto-detected tool), so inside a phase it waits for the\n // phase to print rather than being spent on a frame the next one overwrites.\n if (state.phase) {\n state.phase.lines.push(line)\n return\n }\n if (state.spinner) {\n state.spinner.message(line)\n return\n }\n writer.info(line)\n })\n\n context.hook('kubb:success', ({ message, info }) => {\n if (silent) {\n return\n }\n\n const line = text([styleText('green', '✓'), message, logLevel >= logLevelMap.info && info ? styleText('dim', info) : undefined].filter(Boolean).join(' '))\n\n // A phase step outlives the successes reported inside it, and its own result says the same\n // thing, so let the step carry them.\n if (state.spinner) {\n state.spinner.message(line)\n return\n }\n writer.success(line)\n })\n\n context.hook('kubb:warn', ({ message, info }) => {\n if (logLevel < logLevelMap.warn) {\n return\n }\n\n writer.warn(\n text([styleText('yellow', '⚠'), message, logLevel >= logLevelMap.info && info ? styleText('dim', info) : undefined].filter(Boolean).join(' ')),\n )\n })\n\n // Unguarded: a failure stays visible even at silent.\n context.hook('kubb:error', ({ error }) => {\n if (state.phase) {\n state.phase.failed = true\n }\n\n const line = [styleText('red', '✗'), error.message].join(' ')\n\n if (state.spinner) {\n stopSpinner(line, 'failed')\n } else {\n writer.error(text(line))\n }\n\n const frames = logLevel >= logLevelMap.verbose ? formatErrorFrames(error) : null\n if (!frames) {\n return\n }\n\n writer.block(frames.frames.map((frame) => text(styleText('dim', frame))))\n if (frames.cause) {\n writer.block([styleText('dim', frames.cause.header), ...frames.cause.frames.map((frame) => text(` ${styleText('dim', frame)}`))])\n }\n })\n\n context.hook('kubb:diagnostic', ({ diagnostic }) => {\n // Silent still surfaces errors so failures stay visible. It drops warnings and info.\n if (silent && diagnostic.severity !== 'error') {\n return\n }\n\n stopSpinner()\n stopProgress()\n\n if (Diagnostics.isUpdate(diagnostic)) {\n writer.update(\n [`\\`v${diagnostic.currentVersion}\\` → \\`v${diagnostic.latestVersion}\\``, 'Run `npm install -g @kubb/cli` to update'],\n 'Update available for `Kubb`',\n )\n return\n }\n\n const { headline, details } = Diagnostics.format(diagnostic)\n writer.diagnostic([headline, ...details])\n })\n\n // A `kubb studio` session emits these on the same emitter as its generations, so one logger\n // renders the whole command. The socket opens without being awaited, hence the step.\n context.hook('studio:connecting', ({ url }) => {\n startSpinner(`Connecting to ${styleText('cyan', url)}`)\n })\n\n context.hook('studio:connected', ({ url, versions }) => {\n if (silent) {\n return\n }\n\n const line = `Connected to ${styleText('cyan', url)} ${styleText('dim', `(${formatVersions(versions)})`)}`\n\n if (state.spinner) {\n stopSpinner(line)\n return\n }\n writer.success(text(`✓ ${line}`))\n })\n\n context.hook('studio:ready', () => {\n if (silent) {\n return\n }\n startSpinner('✓ Ready to receive jobs')\n })\n\n context.hook('studio:disconnected', ({ reason }) => {\n if (logLevel < logLevelMap.warn) {\n return\n }\n\n stopSpinner()\n writer.warn(text(`⚠ Kubb Studio ended the session (${reason})`))\n })\n\n context.hook('studio:command:start', ({ command }) => {\n if (silent) {\n return\n }\n stopSpinner()\n writer.info(text(`Kubb Studio asked to ${styleText('bold', command)}`))\n })\n\n context.hook('studio:command:end', ({ command, info }) => {\n if (silent) {\n return\n }\n writer.success(text(`✓ Finished ${command}${info ? ` ${styleText('dim', `(${info})`)}` : ''}`))\n startSpinner('✓ Ready to receive jobs')\n })\n\n context.hook('studio:reconnecting', ({ delayMs }) => {\n if (silent) {\n return\n }\n\n stopSpinner()\n writer.info(text(styleText('dim', `Retrying connection to Kubb Studio in ${formatMs(delayMs)}`)))\n })\n\n context.hook('studio:warn', ({ message, permission }) => {\n if (logLevel < logLevelMap.warn) {\n return\n }\n const remedy = permission ? `; pass --${permission.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`)} to allow it` : ''\n writer.warn(text(`⚠ ${message}${remedy}`))\n })\n\n // Unguarded, like `kubb:error`: a failure stays visible even at silent.\n context.hook('studio:error', ({ error }) => {\n const line = `✗ ${error.message}`\n\n if (state.spinner) {\n stopSpinner(line, 'failed')\n return\n }\n writer.error(text(line))\n })\n\n context.hook('kubb:lifecycle:start', () => {\n reset()\n })\n\n context.hook('kubb:generation:start', ({ config }) => {\n closeGroup('failed')\n reset()\n\n state.totalPlugins = config.plugins?.length ?? 0\n\n if (silent) {\n return\n }\n\n const inputPath = getInputPath(config)\n\n writer.group(text([styleText('bold', config.name ?? 'kubb'), inputPath ? styleText('dim', inputPath) : undefined].filter(Boolean).join(' ')))\n state.groupOpen = true\n\n startSpinner('Generating')\n })\n\n context.hook('kubb:plugin:start', ({ plugin }) => {\n if (silent) {\n return\n }\n state.spinner?.message(text(`Generating ${styleText('dim', plugin.name)}`))\n })\n\n // Buffered, not printed: a step redraws over anything written while it runs.\n context.hook('kubb:plugin:end', ({ plugin, duration, success }) => {\n if (silent) {\n return\n }\n\n recordPluginResult(state, success)\n state.pluginLines.push(text(`${plugin.name} ${success ? 'completed' : 'failed'} in ${formatMsWithColor(duration)}`))\n })\n\n context.hook('kubb:plugins:end', () => {\n if (silent) {\n return\n }\n\n const failed = state.failedPlugins > 0\n stopSpinner(buildProgressLine(state) ?? 'No plugins ran', failed ? 'failed' : 'success')\n\n if (state.pluginLines.length) {\n writer.block(state.pluginLines)\n state.pluginLines = []\n }\n })\n\n context.hook('kubb:files:processing:start', ({ files }) => {\n if (silent) {\n return\n }\n\n stopSpinner()\n state.totalFiles = files.length\n state.processedFiles = 0\n\n state.progress = writer.progress(files.length)\n state.progress.start(text(`Writing ${pluralize(files.length, 'file')}`))\n })\n\n context.hook('kubb:files:processing:update', ({ files }) => {\n if (silent) {\n return\n }\n\n for (const { file, config } of files) {\n state.processedFiles++\n state.progress?.advance(`Writing ${relative(config.root, file.path)}`)\n }\n })\n\n context.hook('kubb:files:processing:end', () => {\n if (silent) {\n return\n }\n stopProgress(`Wrote ${pluralize(state.processedFiles, 'file')}`)\n })\n\n context.hook('kubb:format:start', () => startPhase(PHASES.format))\n context.hook('kubb:format:end', endPhase)\n context.hook('kubb:lint:start', () => startPhase(PHASES.lint))\n context.hook('kubb:lint:end', endPhase)\n context.hook('kubb:hooks:start', () => startPhase(PHASES.hooks))\n context.hook('kubb:hooks:end', endPhase)\n\n context.hook('kubb:hook:start', ({ id }) => {\n if (silent || !id) {\n return\n }\n state.hooks.set(id, { hrStart: process.hrtime(), lines: [] })\n })\n\n // Registered only when not silent, so its presence is what tells the runner to stream\n // (`kubb:hook:line` listenerCount). At silent level the listener is absent, so no streaming happens.\n if (!silent) {\n context.hook('kubb:hook:line', ({ id, line }) => {\n const active = state.hooks.get(id)\n if (!active) {\n return\n }\n\n // A phase step redraws its own line, so its output waits until the phase ends.\n if (state.phase) {\n active.lines.push(line)\n return\n }\n writer.raw([line])\n })\n }\n\n context.hook('kubb:hook:end', ({ id, command, name, args, success, error, stdout, stderr }) => {\n if (!id) {\n return\n }\n\n if (!success && state.phase) {\n state.phase.failed = true\n }\n\n if (silent) {\n // Even when silent, surface a failed hook's captured output.\n if (!success) {\n if (stdout) console.log(stdout)\n if (stderr) console.error(stderr)\n }\n return\n }\n\n const active = state.hooks.get(id)\n if (!active) {\n return\n }\n state.hooks.delete(id)\n\n const label = styleText('dim', name ?? formatCommandWithArgs(command, args))\n const reason = error?.message ? ` (${error.message})` : ''\n const result = success\n ? `${styleText('green', '✓')} ${label} in ${formatMsWithColor(getElapsedMs(active.hrStart))}`\n : `${styleText('red', '✗')} ${label} failed${reason}`\n\n const phase = state.phase\n if (phase) {\n if (phase.showHookResults || !success) {\n phase.lines.push(result)\n }\n phase.output.push(...active.lines)\n return\n }\n\n stopSpinner()\n writer.step(text(result))\n writeOutput(active.lines)\n })\n\n context.hook('kubb:generation:end', () => {\n stopSpinner()\n stopProgress()\n })\n\n context.hook('kubb:lifecycle:end', () => {\n closeGroup('failed')\n reset()\n })\n\n return {\n renderSummary(lines, { status }) {\n if (silent || !state.groupOpen) {\n return\n }\n\n closeGroup(status)\n writer.diagnostic([...lines])\n },\n }\n }\n}\n","import { createLogger } from './createLogger.ts'\nimport type { Logger, LoggerWriter } from './defineLogger.ts'\n\n/**\n * Prefixes that stand in for the symbols clack draws, so plain output reads the same way.\n */\nconst SYMBOLS = { info: 'ℹ', warn: '⚠', error: '✗', step: '◇' } as const\n\n/** Draws with one `write` call per line. Nothing animates, so a step prints at start and end. */\nfunction createWriter(write: (line: string) => void): LoggerWriter {\n return {\n group: write,\n groupEnd: write,\n step: (text) => write(`${SYMBOLS.step} ${text}`),\n info: write,\n success: write,\n warn: write,\n error: write,\n block: (lines) => write(lines.join('\\n')),\n raw: (lines) => write(lines.join('\\n')),\n diagnostic: (lines) => write(lines.join('\\n')),\n update: (lines, title) => write([title, ...lines].join('\\n')),\n spinner: () => ({\n start: write,\n message: write,\n clear: () => {},\n stop: (text) => text && write(text),\n error: (text) => write(`${SYMBOLS.error} ${text}`),\n }),\n progress: () => ({\n start: write,\n advance: write,\n stop: (text) => text && write(text),\n }),\n }\n}\n\n/** The plain logger writing through `write`, e.g. `console.error` so stdout carries only JSON. */\nexport function createPlainLogger(write: (line: string) => void) {\n return {\n name: 'plain',\n install: createLogger(createWriter(write)),\n } satisfies Logger\n}\n\n/**\n * Console adapter for non-TTY environments, and for an AI coding agent reading the output. Reports\n * the same run in the same order as `clackLogger`, without the animation.\n */\nexport const plainLogger = createPlainLogger((line) => console.log(line))\n","import { randomUUID } from 'node:crypto'\nimport { basename, dirname, resolve } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { createModuleLoader } from '@internals/shared'\nimport { toError, tokenize } from '@internals/utils'\nimport type { CLIOptions, Config, KubbHooks, PossibleConfig, PostGenerateCommand, Hookable } from '@kubb/core'\nimport { NonZeroExitError, x } from 'tinyexec'\nimport { type LoadConfigResult, type LoadConfigSource, loadConfig } from 'unconfig'\nimport { isGreaterThan, isValid, truncate } from 'verkit'\nimport { URL_WATCHER_INTERVAL_MS, URL_WATCHER_TIMEOUT_MS, WATCHER_DEBOUNCE_MS, WATCHER_IGNORED_PATHS } from '../../constants.ts'\n\nconst loader = createModuleLoader()\n\n// Kubb configs are JS/TS modules (they call `defineConfig`/`pluginX()`), so YAML and JSON are not\n// supported. The jiti loader handles every module format and the JSX runtime, returning the default export.\nconst tsLoader = (configFile: string) => loader.load(configFile, { default: true })\n\nconst MODULE_NAME = 'kubb'\n\nconst SEARCH_FILES = ['', '.config/', 'configs/'].flatMap((prefix) => [`${prefix}.${MODULE_NAME}rc`, `${prefix}${MODULE_NAME}.config`])\nconst SEARCH_EXTENSIONS = ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs']\n\ntype GetConfigsOptions = {\n /**\n * Explicit path to the Kubb config file. When omitted, the loader searches up from the current directory.\n */\n configPath?: string\n /**\n * Optional OpenAPI input path or URL that overrides `config.input` for this run.\n */\n input?: string\n /**\n * Watch flag forwarded to the user's `defineConfig` function.\n */\n watch?: boolean\n /**\n * Log level forwarded to the user's `defineConfig` function.\n */\n logLevel?: CLIOptions['logLevel']\n}\n\ntype GetConfigsResult = {\n /**\n * Absolute path to the resolved config file.\n */\n configPath: string\n /**\n * Resolved and normalized array of Kubb configs, each guaranteed to have a `plugins` array.\n */\n configs: Array<Config>\n}\n\n/**\n * Discovers the Kubb config and resolves it into a normalized array of configs.\n * Every config in the result is guaranteed to have a `plugins` array.\n */\nexport async function getConfigs({ configPath, input, watch, logLevel }: GetConfigsOptions): Promise<GetConfigsResult> {\n const abs = configPath ? resolve(configPath) : undefined\n const sources: Array<LoadConfigSource<unknown>> = abs\n ? [{ files: [basename(abs)], extensions: [], parser: tsLoader }]\n : [{ files: SEARCH_FILES, extensions: SEARCH_EXTENSIONS, parser: tsLoader }]\n\n let result: LoadConfigResult<unknown>\n try {\n result = await loadConfig<unknown>({ cwd: abs ? dirname(abs) : process.cwd(), sources, merge: false })\n } catch (error) {\n throw new Error('Config failed loading', { cause: error })\n }\n\n const [filepath] = result.sources\n if (!result.config || !filepath) {\n throw new Error('Config not defined, create a kubb.config.js or pass through your config with the option --config')\n }\n\n const config = result.config as PossibleConfig<CLIOptions>\n const cli: CLIOptions = { config: configPath, input, watch, logLevel }\n const resolved = await (typeof config === 'function' ? config(cli) : config)\n const userConfigs = Array.isArray(resolved) ? resolved : [resolved]\n\n return {\n configPath: filepath,\n configs: userConfigs.map((item) => {\n const config: Config = { ...item, plugins: item.plugins ?? [] }\n return config\n }),\n }\n}\n\ntype RunPostGenerateOptions = {\n commands: Array<PostGenerateCommand>\n hooks: Hookable<KubbHooks>\n}\n\n/**\n * Outcome of a single hook subprocess, returned by `runHook` alongside the\n * `kubb:hook:end` hook it emits for the loggers.\n */\ntype HookResult = {\n /**\n * `true` when the command exited with code `0`.\n */\n success: boolean\n /**\n * What went wrong, `null` when the command succeeded.\n */\n error: Error | null\n /**\n * Captured stdout, only present on a non-zero exit.\n */\n stdout?: string\n /**\n * Captured stderr, only present on a non-zero exit.\n */\n stderr?: string\n}\n\n/**\n * Returns `true` when `latest` is a newer semver version than `current`. Compares each numeric\n * part, so `5.10.0` beats `5.9.0` where a plain string comparison would not. Prerelease\n * suffixes are ignored, and a malformed version never reports an update.\n *\n * @example Double-digit minor\n * `isNewerVersion('5.9.0', '5.10.0') // true`\n *\n * @example String comparison would get this wrong the other way\n * `isNewerVersion('5.10.0', '5.9.0') // false`\n */\nexport function isNewerVersion(current: string, latest: string): boolean {\n if (!isValid(current) || !isValid(latest)) return false\n\n return isGreaterThan(truncate(latest, 'patch') as string, truncate(current, 'patch') as string)\n}\n\n/**\n * Runs the `output.postGenerate` commands of a Kubb config in sequence and returns each command's\n * outcome, so the caller can turn failures into diagnostics.\n */\nexport async function runPostGenerate({ commands, hooks }: RunPostGenerateOptions): Promise<Array<HookResult>> {\n const results: Array<HookResult> = []\n\n for (const entry of commands) {\n const { command, name } = typeof entry === 'string' ? { command: entry, name: undefined } : entry\n const [cmd, ...args] = tokenize(command)\n if (!cmd) continue\n\n const hookId = randomUUID()\n const commandWithArgs = [cmd, ...args].join(' ')\n\n await hooks.callHook('kubb:hook:start', { id: hookId, command: cmd, name, args })\n results.push(await runHook({ id: hookId, command: cmd, name, args, commandWithArgs, hooks }))\n }\n\n return results\n}\n\ntype RunHookOptions = {\n id: string\n command: string\n name?: string\n args?: ReadonlyArray<string>\n commandWithArgs: string\n hooks: Hookable<KubbHooks>\n}\n\n/**\n * Spawns a hook command and returns its outcome, mirroring it through `kubb:hook:end` for the\n * loggers. A non-zero exit returns `success: false` rather than throwing, so the caller can turn\n * it into a diagnostic. Other spawn errors do the same. Output is streamed through `kubb:hook:line`\n * only while a listener is attached.\n */\nexport async function runHook({ id, command, name, args, commandWithArgs, hooks }: RunHookOptions): Promise<HookResult> {\n const emitEnd = async (result: HookResult): Promise<HookResult> => {\n await hooks.callHook('kubb:hook:end', { command, name, args, id, ...result })\n return result\n }\n\n // Only stream line-by-line when a logger is listening, so the non-streaming plain\n // logger doesn't pay to iterate the subprocess output.\n const stream = hooks.listenerCount('kubb:hook:line') > 0\n\n try {\n const proc = x(command, [...(args ?? [])], {\n nodeOptions: { detached: process.platform !== 'win32' },\n throwOnError: true,\n })\n\n if (stream) {\n for await (const line of proc) {\n await hooks.callHook('kubb:hook:line', { id, line })\n }\n }\n\n await proc\n await hooks.callHook('kubb:success', { message: `${styleText('dim', name ?? commandWithArgs)} successfully executed` })\n return emitEnd({ success: true, error: null })\n } catch (err) {\n if (!(err instanceof NonZeroExitError)) {\n return emitEnd({ success: false, error: toError(err) })\n }\n\n const stderr = err.output?.stderr ?? ''\n const stdout = err.output?.stdout ?? ''\n\n const error = new Error(`Hook execute failed: ${commandWithArgs}`)\n // Signal the failure via the result and `kubb:hook:end` only, carrying the captured output so\n // the logger can render it. The caller turns this into a coded diagnostic and emits that\n // through `Diagnostics.emit`, so emitting `kubb:error` here would render it twice.\n return emitEnd({ success: false, error, stdout, stderr })\n }\n}\n\ntype SerialRunnerOptions = {\n /**\n * The async work to serialize.\n */\n run(): Promise<void>\n /**\n * Receives errors thrown by `run`, so a failure never rejects the returned trigger.\n */\n onError(error: Error): void\n}\n\n/**\n * Wraps `run` so invocations never overlap: a trigger that lands while a run is in flight\n * marks it dirty and runs once more after it finishes, no matter how many triggers arrived.\n * Useful for event-driven reruns (a file watcher, a queue drain) where bursts should\n * coalesce into a single trailing run.\n *\n * @example\n * ```ts\n * const rebuild = createSerialRunner({\n * run: () => build(),\n * onError: (error) => log.error(error.message),\n * })\n * watcher.on('change', () => void rebuild())\n * ```\n */\nexport function createSerialRunner({ run, onError }: SerialRunnerOptions): () => Promise<void> {\n let running = false\n let dirty = false\n\n return async (): Promise<void> => {\n if (running) {\n dirty = true\n return\n }\n running = true\n do {\n dirty = false\n try {\n await run()\n } catch (error) {\n onError(toError(error))\n }\n } while (dirty)\n running = false\n }\n}\n\ntype WatcherLog = {\n info: (message: string) => void\n error: (message: string) => void\n}\n\n/**\n * Starts a file watcher on the given paths and calls `cb` on any change.\n * Ignores `.git` and `node_modules` directories. Event bursts (an editor save emits several)\n * are debounced into one build, and builds never overlap: changes during a build queue exactly\n * one rebuild.\n */\nexport async function startWatcher(\n path: Array<string>,\n cb: (path: Array<string>) => Promise<void>,\n log: WatcherLog = { info: console.log, error: console.log },\n): Promise<void> {\n const { watch } = await import('chokidar')\n // `ignoreInitial` skips the `add` events chokidar fires for existing files at startup, which\n // would otherwise rebuild right after the initial run.\n const watcher = watch(path, { ignorePermissionErrors: true, ignored: WATCHER_IGNORED_PATHS, ignoreInitial: true })\n\n process.once('SIGINT', () => {\n watcher.close()\n })\n process.once('SIGTERM', () => {\n watcher.close()\n })\n\n // Bursts never overlap builds on the shared hooks emitter: a change during a build\n // queues exactly one rerun.\n const runBuild = createSerialRunner({\n run: () => cb(path),\n onError: () => log.error(styleText('red', 'Watcher failed')),\n })\n let debounceTimer: ReturnType<typeof setTimeout> | null = null\n\n watcher.on('all', (type, file) => {\n log.info(styleText('yellow', styleText('bold', `Change detected: ${type} ${file}`)))\n if (debounceTimer) clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n debounceTimer = null\n void runBuild()\n }, WATCHER_DEBOUNCE_MS)\n })\n}\n\n/**\n * Fetches the body of a remote spec URL, `undefined` when the server does not answer with a\n * readable 2xx body within the timeout. The caller seeds `startUrlWatcher` with the result, so\n * the watcher compares polls against the content the initial build ran on.\n */\nexport async function fetchUrlBody(url: string, timeoutMs: number = URL_WATCHER_TIMEOUT_MS): Promise<string | undefined> {\n try {\n const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) })\n if (!response.ok) return undefined\n return await response.text()\n } catch {\n return undefined\n }\n}\n\ntype UrlWatcherOptions = {\n /**\n * Sink for watcher messages, `console.log` by default.\n */\n log?: WatcherLog\n /**\n * Time in milliseconds between polls.\n */\n intervalMs?: number\n /**\n * Upper bound in milliseconds for one poll request, covering headers and body read.\n */\n timeoutMs?: number\n /**\n * Body the initial build ran against, the baseline for change detection. When omitted (the\n * server was unreachable at startup), the first successful poll rebuilds so the output catches\n * up as soon as the server responds.\n */\n initialBody?: string\n}\n\n/**\n * Polls a remote spec URL and calls `cb` whenever the response body changes. A remote document\n * emits no filesystem events, so this is the URL counterpart of `startWatcher`.\n *\n * `initialBody` seeds the change detection, so an edit landing between the initial build and the\n * first poll still rebuilds. An unreachable server (the API restarting between saves) is reported\n * once per outage and polling continues; after it recovers, a rebuild happens only when the body\n * actually differs from the last one seen, so a plain restart with an unchanged spec stays quiet.\n * Each request is aborted after `timeoutMs`, so a hung response delays at most one poll.\n *\n * Returns a function that stops polling and aborts the in-flight request, so callers (and tests)\n * can shut the watcher down without signaling the process.\n */\nexport function startUrlWatcher(url: string, cb: (path: Array<string>) => Promise<void>, options: UrlWatcherOptions = {}): () => void {\n const { log = { info: console.log, error: console.log }, intervalMs = URL_WATCHER_INTERVAL_MS, timeoutMs = URL_WATCHER_TIMEOUT_MS, initialBody } = options\n\n let lastBody = initialBody\n let offline = false\n let timer: ReturnType<typeof setTimeout> | null = null\n let controller: AbortController | null = null\n let stopped = false\n\n const stop = () => {\n stopped = true\n if (timer) clearTimeout(timer)\n controller?.abort()\n }\n process.once('SIGINT', stop)\n process.once('SIGTERM', stop)\n\n // Builds never overlap on the shared hooks emitter: a change during a build queues exactly\n // one rerun.\n const runBuild = createSerialRunner({\n run: () => cb([url]),\n onError: () => log.error(styleText('red', 'Watcher failed')),\n })\n\n const poll = async (): Promise<void> => {\n controller = new AbortController()\n try {\n // The signal also aborts the body read, so a response that stalls mid-stream still times out.\n const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)])\n const response = await fetch(url, { signal })\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`)\n }\n const body = await response.text()\n if (offline) {\n offline = false\n log.info(styleText('yellow', `${url} is reachable again`))\n }\n const changed = lastBody !== undefined && body !== lastBody\n if (changed) {\n log.info(styleText('yellow', styleText('bold', `Change detected: ${url}`)))\n }\n if (changed || lastBody === undefined) {\n void runBuild()\n }\n lastBody = body\n } catch {\n // `lastBody` survives the outage so recovery rebuilds only on real content changes.\n if (!offline && !stopped) {\n offline = true\n log.error(styleText('red', `Cannot reach ${url}, polling until it responds again`))\n }\n }\n if (!stopped) {\n timer = setTimeout(() => void poll(), intervalMs)\n }\n }\n\n void poll()\n\n return stop\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAeA,MAAa,aAAa;CACxB,UAAU;EACR,SAAS;EACT,OAAO,eAAuB;GAAC;GAAoB;GAAW;EAAU;EACxE,cAAc;CAChB;CACA,OAAO;EACL,SAAS;EACT,OAAO,eAAuB;GAAC;GAAU;GAAW;EAAU;EAC9D,cAAc;CAChB;CACA,OAAO;EACL,SAAS;EACT,OAAO,eAAuB,CAAC,UAAU;EACzC,cAAc;CAChB;AACF;;;;AAKA,MAAa,UAAU;CACrB,QAAQ;EACN,SAAS;EACT,OAAO,eAAuB,CAAC,YAAY,OAAO;EAClD,cAAc;CAChB;CACA,OAAO;EACL,SAAS;EACT,OAAO,eAAuB;GAAC;GAAQ;GAAS;EAAU;EAC1D,cAAc;CAChB;CACA,QAAQ;EACN,SAAS;EAET,OAAO,eAAuB;GAAC;GAAS;GAAe;EAAU;EACjE,cAAc;CAChB;AACF;;;;;AAMA,MAAa,uBAAuB;CAAC;CAAS;CAAS;AAAU;;;;AAKjE,MAAa,oBAAoB;CAAC;CAAU;CAAS;AAAQ;;;;AAK7D,SAAgB,gBAAgB,MAAgC;CAC9D,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,QAAQ,MAAM,MAAM,CAAC,WAAW,GAAG,EAAE,OAAO,SAAS,CAAC;EAC5D,MAAM,GAAG,UAAU,SAAS,QAAQ,SAAS,CAAC,CAAC;EAC/C,MAAM,GAAG,eAAe,QAAQ,KAAK,CAAC;CACxC,CAAC;AACH;;;;;;;AAQA,eAAsB,WAAiC,YAAyD;CAC9G,KAAK,MAAM,aAAa,YACtB,IAAI,MAAM,gBAAgB,SAAS,GACjC,OAAO;CAIX,OAAO;AACT;;;;;;;;;;AAWA,SAA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AAS,YAAY,IAAI,CAAC,WAAW,QAAQ,YAAY,QAAQ,SAAS,CAAC,CAAC;GAClF,MAAM,WAAW,MAAM,MAAM,KAAK,EAAE,OAAO,CAAC;GAC5C,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,QAAQ,SAAS,QAAQ;GAE3C,MAAM,OAAO,MAAM,SAAS,KAAK;GACjC,IAAI,SAAS;IACX,UAAU;IACV,IAAI,KAAK,UAAU,UAAU,GAAG,IAAI,oBAAoB,CAAC;GAC3D;GACA,MAAM,UAAU,aAAa,KAAA,KAAa,SAAS;GACnD,IAAI,SACF,IAAI,KAAK,UAAU,UAAU,UAAU,QAAQ,oBAAoB,KAAK,CAAC,CAAC;GAE5E,IAAI,WAAW,aAAa,KAAA,GAC1B,SAAc;GAEhB,WAAW;EACb,QAAQ;GAEN,IAAI,CAAC,WAAW,CAAC,SAAS;IACxB,UAAU;IACV,IAAI,MAAM,UAAU,OAAO,gBAAgB,IAAI,kCAAkC,CAAC;GACpF;EACF;EACA,IAAI,CAAC,SACH,QAAQ,iBAAiB,KAAK,KAAK,GAAG,UAAU;CAEpD;CAEA,KAAU;CAEV,OAAO;AACT"}
@@ -2,7 +2,7 @@ const require_rolldown_runtime = require("./rolldown-runtime-qbf5tadS.cjs");
2
2
  const require_errors = require("./errors-C-wEou02.cjs");
3
3
  const require_agent = require("./agent-BPqs9VRj.cjs");
4
4
  const require_Telemetry = require("./Telemetry-B3kc9gFh.cjs");
5
- const require_output = require("./output-D-9bGS7y.cjs");
5
+ const require_output = require("./output-9qUFmWFq.cjs");
6
6
  let node_util = require("node:util");
7
7
  let node_crypto = require("node:crypto");
8
8
  let node_process = require("node:process");
@@ -878,7 +878,7 @@ async function getConfigs({ configPath, input, watch, logLevel }) {
878
878
  */
879
879
  function isNewerVersion(current, latest) {
880
880
  if (!(0, verkit.isValid)(current) || !(0, verkit.isValid)(latest)) return false;
881
- return (0, verkit.isGreater)((0, verkit.truncate)(latest, "patch"), (0, verkit.truncate)(current, "patch"));
881
+ return (0, verkit.isGreaterThan)((0, verkit.truncate)(latest, "patch"), (0, verkit.truncate)(current, "patch"));
882
882
  }
883
883
  /**
884
884
  * Runs the `output.postGenerate` commands of a Kubb config in sequence and returns each command's
@@ -1160,6 +1160,12 @@ Object.defineProperty(exports, "linters", {
1160
1160
  return linters;
1161
1161
  }
1162
1162
  });
1163
+ Object.defineProperty(exports, "plainLogger", {
1164
+ enumerable: true,
1165
+ get: function() {
1166
+ return plainLogger;
1167
+ }
1168
+ });
1163
1169
  Object.defineProperty(exports, "pluralize", {
1164
1170
  enumerable: true,
1165
1171
  get: function() {
@@ -1203,4 +1209,4 @@ Object.defineProperty(exports, "startWatcher", {
1203
1209
  }
1204
1210
  });
1205
1211
 
1206
- //# sourceMappingURL=utils-DqUNntyL.cjs.map
1212
+ //# sourceMappingURL=utils-Dcw3l4Wz.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils-Dcw3l4Wz.cjs","names":["spawn","logLevelMap","process","formatMsWithColor","getElapsedMs","styleText","Diagnostics","formatMs","relative","clack","styleText","logLevelMap","styleText","formatMs","getElapsedMs","process","canUseTTY","getAgentName","createCliReporter","jiti","createJiti","resolve","basename","loadConfig","dirname","process","isValid","isGreaterThan","truncate","randomUUID","x","styleText","NonZeroExitError","toError","WATCHER_IGNORED_PATHS","URL_WATCHER_TIMEOUT_MS","URL_WATCHER_INTERVAL_MS"],"sources":["../../../internals/utils/src/tools.ts","../src/loggers/createLogger.ts","../src/loggers/clackLogger.ts","../src/loggers/plainLogger.ts","../src/loggers/utils.ts","../../../internals/shared/src/loader.ts","../src/runners/generate/utils.ts"],"sourcesContent":["import { spawn } from 'node:child_process'\n\n/**\n * How one formatter or linter is invoked: the executable, the argv it takes for an output\n * directory, and what to report when it is not installed.\n */\nexport type ToolCommand = {\n command: string\n args: (outputPath: string) => Array<string>\n errorMessage: string\n}\n\n/**\n * CLI command descriptors for each supported code formatter.\n */\nexport const formatters = {\n prettier: {\n command: 'prettier',\n args: (outputPath: string) => ['--ignore-unknown', '--write', outputPath],\n errorMessage: 'Prettier not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['format', '--write', outputPath],\n errorMessage: 'Biome not found',\n },\n oxfmt: {\n command: 'oxfmt',\n args: (outputPath: string) => [outputPath],\n errorMessage: 'Oxfmt not found',\n },\n} as const satisfies Record<string, ToolCommand>\n\n/**\n * CLI command descriptors for each supported linter.\n */\nexport const linters = {\n eslint: {\n command: 'eslint',\n args: (outputPath: string) => [outputPath, '--fix'],\n errorMessage: 'Eslint not found',\n },\n biome: {\n command: 'biome',\n args: (outputPath: string) => ['lint', '--fix', outputPath],\n errorMessage: 'Biome not found',\n },\n oxlint: {\n command: 'oxlint',\n // --no-ignore so oxlint lints the folder even when it's gitignored (generated output dirs usually are).\n args: (outputPath: string) => ['--fix', '--no-ignore', outputPath],\n errorMessage: 'Oxlint not found',\n },\n} as const satisfies Record<string, ToolCommand>\n\n/**\n * Preference order for `format: 'auto'`, most-preferred first. Spelled out rather than taken from\n * the table's key order, which is arbitrary and would silently change what `auto` picks.\n */\nexport const FORMATTER_PREFERENCE = ['oxfmt', 'biome', 'prettier'] as const\n\n/**\n * Preference order for `lint: 'auto'`, most-preferred first.\n */\nexport const LINTER_PREFERENCE = ['oxlint', 'biome', 'eslint'] as const\n\n/**\n * Whether `name` is on PATH and answers `--version` with a zero exit.\n */\nexport function isToolAvailable(name: string): Promise<boolean> {\n return new Promise((resolve) => {\n const child = spawn(name, ['--version'], { stdio: 'ignore' })\n child.on('close', (code) => resolve(code === 0))\n child.on('error', () => resolve(false))\n })\n}\n\n/**\n * Returns the first installed executable from `candidates`, or `null` when none are found.\n *\n * Not memoized: a long-running host that probes repeatedly should cache the result itself, and a\n * `--watch` build should keep noticing a tool installed mid-session.\n */\nexport async function detectTool<TName extends string>(candidates: ReadonlyArray<TName>): Promise<TName | null> {\n for (const candidate of candidates) {\n if (await isToolAvailable(candidate)) {\n return candidate\n }\n }\n\n return null\n}\n\n/**\n * Tokenizes a shell command string, respecting single and double quotes.\n *\n * @example\n * ```ts\n * tokenize('git commit -m \"initial commit\"')\n * // → ['git', 'commit', '-m', 'initial commit']\n * ```\n */\nexport function tokenize(command: string): Array<string> {\n return (command.match(/[^\\s\"']+|\"([^\"]*)\"|'([^']*)'/g) ?? []).map((token) => token.replace(/^[\"']|[\"']$/g, ''))\n}\n","import { relative } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { formatMs, getElapsedMs } from '@internals/utils'\nimport { Diagnostics, logLevel as logLevelMap } from '@kubb/core'\nimport { formatMsWithColor } from './banner.ts'\nimport type { LoggerContext, LoggerHandle, LoggerOptions, LoggerWriter, LogStatus, WriterProgress, WriterSpinner } from './defineLogger.ts'\nimport {\n buildProgressLine,\n createProgressCounters,\n formatCommandWithArgs,\n formatErrorFrames,\n formatMessage,\n formatVersions,\n getInputPath,\n pluralize,\n recordPluginResult,\n resetProgressCounters,\n} from './utils.ts'\n\n/**\n * One output phase while its step owns the line. A phase buffers what it is told, because a spinner\n * redraws over anything written under it, and prints the lot once it knows its own result.\n */\ntype Phase = {\n successLabel: string\n failureLabel: string\n /**\n * Whether each hook's own result is worth a line. Format and lint run one command, so the phase\n * result already says everything; the post-generate phase runs several.\n */\n showHookResults: boolean\n failed: boolean\n hrStart: [number, number]\n lines: Array<string>\n /**\n * Raw lines a hook printed, drawn outside the group.\n */\n output: Array<string>\n}\n\ntype StartPhaseOptions = {\n /**\n * Shown while the phase runs.\n */\n running: string\n success: string\n failure: string\n showHookResults?: boolean\n}\n\n/**\n * The three output phases, in the order the generate runner runs them.\n */\nconst PHASES = {\n format: { running: 'Formatting', success: 'Formatted', failure: 'Formatting failed' },\n lint: { running: 'Linting', success: 'Linted', failure: 'Linting failed' },\n hooks: {\n running: 'Running post-generate hooks',\n success: 'Post-generate hooks completed',\n failure: 'Post-generate hooks failed',\n showHookResults: true,\n },\n} as const satisfies Record<string, StartPhaseOptions>\n\n/**\n * Drops the blank lines a subprocess leaves at either end of its output, so its block does not open\n * or close on an empty row.\n */\nfunction trimBlankEdges(lines: ReadonlyArray<string>): Array<string> {\n const start = lines.findIndex((line) => line.trim())\n if (start === -1) {\n return []\n }\n\n return lines.slice(start, lines.findLastIndex((line) => line.trim()) + 1)\n}\n\n/**\n * Wires a {@link LoggerWriter} onto the run's hooks. This owns what a run says and in what order:\n * one group per config, a step over the plugin work, a progress bar for the writes, one step per\n * output phase, then the summary and the group's closing result. The writer only decides how each\n * line looks, so every logger reports the same run the same way.\n *\n * @example\n * ```ts\n * export const plainLogger = { name: 'plain', install: (context, options) => createLogger(writer)(context, options) }\n * ```\n */\nexport function createLogger(writer: LoggerWriter) {\n return function install(context: LoggerContext, options?: LoggerOptions): LoggerHandle {\n const logLevel = options?.logLevel ?? logLevelMap.info\n const silent = logLevel <= logLevelMap.silent\n const state = {\n ...createProgressCounters(),\n spinner: null as WriterSpinner | null,\n progress: null as WriterProgress | null,\n hooks: new Map<string, { hrStart: [number, number]; lines: Array<string> }>(),\n /**\n * Plugin results held back while the generation step owns the line.\n */\n pluginLines: [] as Array<string>,\n phase: null as Phase | null,\n groupOpen: false,\n }\n\n function text(message: string): string {\n return formatMessage(message, logLevel)\n }\n\n function startSpinner(message: string) {\n if (silent) {\n return\n }\n\n state.spinner = writer.spinner()\n state.spinner.start(text(message))\n }\n\n function stopSpinner(message?: string, status: LogStatus = 'success') {\n const spinner = state.spinner\n if (!spinner) {\n return\n }\n state.spinner = null\n\n if (message === undefined) {\n spinner.clear()\n return\n }\n if (status === 'failed') {\n spinner.error(text(message))\n return\n }\n spinner.stop(text(message))\n }\n\n function stopProgress(message?: string) {\n const progress = state.progress\n if (!progress) {\n return\n }\n state.progress = null\n progress.stop(message === undefined ? '' : text(message))\n }\n\n function startPhase({ running, success, failure, showHookResults = false }: StartPhaseOptions) {\n state.phase = { successLabel: success, failureLabel: failure, showHookResults, failed: false, hrStart: process.hrtime(), lines: [], output: [] }\n startSpinner(running)\n }\n\n function endPhase() {\n const phase = state.phase\n state.phase = null\n\n if (!phase || silent) {\n return\n }\n\n const duration = formatMsWithColor(getElapsedMs(phase.hrStart))\n\n stopSpinner(phase.failed ? `${phase.failureLabel} after ${duration}` : `${phase.successLabel} in ${duration}`, phase.failed ? 'failed' : 'success')\n\n if (phase.lines.length) {\n writer.block(phase.lines)\n }\n writeOutput(phase.output)\n }\n\n function writeOutput(lines: ReadonlyArray<string>) {\n const output = trimBlankEdges(lines)\n if (output.length) {\n writer.raw(output)\n }\n }\n\n // A run that throws before `kubb:generation:end` never reaches the summary, so the lifecycle\n // end calls this too rather than leave a group without its closing line.\n function closeGroup(status: LogStatus) {\n if (!state.groupOpen) {\n return\n }\n state.groupOpen = false\n\n stopSpinner()\n stopProgress()\n writer.groupEnd(status === 'failed' ? styleText('red', '✗ Generation failed') : styleText('green', '✓ Generation succeeded'))\n }\n\n function reset() {\n stopSpinner()\n stopProgress()\n resetProgressCounters(state)\n state.hooks.clear()\n state.pluginLines = []\n state.phase = null\n state.groupOpen = false\n }\n\n context.hook('kubb:info', ({ message, info }) => {\n if (silent) {\n return\n }\n\n const line = text([styleText('blue', 'ℹ'), message, info ? styleText('dim', info) : undefined].filter(Boolean).join(' '))\n\n // Info carries something new (the auto-detected tool), so inside a phase it waits for the\n // phase to print rather than being spent on a frame the next one overwrites.\n if (state.phase) {\n state.phase.lines.push(line)\n return\n }\n if (state.spinner) {\n state.spinner.message(line)\n return\n }\n writer.info(line)\n })\n\n context.hook('kubb:success', ({ message, info }) => {\n if (silent) {\n return\n }\n\n const line = text([styleText('green', '✓'), message, logLevel >= logLevelMap.info && info ? styleText('dim', info) : undefined].filter(Boolean).join(' '))\n\n // A phase step outlives the successes reported inside it, and its own result says the same\n // thing, so let the step carry them.\n if (state.spinner) {\n state.spinner.message(line)\n return\n }\n writer.success(line)\n })\n\n context.hook('kubb:warn', ({ message, info }) => {\n if (logLevel < logLevelMap.warn) {\n return\n }\n\n writer.warn(\n text([styleText('yellow', '⚠'), message, logLevel >= logLevelMap.info && info ? styleText('dim', info) : undefined].filter(Boolean).join(' ')),\n )\n })\n\n // Unguarded: a failure stays visible even at silent.\n context.hook('kubb:error', ({ error }) => {\n if (state.phase) {\n state.phase.failed = true\n }\n\n const line = [styleText('red', '✗'), error.message].join(' ')\n\n if (state.spinner) {\n stopSpinner(line, 'failed')\n } else {\n writer.error(text(line))\n }\n\n const frames = logLevel >= logLevelMap.verbose ? formatErrorFrames(error) : null\n if (!frames) {\n return\n }\n\n writer.block(frames.frames.map((frame) => text(styleText('dim', frame))))\n if (frames.cause) {\n writer.block([styleText('dim', frames.cause.header), ...frames.cause.frames.map((frame) => text(` ${styleText('dim', frame)}`))])\n }\n })\n\n context.hook('kubb:diagnostic', ({ diagnostic }) => {\n // Silent still surfaces errors so failures stay visible. It drops warnings and info.\n if (silent && diagnostic.severity !== 'error') {\n return\n }\n\n stopSpinner()\n stopProgress()\n\n if (Diagnostics.isUpdate(diagnostic)) {\n writer.update(\n [`\\`v${diagnostic.currentVersion}\\` → \\`v${diagnostic.latestVersion}\\``, 'Run `npm install -g @kubb/cli` to update'],\n 'Update available for `Kubb`',\n )\n return\n }\n\n const { headline, details } = Diagnostics.format(diagnostic)\n writer.diagnostic([headline, ...details])\n })\n\n // A `kubb studio` session emits these on the same emitter as its generations, so one logger\n // renders the whole command. The socket opens without being awaited, hence the step.\n context.hook('studio:connecting', ({ url }) => {\n startSpinner(`Connecting to ${styleText('cyan', url)}`)\n })\n\n context.hook('studio:connected', ({ url, versions }) => {\n if (silent) {\n return\n }\n\n const line = `Connected to ${styleText('cyan', url)} ${styleText('dim', `(${formatVersions(versions)})`)}`\n\n if (state.spinner) {\n stopSpinner(line)\n return\n }\n writer.success(text(`✓ ${line}`))\n })\n\n context.hook('studio:ready', () => {\n if (silent) {\n return\n }\n startSpinner('✓ Ready to receive jobs')\n })\n\n context.hook('studio:disconnected', ({ reason }) => {\n if (logLevel < logLevelMap.warn) {\n return\n }\n\n stopSpinner()\n writer.warn(text(`⚠ Kubb Studio ended the session (${reason})`))\n })\n\n context.hook('studio:command:start', ({ command }) => {\n if (silent) {\n return\n }\n stopSpinner()\n writer.info(text(`Kubb Studio asked to ${styleText('bold', command)}`))\n })\n\n context.hook('studio:command:end', ({ command, info }) => {\n if (silent) {\n return\n }\n writer.success(text(`✓ Finished ${command}${info ? ` ${styleText('dim', `(${info})`)}` : ''}`))\n startSpinner('✓ Ready to receive jobs')\n })\n\n context.hook('studio:reconnecting', ({ delayMs }) => {\n if (silent) {\n return\n }\n\n stopSpinner()\n writer.info(text(styleText('dim', `Retrying connection to Kubb Studio in ${formatMs(delayMs)}`)))\n })\n\n context.hook('studio:warn', ({ message, permission }) => {\n if (logLevel < logLevelMap.warn) {\n return\n }\n const remedy = permission ? `; pass --${permission.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`)} to allow it` : ''\n writer.warn(text(`⚠ ${message}${remedy}`))\n })\n\n // Unguarded, like `kubb:error`: a failure stays visible even at silent.\n context.hook('studio:error', ({ error }) => {\n const line = `✗ ${error.message}`\n\n if (state.spinner) {\n stopSpinner(line, 'failed')\n return\n }\n writer.error(text(line))\n })\n\n context.hook('kubb:lifecycle:start', () => {\n reset()\n })\n\n context.hook('kubb:generation:start', ({ config }) => {\n closeGroup('failed')\n reset()\n\n state.totalPlugins = config.plugins?.length ?? 0\n\n if (silent) {\n return\n }\n\n const inputPath = getInputPath(config)\n\n writer.group(text([styleText('bold', config.name ?? 'kubb'), inputPath ? styleText('dim', inputPath) : undefined].filter(Boolean).join(' ')))\n state.groupOpen = true\n\n startSpinner('Generating')\n })\n\n context.hook('kubb:plugin:start', ({ plugin }) => {\n if (silent) {\n return\n }\n state.spinner?.message(text(`Generating ${styleText('dim', plugin.name)}`))\n })\n\n // Buffered, not printed: a step redraws over anything written while it runs.\n context.hook('kubb:plugin:end', ({ plugin, duration, success }) => {\n if (silent) {\n return\n }\n\n recordPluginResult(state, success)\n state.pluginLines.push(text(`${plugin.name} ${success ? 'completed' : 'failed'} in ${formatMsWithColor(duration)}`))\n })\n\n context.hook('kubb:plugins:end', () => {\n if (silent) {\n return\n }\n\n const failed = state.failedPlugins > 0\n stopSpinner(buildProgressLine(state) ?? 'No plugins ran', failed ? 'failed' : 'success')\n\n if (state.pluginLines.length) {\n writer.block(state.pluginLines)\n state.pluginLines = []\n }\n })\n\n context.hook('kubb:files:processing:start', ({ files }) => {\n if (silent) {\n return\n }\n\n stopSpinner()\n state.totalFiles = files.length\n state.processedFiles = 0\n\n state.progress = writer.progress(files.length)\n state.progress.start(text(`Writing ${pluralize(files.length, 'file')}`))\n })\n\n context.hook('kubb:files:processing:update', ({ files }) => {\n if (silent) {\n return\n }\n\n for (const { file, config } of files) {\n state.processedFiles++\n state.progress?.advance(`Writing ${relative(config.root, file.path)}`)\n }\n })\n\n context.hook('kubb:files:processing:end', () => {\n if (silent) {\n return\n }\n stopProgress(`Wrote ${pluralize(state.processedFiles, 'file')}`)\n })\n\n context.hook('kubb:format:start', () => startPhase(PHASES.format))\n context.hook('kubb:format:end', endPhase)\n context.hook('kubb:lint:start', () => startPhase(PHASES.lint))\n context.hook('kubb:lint:end', endPhase)\n context.hook('kubb:hooks:start', () => startPhase(PHASES.hooks))\n context.hook('kubb:hooks:end', endPhase)\n\n context.hook('kubb:hook:start', ({ id }) => {\n if (silent || !id) {\n return\n }\n state.hooks.set(id, { hrStart: process.hrtime(), lines: [] })\n })\n\n // Registered only when not silent, so its presence is what tells the runner to stream\n // (`kubb:hook:line` listenerCount). At silent level the listener is absent, so no streaming happens.\n if (!silent) {\n context.hook('kubb:hook:line', ({ id, line }) => {\n const active = state.hooks.get(id)\n if (!active) {\n return\n }\n\n // A phase step redraws its own line, so its output waits until the phase ends.\n if (state.phase) {\n active.lines.push(line)\n return\n }\n writer.raw([line])\n })\n }\n\n context.hook('kubb:hook:end', ({ id, command, name, args, success, error, stdout, stderr }) => {\n if (!id) {\n return\n }\n\n if (!success && state.phase) {\n state.phase.failed = true\n }\n\n if (silent) {\n // Even when silent, surface a failed hook's captured output.\n if (!success) {\n if (stdout) console.log(stdout)\n if (stderr) console.error(stderr)\n }\n return\n }\n\n const active = state.hooks.get(id)\n if (!active) {\n return\n }\n state.hooks.delete(id)\n\n const label = styleText('dim', name ?? formatCommandWithArgs(command, args))\n const reason = error?.message ? ` (${error.message})` : ''\n const result = success\n ? `${styleText('green', '✓')} ${label} in ${formatMsWithColor(getElapsedMs(active.hrStart))}`\n : `${styleText('red', '✗')} ${label} failed${reason}`\n\n const phase = state.phase\n if (phase) {\n if (phase.showHookResults || !success) {\n phase.lines.push(result)\n }\n phase.output.push(...active.lines)\n return\n }\n\n stopSpinner()\n writer.step(text(result))\n writeOutput(active.lines)\n })\n\n context.hook('kubb:generation:end', () => {\n stopSpinner()\n stopProgress()\n })\n\n context.hook('kubb:lifecycle:end', () => {\n closeGroup('failed')\n reset()\n })\n\n return {\n renderSummary(lines, { status }) {\n if (silent || !state.groupOpen) {\n return\n }\n\n closeGroup(status)\n writer.diagnostic([...lines])\n },\n }\n }\n}\n","import { styleText } from 'node:util'\nimport * as clack from '@clack/prompts'\nimport { createLogger } from './createLogger.ts'\nimport type { Logger, LoggerWriter } from './defineLogger.ts'\n\n/**\n * Draws with clack: a gutter bar per group, animated steps, and a progress bar for the writes.\n */\nconst writer: LoggerWriter = {\n group: (title) => clack.intro(title),\n groupEnd: (text) => clack.outro(text),\n step: (text) => clack.log.step(text, { spacing: 0 }),\n info: (text) => clack.log.info(text),\n success: (text) => clack.log.success(text),\n warn: (text) => clack.log.warn(text),\n error: (text) => clack.log.error(text),\n block: (lines) => clack.log.message(lines, { spacing: 0 }),\n // A subprocess's output is not Kubb's tree, so it goes out past clack and its gutter bar. The\n // step above it is already stopped by the time this runs.\n raw: (lines) => console.log(styleText('dim', lines.join('\\n'))),\n // The diagnostic carries its own code and indented rows, so clear clack's gutter and bar and let\n // the block stand on its own.\n diagnostic: (lines) => clack.log.message(lines, { symbol: '', secondarySymbol: '' }),\n update: (lines, title) =>\n clack.box(lines.join('\\n'), title, {\n width: 'auto',\n formatBorder: (border: string) => styleText('yellow', border),\n rounded: true,\n withGuide: false,\n contentAlign: 'center',\n titleAlign: 'center',\n }),\n spinner() {\n const spinner = clack.spinner()\n\n return {\n start: (text) => spinner.start(text),\n message: (text) => spinner.message(text),\n clear: () => spinner.clear(),\n stop: (text) => spinner.stop(text),\n error: (text) => spinner.error(text),\n }\n },\n progress(max) {\n const bar = clack.progress({ style: 'block', max, size: 30 })\n\n return {\n start: (text) => bar.start(text),\n advance: (text) => bar.advance(1, text),\n stop: (text) => bar.stop(text),\n }\n },\n}\n\n/**\n * TTY logger for local development, with animated steps and progress bars.\n */\nexport const clackLogger = {\n name: 'clack',\n install: createLogger(writer),\n} satisfies Logger\n","import { createLogger } from './createLogger.ts'\nimport type { Logger, LoggerWriter } from './defineLogger.ts'\n\n/**\n * Prefixes that stand in for the symbols clack draws, so plain output reads the same way.\n */\nconst SYMBOLS = { info: 'ℹ', warn: '⚠', error: '✗', step: '◇' } as const\n\n/** Draws with one `write` call per line. Nothing animates, so a step prints at start and end. */\nfunction createWriter(write: (line: string) => void): LoggerWriter {\n return {\n group: write,\n groupEnd: write,\n step: (text) => write(`${SYMBOLS.step} ${text}`),\n info: write,\n success: write,\n warn: write,\n error: write,\n block: (lines) => write(lines.join('\\n')),\n raw: (lines) => write(lines.join('\\n')),\n diagnostic: (lines) => write(lines.join('\\n')),\n update: (lines, title) => write([title, ...lines].join('\\n')),\n spinner: () => ({\n start: write,\n message: write,\n clear: () => {},\n stop: (text) => text && write(text),\n error: (text) => write(`${SYMBOLS.error} ${text}`),\n }),\n progress: () => ({\n start: write,\n advance: write,\n stop: (text) => text && write(text),\n }),\n }\n}\n\n/** The plain logger writing through `write`, e.g. `console.error` so stdout carries only JSON. */\nexport function createPlainLogger(write: (line: string) => void) {\n return {\n name: 'plain',\n install: createLogger(createWriter(write)),\n } satisfies Logger\n}\n\n/**\n * Console adapter for non-TTY environments, and for an AI coding agent reading the output. Reports\n * the same run in the same order as `clackLogger`, without the animation.\n */\nexport const plainLogger = createPlainLogger((line) => console.log(line))\n","import process from 'node:process'\nimport { styleText } from 'node:util'\nimport { formatMs, getElapsedMs } from '@internals/utils'\nimport type { Config, Reporter, ReporterContext, ReporterPluginFiles } from '@kubb/core'\nimport { createCliReporter, logLevel as logLevelMap } from '@kubb/core'\nimport type { StudioConnectedContext } from '@kubb/studio'\nimport { getAgentName } from '../agent.ts'\nimport { canUseTTY } from '../utils/env.ts'\nimport type { Logger, LoggerContext, LoggerHandle, LoggerOptions } from './defineLogger.ts'\nimport { clackLogger } from './clackLogger.ts'\nimport { plainLogger } from './plainLogger.ts'\n\n/**\n * Display path for a config's input: the string form, or its `path` field when the input is an\n * object. Loggers show it alongside `Generation started`.\n */\nexport function getInputPath(config: Config): string | undefined {\n const { input } = config\n if (typeof input === 'string') return input\n return typeof input?.path === 'string' ? input.path : undefined\n}\n\n/**\n * Counts a noun, so a message never reads `1 files`.\n *\n * @example\n * `pluralize(1, 'config')` returns `'1 config'`\n */\nexport function pluralize(count: number, noun: string): string {\n return `${count} ${count === 1 ? noun : `${noun}s`}`\n}\n\n/**\n * Optionally prefix a message with a [HH:MM:SS] timestamp when logLevel >= verbose.\n * Shared across all logger adapters to avoid duplication.\n */\nexport function formatMessage(message: string, logLevel: number): string {\n if (logLevel >= logLevelMap.verbose) {\n const timestamp = new Date().toLocaleTimeString('en-US', {\n hour12: false,\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n })\n return `${styleText('dim', `[${timestamp}]`)} ${message}`\n }\n return message\n}\n\n/**\n * Renders the versions from a `studio:connected` event as one parenthetical. The runtime is listed\n * only when it differs from the host, and Studio's only when it sent one.\n */\nexport function formatVersions({ studio, kubb, agent }: StudioConnectedContext['versions']): string {\n return [`v${agent}`, kubb !== agent ? `runtime v${kubb}` : undefined, studio ? `Studio v${studio}` : undefined].filter(Boolean).join(', ')\n}\n\n/**\n * Extracts the `.cause` of an `Error` as an `Error`, or `undefined` when absent or not an `Error`.\n */\nfunction toCause(error: Error): Error | undefined {\n return error.cause instanceof Error ? error.cause : undefined\n}\n\n/**\n * First stack frames for verbose error output, including an optional `cause` chain.\n */\nexport function formatErrorFrames(error: Error): { frames: Array<string>; cause?: { header: string; frames: Array<string> } } | null {\n if (!error.stack) {\n return null\n }\n\n const frames = error.stack\n .split('\\n')\n .slice(1, 4)\n .map((frame) => frame.trim())\n const caused = toCause(error)\n\n if (!caused?.stack) {\n return { frames }\n }\n\n return {\n frames,\n cause: {\n header: `└─ caused by ${caused.message}`,\n frames: caused.stack\n .split('\\n')\n .slice(1, 4)\n .map((frame) => frame.trim()),\n },\n }\n}\n\ntype ProgressState = {\n /**\n * Total number of plugins scheduled for this generation run.\n */\n totalPlugins: number\n /**\n * Number of plugins that have finished without error.\n */\n completedPlugins: number\n /**\n * Number of plugins that exited with an error.\n */\n failedPlugins: number\n /**\n * Total number of files expected to be written.\n */\n totalFiles: number\n /**\n * Number of files written so far.\n */\n processedFiles: number\n /**\n * `process.hrtime()` snapshot taken at the start of generation, used to compute elapsed time.\n */\n hrStart: [number, number]\n}\n\n/**\n * Build the progress summary line shown by the clack logger.\n * Returns null when there is nothing to display.\n */\nexport function buildProgressLine(state: ProgressState): string | null {\n const parts: Array<string> = []\n const duration = formatMs(getElapsedMs(state.hrStart))\n\n if (state.totalPlugins > 0) {\n const pluginStr =\n state.failedPlugins > 0\n ? `Plugins ${styleText('green', state.completedPlugins.toString())}/${state.totalPlugins} ${styleText('red', `(${state.failedPlugins} failed)`)}`\n : `Plugins ${styleText('green', state.completedPlugins.toString())}/${state.totalPlugins}`\n parts.push(pluginStr)\n }\n\n if (state.totalFiles > 0) {\n parts.push(`Files ${styleText('green', state.processedFiles.toString())}/${state.totalFiles}`)\n }\n\n if (parts.length === 0) {\n return null\n }\n\n parts.push(`${styleText('green', duration)} elapsed`)\n return parts.join(styleText('dim', ' | '))\n}\n\n/**\n * Creates the per-run progress counters used by the clack logger.\n */\nexport function createProgressCounters(): ProgressState {\n return {\n totalPlugins: 0,\n completedPlugins: 0,\n failedPlugins: 0,\n totalFiles: 0,\n processedFiles: 0,\n hrStart: process.hrtime(),\n }\n}\n\n/**\n * Resets the progress counters in place at the start/end of a generation run.\n */\nexport function resetProgressCounters(state: ProgressState): void {\n state.totalPlugins = 0\n state.completedPlugins = 0\n state.failedPlugins = 0\n state.totalFiles = 0\n state.processedFiles = 0\n state.hrStart = process.hrtime()\n}\n\n/**\n * Records a finished plugin against the progress counters.\n */\nexport function recordPluginResult(state: ProgressState, success: boolean): void {\n if (success) {\n state.completedPlugins++\n } else {\n state.failedPlugins++\n }\n}\n\n/**\n * Tracks per-hook start times so a logger can report a hook's elapsed duration.\n * Used by the plain logger, which keys timing by hook `id`.\n */\ntype HookTimer = {\n start(id: string): void\n /**\n * Returns the elapsed milliseconds since `start(id)`, or `undefined` when no start was recorded.\n */\n end(id: string): number | undefined\n}\n\n/**\n * Creates a {@link HookTimer} backed by a private `id → hrtime` map.\n */\nexport function createHookTimer(): HookTimer {\n const starts = new Map<string, [number, number]>()\n\n return {\n start(id: string): void {\n starts.set(id, process.hrtime())\n },\n end(id: string): number | undefined {\n const hrStart = starts.get(id)\n if (!hrStart) {\n return undefined\n }\n starts.delete(id)\n return getElapsedMs(hrStart)\n },\n }\n}\n\n/**\n * Join a command and its optional args into a single display string.\n *\n * @example With args\n * `formatCommandWithArgs('prettier', ['--write', '.'])` returns `'prettier --write .'`\n */\nexport function formatCommandWithArgs(command: string, args?: ReadonlyArray<string>): string {\n return args?.length ? `${command} ${args.join(' ')}` : command\n}\n\n/**\n * Bridges a {@link Reporter} onto the run's hook emitter: calls `report` with each config's\n * {@link GenerationResult} on `kubb:generation:end`. The reporter never touches the emitter.\n */\nexport function installReporter(context: LoggerContext, reporter: Reporter, ctx: ReporterContext): void {\n const pluginFiles = reporter.needsPluginFiles ? new Map<Config, Map<string, Set<string>>>() : undefined\n\n if (pluginFiles) {\n context.hook('kubb:plugin:end', ({ config, plugin, files }) => {\n const filesByPlugin = pluginFiles.get(config) ?? new Map<string, Set<string>>()\n const seen = new Set([...filesByPlugin.values()].flatMap((paths) => [...paths]))\n const added = files.filter((file) => !seen.has(file.path)).map((file) => file.path)\n\n if (added.length) filesByPlugin.set(plugin.name, new Set([...(filesByPlugin.get(plugin.name) ?? []), ...added]))\n\n pluginFiles.set(config, filesByPlugin)\n })\n }\n\n context.hook('kubb:generation:end', async ({ config, diagnostics = [], filesCreated = 0, status = 'success', hrStart = process.hrtime() }) => {\n const files = pluginFiles?.get(config)\n const grouped: ReporterPluginFiles | undefined = files && [...files].map(([plugin, paths]) => ({ plugin, files: [...paths] }))\n\n await reporter.report({ config, diagnostics, filesCreated, status, hrStart, pluginFiles: grouped }, ctx)\n\n pluginFiles?.delete(config)\n })\n\n if (reporter.drain) {\n context.hook('kubb:lifecycle:end', () => reporter.drain?.(ctx))\n }\n}\n\n/**\n * Installs the live logger (the TUI view) and the given reporters (the output). The reporters are\n * already selected by the caller (the CLI maps `--reporter` to names via `selectReporters`). This\n * only wires them. Loggers receive hook subprocess output through `kubb:hook:line` and the\n * `stdout`/`stderr` on `kubb:hook:end`, so nothing is returned here.\n *\n * Loggers and reporters are independent, except for `cli`: it both installs the live logger view\n * here and registers a reporter that renders the per-config summary through that logger, so the\n * summary lands inside the group the logger opened. The `json` reporter owns stdout, so the whole\n * `cli` reporter (live logger and summary) is skipped whenever `json` is among the reporters, even\n * if `cli` is also listed.\n */\nasync function setupReporters(\n context: LoggerContext,\n {\n logLevel,\n reporters,\n logger: forcedLogger,\n }: LoggerOptions & {\n reporters: ReadonlyArray<Reporter>\n /** Overrides the terminal-based pick, e.g. the plain logger for `kubb studio snapshot`. */\n logger?: Logger\n },\n): Promise<LoggerHandle | undefined> {\n let cliHandle: LoggerHandle | undefined\n const hasJson = reporters.some((reporter) => reporter.name === 'json')\n const ctx: ReporterContext = { logLevel }\n\n for (const reporter of reporters) {\n if (reporter.name !== 'cli') {\n installReporter(context, reporter, ctx)\n continue\n }\n\n if (hasJson) {\n continue\n }\n\n // Spinners and cursor-movement escapes are hard for an AI coding agent to parse, even over a pseudo-TTY.\n const logger = forcedLogger ?? (canUseTTY() && !getAgentName() ? clackLogger : plainLogger)\n const handle = (await logger.install(context, { logLevel })) ?? undefined\n cliHandle = handle\n\n // The summary belongs inside the group the logger opened for this config, so hand the writing\n // to the logger rather than letting the reporter print alongside it.\n installReporter(context, createCliReporter({ render: handle?.renderSummary }), ctx)\n }\n\n return cliHandle\n}\n\nexport default setupReporters\n\n/**\n * Picks the reporters whose `name` matches one of `names`, in the order the names are given.\n * The config carries every available reporter, and the host selects which to activate by name\n * (the CLI maps `--reporter` to this). Duplicate names and names without a matching reporter are\n * skipped.\n */\nexport function selectReporters(reporters: ReadonlyArray<Reporter>, names: ReadonlyArray<string>): Array<Reporter> {\n const seen = new Set<string>()\n const selected: Array<Reporter> = []\n\n for (const name of names) {\n if (seen.has(name)) {\n continue\n }\n seen.add(name)\n\n const reporter = reporters.find((candidate) => candidate.name === name)\n if (reporter) {\n selected.push(reporter)\n }\n }\n\n return selected\n}\n","import { createJiti } from 'jiti'\n\n/**\n * jiti options for loading Kubb config modules: the automatic JSX runtime pointed at\n * `@kubb/renderer-jsx`, and `moduleCache` off so a re-load re-evaluates the file.\n */\nconst JITI_OPTIONS = {\n jsx: { runtime: 'automatic', importSource: '@kubb/renderer-jsx' },\n moduleCache: false,\n} satisfies Parameters<typeof createJiti>[1]\n\n/**\n * Per-call options for {@link ModuleLoader.load}.\n */\ntype LoadModuleOptions = {\n /**\n * Return the module's default export instead of the full namespace.\n */\n default?: boolean\n}\n\n/**\n * Loads `.ts`/`.js` modules via jiti.\n */\ntype ModuleLoader = {\n load<T = unknown>(filePath: string, options?: LoadModuleOptions): Promise<T>\n}\n\n/**\n * Creates a jiti-based loader for Kubb's TypeScript and JavaScript config modules.\n *\n * jiti transpiles TypeScript and the `@kubb/renderer-jsx` JSX runtime on the fly.\n *\n * @example\n * ```ts\n * const config = await createModuleLoader().load('/abs/kubb.config.ts', { default: true })\n * ```\n */\nexport function createModuleLoader(): ModuleLoader {\n const jiti = createJiti(import.meta.url, JITI_OPTIONS)\n\n return {\n load<T>(filePath: string, options?: LoadModuleOptions) {\n return (options?.default ? jiti.import(filePath, { default: true }) : jiti.import(filePath)) as Promise<T>\n },\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { basename, dirname, resolve } from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport { createModuleLoader } from '@internals/shared'\nimport { toError, tokenize } from '@internals/utils'\nimport type { CLIOptions, Config, KubbHooks, PossibleConfig, PostGenerateCommand, Hookable } from '@kubb/core'\nimport { NonZeroExitError, x } from 'tinyexec'\nimport { type LoadConfigResult, type LoadConfigSource, loadConfig } from 'unconfig'\nimport { isGreaterThan, isValid, truncate } from 'verkit'\nimport { URL_WATCHER_INTERVAL_MS, URL_WATCHER_TIMEOUT_MS, WATCHER_DEBOUNCE_MS, WATCHER_IGNORED_PATHS } from '../../constants.ts'\n\nconst loader = createModuleLoader()\n\n// Kubb configs are JS/TS modules (they call `defineConfig`/`pluginX()`), so YAML and JSON are not\n// supported. The jiti loader handles every module format and the JSX runtime, returning the default export.\nconst tsLoader = (configFile: string) => loader.load(configFile, { default: true })\n\nconst MODULE_NAME = 'kubb'\n\nconst SEARCH_FILES = ['', '.config/', 'configs/'].flatMap((prefix) => [`${prefix}.${MODULE_NAME}rc`, `${prefix}${MODULE_NAME}.config`])\nconst SEARCH_EXTENSIONS = ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs']\n\ntype GetConfigsOptions = {\n /**\n * Explicit path to the Kubb config file. When omitted, the loader searches up from the current directory.\n */\n configPath?: string\n /**\n * Optional OpenAPI input path or URL that overrides `config.input` for this run.\n */\n input?: string\n /**\n * Watch flag forwarded to the user's `defineConfig` function.\n */\n watch?: boolean\n /**\n * Log level forwarded to the user's `defineConfig` function.\n */\n logLevel?: CLIOptions['logLevel']\n}\n\ntype GetConfigsResult = {\n /**\n * Absolute path to the resolved config file.\n */\n configPath: string\n /**\n * Resolved and normalized array of Kubb configs, each guaranteed to have a `plugins` array.\n */\n configs: Array<Config>\n}\n\n/**\n * Discovers the Kubb config and resolves it into a normalized array of configs.\n * Every config in the result is guaranteed to have a `plugins` array.\n */\nexport async function getConfigs({ configPath, input, watch, logLevel }: GetConfigsOptions): Promise<GetConfigsResult> {\n const abs = configPath ? resolve(configPath) : undefined\n const sources: Array<LoadConfigSource<unknown>> = abs\n ? [{ files: [basename(abs)], extensions: [], parser: tsLoader }]\n : [{ files: SEARCH_FILES, extensions: SEARCH_EXTENSIONS, parser: tsLoader }]\n\n let result: LoadConfigResult<unknown>\n try {\n result = await loadConfig<unknown>({ cwd: abs ? dirname(abs) : process.cwd(), sources, merge: false })\n } catch (error) {\n throw new Error('Config failed loading', { cause: error })\n }\n\n const [filepath] = result.sources\n if (!result.config || !filepath) {\n throw new Error('Config not defined, create a kubb.config.js or pass through your config with the option --config')\n }\n\n const config = result.config as PossibleConfig<CLIOptions>\n const cli: CLIOptions = { config: configPath, input, watch, logLevel }\n const resolved = await (typeof config === 'function' ? config(cli) : config)\n const userConfigs = Array.isArray(resolved) ? resolved : [resolved]\n\n return {\n configPath: filepath,\n configs: userConfigs.map((item) => {\n const config: Config = { ...item, plugins: item.plugins ?? [] }\n return config\n }),\n }\n}\n\ntype RunPostGenerateOptions = {\n commands: Array<PostGenerateCommand>\n hooks: Hookable<KubbHooks>\n}\n\n/**\n * Outcome of a single hook subprocess, returned by `runHook` alongside the\n * `kubb:hook:end` hook it emits for the loggers.\n */\ntype HookResult = {\n /**\n * `true` when the command exited with code `0`.\n */\n success: boolean\n /**\n * What went wrong, `null` when the command succeeded.\n */\n error: Error | null\n /**\n * Captured stdout, only present on a non-zero exit.\n */\n stdout?: string\n /**\n * Captured stderr, only present on a non-zero exit.\n */\n stderr?: string\n}\n\n/**\n * Returns `true` when `latest` is a newer semver version than `current`. Compares each numeric\n * part, so `5.10.0` beats `5.9.0` where a plain string comparison would not. Prerelease\n * suffixes are ignored, and a malformed version never reports an update.\n *\n * @example Double-digit minor\n * `isNewerVersion('5.9.0', '5.10.0') // true`\n *\n * @example String comparison would get this wrong the other way\n * `isNewerVersion('5.10.0', '5.9.0') // false`\n */\nexport function isNewerVersion(current: string, latest: string): boolean {\n if (!isValid(current) || !isValid(latest)) return false\n\n return isGreaterThan(truncate(latest, 'patch') as string, truncate(current, 'patch') as string)\n}\n\n/**\n * Runs the `output.postGenerate` commands of a Kubb config in sequence and returns each command's\n * outcome, so the caller can turn failures into diagnostics.\n */\nexport async function runPostGenerate({ commands, hooks }: RunPostGenerateOptions): Promise<Array<HookResult>> {\n const results: Array<HookResult> = []\n\n for (const entry of commands) {\n const { command, name } = typeof entry === 'string' ? { command: entry, name: undefined } : entry\n const [cmd, ...args] = tokenize(command)\n if (!cmd) continue\n\n const hookId = randomUUID()\n const commandWithArgs = [cmd, ...args].join(' ')\n\n await hooks.callHook('kubb:hook:start', { id: hookId, command: cmd, name, args })\n results.push(await runHook({ id: hookId, command: cmd, name, args, commandWithArgs, hooks }))\n }\n\n return results\n}\n\ntype RunHookOptions = {\n id: string\n command: string\n name?: string\n args?: ReadonlyArray<string>\n commandWithArgs: string\n hooks: Hookable<KubbHooks>\n}\n\n/**\n * Spawns a hook command and returns its outcome, mirroring it through `kubb:hook:end` for the\n * loggers. A non-zero exit returns `success: false` rather than throwing, so the caller can turn\n * it into a diagnostic. Other spawn errors do the same. Output is streamed through `kubb:hook:line`\n * only while a listener is attached.\n */\nexport async function runHook({ id, command, name, args, commandWithArgs, hooks }: RunHookOptions): Promise<HookResult> {\n const emitEnd = async (result: HookResult): Promise<HookResult> => {\n await hooks.callHook('kubb:hook:end', { command, name, args, id, ...result })\n return result\n }\n\n // Only stream line-by-line when a logger is listening, so the non-streaming plain\n // logger doesn't pay to iterate the subprocess output.\n const stream = hooks.listenerCount('kubb:hook:line') > 0\n\n try {\n const proc = x(command, [...(args ?? [])], {\n nodeOptions: { detached: process.platform !== 'win32' },\n throwOnError: true,\n })\n\n if (stream) {\n for await (const line of proc) {\n await hooks.callHook('kubb:hook:line', { id, line })\n }\n }\n\n await proc\n await hooks.callHook('kubb:success', { message: `${styleText('dim', name ?? commandWithArgs)} successfully executed` })\n return emitEnd({ success: true, error: null })\n } catch (err) {\n if (!(err instanceof NonZeroExitError)) {\n return emitEnd({ success: false, error: toError(err) })\n }\n\n const stderr = err.output?.stderr ?? ''\n const stdout = err.output?.stdout ?? ''\n\n const error = new Error(`Hook execute failed: ${commandWithArgs}`)\n // Signal the failure via the result and `kubb:hook:end` only, carrying the captured output so\n // the logger can render it. The caller turns this into a coded diagnostic and emits that\n // through `Diagnostics.emit`, so emitting `kubb:error` here would render it twice.\n return emitEnd({ success: false, error, stdout, stderr })\n }\n}\n\ntype SerialRunnerOptions = {\n /**\n * The async work to serialize.\n */\n run(): Promise<void>\n /**\n * Receives errors thrown by `run`, so a failure never rejects the returned trigger.\n */\n onError(error: Error): void\n}\n\n/**\n * Wraps `run` so invocations never overlap: a trigger that lands while a run is in flight\n * marks it dirty and runs once more after it finishes, no matter how many triggers arrived.\n * Useful for event-driven reruns (a file watcher, a queue drain) where bursts should\n * coalesce into a single trailing run.\n *\n * @example\n * ```ts\n * const rebuild = createSerialRunner({\n * run: () => build(),\n * onError: (error) => log.error(error.message),\n * })\n * watcher.on('change', () => void rebuild())\n * ```\n */\nexport function createSerialRunner({ run, onError }: SerialRunnerOptions): () => Promise<void> {\n let running = false\n let dirty = false\n\n return async (): Promise<void> => {\n if (running) {\n dirty = true\n return\n }\n running = true\n do {\n dirty = false\n try {\n await run()\n } catch (error) {\n onError(toError(error))\n }\n } while (dirty)\n running = false\n }\n}\n\ntype WatcherLog = {\n info: (message: string) => void\n error: (message: string) => void\n}\n\n/**\n * Starts a file watcher on the given paths and calls `cb` on any change.\n * Ignores `.git` and `node_modules` directories. Event bursts (an editor save emits several)\n * are debounced into one build, and builds never overlap: changes during a build queue exactly\n * one rebuild.\n */\nexport async function startWatcher(\n path: Array<string>,\n cb: (path: Array<string>) => Promise<void>,\n log: WatcherLog = { info: console.log, error: console.log },\n): Promise<void> {\n const { watch } = await import('chokidar')\n // `ignoreInitial` skips the `add` events chokidar fires for existing files at startup, which\n // would otherwise rebuild right after the initial run.\n const watcher = watch(path, { ignorePermissionErrors: true, ignored: WATCHER_IGNORED_PATHS, ignoreInitial: true })\n\n process.once('SIGINT', () => {\n watcher.close()\n })\n process.once('SIGTERM', () => {\n watcher.close()\n })\n\n // Bursts never overlap builds on the shared hooks emitter: a change during a build\n // queues exactly one rerun.\n const runBuild = createSerialRunner({\n run: () => cb(path),\n onError: () => log.error(styleText('red', 'Watcher failed')),\n })\n let debounceTimer: ReturnType<typeof setTimeout> | null = null\n\n watcher.on('all', (type, file) => {\n log.info(styleText('yellow', styleText('bold', `Change detected: ${type} ${file}`)))\n if (debounceTimer) clearTimeout(debounceTimer)\n debounceTimer = setTimeout(() => {\n debounceTimer = null\n void runBuild()\n }, WATCHER_DEBOUNCE_MS)\n })\n}\n\n/**\n * Fetches the body of a remote spec URL, `undefined` when the server does not answer with a\n * readable 2xx body within the timeout. The caller seeds `startUrlWatcher` with the result, so\n * the watcher compares polls against the content the initial build ran on.\n */\nexport async function fetchUrlBody(url: string, timeoutMs: number = URL_WATCHER_TIMEOUT_MS): Promise<string | undefined> {\n try {\n const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) })\n if (!response.ok) return undefined\n return await response.text()\n } catch {\n return undefined\n }\n}\n\ntype UrlWatcherOptions = {\n /**\n * Sink for watcher messages, `console.log` by default.\n */\n log?: WatcherLog\n /**\n * Time in milliseconds between polls.\n */\n intervalMs?: number\n /**\n * Upper bound in milliseconds for one poll request, covering headers and body read.\n */\n timeoutMs?: number\n /**\n * Body the initial build ran against, the baseline for change detection. When omitted (the\n * server was unreachable at startup), the first successful poll rebuilds so the output catches\n * up as soon as the server responds.\n */\n initialBody?: string\n}\n\n/**\n * Polls a remote spec URL and calls `cb` whenever the response body changes. A remote document\n * emits no filesystem events, so this is the URL counterpart of `startWatcher`.\n *\n * `initialBody` seeds the change detection, so an edit landing between the initial build and the\n * first poll still rebuilds. An unreachable server (the API restarting between saves) is reported\n * once per outage and polling continues; after it recovers, a rebuild happens only when the body\n * actually differs from the last one seen, so a plain restart with an unchanged spec stays quiet.\n * Each request is aborted after `timeoutMs`, so a hung response delays at most one poll.\n *\n * Returns a function that stops polling and aborts the in-flight request, so callers (and tests)\n * can shut the watcher down without signaling the process.\n */\nexport function startUrlWatcher(url: string, cb: (path: Array<string>) => Promise<void>, options: UrlWatcherOptions = {}): () => void {\n const { log = { info: console.log, error: console.log }, intervalMs = URL_WATCHER_INTERVAL_MS, timeoutMs = URL_WATCHER_TIMEOUT_MS, initialBody } = options\n\n let lastBody = initialBody\n let offline = false\n let timer: ReturnType<typeof setTimeout> | null = null\n let controller: AbortController | null = null\n let stopped = false\n\n const stop = () => {\n stopped = true\n if (timer) clearTimeout(timer)\n controller?.abort()\n }\n process.once('SIGINT', stop)\n process.once('SIGTERM', stop)\n\n // Builds never overlap on the shared hooks emitter: a change during a build queues exactly\n // one rerun.\n const runBuild = createSerialRunner({\n run: () => cb([url]),\n onError: () => log.error(styleText('red', 'Watcher failed')),\n })\n\n const poll = async (): Promise<void> => {\n controller = new AbortController()\n try {\n // The signal also aborts the body read, so a response that stalls mid-stream still times out.\n const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)])\n const response = await fetch(url, { signal })\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`)\n }\n const body = await response.text()\n if (offline) {\n offline = false\n log.info(styleText('yellow', `${url} is reachable again`))\n }\n const changed = lastBody !== undefined && body !== lastBody\n if (changed) {\n log.info(styleText('yellow', styleText('bold', `Change detected: ${url}`)))\n }\n if (changed || lastBody === undefined) {\n void runBuild()\n }\n lastBody = body\n } catch {\n // `lastBody` survives the outage so recovery rebuilds only on real content changes.\n if (!offline && !stopped) {\n offline = true\n log.error(styleText('red', `Cannot reach ${url}, polling until it responds again`))\n }\n }\n if (!stopped) {\n timer = setTimeout(() => void poll(), intervalMs)\n }\n }\n\n void poll()\n\n return stop\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAeA,MAAa,aAAa;CACxB,UAAU;EACR,SAAS;EACT,OAAO,eAAuB;GAAC;GAAoB;GAAW;EAAU;EACxE,cAAc;CAChB;CACA,OAAO;EACL,SAAS;EACT,OAAO,eAAuB;GAAC;GAAU;GAAW;EAAU;EAC9D,cAAc;CAChB;CACA,OAAO;EACL,SAAS;EACT,OAAO,eAAuB,CAAC,UAAU;EACzC,cAAc;CAChB;AACF;;;;AAKA,MAAa,UAAU;CACrB,QAAQ;EACN,SAAS;EACT,OAAO,eAAuB,CAAC,YAAY,OAAO;EAClD,cAAc;CAChB;CACA,OAAO;EACL,SAAS;EACT,OAAO,eAAuB;GAAC;GAAQ;GAAS;EAAU;EAC1D,cAAc;CAChB;CACA,QAAQ;EACN,SAAS;EAET,OAAO,eAAuB;GAAC;GAAS;GAAe;EAAU;EACjE,cAAc;CAChB;AACF;;;;;AAMA,MAAa,uBAAuB;CAAC;CAAS;CAAS;AAAU;;;;AAKjE,MAAa,oBAAoB;CAAC;CAAU;CAAS;AAAQ;;;;AAK7D,SAAgB,gBAAgB,MAAgC;CAC9D,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,SAAA,GAAQA,mBAAAA,MAAAA,CAAM,MAAM,CAAC,WAAW,GAAG,EAAE,OAAO,SAAS,CAAC;EAC5D,MAAM,GAAG,UAAU,SAAS,QAAQ,SAAS,CAAC,CAAC;EAC/C,MAAM,GAAG,eAAe,QAAQ,KAAK,CAAC;CACxC,CAAC;AACH;;;;;;;AAQA,eAAsB,WAAiC,YAAyD;CAC9G,KAAK,MAAM,aAAa,YACtB,IAAI,MAAM,gBAAgB,SAAS,GACjC,OAAO;CAIX,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,SAAS,SAAgC;CACvD,QAAQ,QAAQ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I5B,MAAM,WAAW,mBAAmB;EAClC,WAAW,GAAG,CAAC,GAAG,CAAC;EACnB,eAAe,IAAI,OAAA,GAAMJ,UAAAA,UAAAA,CAAU,OAAO,gBAAgB,CAAC;CAC7D,CAAC;CAED,MAAM,OAAO,YAA2B;EACtC,aAAa,IAAI,gBAAgB;EACjC,IAAI;GAEF,MAAM,SAAS,YAAY,IAAI,CAAC,WAAW,QAAQ,YAAY,QAAQ,SAAS,CAAC,CAAC;GAClF,MAAM,WAAW,MAAM,MAAM,KAAK,EAAE,OAAO,CAAC;GAC5C,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,QAAQ,SAAS,QAAQ;GAE3C,MAAM,OAAO,MAAM,SAAS,KAAK;GACjC,IAAI,SAAS;IACX,UAAU;IACV,IAAI,MAAA,GAAKA,UAAAA,UAAAA,CAAU,UAAU,GAAG,IAAI,oBAAoB,CAAC;GAC3D;GACA,MAAM,UAAU,aAAa,KAAA,KAAa,SAAS;GACnD,IAAI,SACF,IAAI,MAAA,GAAKA,UAAAA,UAAAA,CAAU,WAAA,GAAUA,UAAAA,UAAAA,CAAU,QAAQ,oBAAoB,KAAK,CAAC,CAAC;GAE5E,IAAI,WAAW,aAAa,KAAA,GAC1B,SAAc;GAEhB,WAAW;EACb,QAAQ;GAEN,IAAI,CAAC,WAAW,CAAC,SAAS;IACxB,UAAU;IACV,IAAI,OAAA,GAAMA,UAAAA,UAAAA,CAAU,OAAO,gBAAgB,IAAI,kCAAkC,CAAC;GACpF;EACF;EACA,IAAI,CAAC,SACH,QAAQ,iBAAiB,KAAK,KAAK,GAAG,UAAU;CAEpD;CAEA,KAAU;CAEV,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubb/cli",
3
- "version": "5.4.1",
3
+ "version": "5.4.3",
4
4
  "description": "Official CLI for Kubb. Run kubb generate, kubb init, kubb validate, kubb studio, and kubb mcp to manage the full code generation lifecycle.",
5
5
  "keywords": [
6
6
  "cli",
@@ -63,24 +63,24 @@
63
63
  "dependencies": {
64
64
  "@clack/prompts": "^1.8.1",
65
65
  "@gunshi/plugin-dryrun": "^0.37.3",
66
- "@kubb/core": "5.4.1",
66
+ "@kubb/core": "5.4.3",
67
67
  "chokidar": "^5.0.0",
68
68
  "gunshi": "^0.37.3",
69
69
  "jiti": "^2.7.0",
70
70
  "tinyexec": "^1.3.1",
71
71
  "unconfig": "^7.5.0",
72
- "verkit": "^0.4.1"
72
+ "verkit": "^0.5.0"
73
73
  },
74
74
  "devDependencies": {
75
75
  "@internals/shared": "0.0.1",
76
76
  "@internals/utils": "0.0.1",
77
- "@kubb/adapter-oas": "5.4.1",
78
- "@kubb/studio": "5.4.1"
77
+ "@kubb/adapter-oas": "5.4.3",
78
+ "@kubb/studio": "5.4.3"
79
79
  },
80
80
  "peerDependencies": {
81
- "@kubb/adapter-oas": "5.4.1",
82
- "@kubb/mcp": "5.4.1",
83
- "@kubb/studio": "5.4.1"
81
+ "@kubb/adapter-oas": "5.4.3",
82
+ "@kubb/mcp": "5.4.3",
83
+ "@kubb/studio": "5.4.3"
84
84
  },
85
85
  "peerDependenciesMeta": {
86
86
  "@kubb/adapter-oas": {
@@ -1,2 +0,0 @@
1
- import { n as getWorkerStatus } from "./background-BDZa6MJS.js";
2
- export { getWorkerStatus };
@@ -1 +0,0 @@
1
- {"version":3,"file":"package-DjS7Xk-S.cjs","names":[],"sources":["../package.json"],"sourcesContent":[""],"mappings":""}
@@ -1,6 +0,0 @@
1
- //#region package.json
2
- var version = "5.4.1";
3
- //#endregion
4
- export { version as t };
5
-
6
- //# sourceMappingURL=package-IY922xjh.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"package-IY922xjh.js","names":[],"sources":["../package.json"],"sourcesContent":[""],"mappings":""}
@@ -1 +0,0 @@
1
- {"version":3,"file":"run-BsP5syy1.js","names":["logLevelMap"],"sources":["../../../internals/utils/src/openInBrowser.ts","../../../internals/utils/src/fs.ts","../src/runners/studio/credentials.ts","../src/runners/studio/run.ts"],"sourcesContent":["import { execFile } from 'node:child_process'\nimport process from 'node:process'\nimport { isCIEnvironment } from './isCIEnvironment.ts'\n\n/**\n * Opens a URL or local file in the default browser, unless running in CI.\n */\nexport function openInBrowser(target: string): void {\n if (isCIEnvironment()) return\n\n if (process.platform === 'win32') {\n execFile('cmd', ['/c', 'start', '', target], () => {})\n } else {\n execFile(process.platform === 'darwin' ? 'open' : 'xdg-open', [target], () => {})\n }\n}\n","import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","import { hash } from 'node:crypto'\nimport { mkdir, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { clean, read } from '@internals/utils'\n\n/**\n * Root for everything the CLI persists between runs: the paired credential, the machine secret,\n * the last Studio config, and the live-session registry. `KUBB_HOME` relocates all of it.\n */\nfunction getKubbHome(): string {\n return process.env.KUBB_HOME ?? path.join(homedir(), '.kubb')\n}\n\n/**\n * Root for the credential and machine identity of the current project.\n *\n * Studio agents are project connections, so two projects on one machine must not share the same\n * persisted token or machine secret.\n */\nexport function getProjectKubbHome(project = process.cwd()): string {\n const projectId = hash('sha256', project)\n return path.join(getKubbHome(), 'projects', projectId)\n}\n\nconst CREDENTIALS_FILENAME = 'credentials.json'\n\n/**\n * Absolute path of the stored credential, so callers can name it in output without rebuilding it.\n */\nexport function getCredentialsPath(): string {\n return path.join(getProjectKubbHome(), CREDENTIALS_FILENAME)\n}\n\nexport type Credentials = {\n /**\n * The Studio instance this machine paired with. A different `--url` means re-pairing.\n */\n studioUrl: string\n /**\n * Bearer token for this machine. Never logged, never printed.\n */\n token: string\n agentId: string\n agentSlug: string\n /**\n * Permissions the user has already granted, keyed by absolute project path, so the CLI asks\n * once per project instead of on every run.\n */\n projects?: Record<string, { allowRead?: boolean; allowWrite?: boolean; allowConfigEdit?: boolean; allowExec?: boolean }>\n}\n\n/**\n * Reads the stored credential, or null when this machine has not paired yet or the file is\n * unreadable or corrupt. A bad file is treated as \"not paired\" so `kubb studio login` can\n * overwrite it rather than the CLI dying on it.\n */\nexport async function readCredentials(): Promise<Credentials | null> {\n const raw = await read(getCredentialsPath()).catch(() => null)\n if (!raw) {\n return null\n }\n\n try {\n return JSON.parse(raw) as Credentials\n } catch {\n return null\n }\n}\n\n/**\n * Writes the credential with owner-only permissions. The file holds a bearer token, so the mode\n * is set at creation time rather than left to the process umask or fixed up afterward, which\n * would leave the token briefly readable under the umask's default mode.\n */\nexport async function writeCredentials(credentials: Credentials): Promise<void> {\n const file = getCredentialsPath()\n\n await mkdir(path.dirname(file), { recursive: true, mode: 0o700 })\n await writeFile(file, JSON.stringify(credentials, null, 2), { mode: 0o600 })\n}\n\n/**\n * Forgets the stored credential. Succeeds when there was nothing to forget.\n */\nexport async function clearCredentials(): Promise<void> {\n await clean(getCredentialsPath())\n}\n","import { hostname } from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { styleText } from 'node:util'\nimport * as prompts from '@clack/prompts'\nimport { KUBB_CONFIG_FILENAME } from '@internals/shared'\nimport { isCIEnvironment, openInBrowser, toError } from '@internals/utils'\nimport type { CLIOptions, Config } from '@kubb/core'\nimport { cliReporter, logLevel as logLevelMap } from '@kubb/core'\nimport {\n createFileStorage,\n type ClientOptions,\n defaultStudioUrl,\n type InvalidAgentTokenError,\n pairAgent,\n PairingCanceledError,\n runConnection,\n setStorage,\n} from '@kubb/studio'\nimport { buildTelemetryEvent, sendTelemetry } from '../../Telemetry.ts'\nimport setupReporters from '../../loggers/utils.ts'\nimport { createSpinner, logBlock, logIntro, logOutro, logTip } from '../../loggers/output.ts'\nimport { canUseTTY } from '../../utils/env.ts'\nimport { getConfigs } from '../generate/utils.ts'\nimport { clearCredentials, type Credentials, getCredentialsPath, getProjectKubbHome, readCredentials, writeCredentials } from './credentials.ts'\nimport { version } from '../../../package.json'\n\ntype Permission = 'allowRead' | 'allowWrite' | 'allowConfigEdit' | 'allowExec'\n\nexport type StudioOptions = {\n /**\n * Current `@kubb/cli` version, reported to Studio and used for the telemetry payload.\n */\n version: string\n configPath?: string\n /**\n * Base URL of the Studio instance, for a self-hosted deployment. Resolved before it reaches here,\n * since stored credentials are bound to it.\n */\n studioUrl: string\n /**\n * What Studio may do in this project. Each flag grants outright; the rest are asked once per\n * project through {@link resolvePermissions}.\n */\n permission: Record<Permission, boolean>\n /**\n * Whether to open the approval page in a browser during pairing.\n */\n autoOpen: boolean\n logLevel?: CLIOptions['logLevel']\n}\n\nexport type SnapshotOptions = StudioOptions & {\n /**\n * Organization CI API key. Falls back to `KUBB_TOKEN`.\n */\n token?: string\n /**\n * Stable identity for the CI agent. Falls back to CI auto-detection.\n */\n id?: string\n /** Identity of another CI agent to also compare with. Falls back to CI auto-detection. */\n baseId?: string\n /**\n * Package name for the generated tarball. Falls back to the nearest package.json.\n */\n name?: string\n /**\n * Package version for the generated tarball. Falls back to the nearest package.json.\n */\n packageVersion?: string\n /**\n * Seconds to wait for the job to finish.\n */\n timeout?: number\n /**\n * Print the result as one JSON object instead of a summary.\n */\n json?: boolean\n}\n\ntype StudioValues = {\n config?: string\n url?: string\n allowRead: boolean\n allowWrite: boolean\n allowConfigEdit: boolean\n allowExec: boolean\n open?: boolean\n logLevel?: CLIOptions['logLevel']\n}\n\nexport function createStudioOptions(values: StudioValues): StudioOptions {\n return {\n version,\n configPath: values.config,\n studioUrl: values.url ?? defaultStudioUrl,\n permission: {\n allowRead: values.allowRead,\n allowWrite: values.allowWrite,\n allowConfigEdit: values.allowConfigEdit,\n allowExec: values.allowExec,\n },\n autoOpen: values.open ?? true,\n logLevel: values.logLevel,\n }\n}\n\ntype LoginOptions = {\n /**\n * Aborting this cancels an in-flight pairing request or poll and rejects with\n * {@link PairingCanceledError}. Wired to `kubb studio`'s shutdown signal, so Ctrl+C during\n * pairing cancels it instead of leaving the poll running.\n */\n signal?: AbortSignal\n /**\n * Credentials from before this login. When the fresh pairing resolves to the same agent on the\n * same Studio, its saved project permissions carry forward instead of being asked again.\n * Left out for an explicitly requested `kubb studio login`, which always starts clean.\n */\n previousCredentials?: Credentials | null\n}\n\n/**\n * Pairs this machine with Studio and stores the resulting token.\n *\n * The CLI holds a code and the browser approves it, rather than the user copying a token out of\n * the UI. The token comes back over the CLI's own HTTPS POST, so it never lands in a URL, a\n * server log, or a `Referer` header.\n */\nexport async function login({ studioUrl, autoOpen }: StudioOptions, { signal, previousCredentials }: LoginOptions = {}): Promise<Credentials> {\n const spinner = createSpinner()\n // The spinner only starts once a code is shown.\n let waiting = false\n\n try {\n const { token, agent } = await pairAgent({\n studioUrl,\n type: 'cli',\n name: path.basename(process.cwd()),\n hostname: hostname(),\n signal,\n onCode: (session) => {\n console.log(`\\nOpen ${styleText('cyan', session.verification_uri)} and approve the code ${styleText('bold', session.user_code)}`)\n\n if (autoOpen) {\n openInBrowser(session.verification_uri_complete)\n }\n\n spinner.start('Waiting for approval')\n waiting = true\n },\n onRetry: (error) => spinner.message(`Could not reach Kubb Studio, retrying: ${error.message}`),\n })\n spinner.stop(`Paired as ${agent.name}`)\n\n const keepsIdentity = previousCredentials?.studioUrl === studioUrl && previousCredentials.agentId === agent.id\n const credentials: Credentials = {\n studioUrl,\n token,\n agentId: agent.id,\n agentSlug: agent.slug,\n ...(keepsIdentity && previousCredentials?.projects ? { projects: previousCredentials.projects } : {}),\n }\n await writeCredentials(credentials)\n\n console.log(`Credentials stored in ${getCredentialsPath()}`)\n\n return credentials\n } catch (error) {\n if (waiting) {\n spinner.stop(error instanceof PairingCanceledError ? 'Pairing canceled' : 'Pairing failed')\n }\n throw error\n }\n}\n\n/**\n * What each permission is asked as, in the order the questions appear.\n */\nconst PERMISSIONS: ReadonlyArray<{\n key: Permission\n /**\n * Short label for status output and the connect summary.\n */\n label: string\n question: (project: string, configPath: string) => string\n}> = [\n {\n key: 'allowRead',\n label: 'read generated files',\n question: () => 'Let Kubb Studio read the files a generation produced?',\n },\n { key: 'allowWrite', label: 'write generated files', question: (project) => `Let Kubb Studio write generated files into ${project}?` },\n {\n key: 'allowConfigEdit',\n label: 'edit kubb.config.ts',\n question: (_project, configPath) => `Let Kubb Studio change plugin options in ${configPath}?`,\n },\n {\n key: 'allowExec',\n label: 'run formatter, linter, postGenerate',\n question: () => 'Let Kubb Studio run the formatter, the linter, and output.postGenerate?',\n },\n]\n\n/**\n * One row per permission, for the connect banner and `kubb studio status`. A list rather than a\n * joined line: four labels this long read as one run-on sentence side by side.\n */\nexport function formatPermissionRows(granted: Record<Permission, boolean>): Array<string> {\n return PERMISSIONS.map(({ key, label }) => `${granted[key] ? styleText('green', '✔') : styleText('red', '✘')} ${label}`)\n}\n\n/**\n * Resolves Studio permissions for the current project.\n * Flags win, saved answers are reused, and new answers are stored unless `persist` is false.\n */\nexport async function resolvePermissions(\n options: StudioOptions,\n credentials: Credentials,\n configPath: string = KUBB_CONFIG_FILENAME,\n /**\n * Stores new answers in `~/.kubb/credentials.json`.\n * Pass `false` for `KUBB_AGENT_TOKEN` sessions so a temporary token is not written back to disk.\n */\n persist = true,\n): Promise<Record<Permission, boolean>> {\n const project = process.cwd()\n const remembered = credentials.projects?.[project]\n const granted: Record<Permission, boolean> = { allowRead: false, allowWrite: false, allowConfigEdit: false, allowExec: false }\n const answers: Partial<Record<Permission, boolean>> = {}\n prompts.updateSettings({ withGuide: true })\n\n for (const { key, question } of PERMISSIONS) {\n if (options.permission[key] || typeof remembered?.[key] === 'boolean') {\n granted[key] = options.permission[key] || remembered?.[key] === true\n continue\n }\n\n if (isCIEnvironment() || !canUseTTY()) {\n granted[key] = false\n continue\n }\n\n granted[key] = (await prompts.confirm({ message: question(project, configPath), initialValue: false })) === true\n answers[key] = granted[key]\n }\n if (persist && Object.keys(answers).length) {\n await writeCredentials({\n ...credentials,\n projects: { ...credentials.projects, [project]: { ...remembered, ...answers } },\n })\n }\n\n return granted\n}\n\n/**\n * Loads the project's Kubb config the same way `kubb generate` does.\n * Returns the first config.\n */\nexport async function loadConfigs(options: StudioOptions): Promise<{ configPath: string; config: Config }> {\n const { configPath, configs } = await getConfigs({ configPath: options.configPath, logLevel: options.logLevel })\n const [config] = configs\n\n if (!config) {\n throw new Error('Config not defined, create a kubb.config.ts or pass it with --config')\n }\n\n // `getConfigs` resolves this to an absolute path. Relativized here, once, so the permission\n // prompt and the path Studio receives over the wire both show the project-relative form instead\n // of leaking the local filesystem layout.\n return { configPath: path.relative(process.cwd(), configPath) || configPath, config }\n}\n\n/**\n * Why a rejected token could not be recovered automatically: it came from `KUBB_AGENT_TOKEN`, no\n * browser is available to re-pair with, or the token this run already re-paired for was rejected\n * again.\n */\ntype RejectedTokenReason = 'envToken' | 'nonInteractive' | 'reauthExhausted'\n\n/**\n * Explains a rejected token to the operator. Builds the error and nothing else, so each caller\n * decides what happens to the credentials.\n */\nfunction explainRejectedToken(error: InvalidAgentTokenError, reason: RejectedTokenReason): Error {\n if (reason === 'envToken') {\n return new Error(`${error.message} Pair again and update KUBB_AGENT_TOKEN.`)\n }\n\n if (reason === 'reauthExhausted') {\n return new Error(`${error.message} Studio rejected the newly approved token too. Run \\`kubb studio login\\` and try again.`)\n }\n\n return new Error(`${error.message} Run \\`kubb studio login\\` to pair again.`)\n}\n\nexport type PreparedConnection = {\n configPath: string\n credentials: Credentials\n permissions: StudioOptions['permission']\n}\n\n/** Validates the project and resolves pairing and permissions before starting its worker. */\nexport async function prepareConnection(options: StudioOptions, signal?: AbortSignal): Promise<PreparedConnection> {\n const { configPath } = await loadConfigs(options)\n const envToken = process.env.KUBB_AGENT_TOKEN\n const stored = envToken ? null : await readCredentials()\n const credentials = await (async () => {\n if (envToken) return { studioUrl: options.studioUrl, token: envToken, agentId: '', agentSlug: '' }\n if (stored?.studioUrl === options.studioUrl) return stored\n if (isCIEnvironment()) {\n throw new Error(`Not paired with ${options.studioUrl}. Set KUBB_AGENT_TOKEN, or run \\`kubb studio login\\` on a machine with a browser.`)\n }\n return login(options, { signal })\n })()\n const permissions = await resolvePermissions(options, credentials, configPath, !envToken)\n return { configPath, credentials, permissions }\n}\n\nexport type WorkerState = 'starting' | 'connected' | 'reconnecting' | 'authentication required' | 'stopped'\n\n/** Runs the same project connection in the foreground or in a background worker. */\nexport async function connect(\n options: StudioOptions,\n context: {\n prepared?: PreparedConnection\n signal?: AbortSignal\n onState?: (state: WorkerState) => void | Promise<void>\n } = {},\n): Promise<void> {\n const shutdown = new AbortController()\n const signal = context.signal ?? shutdown.signal\n const stop = () => shutdown.abort()\n const events = process as unknown as NodeJS.EventEmitter\n if (!context.signal) {\n events.once('SIGINT', stop)\n events.once('SIGTERM', stop)\n }\n let hinted = false\n let reauthenticated = false\n try {\n if (!context.prepared) {\n const { getWorkerStatus } = await import('./background.ts')\n const worker = await getWorkerStatus()\n if (worker.running) throw new Error('This project is running in the background. Run `kubb studio stop` first.')\n }\n const prepared = context.prepared ?? (await prepareConnection(options, signal))\n let { credentials, permissions } = prepared\n const { configPath } = prepared\n await runConnection({\n credentials,\n signal,\n clientOptions: (): Omit<ClientOptions, 'token' | 'onAuthRequired'> => ({\n studioUrl: options.studioUrl,\n configPath,\n version: options.version,\n root: process.cwd(),\n permissions,\n loadConfig: async () => (await loadConfigs(options)).config,\n installLogger: async (hooks) => {\n if (!context.onState) await setupReporters(hooks, { logLevel: logLevelMap[options.logLevel ?? 'info'], reporters: [cliReporter] })\n hooks.hook('studio:connected', () => {\n if (!hinted && !context.onState && options.logLevel !== 'silent') logBlock(styleText('dim', 'Press Ctrl+C to disconnect'))\n hinted = true\n })\n hooks.hook('studio:ready', async () => {\n await context.onState?.('connected')\n if (!context.onState) logTip()\n })\n hooks.hook('studio:reconnecting', () => context.onState?.('reconnecting'))\n hooks.hook('studio:error', ({ error }) => {\n if (context.onState) console.error(error.message)\n })\n },\n }),\n onTokenRejected: async ({ error, live }) => {\n await context.onState?.('authentication required')\n if (process.env.KUBB_AGENT_TOKEN) throw explainRejectedToken(error, 'envToken')\n if (!live) await clearCredentials()\n if (reauthenticated) throw explainRejectedToken(error, 'reauthExhausted')\n if (context.onState || isCIEnvironment() || !canUseTTY()) throw explainRejectedToken(error, 'nonInteractive')\n console.log(styleText('yellow', live ? `${error.message} Studio needs you to approve access again.` : `${error.message} Pairing again...`))\n if (live) await clearCredentials()\n try {\n credentials = await login(options, { signal, previousCredentials: credentials })\n } catch (error) {\n if (error instanceof PairingCanceledError) {\n if (live && options.logLevel !== 'silent') logOutro('Disconnected')\n return null\n }\n throw error\n }\n reauthenticated = true\n permissions = await resolvePermissions(options, credentials, configPath, !process.env.KUBB_AGENT_TOKEN)\n return credentials\n },\n })\n if (!context.onState && signal.aborted && options.logLevel !== 'silent') logOutro('Disconnected')\n } catch (error) {\n if (!(error instanceof PairingCanceledError)) throw error\n } finally {\n events.off('SIGINT', stop)\n events.off('SIGTERM', stop)\n }\n}\n\n/**\n * Reports the paired agent and any saved permissions for the current project.\n */\nexport async function status(options: StudioOptions): Promise<void> {\n const credentials = await readCredentials()\n\n if (!credentials) {\n console.log('Not paired. Run `kubb studio login`.')\n\n return\n }\n\n console.log(`Paired with ${credentials.studioUrl} as ${styleText('cyan', credentials.agentSlug || credentials.agentId)}`)\n\n if (credentials.studioUrl !== options.studioUrl) {\n console.log(styleText('yellow', `Connecting to ${options.studioUrl} needs pairing again.`))\n }\n\n const remembered = credentials.projects?.[process.cwd()]\n\n if (!remembered) {\n console.log(styleText('dim', 'No saved permissions for this project. Run `kubb studio` to connect and choose.'))\n\n return\n }\n\n console.log(styleText('dim', 'Saved permissions'))\n\n for (const row of formatPermissionRows({\n allowRead: remembered.allowRead === true,\n allowWrite: remembered.allowWrite === true,\n allowConfigEdit: remembered.allowConfigEdit === true,\n allowExec: remembered.allowExec === true,\n })) {\n console.log(row)\n }\n}\n\n/**\n * Runs a Studio command with shared setup and telemetry reporting.\n */\nexport async function run(options: StudioOptions, action: () => Promise<unknown>, { block = false, json = false } = {}): Promise<void> {\n // The machine secret lives here and pairing binds it, so storage is installed before anything\n // reads `getMachineToken()`, which `startPairing` does, before any client exists.\n setStorage(createFileStorage(getProjectKubbHome()))\n\n const hrStart = process.hrtime()\n const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'studio', kubbVersion: options.version, hrStart, status }))\n\n try {\n if (options.logLevel !== 'silent' && !json) {\n logIntro({\n warning: styleText('yellow', 'This feature is still under development, use with caution'),\n block,\n })\n }\n\n await action()\n\n await report('success')\n } catch (error) {\n await report('failed')\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